text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
I am having trouble writing a list of items into a csv file, with each item being on a new row. Here is what I have, it does what I want, except it is putting each letter on a new row... import csv data = ['First Item', 'Second Item', 'Third Item'] with open('output.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) for i in data: writer.writerows(i) Use a nested list: writer.writerows([[i]]). Explanation from writing data from a python list to csv row-wise: .writerowtakes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column. So, as all you need is a single column, ...
https://codedump.io/share/AhGxJ7rqdrWe/1/how-to-write-list-to-csv-with-each-item-on-a-new-row
CC-MAIN-2016-44
refinedweb
127
76.42
We were all juniors at some time, and in the spirit of sharing here: what's some good advice for junior developers? What things would you like to tell yourself when you were a junior? We were all juniors at some time, and in the spirit of sharing here: what's some good advice for junior developers? What things would you like to tell yourself when you were a junior? Miguel Brito - Ahmed Atef - Madza - Suraj Vishwakarma - Discussion If I have Doc Brown's DeLorean, this is what I would advise my younger self import this. Learn it by heart, then read no. 3 (above) again There's a lot more, but these are my big ones This comment needs a "share" button. Dude, make a post out of this! Here it is If I knew then what I know now Ted Hagos ・ Oct 5 '18 ・ 1 min read Dude thanks for this! I'll be sharing it with some buddies. Glad you liked it I'll get right on it. Thanks thanks @Ted_Hagos , i just started out as a junior dev needs a PR. So there's the tongue-in-cheek (ish) advise. Levity aside, let's look at another angle of the question. How does one get out or graduate from being a junior to something else; a senior, I suppose. This is an age-old question and a lot of brilliant minds tried to answer this (I'm pretty sure, a lot more brilliant minds in the future will still try to answer it), this is my favorite so far Programmer Competency Matrix. Some of the item on the matrix might be abstract but some can get hairy detailed. I don't agree with all of it, but (at least) where I work(ed), there seems to be a general agreement on it. Take it with a grain of salt; remember, you found it on the internet Please Sir be my mentor. I'd love to, but I'm terrible mentor. Thanks though Ok sir,though u don't sound like u will be a terrible mentor, but i respect your decision. Okay Sir, though you don't sound like one who would make a terrible mentor, but I respect your decision. This is probably the best advice I've ever gotten... ever. Thanks! Please post repeated architecture and production information,thank you Can you explain the point 3. I thought using design pattern is a good code practice. He's basically saying "fit the solution to the problem, and don't over-engineer". Not everything needs a design pattern, so sometimes just keep it simple, avoid abstraction layers if possible, and don't optimise prematurely. Design patterns are names for common solutions to common problems and therefore often just a label to shorten a discussion. Do not apply a pattern for the pattern's sake, but apply the right pattern to fit a given problem. People should respect you. It's your right to push back against disrespectful interactions. If it's waved away with "oh, [person] is just like that," know that a) that is bullshit and b) both the person being disrespectful AND the one dismissing it are wrong. You can become a great developer EVEN if you spend your nights & weekends doing other things. Be focused, make those work hours count, and then leave your office and spend your free time out in the wider world. Resist tribalism in all forms. a) Your role as a software engineer isn't more or less important to the company than other roles. b) Your place on the stack isn't more or less prestigious than other places. c) The technology you use has its ideal use cases - and so do all the alternatives. Anyone who justifies something by saying it's "an industry best practice" actually has NO IDEA why they're doing it. Push (gently, respectfully) to see if they can articulate the actual positive outcome they expect. a) same goes for "idiomatic," "more elegant," and "cleaner" Do not read Robert Martin's books, unless you're working at a large, old company - and in that case, view them as anthropological studies that will help you survive in an alien environment. More seriously - they're written for a previous generation, and while they might help you understand the current crop of 'senior' developers better, their techniques and attitudes are out of date and won't be useful to you moving forward. You're in a new world! You have the chance to make a real impact with your communication and technical skills. Go out & do it your way. It's too bad I can only click the ❤ once Could not agree more Totally agree with this. I really had my hair on fire for the first few months I got a job, all because I believed I needed to be programming all day AND night. I only realized that could not be the answer when I found myself burnt out from programming in an actual job setting working with actual people. Spending 6 - 8 hours doing something was already plenty of practice. Taking care of myself was still required, and when I did so I became a better engineer (and better everything). I’ve followed you for some time on twitter and most of what u say ressonate with me. But this last point is plain wrong. It disapoints me. It makes me sad that u give such bad advice to new developers just because you have a grudge on UncleBob. You should do some introspection and try to improve yourself as a person. The fist 4 points apply to any employee in just about any job. Pretty much common sense. The 5th point is an unfortunate opinion. If the concepts in the Clean Code series were taught in college, we would an entirely different software landscape and the entire industry would be much more productive and less of a cause for stress. Thus allowing you more time to do what you love. Yes, "you're in a new world! Go out & do it your way!" Ignore best practices! Feel empowered and special, ignorantly making the same mistakes that created mountains of awful legacy code left by the last generation of coders. Later, you can enjoy your "participant" trophy while professionals try to clean up the inscrutable, unmanageable, buggy hacks you've left behind! I've heard Robert Martin books recommended over and over again, so really appreciate this thought! Uncle Bob is politically conservative. Sarah finds him offensive, so she's added an attack against him to the end of her otherwise excellent advice. Sarah should heed her own advice about tribalism. Yeah, the difference between Clean Code and this advice column is time and evidence. There's evidence that the concepts taught in clean code work well and there's been plenty of time and happy developers to see it. Other than a pat on the back and a blackballing of Bob, I doubt there will be little useful substance from this piece in more than a few months of a young developer's life...stuff that they already didn't know or outgrow. It's common sense. What isn't common sense how to organize and test code at every level. It's one of the most empathetic things you can learn for your team and the one thing no one knows how to do out of school. I've seen devs drowning in complexity and domain with no way to organize or think about it. Then the framework abuse happens cause they don't know the concepts behind what makes the framework work. This is just advocating the kind of blind solipsism it claims to reject. Talk about tribalism. All amazing advice Sarah! Thank you for a great answer. Seems most others answer the wrong question, either "how can a junior developer get to where I am?" (which was where my thinking went at first and why I felt uncomfortable giving an answer) or "what would I like my co-workers to be like?" I would only like to add regarding point 1 that you also have a right to expect an environment where you are comfortable to speak and if that isn't the case it's never your fault. Any place where they think this happens automatically just because "we're all good people" is probably wrong in this, it needs to be actively encouraged. So I guess the best advice I can give to juniors is that if there is something you want to change then "change your workplace or change your workplace." (don't remember who I'm quoting/paraphrasing) Why do you think that Robert Martin’ books are out of date ? I don't think they're entirely out of date for all developers, but I agree with Sarah's assessment for juniors. I specifically instruct juniors not to bother with that material early on in their career, but highly recommend it to folks who are a little further along—as great reference material, with some parts worth ignoring. It's not that the advice and techniques are all out of date, but for juniors it could be hard to separate the dated from non-dated. It makes sense that an older book which covers a lot of ground would not stand up entirely over time. I'm not speaking for Sarah's reasoning, but this is my answer for your question! So it's okay for junior devs to write bad code early in their careers?! What a bizarre attitude It's okay for everyone to write bad code sometimes. Not everything has to be perfectly structured and totally optimised. 'Tactical' can be good sometimes, and technical debt isn't always evil - as long as you aren't blind to it and have a plan to get rid of it or pay down the debt. Pragmatism is a key element of remaining commercial. I could not agree more with point 5. Those books are a relic and most of the stuff in there has nothing to do with how software is actually built in the world (thankfully). Would you care to post a sample of your code? I assume it is miserable. Because your attitude is very odd I have programmed in a bunch of professional contexts and never had a complaint. All without that miserable character. Which 'stuff' in those books do you disagree with? Is it the well structured code with sensible class, function and variable names and decent sized functioned, or the good OO practice and patterns or the properly tested code? The comment about not reading Uncle Bob's books is pure prejudice. Except if it is some kind of joke which I don't get. Talk about hypocrisy: tribalism and disrespect steeped in ideology are the norm of most interactions one reads from you. I would give just one advice to all programmers in start of their career. Please spare sometime and read Robert C.Martin books on clean code. Namely Clean Code and The Clean Coder It changes perspective of how one reads and writes code for better. I taught myself to program on the job to automate a lot of repetitive tasks and eventually built a rather complex web app. One of the things I look back on now that I have been doing this for a number of years is my decision to look up and curate a list of best practices. I followed that as closely as possible and I think that was a life saver. I think any developer of any level can benefit by taking the extra effort to follow a best practice guideline. Just remember that they are in fact guidelines and that sometimes there are better ways to do things in a specific scenario, but that will come with experience. can you maybe share your curated list of best practises? I don't have my original list from 3~4 years, a job, and a move across the country ago but here is the gist: Now not all of these may apply to you, such as Symfony, but I think for the most part these are universal. I may be a little short on experience to give my advice here, I'm not exactly a senior but here's my two cents worth from what I've picked up from my own experience :) If you have what you think is a good idea about how to approach a problem, voice it to your team! If it is a genuinely good idea, then it may be accepted and you can take the credit, and it will really boost your confidence! If it's not such a good idea, that's okay! More often than not, the more senior members of your team will explain to you why it's not such a good idea and possibly even give you pointers on what is, and then you've learned something - making you a better developer in the process. Don't be afraid to ask questions! If you're stuck on a problem for more than an hour or so and you can't think of a way around it after searching for your it on your own, ask a team member regardless of how silly you might think it is! Chances are that it isn't at all that silly, and your team will be happy to help you in any way they can. After all, it's not only juniors that need to ask questions, senior developers aren't necessarily omniscient beings (although some do seem to be!) Don't abuse or rely on this though, try searching/reading first - figuring stuff out on your own is a much more valuable experience than just getting an answer from somebody else! Approach learning from an "Understand, don't imitate" perspective. Given the wealth of advice and examples available, it's so easy to find a solution that matches your exact scenario and just use that solution, rather than understand it. Learn how, and more importantly why, that solution works and apply that why to your scenario, even if it is the same. Not getting your pull request through code review first time is okay. Everybody has their own approaches to problems, and a comment on your code review saying "X could be improved by Y because Z" doesn't necessarily mean you're not a good enough developer for only thinking of X, rather than Y. It's usually more a case of your haven't encountered a scenario that leads you to see the reasoning Z that causes you to use Y over X yet. That's all I've got for now, hope it helps someone! :) PS: Don’t work yourself to exhaustion trying to play catch up with the other developers, go at your own pace! Future you, your friends and your family will thank you for it! Coffee and vitamin supplements might be good for a temporary focus boost, but nothing compared to rest, socialising, exercise and hobbies! Be open to change and don't let your job dictate what you are able to learn. By "be open to change" I mean don't tie yourself to a specific technology, language, framework, whatever. Over the course of your career, you will end up changing course and I've found that those who are adaptable and open to learning new technologies are generally the most successful long term. By "don't let your job dictate what you are able to learn" I mean, follow your passions regardless of what your job requires. Never say, "I want to learn X, but my job doesn't care about it." If you want to learn something, find a way to learn it, regardless of your job. It takes commitment and effort, but it pays off in the long run and keeps you from feeling constrained. Finally, despite what I say in the paragraph above, do not believe anyone who tells you that you need to spend all your free time coding or beefing up your GitHub profile. Be a well rounded person, with interests outside of tech and code. The people and places that don't appreciate that should be avoided. "First you search, then you ask". Learning things by yourself is much more valuable than sinply having somebody tell you how it's done, and even if you don't figure it out, you'll know better what it is you're struggling with. Eventually, if you're not figuring it out, don't be afraid to ask a senior developer, but prepare for the inevitable question, "what have you tried already?" Focus on your growth and don't compare yourself to others. You should be inspired by other people's accomplishments. Don't worry about the framework of the day or library of the year. Focus on the basics. Take everything with a grain of salt. Do your own research and make an educated decision. Don't just make data-driven decisions. Let the data guide you. Embrace change. Nothing is permanent. Employers don't hand down a big raise, bonus, or promotion. You control your career, so you need to ask for it. Side projects will help you stay on the cutting-edge. Pick a language, framework, and ecosystem and stick to it as long as you can. However, be prepared to learn something new when the time comes. Interviews are unfair. Don't let them demotivate you. Don't be afraid of engineers senior to you and those who have been in the industry for long. They will most likely be opinionated and they're not always right. At the same time, you can learn a lot from them and they can learn from you. Learn the basic concept of javascript first instead of learning frameworks like angular or react I'd generalize this to all languages and frameworks. +1 though. There are tons of things to do when you are a junior and people here here are suggesting a lot of great things, but if there is a single advise that I would give to a junior it would be: Read code. See how people have solve a problem and how the solution was formed in order to be Solid and testable. Then when you write code try to implement a thing or two be yourself. Bruno Souza (Java Champion) has given me this advice and I keep doing it ever since. I've read through all the otherwise wonderful advice on this thread, and there seems to be one area that we've all overlooked, and which in hindsight I wish I started thinking about earlier. Ethics. We don't like to think about our profession as one that has moral responsibility for the things that we create. Morality is a squishy concept, ever shifting and difficult to pin down, but with software playing an ever bigger part in our society, we simply can't avoid that discussion. I'm not going to pontificate about what's right and what isn't, not least of all because I don't know either, but I'm sure it's important, and we must start thinking about it as early in our careers as possible. Two things: First, understand that the code you write is going to have real impact on real people. Algorithms are not unbiased by default because a person had to write them. Your preconceptions and biases will leak into your algorithms unless you actively defend against them. Second, admit your mistakes and learn from them. Most of us have a story about deleting that one file that brings down a system at critical time of year. If we ever meet over a beer, I’ll tell you about crashing our learning management system during final exams. When (not if) this happens, take responsibility for it. It will be uncomfortable, and you may fear for your job, but I promise, if you are working for a quality organization, your honesty will be appreciated by your managers, but more importantly, by your colleagues. You can only throw coworkers under the bus so many times before they return the favor. Some overtime or off-hours stuff is more or less de rigueur in this industry, but expectations should be clear up front and the company you work for should respect your time. Never work for free. Think about the impact your work will have and whether you'd be happy to sign your name to it. You can't eat standards but it's good to have them. Hierarchies are efficient but can be working efficiently at cross purposes with you. The flipside is that they're brittle; sometimes it's easier to ask forgiveness than permission. The trick is in anticipating and managing the risks and consequences involved. If you have to do the same thing more than twice, consider automating it. Consistent, highly available, partition tolerant: pick two, depending on requirements. Cheap, reliable, fast: pick two, depending on requirements. Clever or maintainable: pick one, and there's a correct answer. Reporting a problem you've discovered is good, thorough analyses are better, proposing a solution is best. It doesn't have to be right, it just has to start the discussion. Everything everyone has ever written about "agile" boils down to "more and shorter feedback loops". It's a good idea but shouldn't be over-complicated. Adapt processes to fit people: people may be the squishy part of the equation but we aren't liquids and don't take the shape of our container. Pay attention and put some effort into how you communicate, especially in contexts where you can't rely on facial expressions and body language to add nuance. It's easy to make assumptions about what other people know and feel and easy to come off differently than you intended, and it's rarely for the better. Every Turing-complete programming language is a different method of expressing the same fundamental formulations and processes, and understanding the general principles underlying them is more important than the ability to navigate any one system (& the former is arguably a prerequisite for doing the latter well). The specific language you're working in is essentially a matter of taste; the concepts always map across one way or another. Crap code in prod makes you more money than elegant code you haven't finished yet, but by the same token there's nothing so permanent as a temporary kludge. For all the stereotypes of hyper-rationality, software people really, really love fads and often overlook limitations or issues that make their pet idea a bad fit for what they're trying to do. The current overuse of blockchain only proves we didn't learn the real lessons from NoSQL or microservices. Object/relational mappers are more trouble than they're worth. 1°) don't be arrogant, thinking you never make bugs and try to hide it 2°) don't be lazy, try to find and fix these bugs, dont count on QAs to do this job for you, that's unprofessional 3°) don't be impatient, learn as much as you can before thinking you are a senior (yeah read Uncle Bob ;) ) 4°) don't be coder only, try to really understand the need of business and not just do the minimum of their requirement especially when requirements are fuzzy. Requirements are the hard part actually not the coding part. 5°) do have empathy for business people, don't think they're stupid just because they cannot understand your technical jargons, they also have a lot of complexities in their field you wouldn't even understand either. 6°) life is not fair, your career also depends on how you sell yourself to Tech Leads / Managers - but don't oversell or you'll get into imposture syndrome which will lead you to always cheat with people and yourself. There are a lot more but that's first things I have in mind. Always accept the suggestions of seniors! And don't give up the first "shity tasks". +Always understand the background of the problems: if it is not clear what and why are you doing use google and understand the issue in full details! The background story: As I started as a junior, fresh from the university I started at a big company. I had a lot of great ideas about how to solve the different issues, but most of the cases the senior developers on the team just told me that it's not really a good idea, sometimes with a reason, sometimes without that. Later on with time I understood that these were really not so great ideas as I thought. So in my first year I got always tasks which were extra boring for me and I thought they are too easy. So I was a bit demotivated. In the first time I had still a lot of mistakes in these easy tasks. So first I needed to reach the level that I could implement these easy tasks fast and without bugs, after that I got more and more complex tasks. Every time I could successfully fix something I got something more difficult as next task and it worked well. After one year I was working on really interesting and challenging tasks and I was able to achieve them. You will find many similar answers for THE junior (general stuff), but the tricky part is to give advice for A specific person. Each individual has its own ups and downs, lacks and skills. So think of your career, what are your aspirations, what do you like, what are your opportunities (probably are limited by geographical or other working preferences), in what areas do you lack and get more specific feedback to reach your next career step. I guess this counts as an advice as well :)) In short: do as many different things as you can. Now a slightly longer explanation. Of course I don't mean to just rush from one thing to the other, never quite learning anything. Of course take your time to familiarise yourself with the tools you're working with, the environment, and so on. But if you're feeling you're already up to speed and comfortable, and an opportunity arises to do something in a new language (for example), and it's okay that you haven't got any experience in it yet, go for it. (Never lie about your experience, leave that sort of stuff to management consultants. :)) What I also don't mean is to never stop doing this. This kind of strategy is fine when you're starting out, and some people stay like that forever, but most eventually will settle for one thing and go very deep in it. But even they will benefit from knowledge of other languages, paradigms or indeed roles. And of course the usual caveat: this isn't a recipe for success (indeed it's not about success at all, more like feeling your life is worthwhile), just a heuristic that is based on a tiny sample I've personally witnessed, and for added bias, I fall into that sample too. Your worst days, when you practically feel like quitting, are often the days you learn the most. Sometimes you don't even realize how much you've learned, and you feel like you just wasted your time, but those days can be extremely helpful. Had this thought top of mind after reading @jmdembe 's tweet a few minutes ago: Don't act like a junior, act like a senior, kinda the "do" version of "Dress for the job you want, not the job you have". Don't just do your job and stop there, find out more about the product, the company, the workflow, and implement changes to make things work better. Personal example: I was hired to run environmental chambers and DC power supplies for a company that was testing computer-like equipment for reliability. Essentially, crank the temperature up and down and vary the voltage till the product fails, then get the engineers to fix the root cause, then retest. This means product won't fail at customer sites... This is a very tedious, boring, time-consuming, and error prone process. Crank up the temperature, wait an hour for the machine to stabilize, turn the voltage down by one percent at a time till the product fails, reboot at nominal voltage, turn it up one percent at a time till it fails, reboot at nominal, pick a new temperature, rinse, lather, repeat. Ripe for automation! But programming wasn't in my job description. By the time I was done we had a half a dozen chambers, multiple sets of DC power supplies, video sources and recorders, and everything was running 24x7 on a scripting 'language' I developed for putting things through their paces. Wrote and implemented it all in those one-hour temperature soak periods, plus nights and weekends, plus time I freed up from having to sit and watch the chambers. Big win, and my Grand Unified Program made a big difference in our department's productivity and throughput. Every job is going to be different, but don't just learn what you need to do your job, learn everything about the company and the industry and the technology, and use that knowledge to make things better. Don't start by asking permission, and always ask forgiveness. 8*) It's really hard to give advice to anyone let alone someone who is trying to work in an environment as fast pace as development, but here are some general things I talk about to people around me and stuff that awesome people have suggested to me. Be ready to adapt. Not one programming job is the same, not even within the same company, not even within the same team! Find out what works and push in that direction. People will recognize your efforts, and if it aligns with the context, they will rally to you. Admit when you failed and give credit to others for every little thing. Stay out of the x language, y framework is the best mentality. There isn't a single Way to the Top, because The Top looks different for different people. For more on that, I'd recommend: So try to develop all-around competency, but figure out what draws you. Maybe it's writing awesome application code. Maybe it's visual aesthetics for web and mobile apps. Maybe it's Ops. Maybe it's algorithms and/or machine learning. Maybe it's dealing with people and being a leader. (Industry secret: Many managers, even with programming backgrounds, are less skilled programmers than most of their subordinates, and that's not actually a problem!) You need a little bit of everything (though there are exceptions, e.g. you can probably skip machine learning if you're focused on line-of-business web apps, and there are probably almost no cases where knowledge of both writing mobile apps and hardware hacking is necessary), so look for opportunities to round out your experience. Over time, you will hopefully find a specialization where you can really shine. It's kind of like college in the US (i.e. not European) model - take some general courses and then declare a major. It's OK not to have a major yet when you're new. It's also totally OK to like lots of things as you move along, and go back and forth flexing different muscles as you progress. (As an example, see Charity Majors' essay on bouncing between engineering and management positions.) Finally, if anyone RTFMs you or references you to Eric S. Raymond's essay on how to ask smart questions, RUN and don't look back. As a junior, you need an environment where you feel safe asking questions, knowing you'll be respected for doing so. That difference can shave years off the time it takes to graduate from junior to mid. Oh, and when you do move into a more senior role, remember how hard it is to be junior, and find ways to mentor/pair/be available/encourage questions DURING work hours. P.S. If you're interested in public speaking, you don't need to be an industry expert. Most speakers aren't, they just (ideally) know how to research and craft data into a good story! You really can become a prolific meetup/conference speaker much earlier in your career than you'd think! Remove the junior part. Find reputable online people that you trust and learn from them. When co-workers teach you, compare what they tell you with what you've learned. Trust, but verify. Why? Because depending on where you work, many people who try to tell you how to work don't know what they're talking about. Or they know some things really well but not others. Sadly, the less they know, the more likely they are to try to teach you. That puts you in a difficult position, one where you have to evaluate the knowledge of people with more experience than you. (This could be unnecessarily negative. Maybe I just had really bad experiences.) The point isn't that you should correct everyone or try to be smarter than them. Rather, you need to defend yourself against learning wrong things. If someone tells you things that you learn are wrong, politely question them. It could be a misunderstanding, or perhaps you didn't understand what you read. If it's black-and-white and they don't get it, stop questioning them out loud but question everything silently. Hopefully you'll find people who have spent some time on the right track. In my first few years I had the chance to learn from several and missed it each time because no one told me what I'm telling you. If you find such people, learn as much as you can from them. I am currently working as an intern in a game development company. The reality of working in actual company tells me that the stuff I have spent years and years studying in Uni or college might not be applicable in my work. Stepping into the office feels like literally stepping into an alien spaceship. The task I was assigned was too big and I wasn't able to handle it until had panic attack. However, I do acknowledge my lack of "productivity" mostly stems from Impostor Syndrome and me overcomparing myself with my fellow devs. I would say everyone has their own pace. Do not rush yourself, you will get to where you want. Here's some of my advice to junior developers that join us: be yourself. Some of the best code out there is not spoken for. Some of the smartest hacks were not discovered by usual heroes. Keep personal happiness over everything else. The most performant code is one that hasn't been written yet. No code is no bug. Read a lot. Write a lot. Code a lot. Don’t be afraid of working with older, less fashionable languages or frameworks. They were fashionable at some point for a reason. Even ignore you’re not using the latest and greatest tech you have a tremendous amount to learn from soft skills to version control to team work. Learn everything you can and never stop being curious. Don't get overwhelmed by things that you don't know. Focus on one problem at a time instead of trying to figure out solutions for many different problems. Take a break. Patience One and only one option for self-learner Learn how todo unit tests and functional tests, they will save you.
https://dev.to/sergio/what-is-your-best-advice-for-a-junior-software-developer-32gn
CC-MAIN-2020-50
refinedweb
6,006
70.84
ALLOCA(3C) ALLOCA(3C) alloca - allocate dynamic space #include <alloca.h> void *alloca (unsigned size); <alloca.h> is required. Space allocated when a function foo calls alloca is freed automatically when foo returns. It is an error to call free with a pointer returned by alloca. Not all environments have alloca in their libraries, so code using it is not necessarily portable. Reasonably portable public domain versions of this function are available from various sources on the Internet and the World Wide Web. malloc(3), calloc(3), free(3), /usr/include/alloca.h In this implementation alloca cannot fail (though if size makes the process too large IRIX may kill the process). Since alloca always returns a valid pointer, no diagnostics are possible. Portability may be enhanced if the function calling alloca tests for a return value of 0 and handles 0 as an error. Do not call alloca as an argument to another function, as in foo(alloca(20));. Instead use, for example, cp = alloca(20); foo(cp);. PPPPaaaaggggeeee 1111
http://nixdoc.net/man-pages/IRIX/man3/standard/alloca.3.html
CC-MAIN-2013-20
refinedweb
171
50.73
It has been a while since I posted. I have been busy working on a video for a publishing company on Angular 2 and, more importantly, very busy at work. I decided to take on the video project as part of my own learning. I do not want to spend too much time on setting up an environment, so I decided to write this post to remind me how to do it. This is just steps by step environment setup guide using betas of both ASP.NET 5 (v. next) and Angular 2. I am going to assume you setup Visual Studio 2015 and installed ASP.NET 5 RC. Let’s get started. Start Visual Studio 2015 and create new project. Use Empty ASP.NET 5 template. Now we need to enable static files support. Open project.json file and under dependencies add static files package: "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final" }, Then we need to enable static files in the application code. We do so by editing Startup.cs and adding corresponding line to Configure method. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseStaticFiles(); } Let’s add index.html page under wwwroot folder. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <h2>ASP.NET 5 and Angular 2</h2> </body> </html> Nothing fancy, but it is time to ensure that so far everything works. Open up command prompt and navigate to your project folder. Important to stress this, not solution, but project folder where your project.json file is located. Let’s run dnx and start up web server. Just type dnx web to run web command from project.json. You should see something like the following: Now let’s open the browser and navigate to localhost:5000/index.html. We should see the phrase we put into index.html for testing. So far so good. Time to install all Angular 2 components. Add new item to the project, NPM Configuration file. This will create project.json. Open it and let’s paste in all Angular 2 dependencies: { "version": "1.0.0", "name": "ASP.NET", "private": true, "dependencies": { "angular2": "2.0.0-beta.0", "systemjs": "0.19.9", "es6-promise": "3.0.2", "es6-shim": "0.34.0", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.0", "zone.js": "0.5.10" }, "devDependencies": { } } As soon as you save the file, you will see that Visual Studio starts restoring all the packages. Give it a minute to make sure the message about restoring goes away. I am going to put my application TypeScript files under app folder, not wwwroot. I am going to keep all TypeScript files there. Then I am going to copy them to wwwroot later. Go ahead and add Main.ts TypeScript file to that folder. Before we go further, let’s configure TypeScript. Add new item to the project, at the root of the project, and pick TypeScript JSON Configuration File template. We need to add a few things to the file. We need to enable decorators functionality. We also are going to use systemjs for module loading. We are going to use node style module resolution. I also turn on noImplicitAny, but this is a personal preference. { "compilerOptions": { "noImplicitAny": true, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "emitDecoratorMetadata": true, "experimentalDecorators": true, "module": "system", "moduleResolution": "node" }, "exclude": [ "node_modules", "wwwroot" ] } We are going to import component from Angular 2 and create a simple component. I am putting it into Man.ts import {Component} from 'angular2/core'; @Component({ selector: 'app-shell', template: '<h1>Angular 2 Welcome page for {{name}}</h1>' }) export class Main { name: string; constructor() { this.name = "Sergey"; } } So, let’s walk through this simple code. We are importing Component decorator class. We are adding it to our class, called Main. Our class has just one property that we set in the constructor. In the component decorator definition we are just telling Angular to find element with the tag of <app-shell> and replace it with the template. Template string contains our property just to ensure that everything works and binds properly. We need to start our app by using bootstrapping functionality from Angular 2. Create new file called Boot.ts. import {Main} from "./Main"; import {bootstrap} from 'angular2/platform/browser' bootstrap(Main); In this file we are importing our own class, Main from Main module. We are importing bootstrap component from Angular. Finally, we are bootstrapping our Main class. Now we need to adjust our index.html and add all needed Angular 2 scripts and system.js module loader code. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <app-shell><h2>Loading...</h2></app-shell> > System.config({ packages: { app: { format: 'register', defaultExtension: 'js', } } }); System.import('app/boot') .then(console.log('started application'), console.log('Error occrred while starting application')); </script> </body> </html> I found this code on Angular 2 getting started page. You can see my app-shell element I am going to replace. I am temporarily putting in Loading to let user know the page is being constructed. Then I am adding four required scripts. Finally, I am configuring system.js. I am telling it I have one package, called app, which is assumed to be in app folder under the root. I am telling it to use js extension by default. I am telling it to use register style module loader. Time to copy all the files over. We are going to use gulp for this. Let’s add another file to our project. We need to install gulp. Just open another command prompt and again navigate to the project’s root where project.json file is located. Type npm install gulp. Time to edit our gulpfile /* This file in the main entry point for defining Gulp tasks and using Gulp plugins. Click here to learn more. */ var gulp = require('gulp'); gulp.task('thirdparty', function () { gulp.src('./node_modules/angular2/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/angular2')); gulp.src('./node_modules/es6-promise/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/es6-promise'));/es6-shim/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/es6-shim')); gulp.src('./node_modules/rxjs/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/rxjs')); }); gulp.task('copy', function () { gulp.src('./app/**/*.*') .pipe(gulp.dest('./wwwroot/app')); }); gulp.task('watch', function () { gulp.watch('./app/**/*.js', ['copy']); }); gulp.task('default', ['thirdparty']); Let’s walk through my tasks. First task is thirdparty. I am simply copying Angular 2 and its dependencies from node_modules folder to the same folder under wwwroot. In the second task called copy I am copying my application files from app folder to wwwroot folder. I do not need to compile them because Visual Studio does this for me automatically. You may need to pull up VS options page and look under Editor / TypeScript if compilation does not occur for your automatically. The third task is watch task which will monitor my app folder and continuously copy the files to wwwroot. Time to run gulp. Since you already have folder pulled up, type gulp thirdparty. This will copy Angular 2 stuff over. Wait for that task to finish, then type gulp watch. Now simply edit something on our Main.ts, like change the canned messages. Then in Windows explorer make sure that the files got copied over. We are ready to refresh the browser and see that everything worked! You can download the sample app here. Enjoy. For IE11, I think you need in index.html Regards, David Lewis I meant add a script for “node_modules/es6-shim/es6-shim.js” to index.html Great post. Thanks! Any idea how to enable debugging in Typescript ? You can use browser tools or Visual Studio, but you have to run in IE (run button in tool bar)
http://www.dotnetspeak.com/angular/angular-2-beta-asp-net-v-next-release-candidate-and-typescript-so-happy-together/
CC-MAIN-2021-04
refinedweb
1,309
62.04
This is your resource to discuss support topics with your peers, and learn from each other. 12-13-2010 02:39 AM Have been trying to embed fonts and can't seem to get it to work. Have copied and pasted code from existing AS3 projects that successfully embedded fonts using the Flex 4.1 SDK. I am using the BlackBerry 0.9.1 SDK and am testing outside of the simulator. All the code is completely in AS3. And looks like the code below: [Embed(source="fonts/FontName.ttf", fontName='Extended', fontStyle="normal", fontWeight="normal")] public static var FontExtended:Class; Is anyone else being able to embed fonts? 12-13-2010 03:12 AM hey nitro, try the following line, i noticed you were missing some attributes in your line: [Embed(source='fonts/FontName.ttf', fontName='Extended', fontStyle='normal', fontWeight='normal', mimeType='application/x-font' )] private var FontExtended:Class; and also what gets most people is the path to their font. make sure that is correct and you should be golden. good luck! 12-13-2010 11:01 AM I've actually gotten it to work without the mimeType in Flex 4.1. Tried that property in the my Blackberry OS SDK and it still does not work. Does it work for you? 12-13-2010 11:33 AM In the newer Flex SDK's the mxmlc compiler by default embeds the fonts in the newer CFF format that is compatible with the newer Text Layout Engine (TLF), which runs on the Flash Player's newer (FP 10+) FTE APIs. To embed the Fonts in the older font type to use with non-TLF objects you need to add to the metadata embedAsCFF=false. Here is some more info: 12-13-2010 12:06 PM I had tried the embedAsCFF="false" as well but with no success. Had gotten that solution on your video on the Adobe site last night. I've also tried out various fonts in case the actual font was a problem. [Embed(source="fonts/myFont.ttf", fontName='myFontName', fontStyle="normal", fontWeight="normal", embedAsCFF="false", mimeType="application/x-font")] I'm using the TextFlow, TextLayoutFormat, and ContainerController to create the text box. Some of the properties set are: textLayoutFormat.fontFamily = 'myFontName'; textLayoutFormat.renderingMode = 'cff'; textLayoutFormat.fontLookup = 'embeddedCFF'; I've tried commenting these out to use the default values but still a no go. I'm testing on a Mac using Flash Builder 4. 12-13-2010 12:17 PM TextFlow is a TLF class so try setting embedAsCFF=true. If you can post a simple code sample that is not working for you I can try it on my end. 12-13-2010 12:45 PM Thanks for your help. The library I am using is on github, called LiquidGear. It can be downloaded at: The main AS file would simply the following code, which works on Flex 4.1 but not the Blackberry Tablet SDK. package { import lg.flash.elements.Text; [SWF(width="1024", height="600", backgroundColor="#000000", frameRate="30")] public class MyApp extends Sprite { [Embed(source="fonts/svenings.ttf", fontName='Extended', fontStyle="normal", fontWeight="normal", embedAsCFF="true", mimeType="application/x-font")] public static var FontExtended:Class; public function MyApp() { var test:Text = new Text({id:'test', x:0, text:'Test', font:'Extended', embedFonts:true, size:48, color:0xffffff}); addChild(test); } } } Thanks again, Giraldo 12-13-2010 12:49 PM I can't get any font to embed with the playbook either, no errors or anything, just not working. Also works fine in everything else. 12-13-2010 02:55 PM This code worked for me on the PlayBook Simulator: package { import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; import lg.flash.elements.Text; [SWF(width="1024", height="600", backgroundColor="#000000", frameRate="30")] public class MyApp extends Sprite { [Embed(source="fonts/Webdings.ttf", fontName='MyFontName', fontStyle="normal", fontWeight="normal", embedAsCFF="false", mimeType="application/x-font")] public static var FontExtended:Class; public function MyApp() { var test:Text = new Text({id:'test', x:0, text:'Test', font:'MyFontName', embedFonts:true, size:32, color:0xffffff}); addChild(test); } } } So I would try a different font .ttf file to see if its a font file issue. 12-13-2010 11:50 PM Just got mine to work with: package classes { public class AssetManager { //Embed the .ttf in my src/fonts folder. Note the fontName [Embed(source='/fonts/arial.ttf', fontName="TestFont", mimeType="application/x-font-truetype")] public static const TestFontTTF:String; public function AssetManager() { } } } In main app: package { import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; import classes.AssetManager; [SWF(width="1024", height="600", backgroundColor="#1b263e", frameRate="30")] public class TestApp extends Sprite { public function TestApp(){ var assetManager:AssetManager = new AssetManager(); var testTF:TextFormat = new TextFormat("TestFont",15,0xFFFFFF); var testText:TextField = new TextField(); testText.defaultTextFormat = testTF; testText.embedFonts = true; testText.text = 'Testing embed font'; testText.x = 300; testText.y = 300; testText.textColor = 0x0000FF; addChild(testText); } } }
http://supportforums.blackberry.com/t5/Adobe-AIR-Development/Embedding-Fonts/m-p/678201/highlight/true
CC-MAIN-2014-49
refinedweb
824
51.44
ERC20 Example ERC20 is a standard for fungible tokens and is defined in the EIP-20 Token Standard by Ethereum. With the ERC20 standart you can create your own tokens and transfer them in the EVM on IOTA Smart Contracts without fees. You can use the Remix IDE to deploy any regular Solidity Smart Contract. Set the environment to Injected Web3, and connect Remix with your MetaMask wallet. Read this how to connect your Metamask with the public Testnet.. 1. Create a Smart Contract Create a new Solidity file, for example ÈRC20.sol in the contracts folder of your Remix IDE and add this code snippet: pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ExampleERC20Token is ERC20 { constructor() ERC20("ExampleERC20Token", "EET") { _mint(msg.sender, 1000000 * 10 ** decimals()); } } This imports all functions from the OpenZeppelin smart contract and creates a new ERC20 token with your name and Symbol. OpenZeppelin provides many audited smart contracts and is a good point to start and learn. You can change the token name ExampleERC20Token and the token symbol EET. 2. Compile Go to the second tab and compile your smart contract with the "Compile ERC20.sol" button. 3. Deploy Go to the next tab and select Injected Web3 as your environment. Ensure that your MetaMask is installed and setup correctly. Choose your ´ExampleERC20Token´ smart contract in the contract dropdown. Press the "Deploy" button - then your MetaMask will popup and you need to accept the deployment. Your MetaMask browser extension will open automatically - press confirm. 4. Add your token to MetaMask Get the contract address from the transaction after successful deployment. You can click on the latest transaction in your MetaMask Activity tab. If your MetaMask is configured correctly, the IOTA EVM Explorer opens the transaction. Copy the contract address and import your token into MetaMask. 5. Have some Fun! Now you should see your token in MetaMask - send them to your friends without any fees or gas costs. You also can ask in the Discord Chat Server to send them around and discover what the community is building on IOTA Smart Contracts.
http://wiki.iota.org/smart-contracts/guide/evm/examples/ERC20
CC-MAIN-2022-33
refinedweb
352
57.67
Welcome. Let’s consider the Account class: public class Account { private String id = RandomStringUtils.randomAlphanumeric(6); private boolean status; private String zone; private BigDecimal amount; public Account() { status = true; zone = Zone.ZONE_1.name(); amount = createBigDecimal(0.00); } public Account(boolean status, Zone zone, double amount) { this.status = status; this.zone = zone.name(); this.amount = createBigDecimal(amount); } public enum Zone { ZONE_1, ZONE_2, ZONE_3 } public static BigDecimal createBigDecimal(double total) { return new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("id: ").append(getId()) .append("\nstatus: ") .append(getStatus()) .append("\nzone: ") .append(getZone()) .append("\namount: ") .append(getAmount()); return sb.toString(); } public String getId() { return id; } public boolean getStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public String getZone() { return zone; } public void setZone(String zone) { this.zone = zone; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { if (amount.signum() < 0) throw new IllegalArgumentException("The amount does not accept negative values"); this.amount = amount; } } There are 4 getter methods in the class. Pay extra attention to them. If we create a separate unit test for each getter method, we get too many redundant lines of code. This situation can be handled with help of by applying different rules and technics, e.g. do not perform database connection in unit tests (by definition unit tests are isolated) or perform initialisations of expensive objects in the @Before block. Choose good names for unit tests. A name of a test can be as long as you want, but it should represent what technics. Basics of test design technics technics. General purpose of test design technics two groups: positive & negative scenarios. The first one is for test data which is allowed by a system and leads to successful results. The second one is for so called “failure scenarios”, when we use inappropriate data for interaction with the system. According to the classes of equivalence technic we can select single random integer technic. According to it we have to choose 2 valid values from the left and right sides of the range. In our case we take 1 as the lowest allowed positive integer and 1000 from the right side. The next step is to choose 2 invalid values on boundaries. So it’s 0 and 1001. So in the end we have 6 values which we need to use in the unit test: - (1, 500, 1000) – for positive scenarios - (0, 125.50, 1001) – for negative scenarios Summary In this post I tried to explain all aspects of TDD and show how important unit tests are in the TDD. So I hope after such detailed and long bla-bla theory we can continue with practice. In my next article I’ll demonstrate how to develop tests before a functionality. We will do it step by step, starting from a documentation analysis and finishing with a code refactoring. Be sure, that all test will be green :) nice, nice 1 thing, although this series is not for non-logica-thinkers still i think to better refrase this: But as a rule one unit test implies invocation of several methods. to But as a rule: one unit test implies invocation of several methods. Absolutely agree! Just an FYI: the word that you spelled “technic” is supposed to be spelled “technique”. Not that your article is bad in the technical department, and I recommend this to several bloggers, but it wouldn’t be a bad idea to find someone who is really good with English grammar and spelling to double check your posts so they can be clearer for your readers. Big thanks I’ll fix the mistakes =)
https://www.javacodegeeks.com/2015/11/introduction-in-java-tdd-part-1.html
CC-MAIN-2018-39
refinedweb
607
56.45
It seems people are looking for my blog on how to compile lparse with modern GCC or Ubuntu. The major problem is that many programs in lparse source code do not include stdio.h or other needed head files. I do not know why on some platform such code can be compiled. At least it does not work for my GCC 4.x. And it seems since version 4.2, GCC is getting strict on C standard. Here is the solution to solve such problems if you are using GCC 4.4.1 on Ubuntu Linux 9.10. An earlier version for GCC 4.33 on Ubuntu Linux 9.04 is at Janosch reported the problem on Ubuntu 9.10. So I am writing this blog entry. Step 1: Install bison. You can use sudo apt-get install bisonor other ways. Step 2: Comment out line 85 of src/extern.h //long int strtol(const char *nptr, char **endptr, int base);PS: I do not know why the HAVE_STRTOLdoes not work. Step 3: Include stdarg.hand stdio.hinto src/global.h #include <stdio.h> #include <stdarg.h> Step 4: Done! Make and you shall get tons of warnings but finally the lparse executable. 1 comment: Thanks a lot. All problems solved.
http://forrestbao.blogspot.com/2010/02/lparse-111-compiling-conflicts-with-gcc.html
CC-MAIN-2017-13
refinedweb
211
88.74
Edited: 2nd March 2015 In this article I will continue to suggest easy ways that one can explore the cached query plans via SQL and XML as explained in ‘Exploring Query Plans in SQL‘. I will demonstrate some more tricks, such as how to find query plan warnings inside the cached query plans. If you are not checking for warnings in your query plans during development or when testing, then you are missing some valuable information that could make a considerable difference to the performance of your queries. You can, for example, detect implicit conversion, missing statistics, and missing indexes. The table-valued functions I show you here will allow you to see, without having to get involved in XML, all the warnings in plan cache for a particular database, or allow you to select particular types. This method would only be suitable for use in the test or development environment. In production, or where the plan cache is large, it would cause a significant performance hit. Query plan Warnings Query plan Warnings are included inside the query plan to alert you to problems that the query optimizer can’t solve for you. For example, if the query tries to compare one string field with a decimal value, the database engine will use auto-convert to execute the query but will include a warning ( PlanAffectingConvert warning) because the query could run better if the value was a string instead of a decimal value. Until SQL Server 2008, the warnings didn’t appear in the query plan. This meant that you had to use SQL Profiler to see them. Since SQL Server 2008, the warnings are displayed in query plans. Another warning example is MissingIndex: this warning advises us that the query would run much better with an index that doesn’t exist yet. These query plan warnings are valuable information that points to ways that you can make your queries, applications and environment better. Let’s talk about how to find them in the query plan cache. First things First: Filtering by Database Before we get too deeply into selecting the Query-plan Warnings, we will need a way of selecting just the plans for a particular database. In the article ‘Exploring Query Plans in SQL‘, I demonstrated how to find details about the query plans in the cache, but the cache contains plans for all the databases in the server. What if we would like to see information about only one database? How could we filter the queries by one specific database? The query plans in the cache are in XML format following the query plan schema (), so if you inspect this you’ll notice that we can use XML queries to find the ‘ ColumnReference‘ element that has ‘ Database' attribute. We can filter the query plan by this combination to select the pans of a particular database. The query for this will be: The xmlnamespaces declaration in the beginning of the query simplifies the syntax of the xquery expression, removing the need for the namespace declaration from the xquery expression. Creating a table-valued function to filter by database This is an ideal query to transform into a function: The query will became easier to use and we can use the function to create more complex queries filtered on a particular database. For each function we create the need to get too familiar to XML decreases, because the function hides these details. The function will be like this: As well as the use of the ‘ WITH xmlnamespaces' clause, I also used the lower-case function, so the parameter becomes case-insensitive. This can prevent all manner of confusion. We can now adopt this function for a whole range of database-specific queries. A simple query using the function might be: Look. No XML at all. Now it has become a lot easier to return from the plan cache only the queries from a single database. However, as you’ll see in a moment, there is some extra magic that can be used with this query by means of XQuery on the table-valued output of this function. Finding Warnings in the Plan Cache Test Environment I will use the AdventureWorks2012 database to test the functions, but with additional tables created by Adam Machanic in his blog post ‘Thinking Big (Adventure)’ Finding PlanAffectingConvert Warning Grant Fritchey has written about PlanAffectingConvert. in his article ‘The Seven Sins against TSQL Performance‘, it’s a query plan warning about there being an implicit convertion in the plan. Implicit conversion happens when we try to compare information of different types. For example, if we try to compare a string field with an integer SQL Server will convert the information implicit, but this has a cost and can cause problems to the query, so we receive a warning about the conversion. Let’s use the same sample query used by Grant in his article, we can notice the warning in the query plan: After running this query, the plan will be in the cache and it has the PlanAffectingConvert warning in it. So, let’s create a query using our new ‘ planCacheFromDatabase‘ function to find PlanAffectingConvert in the plan cache: As you can see, all I had to do was use the previous created function, planCacheFromDatabase and filter the query plans to find which one has the PlanAffectingConvert warning. Finding Warnings PlanAffectingConvert is only one of many warnings that can appear in query plans. We need to retrieve from the cache the query plans that have warnings, with the information of which and how many warnings each query plan has. With this information we can analyze and change the query to solve the problems. It’s important to notice that there are different kinds of warnings. These warnings can appear in any element of the query plan, so there are many ‘warnings’ elements in the query plan schema. One example is the ColumnWithNoStatistics warning. While ‘ PlanAffectingConvert' appeared over the ‘ Select‘ element in the plan, ‘ ColumnWithNoStatistics' will appear over ‘ scan‘ elements if we do a query over a column with no statistics. Statistics are very important, even in fields with no index, because they help the query optimizer to choose the best plan for the query. When we do a query over a field with no statistics and the query could be improved with them, the warning ‘ ColumnWithNoStatistics' is included in the query plan. It’s important to notice that SQL Server databases have the configuration ‘Auto Create Statistics‘ with the default as true. This means that we will never see this warning, because SQL Server will automatically create the statistics when needed. This is the best setting in the production environment, even though it will affect all the clients while SQL Server creates the statistics over big tables. For the Test or development environment, it is possible to disable ‘Auto Create Statistics’ and to look for ‘ ColumnWithNoStatistics‘ in the cache to find where you would need to create statistics (or even indexes). To simulate this warning we need to temporarily disable ‘Auto Create Statistics’ in AdventureWorks database, it will be like this: After disabling the ‘auto create statistics’ we can generate this warning with the following query: Make sure that, once you’ve run your tests, you re-enable ‘Auto Create Statistics’ . Now that we see the importance of warnings like ‘ ColumnWithNoStatistics‘, ‘ PlanAffectingQuery‘ and many others, let’s create a query to find which and how many warnings each query plan in the cache has: Let’s see the tricks I used in the above query: - To combine in the same query the xmlnamespacesand one CTE (Common Table Expression) I used only one ‘with’ clause and a comma to separate the xmlnamespacesand the CTE - The xquery expression doesn’t include the path of the ‘Warnings’ element because the ‘Warnings’ element can appear in different paths in the schema. - Below the ‘Warnings’ element each warning is a different element and the name of the element is the name of the warning. The ‘ local-name‘ function retrieves the name of the element (the warning name) for the query. Each query plan can have many warnings of many different kinds, so the above query counts how many warnings of each kind each plan has. The above query is a good candidate to become a function, so here it is: After the function has been created, we can retrieve all the warnings in the cache for the AdventureWorks database, and it is as simple as the following query: … And once again, no XML in sight! Summary In this article we talked about the importance of warnings in query plan cache, and how we can use this information in development, or while testing, to make our environment better. You saw queries to find query plans with warnings in the plan cache and we created functions so you can use these techniques without the need to create XML queries at the time that you are investigating warnings. Load comments
https://www.red-gate.com/simple-talk/databases/sql-server/t-sql-programming-sql-server/checking-the-plan-cache-warnings-for-a-sql-server-database/
CC-MAIN-2022-05
refinedweb
1,498
54.15
Classy Vision is an end-to-end framework for image and video classification. Classy Vision makes it easy to write and launch distributed training jobs. In this tutorial, we will cover: Make sure you have Classy Vision installed. To install it, run this in your terminal: ! pip install classy_vision If you would like to use GPUs for training, make sure your environment has a working version of PyTorch with CUDA: import torch torch.cuda.is_available() The cell above should output True. Check out this link for more details on how to install PyTorch. For this tutorial, we will be using Tensorboard. Install it with the following (on your terminal): ! pip install tensorboard tensorboardX ! classy-project my-project %cd my-project To launch a training run on the current machine, run the following: ! ./classy_train.py --config configs/template_config.json That's it! You've launched your first training run. This trained a small MLP model on a dataset made of random noise, which is not that useful. The classy-project utility creates the scaffolding for you project, and you should modify it according to your needs. We'll learn how to customize your runs on the next few tutorials. Let's take a look at what classy-project has created for us: ! find . | grep -v \.pyc | sort Here's what each folder means: configs: stores your experiment configurations. Keeping all your experiments as separate configuration files helps making your research reproducible; models: code for your custom model architectures; losses: code for your custom loss functions; datasets: code for your custom datasets; classy_train.py: script to execute a training job; This uses the Classy Vision library to configure the job and execute it, and you might change it according to your needs; template_config.json: experiment configuration file. This file is read by classy_train.pyto configure your training job and launch it. Let's take a peek at the configuration file: ! cat configs/template_config.json That file can be shared with other researchers whenever you want them to reproduce your experiments. We generate json files by default, but YAML will be officially supported soon. classy_train.py can also be called from torch.distributed.launch, similar to regular PyTorch distributed scripts: ! python -m torch.distributed.launch --use_env --nproc_per_node=2 ./classy_train.py --config configs/template_config.json --distributed_backend ddp If you have two GPUs on your current machine, that command will launch one process per GPU and start a DistributedDataParallel training run. Tensorboard is a very useful tool for visualizing training progress. Classy Vision works with tensorboard out-of-the-box, just make sure you have it installed as described in the Setup section. By default classy_train.py will output tensorboard data in a subdirectory of your project directory (typically named output_<timestamp>/tensorboard), so in our case we can just launch tensorboard in the current working directory: %load_ext tensorboard %tensorboard --logdir . You can also customize the tensorboard output directory by editing classy_train.py. from classy_vision.generic.util import load_checkpoint from classy_vision.models import ClassyModel # This is important: importing models here will register your custom models with Classy Vision # so that it can instantiate them appropriately from the checkpoint file # See more information at import models # Update this with your actual directory: checkpoint_dir = './output_<timestamp>/checkpoints' checkpoint_data = load_checkpoint(checkpoint_dir) model = ClassyModel.from_checkpoint(checkpoint_data) model ! ./classy_train.py --config configs/template_config.json --checkpoint_folder ./output_<timestamp>/checkpoints Training scripts and configuration files are useful for running large training jobs on a GPU cluster (see our AWS tutorial), but a lot of day-to-day work happens interactively within Jupyter notebooks. Classy Vision is designed as a library that can be used without our built-in training scripts. Let's take a look at how to do the same training run as before, but within Jupyter instead of using classy_train.py: import classy_vision from datasets.my_dataset import MyDataset from models.my_model import MyModel from losses.my_loss import MyLoss from classy_vision.dataset.transforms import GenericImageTransform from torchvision import transforms train_dataset = MyDataset( batchsize_per_replica=32, shuffle=False, transform=GenericImageTransform( transform=transforms.Compose( [ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ) ), num_samples=100, crop_size=224, class_ratio=0.5, seed=0, ) test_dataset = MyDataset( batchsize_per_replica=32, shuffle=False, transform=GenericImageTransform( transform=transforms.Compose( [ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ) ), num_samples=100, crop_size=224, class_ratio=0.5, seed=0, ) from classy_vision.tasks import ClassificationTask from classy_vision.optim import SGD from classy_vision.optim.param_scheduler import LinearParamScheduler model = MyModel() loss = MyLoss() optimizer = SGD(momentum=0.9, weight_decay=1e-4, nesterov=True) optimizer.set_param_schedulers( {"lr": LinearParamScheduler(start_lr=0.01, end_lr=0.009)} ) from classy_vision.trainer import LocalTrainer task = ClassificationTask() \ .set_model(model) \ .set_dataset(train_dataset, "train") \ .set_dataset(test_dataset, "test") \ .set_loss(loss) \ .set_optimizer(optimizer) \ .set_num_epochs(1) trainer = LocalTrainer() trainer.train(task) That's it! Your model is trained now and ready for inference: import torch x = torch.randn((1, 3, 224, 224)) with torch.no_grad(): y_hat = model(x) y_hat We have looked at training models using synthetic data so far. A more typical workflow involves training a model on a real world dataset like ImageNet, which we will cover in this section. To be able to train using ImageNet, first download the dataset archives from. Then, extract the data to a format expected by torchvision.datasets.ImageFolder inside subdirectories for the individual splits ( train and val). We can then pass the root path containing these archives to the ImageNetDataset. The following configuration can be used to train a ResNet 50 on ImageNet to 76.4% top-1 accuracy in 90 epochs. The optimizer configuration uses SGD with momentum, gradual learning rate warm up for the first 5 epochs and 1/10 learning rate drops at epochs 30, 60 and 80. The learning rate is calculated for a setup with 32 GPUs and can be scaled based on the overall batch size [1]. config = { "name": "classification_task", "num_epochs": 90, "loss": { "name": "CrossEntropyLoss" }, "dataset": { "train": { "name": "classy_imagenet", "split": "train", "batchsize_per_replica": 32, "num_samples": None, "use_shuffle": True, "root": "/path/to/imagenet/" # replace with path to the extracted dataset }, "test": { "name": "classy_imagenet", "split": "val", "batchsize_per_replica": 32, "num_samples": None, "use_shuffle": False, "root": "/path/to/imagenet/" # replace with path to the extracted dataset } }, "meters": { "accuracy": { "topk": [1, 5] } }, "model": { "name": "resnet", "num_blocks": [3, 4, 6, 3], "small_input": False, "zero_init_bn_residuals": True, "heads": [ { "name": "fully_connected", "unique_id": "default_head", "num_classes": 1000, "fork_block": "block3-2", "in_plane": 2048 } ] }, "optimizer": { "name": "sgd", "param_schedulers": { "lr": { "name": "composite", "schedulers": [ {"name": "linear", "start_lr": 0.1, "end_lr": 0.4}, {"name": "multistep", "values": [0.4, 0.04, 0.004, 0.0004], "milestones": [30, 60, 80]} ], "update_interval": "epoch", "interval_scaling": ["rescaled", "fixed"], "lengths": [0.0555, 0.9445] } }, "weight_decay": 1e-4, "momentum": 0.9 } } In this tutorial, we learned how to start a new project using Classy Vision, how to perform tranining locally and how to do multi-gpu training on a single machine. We also saw how to use Tensorboard to visualize training progress, how to load models from checkpoints and how resume training from a checkpoint file. We also went over how to use the ImageNet dataset to train a ResNet 50. In the next tutorials, we'll look into how to add custom datasets, models and loss functions to Classy Vision so you can adapt it to your needs, and how to launch distributed training on multiple nodes.
http://classyvision.ai/tutorials/getting_started
CC-MAIN-2020-10
refinedweb
1,228
50.12
. Github Repository The code for today’s demo application is available on github: june-2014-blog-pythonjs. Prerequisites Sign up for an OpenShift Account. It is completely free and Red Hat gives every user three free gears on which to run your applications. At the time of writing, the combined resources allocated for each user helps you create a namespace and upload your SSH key to the OpenShift server. Step 1: Create the OpenShift Node.js Application To create a Node.js 0.10 application on OpenShift, type the command shown below. Note: Be sure to use a medium or large sized gear. This application will not work with a small gear as PythonJS is very CPU and memory intensive. $ rhc app create pythonjs nodejs-0.10 --gear large This command creates an application container for us, called a gear, and sets up all of the required SELinux policies and Cgroup configurations. Next, it installs all of the required software on your gear. OpenShift also sets up a private Git repository with some template code and clones the repository to your local system. Finally, OpenShift propagates DNS updates to the outside world. Step 2: Delete the template application source The template application created by OpenShift is an Express web framework application. Since you are writing the Node application in Python, you can delete the template code by running the command shown below. $ rm -rf deplist.txt index.html node_modules/ package.json server.js Step 3: Create package.json and download required libraries The package.json file is a JSON file that is used to specify the Node’s application metadata and its dependencies. Create a new file called package.json in the application root and add the following contents to it. { "name":"PythonJSApp", "description":"My First PythonJS Application", "version":"0.0.1" } This application uses PythonJS which converts Python code to Node,js code. Before you can use PythonJS, you have to install it. Run the following command to install the required library. $ npm install --save python-js ws This downloads the required dependencies and populate the package.json with the python-js and ws dependencies. Step 4: Create the Python Tornado Application Create a new file called app.py in the application root and paste the following content into it. import tornado, tornado.web, tornado.ioloop import os PATHS = { 'webroot': './static'} def get_main_page(server): local_path = os.path.join( PATHS['webroot'], "index.html" ) data = open(local_path, 'r').read() data = convert_python_html_document( data ) return data def convert_python_html_document( data ): doc = list() script = None for line in data.splitlines(): if line.strip().startswith('<script'): if 'type="text/python"' in line: doc.append( '<script type="text/javascript">') script = list() else: doc.append( line ) elif line.strip() == '</script>': if script: #src = '\n'.join( script ) src = chr(10).join(script) js = pythonjs.translator.to_javascript( src ) doc.append( js ) doc.append( line ) script = None elif isinstance( script, list ): script.append( line ) else: doc.append( line ) return '\n'.join( doc ) class MainHandler( tornado.web.RequestHandler ): def get(self, path=None): print('path', path) if path == "": data = get_main_page() self.set_header("Content-Type", "text/html; charset=utf-8") self.write( get_main_page() ) elif path == 'pythonjs.js': data = pythonjs.runtime.javascript self.set_header("Content-Type", "text/javascript; charset=utf-8") self.set_header("Content-Length", len(data)) self.write(data) else: if path == 'favicon.ico': self.write('') else: self.write('File not found') handlers = [ ('/', MainHandler) ] app = tornado.web.Application( handlers ) ip = 'localhost' port = 8080 if os.environ.get('OPENSHIFT_NODEJS_IP'): ip = os.environ.get('OPENSHIFT_NODEJS_IP') port = int(os.environ.get('OPENSHIFT_NODEJS_PORT')) app.listen(port,ip) tornado.ioloop.IOLoop.instance().start() print('App running on %s:%s' % (ip,port)) The code shown above does the following: Imports all of the required libraries. Defines a new class called MainHandler that MainHandler responds with index.html. Creates the Tornado application instance by passing it the handlers array. Starts the application using the start() function. Step 5: Create the view Create a new directory called static inside the application root. Create a file named index.html inside the static directory and paste the following content into it. <html> <head> <script src="pythonjs.js"></script> <script type="text/python"> a = 'hello' b = 'world' def test(): print(a+b)> </head> <body> <button id="mybutton" onclick="test()">click me</button> </body> </html> The Python code inside <script type="text/python"> is converted to JavaScript by PythonJS. Step 6: Create the PythonJS runner To run this application, you need to create a runner that converts the Python application to a Node.js application. Create a new file called server.js and place the following content into it. It translates the Tornado API into the NodeJS http API. #!/usr/bin/env node var fs = require('fs') var pythonjs = require('python-js') var pycode = fs.readFileSync( './app.py', {'encoding':'utf8'} ) var jscode = pythonjs.translator.to_javascript( pycode ) eval( pythonjs.runtime.javascript + jscode ) Step 7: Deploying to the Cloud If we push the code to OpenShift, it will not work because the PythonJS Tornado bindings do not provide IP address configuration. I have created a pull request with a fix. For the time being, open the tornado.py file in the node_modules/python-js/fakelibs directory and update the listen function with the one shown below. In case you get indentation errors then please copy the code from Github repository. def listen(self, port, address=""): print 'listening on:', port server = self[...] if self._ws_handler: options = { 'server' : server, 'path' : self._ws_path } with javascript: wss = new( __ws.Server(options[...]) ) print 'wss', wss self.wss = wss self.wss.on('connection', self.on_ws_connection) server.listen( port, address ) Now commit the code to the local git repository and then push the changes to to OpenShift. Please note that we are also committing the node_modules directory. This is required otherwise OpenShift will download the dependencies using npm and our change to the tornado binding won’t be deployed. $ git add . $ git commit -am "PythonJS application" $ git push After the code is pushed, and the application is deployed on OpenShift, we can view the running application at-{domain-name}.rhcloud.com. Next Steps - Sign up for OpenShift Online and try this out yourself - Promote and show off your awesome app in the OpenShift Application Gallery today. Automatic Updates Stay informed and learn more about OpenShift by receiving email updates.
https://blog.openshift.com/how-to-write-nodejs-applications-in-python-using-pythonjs-on-openshift/
CC-MAIN-2017-34
refinedweb
1,045
53.47
I would like to write what is effectively a "virtual grain" that determines some value based on the value of other grains, using a custom grain. Specifically, I want to provide a grain values, env, that tells me which virtual environment the host is running in. The options will be aws, or none currently, but in the future will include datacentre and office. I'll be using this information to determine configs like which SMTP relay to use, etc. My first attempt was to use the __grains__ dict, but it appears to be empty when accessed within the custom grain. def find_env(): if __grains__['os'] == 'Amazon': return {'env':['aws']} return {'env': []} this results in an exception: KeyError: 'os' I realise that I could statically assign the grains on the minion or on the command line, but I feel that any bit of information that can be derived automatically should be. Is there a way to access existing grain data when writing custom grains, or another way of automatically classifying hosts so that I can target the state to them?
https://serverfault.com/questions/631942/using-grain-data-in-a-custom-salt-stack-grain
CC-MAIN-2019-22
refinedweb
179
54.46
Solution Need Views: 5430: ___________” Please change your line cordinates bhia ap ne bna li ha cs602 k phly question ka ans kia dosra tu ho gya solution........... line ka size kam kro 70 degree pe chala jaiga kesi na bnai ha tu plz share kar dy main ne bohat try ki muj sy nahi ho raha ab khud try karo agr solution mily tu mughy send kar dyna plz usmanfarid1994@gmail.com <graphics.h> #include <conio.h> main() { int gd=DETECT,gm,points[]={320,150,420,300,250,300,320,150}; initgraph(&gd, &gm, "C:\\TC\\BGI"); drawpoly(4, points); getch(); closegraph(); return 0; } © 2021 Created by + M.Tariq Malik. Promote Us | Report an Issue | Privacy Policy | Terms of Service
https://vustudents.ning.com/forum/topics/cs602-assignment-no-2?groupUrl=cs602computergraphics&commentId=3783342%3AComment%3A6076382&groupId=3783342%3AGroup%3A60025
CC-MAIN-2021-17
refinedweb
121
67.89
This question goes out to everyone who knows the latest c++ standard by heart:P. We have the following program: #include <iostream> using namespace std; void wow(int& x, int& y, int&z) { x=x+1; y=z; z=z+1; } int main() { int i=0; int A[2]={10,11}; wow(i, A[i], i); cout<<i<<endl; cout<<A[0]<<endl; cout<<A[1]<<endl; } So we have parameter passing by reference and in the function wow we give 2 times the same variable... This was one of the questions they gave us in the exam of the course "Compilers and language principals..." The gave us the above code...and told us to say what it will print if we had parameter passing by reference, call by value, call by name, call by value result... The gave us the above code in pascal so i "translated it" in c++....{i know that c++ doesn't support all the possible parameter passing techniques} PS:: why the gave us the code in Pascal {pascal isn't in our curricula}...did pascal support all the above methods in parameter passing {or the gave us the code in pascal in order to look like pseudocode}? PS2::if i compile the program i get an answer, but i am still asking if this is undefined behaviour because i read in the book Concepts.of.Programming.Languages.7th.Edition{0321330250- Addison.Wesley} that it is a no-no to give the same argument to function that utilizes parameter passing by reference....
https://www.daniweb.com/programming/software-development/threads/88190/is-this-undefined-behaviour
CC-MAIN-2016-50
refinedweb
257
65.96
How to edit an array in another function than the main function in c programming? I'd like to increase each element in the array by one in another function than the main function. Then, I'd like to call this function and print in the main function. #include <stdio.h> int function(int array2[5]) { int i; while(i<4) { array2[i]=array2[i]+1; i++; } return array2[5]; } int main() { int array[5]={1,2,3,4,5}; int answer; answer[5]=function(array[5]); int j; while(j<4) { printf("%d \n",answer[j]); j++; } return 0; } 3 answers - answered 2021-04-20 19:22 Garr Godfrey Some important things to know: - When you pass an array in C, you don't make a copy. It is the same array, so modifying the array that is passed in modifies the original. - The [] are operators and not part of the variable name. - The [] work differently in declaring a type than when used in an expression. array[5]gives you the 6th element in array, but int array[5]declares an array with 5 elements. - Accessing an element beyond the end of the allocated array has undefined behavior, but usually will crash. - If you declare a variable int answerit is not an array, and cannot become an array. It is just one int - If you want to make a copy of an array, you need to explicitly copy. There are standard libraries that might do it, but you should learn to copy each element, one by one, to the new array. - answered 2021-04-20 19:38 Kozmotronik There you go. I suppose this is what you want: #include <stdio.h> // Since the array named parameters are scoped only within its function, // they are apart from your array in the main. void function(int array[], int len) { int i = 0; while(i<len) { array[i]=array[i]+1; i++; } } // Or alternatively you can process the array using a pointer void functionWithPointer(int *array, int len) { int i = 0; while(i<len) { *(array+i) = *(array+i)+1; i++; } } int main() { int array[]={1,2,3,4,5}; // int answer; // Not necessary int length = sizeof(array) / sizeof(int); // !!!ATTENTION function(array, length); // The array values updated by 1 printf("Array values after 1st update\n"); for(int k=0; k<length; k++) { printf("%d \n",array[k]); } functionWithPointer(array, length); // The array values updated by 1 again printf("Array values after 2nd update\n"); int j; while(j<length) { printf("%d \n",array[j]); j++; } return 0; } Here is the output: Array values after 1st update 2 3 4 5 6 Array values after 2nd update 3 4 5 6 7 - answered 2021-04-20 19:52 Vlad from Moscow The return type intof the function does not make a sense. int function(int array2[5]) { And moreover you are trying to return the non-existent 6-th element of an array with only 5 elements. return array2[5]; Within the function you are using uninitialized variable i int function(int array2[5]) { int i; while(i<4) { //... that results in undefined behavior. Also the used magic number 4does not make a sense at least because you are trying to pass to the function an array with 5elements. The function should be declared with a second parameter that specifiers the number of elements in the passed array. This function declaration int function(int array2[5]); does not mean that the passed to the function array has exactly 5elements. The compiler will adjust the parameter declaration of the function to pointer to the array element type like int function(int *array2); In this statement in main int answer; answer[5]=function(array[5]); you are using the subscript operator with an object of the scalar type int. So the compiler shall issue an error message. Here is a demonstrative program that shows how the function can be defined. #include <stdio.h> void function( int a[], size_t n ) { for ( ; n--; ++a ) { ++*a; } } int main(void) { int a[] = { 1, 2, 3, 4, 5 }; const size_t N = sizeof( a ) / sizeof( *a ); for ( size_t i = 0; i < N; i++ ) { printf( "%d ", a[i] ); } putchar( '\n' ); function( a, N ); for ( size_t i = 0; i < N; i++ ) { printf( "%d ", a[i] ); } putchar( '\n' ); return 0; } The program output is 1 2 3 4 5 2 3 4 5 6
https://quabr.com/67184942/how-to-edit-an-array-in-another-function-than-the-main-function-in-c-programming
CC-MAIN-2021-21
refinedweb
731
56.18
ZOJ 4020 Traffic Light DreamGrid City is a city with intersections arranged into a grid of rows and columns. The intersection on the -th row and the -th column can be described as , and two intersections and are connected by a road if . At each intersection stands a traffic light. A traffic light can only be in one of the two states: 0 and 1. If the traffic light at the intersection is in state 0, one can only move from to or ; If the traffic light is in state 1, one can only move from to or (of course, the destination must be another intersection in the city). BaoBao lives at the intersection , and he wants to visit his best friend DreamGrid living at the intersection . After his departure, in each minute the following things will happen in order: - BaoBao moves from his current intersection to another neighboring intersection along a road. As a law-abiding citizen, BaoBao has to obey the traffic light rules when moving. - Every traffic light changes its state. If a traffic light is in state 0, it will switch to state 1; If a traffic light is in state 1, it will switch to state 0. As an energetic young man, BaoBao doesn't want to wait for the traffic lights, and he must move in each minute until he arrives at DreamGrid's house. Please tell BaoBao the shortest possible time he can move from to to meet his friend, or tell him that this is impossible. Input There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case: The first line contains two integers and (), indicating the size of the city. For the following lines, the -th line contains integers (), where indicates the initial state of the traffic light at intersection . The next line contains four integers , , and (, ), indicating the starting intersection and the destination intersection. It's guaranteed that the sum of over all test cases will not exceed . Output For each test case output one line containing one integer, indicating the shortest possible time (in minute) BaoBao can move from to without stopping. If it is impossible for BaoBao to arrive at DreamGrid's house, print "-1" (without quotes) instead. Sample Input Sample Output Hint For the first sample test case, BaoBao can follow this path: . For the second sample test case, due to the traffic light rules, BaoBao can't go from to directly. Instead, he should follow this path: . For the third sample test case, it's easy to discover that BaoBao can only go back and forth between and get:数组太大可以用向量来存,记得先push_back(0)使得矩阵列从1开始。以为数组太小段错误,wa了好几次 状态变化也很容易解决,步数为偶数次的时候不变,奇数次的时候相反 #include<bits/stdc++.h> using namespace std; typedef long long ll; #define INF 0x3f3f3f3f #define Max (int)1e5+10 struct node { int x,y,d; }; vector<int> a[Max],vis[Max]; typedef pair<int ,int > p; int sx, sy, fx, fy,n,m,mi; int dx[4]={0,0,1,-1}; int dy[4]={1,-1,0,0}; bool is(int x,int y) { if(x>0&&x<=n&&y>0&&y<=m&&vis[x][y]==0) return 1; return 0; } int bfs() { queue<node> que; vis[sx][sy] = 1; node start; start.d=0; start.x=sx; start.y=sy; que.push(start); while(que.size()) { start=que.front(); que.pop(); int x=start.x,y=start.y; int state=a[x][y]; if(start.d%2) { if(state) state=0; else state=1; } if (state == 0) { node t; for(int i=2;i<4;i++) { t.x=x+dx[i]; t.y=y+dy[i]; t.d=start.d+1; if(t.x== fx&& t.y==fy) return t.d; if(is(t.x,t.y)) { vis[t.x][t.y] = 1; que.push(t); } } } else { node t; for(int i=0;i<2;i++) { t.x=x+dx[i]; t.y=y+dy[i]; t.d=start.d+1; if(t.x== fx&& t.y==fy) return t.d; if(is(t.x,t.y)) { vis[t.x][t.y] = 1; que.push(t); } } } } return -1; } int main() { int t,i,j; cin >> t; while (t--) { scanf("%d%d", &n, &m); for(int i=1;i<=n;i++) { a[i].clear(); vis[i].clear(); a[i].push_back(0); vis[i].push_back(0); } for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { int x; cin>>x; a[i].push_back(x); vis[i].push_back(0); } scanf("%d%d%d%d", &sx, &sy, &fx, &fy); if(sx==fx&&sy==fy) printf("0\n"); else printf("%d\n", bfs()); } return 0; }
https://blog.csdn.net/PinkAir/article/details/79948815
CC-MAIN-2018-17
refinedweb
778
72.66
I want to delete the uploaded image files with the AWS-SDK-Core Ruby Gem. I have the below code: require 'aws-sdk-core' def pull_picture(picture) Aws.config = { :access_key_id => ENV["AWS_ACCESS_KEY_ID"], :secret_access_key => ENV["AWS_SECRET_ACCESS_KEY"], :region => 'us-west-2' } s3 = Aws::S3::Client.new test = s3.get_object( :bucket => ENV["AWS_S3_BUCKET"], :key => picture.image_url.split('/')[-2], ) end But I am getting the below error: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint. I am sure that the region is correct as if I try to change it to us-east-1, the below error comes up: The specified key does not exist. May I know how can I resolve this issue? I had faced the similar kind of error in the recent past as my bucket was in region us-west-2 and my URL pattern had the bucketname in the path. When I changed my URL pattern to have bucketname as URL subdomain to grab the files and it just worked for me. e.g. My previous URL was as follows: Then I replaced it as follows : OR I also have faced the same issue in the past. After a lot of research I found that the root cause of issue was with my com.amazonaws dependencies. After I added the dependencies my error got disappeared.
https://kodlogs.com/34298/the-bucket-you-are-attempting-to-access-must-be-addressed-using-the-specified-endpoint
CC-MAIN-2021-04
refinedweb
230
65.01
Building an i18n translator using React Joel D Souza Updated on ・2 min read It's so obvious that websites need to be internationalized. But creating multiple versions of the same website is not the best answer to it. Using React we can completely globalize our application. I'm going to show you how it can be done. This application includes: Translate Engine It does nothing but gets a word and returns the translated word based on the language selected. You need to pass the selected language and a word to this component. The children for the Translate component should only be a string. I have used Redux below, but you can use local state or Context API to set the language. import React, { PureComponent } from "react" import { connect } from "react-redux" // The function which returns you translated words based on a language. import Dictionary from "./dictionary" class Translate extends PureComponent { translateWord(word) { try { const { lang } = this.props // lang = "es" const languageDb = Dictionary(lang) if (word in languageDb.words) { return languageDb.words[word] } return word } catch (err) { console.error('Error while translating::translateWord', err) // If something goes wrong return the word as it is. return word } } render() { let { children, lang } = this.props if (typeof children === "string" && lang !== "en") { // pass the lowerCased word to get in the translated form. return this.translateWord(children.toLowerCase()) } return <>{children}</> } } const mapStateToProps = (state) => { return { lang: state.lang, } } export default connect(mapStateToProps, null)(Translate) Dictionary This can be an object/function that returns a list of all the available translated words based on a language. You'll have to feed a JSON object (as shown below) that lists all the translated words. import es from "./es.json" import ru from "./ru.json" import de from "./de.json" const languages = { es, ru, de, } export default function(lang) { return languages[lang] } This is how my spanish DB ( es.json) looks like: { "lang":"es", "words" : { "search" : "registrar", "conversation" : "conversación" } } You can use the translate component as shown below, But remember its children can only be a string. <Translate>Hello</Translate> I have created a simple sandbox for you to understand better practically. I have also created a hooks version below as suggested in comments. The hooks version: This is my first post/blog I have ever written and published. I thought of giving it a try during the pandemic lockdown. Let me know for suggestions on how to improve the content. Happy coding! Stay Inside and Stay Safe 🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained In the next post we are going to explore CSS @apply to supercharge what we talk about here.... I like the idea. It's handy. Would you consider updating it to React hooks? Yeah, sure. I can create a new sandbox with the hooks version. I have created and added a new hooks version above. Apologies, I was thinking of custom hooks. Interesting... you want me to create a hook that returns the translated word? 👍 Good write up Joel ! Thanks man. Really appreciate it.
https://practicaldev-herokuapp-com.global.ssl.fastly.net/reflexgravity/building-an-i18n-translator-using-react-4e5e
CC-MAIN-2020-24
refinedweb
499
59.9
Metaprogramming can be described in two ways: “Computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime”. More simply put: Metaprogramming is writing code that writes code during runtime to make your life easier. Many languages feature a with statement that allows programmers to omit the receiver of method calls. with can be easily emulated in Ruby using instance_eval: def with(object, &block) object.instance_eval &block end The with method can be used to seamlessly execute methods on objects: hash = Hash.new with hash do store :key, :value has_key? :key # => true values # => [:value] end With Ruby you can modify the structure of the program in execution time. One way to do it, is by defining methods dynamically using the method method_missing. Let's say that we want to be able to test if a number is greater than other number with the syntax 777.is_greater_than_123?. # open Numeric class class Numeric # override `method_missing` def method_missing(method_name,*args) # test if the method_name matches the syntax we want if method_name.to_s.match /^is_greater_than_(\d+)\?$/ # capture the number in the method_name the_other_number = $1.to_i # return whether the number is greater than the other number or not self > the_other_number else # if the method_name doesn't match what we want, let the previous definition of `method_missing` handle it super end end end One important thing to remember when using method_missing that one should also override respond_to? method: class Numeric def respond_to?(method_name, include_all = false) method_name.to_s.match(/^is_greater_than_(\d+)\?$/) || super end end Forgetting to do so leads to a inconsistent situation, when you can successfully call 600.is_greater_than_123, but 600.respond_to(:is_greater_than_123) returns false. In ruby you can add methods to existing instances of any class. This allows you to add behavior to and instance of a class without changing the behavior of the rest of the instances of that class. class Example def method1(foo) puts foo end end #defines method2 on object exp exp = Example.new exp.define_method(:method2) {puts "Method2"} #with method parameters exp.define_method(:method3) {|name| puts name} send() is used to pass message to object. send() is an instance method of the Object class. The first argument in send() is the message that you're sending to the object - that is, the name of a method. It could be string or symbol but symbols are preferred. Then arguments those need to pass in method, those will be the remaining arguments in send(). class Hello def hello(*args) puts 'Hello ' + args.join(' ') end end h = Hello.new h.send :hello, 'gentle', 'readers' #=> "Hello gentle readers" # h.send(:hello, 'gentle', 'readers') #=> Here :hello is method and rest are the arguments to method. class Account attr_accessor :name, :email, :notes, :address def assign_values(values) values.each_key do |k, v| # How send method would look a like # self.name = value[k] self.send("#{k}=", values[k]) end end end user_info = { name: 'Matt', email: '[email protected]', address: '132 random st.', notes: "annoying customer" } account = Account.new If attributes gets increase then we would messup the code #--------- Bad way -------------- account.name = user_info[:name] account.address = user_info[:address] account.email = user_info[:email] account.notes = user_info[:notes] # --------- Meta Programing way -------------- account.assign_values(user_info) # With single line we can assign n number of attributes puts account.inspect Note: send() itself is not recommended anymore. Use __send__() which has the power to call private methods, or (recommended) public_send()
https://sodocumentation.net/ruby/topic/5023/metaprogramming
CC-MAIN-2021-21
refinedweb
576
59.09
What You Should Know About Investing in Corporate Bonds Just as maturity is a major consideration when choosing a Treasury, it should also be a big consideration when choosing corporate bonds. In general (but certainly not always), the longer the bond’s maturity, the higher its interest rate will be because your money will potentially be tied up longer. And the longer the maturity, the greater the volatility of the price of the bond should you wish to cash out at any point. One consideration that pertains to corporate bonds but not to Treasuries is the nasty issue of callability. Treasuries aren’t called. (Once upon a time they were, but no longer.) Corporate bonds (as well as municipal bonds) often are. And that can make a huge difference in the profitability of your investment. Callability and corporate bonds Few things in life are as frustrating as a computer crashing. It seems to catch all of us at the least opportune moment, such as right smack in the middle of a huge work project. If you own a callable bond, chances are that it will be called at the worst moment — just as interest rates are falling and the value of your bond is on the rise. At that moment, the company that issued the bond, if it has the right to issue a call, no doubt will. And why not? Interest rates have fallen. The firm can pay you off and find someone else to borrow money from at a lower rate. Because calls aren’t fun, callable bonds must pay higher rates of interest. If you’re inclined to go for the extra juice that comes with a callable bond, fine. But you should always do so with the assumption that your callable bond will be called. With that in mind, ask the broker to tell you how much (after taking his markup into consideration) your yield will be between today and the call date. Consider that a worst-case-yield. (It’s often referred to as yield-to-worst-call, sometimes abbreviated YTW.) Consider it the yield you’ll get, and compare it to the yield you’ll be getting on other comparable bonds. If you choose the callable bond and it winds up not being called, hey, that’s gravy. Some squirrelly bond brokers, to encourage you to place your order to buy, will assure you that a certain callable bond is unlikely to be called. They may be right in some cases, but you should never bank on such promises. That being said, interest rates are likely to be climbing rather than falling in the coming years, so callability probably won’t be as big an issue as it has been in the past. Convertibility and corporate bonds Another wrinkle in corporate bonds is a particular kind of issue called a convertible bond. Some corporate bond issuers sell bonds that can be converted into a fixed number of shares of common stock. With a convertible bond, a lender (bondholder) can become a part owner (stockholder) of the company by converting the bond into company stock. Having this option is a desirable thing (options are always desirable, no?), and so convertible bonds generally pay lower interest rates than do similar bonds that are not convertible. If the stock performs poorly, no conversion happens; you are stuck with your bond’s lower return (lower than what a nonconvertible corporate bond would get). If the stock performs well, a conversion happens, so you win — so to speak. Know this: Convertible bonds, which are fairly common among corporate bonds, introduce a certain measure of unpredictability into a portfolio. Perhaps the most important investment decision you can make is how to divide your portfolio between stocks and bonds. With convertibles, whatever careful allotment you come up with can be changed overnight. Your bonds suddenly become stocks. You are rewarded for making a good investment, but just as soon as you receive that reward, your portfolio becomes riskier. It’s the old trade-off in action. Convertible bonds may not be horrible investments, but they don’t deserve a very sizeable allotment in most individuals’ portfolios. Reversing convertibility . . . imagine that One relative newcomer to the world of corporate bonds is the reverse convertible security, sometimes referred to as a revertible or a revertible note. A reverse convertible converts to a stock automatically if a certain company stock tumbles below a certain point by a certain date. Why would anyone want such a thing? You guessed it: The bond pays a thrillingly high interest rate (perhaps 2 or 3 or more percentage points above and beyond even the high rates paid on junk bonds), but only for a year or so. That’s the hook. The catch is that the company paying the high interest rate is often in dire trouble. If it goes under, you could lose a bundle. Is that really the kind of risk you want to take with a fixed-income investment?
https://www.dummies.com/personal-finance/investing/bonds/what-you-should-know-about-investing-in-corporate-bonds/
CC-MAIN-2018-47
refinedweb
834
62.68
Home -> Community -> Mailing Lists -> Oracle-L -> RE: How does oracle resolve a reference to an object Hi Gene, Private synonyms and tables live in the same namespace. That is, for any given user, said user can have a table named TABLE or a private synonym named TABLE, but not both. Oracle tries to resolve names in the current namespace first, so, if there is a table or private synonym owned by user, oracle will first use that, if not, it will look for a public synonym named TABLE and use that. Consider also that USER can use USER2's namespace to resolve objects (within the limits of object permissions) by using the "ALTER SESSION SET CURRENT_SCHEMA user2;" command. In this case, Oracle will search USER2's namespace, then fall back to PUBLIC. In this case, objects in the USER namespace would not be seen.: Monday, May 15, 2006 5:12 PM To: oracle-l_at_freelists.org Subject: -- -- Received on Mon May 15 2006 - 16:21:06 CDT Original text of this message
http://www.orafaq.com/maillist/oracle-l/2006/05/15/0696.htm
CC-MAIN-2015-11
refinedweb
171
67.69
The major update 1.4.0 marks an important step in the history of Felgo and brings loads of improvements – let’s have a look at them: - BlackBerry 10 Support – Publish for a growing new platform without any cost or additional work - Downloadable Package Support – This component allows to keep your app size small and under the 50MB limit for the app stores - Desktop App Store Publishing – The new desktop publishing guides make it easy to publish your game to Mac App Store and Windows Store - Many More Wizards – Start a new project from 12 different templates for popular game genres like platformers, arcade or physics games - Good Vibrations – Improve user feedback with the new vibration support - Screenshots – Allow players to take screenshots in the game Let’s now dive a bit deeper into the improvements of the update… BlackBerry 10 Support We are very proud to announce a new key platform Felgo is supporting: Since our launch we have received many customer requests asking for BlackBerry 10 support, so we think it’s time to add it to Felgo, now. 🙂 The great thing about it from a developer perspective is that it comes at no additional costs for our Pro customers! With the quarterly license you can publish for BlackBerry, iOS and Android for $189 per quarter ($63 per month) or with the annual license for $599 per year ($49 per month). The free version allows you to deploy the application to your local BlackBerry device so you can test before you buy. Publishing in BlackBerry App App World – let us know how your games are doing there and feel free to apply for our showcase section to show off your app on the Felgo website. Downloadable Package Support The new DownloadablePackage component allows to download additional resources over the web while the game is running. The most popular use cases for downloadable packages are: - You want to keep your app store binary as small as possible for the first download - You offer additional content packages with in-app purchases which should be downloaded after a purchase - Your game apk on Android exceeds the maximum size of 50MB for Google Play Store and you therefore need to download game resources at a later time - You want to allow 3G download on iOS devices and keep your iOS binary under the download size limit of 50MB The API is as lean as it can get – in this example an image is stored in the zip package and is shown when the download is finished: import VPlay 1.0 import QtQuick 1.1 GameWindow { DownloadablePackage { id: package1 source: "" Component.onCompleted: { // if this package is not available yet, download it at application start package1.download() } } Scene { Image { source: package1.available ? fileUtils.getMultiPathUrl("package-image.png") : "local-image.png" } } } Publishing Guides for Windows and Mac App Store Publishing for Windows and the Mac App Store is now fully covered in our publishing guides! Use this possibility to reach more players on new platforms. Thanks to the cross-platform capabilities of Felgo, without any code modifications. Qt Creator Wizards with Full Game Templates Starting from Felgo version 1.4.0, you now can choose from 12 different templates for new projects. New templates exist for games with multiple scenes and levels, and for all our demo games. This helps you to speed up development, as you can start with full games of popular genres like arcade, physics, racing, strategy or platformer games. Vibration & Screenshots With the new vibrate() function you can improve user feedback in your games or create whole new games built around vibrations. And with captureScreenshot() your players can now take screenshots and display them, for example of levels your users created on their devices. There is even more in this update like implemented feature requests from our community or bug fixes. See the changelog for all the updates. Further Improvements compared to last stable release 1.3.0 Compared to the last major update 1.3.0, the last 7 daily builds also brought these improvements that are now available in 1.4.0: - The. See this powerful component in action in our live app store game Squaby. - The ItemEditor component allows to change properties at runtime: imagine testing different gravity settings for a physics-based game and see the objects react to the change while you are moving a slider. Or adjusting the applied force of a jumping character without restarting the game and test the different settings. You can have a look at the source code or the live version of the app we built to demonstrate this functionality: the Particle Editor for Cocos2d and Felgo - In-app purchases are now available with the Store plugin on iOS and Android from a cross-platform and easy-to-use QML API. For benefits of the freemium model and how to implement it, see the full announcement in this blog post. - Support multiple languages in your game to increase the downloads and for better engaged players. With dedicated translation tools this is a simple process – just follow our guide How to make a multi language game with Felgo. As you can see, we have been busy bees. 😉 You can look forward to a big announcement for true cross-platform gaming services made by Felgo, and also frequently demanded Ad plugins will be available soon. You can actively steer the direction which features we add first: just use our Roadmap and let us know what you would like to see in the upcoming daily builds. Users on the Free Plan got upgraded to the previous major version 1.3.0. For all the latest features added in this release, unlimited publishing to iOS, Android and BlackBerry 10, become a Pro Subscriber and stay at the edge of development with daily builds.
https://felgo.com/cross-platform-development/update-1-4-blackberry-10-downloadablepackages-desktop-publishing-and-more
CC-MAIN-2020-16
refinedweb
969
54.97
My Ruby on Rails application always renders the layouts/application.html.erb view instead the views I want it to. Has anyone an Idea why that might be so? My routes file looks like this: Rails.application.routes.draw do root 'startup#index' resources :users end class ApplicationController < ActionController::Base protect_from_forgery with: :exception end By default, a controller action in Rails renders the view template for your action, wrapped up into a layout (which is application/layout) ActionView::TemplateHandlers manages the lookup for the extension (.html.erb, .html.haml, .json.erb, etc ...) so, in an action called index, you will get this implicit call unless you call render yourself : def edit # your code render action :'edit', layout: 'application/layout' # implicitly called end Rails will then start processing your layout and put the content of your edit template in place of any yield within your layout. Thus, a typical layout will look like this : <!doctype html> <head> </head> <body> <!-- layout content before view --> <%= yield %> <!-- layout content after view --> </body>
https://codedump.io/share/mo3JY8wE0Zpd/1/rails-aways-renders-the-applicationhtmlerb-instead-of-wanted-views
CC-MAIN-2016-50
refinedweb
168
55.84
On Mon, Apr 9, 2012 at 3:15 AM, David Rientjes <rientjes@google.com> wrote:>> I think you nailed it.>> I suspect the problem is 1eda5166c764 ("staging: android/lowmemorykiller:> Don't unregister notifier from atomic context") merged during the 3.4> merge window and, unfortunately, backported to stable.Ok. That does seem to match everything.However, I think your patch is the wrong one.The real bug is actually that those notifiers are a f*cking joke, andthe return value from the notifier is a mistake.So I personally think that the real problem is this code inprofile_handoff_task: return (ret == NOTIFY_OK) ? 1 : 0;and ask yourself two questions: - what the hell does NOTIFY_OK/NOTIFY_DONE mean? - what happens if there are multiple notifiers that all (or some)return NOTIFY_OK?I'll tell you what my answers are: (a) NOTIFY_DONE is the "ok, everything is fine, you can free thetask-struct". It's also what that handoff notifier thing returns ifthere are no notifiers registered at all. So the fix to the Android lowmemorykiller is as simple as justchanging NOTIFY_OK to NOTIFY_DONE, which will mean that the callerwill properly free the task struct. The NOTIFY_OK/NOTIFY_DONE difference really does seem to be just"NOTIFY_OK means that I will free the task myself later". That's whatthe oprofile uses, and it frees the task. (b) But the whole interface is a total f*cking mess. If *multiple*people return NOTIFY_OK, they're royally fucked. And the whole (andonly) point of notifiers is that you can register multiple differentones independently.So quite frankly, the *real* bug is not in that android driver(although I'd say that we should just make it return NOTIFY_DONE andbe done with it). The real bug is that the whole f*cking notifier is amistake, and checking the error return was the biggest mistake of all.Werner: just test David's patch (do *not* change both the error value*and* apply David's patch - that would free the task-struct twice). Idon't think his patch is what I want to apply eventually, but itshould fix the issue.Sadly, I don't think we have anybody who really "owns"kernel/profile.c - the thing is broken, it was misdesigned, and nobodyreally cares. Which is why we'll probably have to fix this by justmaking that Android thing return NOTIFY_DONE, and just accept that thewhole thing is a f*cking joke. Linus
https://lkml.org/lkml/2012/4/9/177
CC-MAIN-2016-18
refinedweb
402
56.86
Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris This covers styled-components 3.0. There have been some changes since. It's worth looking through the release notes for major changes, Release notes NOTE, I know the markdown rendering looks a little off on this one. If it bothers you too much, have a read here where the original article is Original article There are a ton of ways to style components in React. This is probably my favorite way of doing it and it differs somewhat conceptually from other ways of styling. The case for the styled-components approach When you start out styling your React components you may opt for defining CSS classes and assigning them to each element, like so: <div className="card"> <div className="card-header"> <h3>{card.header}</h3> </div> <div className="content">{card.content}</div> </div> There is really nothing wrong with the above, it is a viable approach even though some of you might think that’s a lot of repeated typing of the word className. You can argue at this point that I can create a component for the card, the card header, and the card content respectively. Yes, we can do that. Then it might look like this instead: <card header={card.header}> {card.content} </card> Now, this example may be a bit trivial and it might be a piece of cake to make such a component. Also, we all know how dead easy it is to create components in React. So what you need to ask yourself is do I really need a component for that, when all I want to do is add some CSS styling and name my HTML element what I please? If this is where your thoughts are heading then maybe styled-components library might be for you? Installing and setting up styled-components We can simply install styled-components via NPM, like so: yarn add styled-components // OR npm install — save styled-components After this, we are ready to go and use it in our React project. Our first styling The example the homepage for this library uses is that of buttons. You might end up creating different buttons meant for different purposes in your app. You might have default buttons, primary buttons, disabled buttons and so on. Styled components lib enable you to keep all that CSS in one place. Let’s start off by importing it: import styled from ‘styled-components’; Now to use it we need to use double backticks `, like so: const Button = styled.button``; At this point, we don’t have anything that works bit it shows you the syntax. As we can see above we call styled.nameOfElement`` to define a style for our element. Let’s add some style to it: const Button = styled.button` background: black; color: white; border-radius: 7px; padding: 20px; margin: 10px; font-size: 16px; :disabled { opacity: 0.4; } :hover { box-shadow: 0 0 10px yellow; } `; What we can see from the above example is that we are able to use normal CSS properties in combination with pseudo selectors like :disabled and :hover. If we want to use our Button as part of our JSX we can simply do so, like so: <div> <Button> press me </Button> </div> We can intermix our Button with all the HTML or JSX that we want and we can treat it just like the HTML element button, because it is one, just with some added CSS styling. Using attributes The styled-component library can apply styles conditionally by looking for the occurrence of a specified attribute on our element. We can use existing attributes as well as custom ones that we make up. Below we have an example of defining a primary button. What do we mean with primary versus a normal button? Well in an application we have all sorts of buttons, normally we have a default button but we have also a primary button, this is the most important button on that page and usually carries out things like saving a form. It’s a quite common scenario to style a primary button in a different way so we see a difference between such a button and a normal button so the user understands the gravity of pushing it. Let’s now show how we design such a button and showcase the usage of attributes with styled-components. We have our styled Button and we can add the attribute primary, like so: <Button primary >I am a primary button</Button> Our next step is updating our Button definition and write some conditional logic for if this attribute primary is present. We can do so with the following construct: ${props => props.primary && css` `} We use the ${} to signal that we are running some conditional logic and we refer to something called props. props is simply a dictionary containing all the attributes on our element. As you can see above we are saying props.primary is to be truthy, it is defined in our attributes dictionary. If that is the case then we will apply CSS styling. We can tell the latter from the above code through our use of css function. Below we use the above construct add some styling that we should only apply if the primary attribute is present: const Button = styled.button` background: black; color: white; border-radius: 7px; padding: 20px; margin: 10px; font-size: 16px; :disabled { opacity: 0.4; } :hover { box-shadow: 0 0 10px yellow; } ${props => props.primary && css` background: green; color: white; `} `; Now we have a more full example of how to test for the existence of a particular attribute. Just one note, we said we needed to use the css function. This is a function that we find in the styled-components namespace and we can, therefore, use it by updating our import statement to look like this: import styled, { css } from 'styled-components'; Adapting We’ve shown how we can look at if certain attributes exist but we can also set different values on a property depending on whether an attribute exists. Let’s have a look at the below code where we change the border-radius depending whether a circle attribute is set: const Button = styled.button`’)} `; The interesting bit of the code is this: border-radius: ${props => (props.round ? ‘50%’ : ‘7px’)} We can trigger the above code to be rendered by declaring our Button like so: <Button round >Round</Button> Styling an existing component This one is great for styling 3rd party components or one of your own components. Imagine you have the following components: // Text.js import React from 'react'; import PropTypes from 'prop-types'; const Text = ({ text }) => ( <div> Here is text: {text}</div> ); Text.propTypes = { text: PropTypes.string, className: PropTypes.any, }; export default Text; Now to style this one we need to use the styled function in a little different way. Instead of typing styled`` we need to call it like a function with the component as a parameter like so: const DecoratedText = styled(Text)` // define styles `; <DecoratedText text={“I am now decorated”} /> In the component we need to take the className as a parameter in the props and assign that to our top-level div, like so: // Text.js import React from ‘react’; import PropTypes from ‘prop-types’; const Text = ({ text, className }) => ( <div className={className}> Here is text: {text}</div> ); Text.propTypes = { text: PropTypes.string, className: PropTypes.any, }; export default Text; As you can see above calling the styled() function means that it under the hood produces a className that it injects into the component that we need to set to our top-level element, for it to take effect. Inheritance We can easily take an existing style and add to it by using the method extend, like so: const GiantButton = Button.extend` font-size: 48px; `; Change Styled components In some cases, you might want to apply the style intended for a specific type of element and have that applied to another type of element. A common example is a button. You might like all the styling a specific button comes with but you might want to apply that on an anchor element instead. Using the withComponent() method allows you to do just that: const LinkButton = Button.withComponent('a'); The end result of the above operation is an anchor, a tag with all the styling of a Button. NOTE, if you are on version 3.0 or lower withComponent() is still the way to do this. From 4.0 and forward you are recommended to use the as property, like so: const Component = styled.div` color: red; ` // Examples <Component>Hello world!</Component> <Component as="span">Hello world!</Component> <Component as={Link}Hello world!</Component> Using the attribute function Sometimes all you need is just to change a small thing in the component styling. For that, the attrs() function allows you to add a property with a value. Let’s illustrate how we can add this: const FramedText = styled(Text).attrs({ title: ‘framed’ })` border: solid 2px black; color: blue; font-size: 16px; padding: 30px; `; Above we have chained styled() and attrs() and we end with a double ` tick. Another example is: const Button = styled.button.attrs({ title: 'titled' })`’)} `; Theming Styled components export a ThemeProvider that allows us to easily theme our styled-components. To make it work we need to do the following: - import the ThemeProvider - set it as root Element of the App - define a theme - refer to a property in theme and set that to the desired CSS property Set up In the component where we intend to use a Theme, we need to import and declare a ThemeProvider. Now, this can be either the root element of the entire app or the component you are in. ThemeProvider will inject a theme property inside of either all components or from the component you add it to and all its children. Let’s look at how to add it globally: ReactDOM.render( <ThemeProvider theme={{ color: 'white', bgcolor: 'red' }}> <App /> </ThemeProvider>, document.getElementById('root'), ); Now we are ready to change our components accordingly to start using the theme we set out. Let’s take the Button component that we defined and have it use our theme, like so: const Button = styled.button.attrs({ title: 'titled' })` background: ${props => props.theme.bgcolor}; color: ${props => props.theme.color}; border-radius: 7px; padding: 20px; margin: 10px; font-size: 16px; :disabled { opacity: 0.4; } :hover { box-shadow: 0 0 10px yellow; } ${props => props.primary && css` background: green; color: white; `} border-radius: ${props => (props.round ? '50%' : '7px')} `; Let’s zoom in on what we did: background: ${props => props.theme.bgcolor}; color: ${props => props.theme.color}; As you can see we are able to access the themes property by writing props.theme.[nameOfThemeProperty]. Theme as a higher-order component factory If we want to use the theme inside of a component we can do so but we need to use a helper called withTheme(). It takes a component and the theme property to it, like so: import { withTheme } from 'styled-components'; class TextComponent extends React.Component { render() { console.log('theme ', this.props.theme); } } export default withTheme(TextComponent); Summary We have introduced a new way of styling our components by using the styled-components library. We’ve also learned that we get a more semantic looking DOM declaration of our components when we compare it to the classical way of styling using className and assigning said property CSS classes. Further reading The official documentation provides some excellent example of how to further build out your knowledge styled-components official documentation Hopefully, this has convinced you that this is a good way of styling your React components. Since I found this library this is all I ever use, but that’s me, you do you :) Discussion (7) Such a helpful post! The only issue I had was the syntax highlighting / theme. It was tough to spot the back-ticks and some of the main text in the code examples wherever there was dark red text against a black background. Yea, sorry about that. Unsure how to solve it at dev.to. It does look better at my own blog: softchris.github.io/pages/react-st... Thanks for the link! Looks great there 😀 Im currently using StyledComponents in on a live product. I love it. I feel it is worth mentioning a few issues that people need to be aware of though: divhell as there is no support for react fragments. All these problems are project/user specific, and easily avoidable. As this is picked up more, then I imagine these issues will stop being so much of an issue. I would highly recommend checking out this library as it is amazing to use and makes the components highly readable. Nice write up! Maybe it'd be a good idea also to mention that the version of styled components discussed here is 3.x. There have been some significant changes in v4 :) Also the link to the original article for some reason links me back here, at least on my phone. Thanks for that Lee. I'll make sure to update
https://dev.to/itnext/styled-components-the-styling-library-for-your-react-apps-you-don-t-want-to-be-without-5dlh
CC-MAIN-2022-33
refinedweb
2,192
62.48
Get the highlights in your inbox every week. Build a motion detection system with a Raspberry Pi | Opensource.com Build a motion detection system with a Raspberry Pi Set up an inexpensive home security system to alert you when someone is lurking around your house. Subscribe now If you want a home security system to tell you if someone is lurking around your property, you don't need an expensive, proprietary solution from a third-party vendor. You can set up your own system using a Raspberry Pi, a passive infrared (PIR) motion sensor, and an LTE modem that will send SMS messages whenever it detects movement. Prerequisites You will need: - A Raspberry Pi with Ethernet connection and Raspberry Pi OS - An HC-SR501 PIR motion sensor - 1 red LED - 1 green LED - An LTE modem (I used the Teltonika TRM240) - A SIM card The PIR motion sensor The PIR motion sensor will sense motion when something that emits infrared rays (e.g., a human, animal, or anything that emits heat) moves in the range of the sensor's field or reach. PIR motion sensors are low power and inexpensive, so they're used in many products that detect motion. They can't say how many people are in the area and how close they are to the sensor; they just detect motion. pir-sensor.jpg The LTE modem Long-term evolution (LTE) is a standard for wireless broadband communication based on the GSM/EDGE and UMTS/HSPA technologies. The LTE modem I'm using is a USB device that can add 3G or 4G (LTE) cellular connectivity to a Raspberry PI computer. In this project, I'm not using the modem for cellular connectivity, but to send messages to my phone when motion is detected. I can control the modem with serial communication and AT commands; the latter send messages from the modem to my phone number. modem.jpg How to set up your home security system Step 1: Install the software First, install the necessary software on your Raspberry Pi. In the Raspberry Pi's terminal, enter: sudo apt install python3 python3-gpiozero python-serial -y Step 2: Set up the modem Insert your SIM card into your LTE modem by following these instructions for the TRM240. Make sure to mount the antenna on the modem for a better signal. Step 3: Connect the modem to the Raspberry Pi Connect the LTE modem to one of the Raspberry Pi's USB ports, then wait for the device to boot up. You should see four new USB ports in the /dev directory. You can check them by executing this command in the terminal: ls /dev/ttyUSB* You should now see these devices: deviceoutput.png You will use the ttyUSB2 port to communicate with the device by sending AT commands. Step 4: Connect the sensors to the Raspberry Pi Connect the PIR sensor: Connect the VCC and GND pins to the respective pins on the Raspberry Pi, and connect the motion sensor's output pin to the 8 pin on the Raspberry Pi. See below for a schematic on these connections, and you can learn more about Raspberry Pi pin numbering in the GPIO Zero docs. Connect the LED lights: If you want indicator LEDs to light up when motion is detected, connect the cathode (short leg, flat side) of the LED to a ground pin; connect the anode (longer leg) to a current-limiting resistor; and connect the other side of the resistor to a GPIO pin (the limiting resistor can be placed either side of the LED). Connect the red LED to the 38 pin on the board and the green LED to the 40 pin. Note that this step is optional. If you don't want indicator LEDs when motion is detected, delete the LED sections from the example code below. wiring.png Step 5: Launch the program Using the terminal (or any text editor), create a file named motion_sensor.py, and paste in the example code below. Find and change these fields: phone_number If you used different pins to connect the sensors, make sure to change the code accordingly. When everything is set and ready to go, start the program from the terminal by entering: python3 motion_sensor.py If you don't have the required privileges to start the program, try this command: sudo python3 motion_sensor.py motionssensorsetup.jpg Example code from gpiozero import MotionSensor, LED from time import sleep, time from sys import exit import serial import threading # Raspberry Pi GPIO pin config sensor = MotionSensor(14) green = LED(21) red = LED(20) # Modem configuration device = '/dev/ttyUSB2' message = '<message>' phone_number = '<phone_number>' sms_timeout = 120 # min seconds between SMS messages def setup(): port.close() try: port.open() except serial.SerialException as e: print('Error opening device: ' + str(e)) return False # Turn off echo mode port.write(b'ATE0 \r') if not check_response('OK', 10): print('Failed on ATE0') return False # Enter SMS text mode port.write(b'AT+CMGF=1 \r') if not check_response('OK', 6): print('Failed on CMGF') return False # Switch character set to 'international reference alphabet' # Note: this still doesn't support all characters port.write(b'AT+CSCS="IRA" \r') if not check_response('OK', 6): print('Failed on CSCS') return False return True def check_response(string, amount): result = '' try: result = port.read(amount).decode() except: return False if not string in result: try: # Write 'ESC' to exit SMS input mode, just in case port.write(b'\x1B \r') except: return False return string in result def send_sms(): global currently_sending, last_msg_time currently_sending = True try: port.write('AT+CMGS="{}" \r'.format(phone_number).encode()) if not check_response('>', 6): print('Failed on CMGS') currently_sending = False return # Write the message terminated by 'Ctrl+Z' or '1A' in ASCII port.write('{}\x1A \r'.format(message).encode()) while True: result = port.readline().decode() if 'OK' in result: print('> SMS sent successfully') last_msg_time = time() currently_sending = False return if 'ERROR' in result: print('> Failed to send SMS [{}]'.format(result.rstrip())) currently_sending = False return except: # Initiate setup if the got while the program was running setup() currently_sending = False def on_motion(): print('Motion detected!') green.off() red.on() if time() - last_msg_time > sms_timeout and not currently_sending: print('> Sending SMS...') threading.Thread(target=send_sms).start() def no_motion(): green.on() red.off() print('* Setting up...') green.on() red.on() port = serial.Serial() port.port = device port.baudrate = 115200 port.timeout = 2 last_msg_time = 0 currently_sending = False if not setup(): print('* Retrying...') if not setup(): print('* Try restarting the modem') exit(1) print('* Do not move, setting up the PIR sensor...') sensor.wait_for_no_motion() print('* Device ready! ', end='', flush=True) green.on() red.off() sensor.when_motion = on_motion sensor.when_no_motion = no_motion input('Press Enter or Ctrl+C to exit\n\n')
https://opensource.com/article/20/11/motion-detection-raspberry-pi
CC-MAIN-2021-21
refinedweb
1,120
53.21
23 October 2008 12:53 [Source: ICIS news] TOKYO (ICIS news)--Japanese high-function fibre producer Teijin Techno Products has started operations of its yen (Y) 2.3bn ($23m) biomass boiler which can reduce carbon dioxide (CO2) emissions by 33,000 tonnes/year at its Mihara factory, its parent company Teijin said on Wednesday. The boiler uses woody biomass feedstock such as waste construction materials and bark and recycled fuels including used tyres, according to Teijin.The producer planned to supply the power generated by the new boiler to other Teijin group companies and also sell it to non-Teijin firms in Mihara, ?xml:namespace> This was part of group-wide efforts to use renewable energy such as biomass and liquefied natural gas (LNG) to reduce CO2 emissions, the producer said. The Teijin group targeted to cut CO2 emissions by more than 10% of the amount in 1990 by fiscal year 2010 ending March 2011 and 20% by fiscal 2020, the firm added. ($1 = Y100
http://www.icis.com/Articles/2008/10/22/9151208/japans-teijin-techno-starts-biomass-boiler-ops.html
CC-MAIN-2014-42
refinedweb
165
53.75
I'm trying to write a command to rearrange tabs with ctrl+alt+pageup/pagedown. Now I think that there is a small off-by-one bug in the new setViewPosition call. You can test this by using the console, but I also created the following command to help. With this you can move a view by typing ctrl+m followed by the new index. : MoveTab from 0 to 1: end position is 0 MoveTab from 0 to 2: end position is 1 MoveTab from 1 to 3: end position is 2 Here is a working script to move a tab with ctrl+alt+pagedown/pageup. I had to add 2 to the index to move the tab right, but it looks strange.. <binding key="ctrl+alt+pagedown" command="moveTab 2"/> <binding key="ctrl+alt+pageup" command="moveTab -1"/> class MoveTab(sublimeplugin.TextCommand): def run(self, view, args): groupIndex, tabIndex = view.window().getViewPosition(view) view.window().setViewPosition(view, groupIndex, tabIndex + int(args[0])) Very nice, thank you. I missed this command just a few hours ago.
https://forum.sublimetext.com/t/a-problem-with-setviewposition-api/575/3
CC-MAIN-2016-40
refinedweb
176
65.01
If you had tried to understand, instead of calling me impressionable and discounting the validity of my gender expression, maybe we would still be talking. Maybe I wouldn’t have hidden my transness for more than two years to satisfy the implicit expectations of me not to be a boy. It’s just one of those things, isn’t it? That people do expect women to be women. Actually, whatever ones’ views on trans-ness we do all still expect women to be women. That being what the vast majority are. So what’s with this implicit stuff? It’s hard to hear that you are responsible for hurting someone. But, if you got this far, I’m going to give you a tip: instead of asking questions, take action to make people feel comfortable enough to be honest. Projecting your ideas of normality and coating them in a thick layer of “concern” achieves nothing. At the end of the day, you took away my right to define myself and to decide when I would share that with other people. This is how you pushed me away. Reflect and do better. Apparently her aunt started asking “Why’s she dressing like a boy?” This being unforgiveable. Sigh. For that is rather to miss the point of language, the very thing that makes us human. The best theory yet about how it arose is so that we could gossip about those in our clan grouping, this being one of the things which reinforces the bonds of said clan and thus enables us to survive this harsh world.. “The best theory yet about how it arose is so that we could gossip about those in our clan grouping, this being one of the things which reinforces the bonds of said clan and thus enables us to survive this harsh world.” For those with academic access or willing to pay some interesting work on the subject of language development here Podcast discussion with one of the authors here The aunt got the question wrong. Instead of “Do you want to be a boy?” which apparently admits of the possibility of changing sex, she should have asked “Would you have liked to be a boy?” which recognises that it’s all right to dream. >Claims to be a man >Writes a bitchy, passive-aggressive, emotionally free-bleeding essay about xir feelings ¯\_(ツ)_/¯ Bonus content: As if gender is not a beautiful spectrum, which sexuality sometimes intersects with, but is not dictated by. Imagine actually believing this. NiV – please explain. 50+ comments…? I think it is extremely unlikely that her transphobic aunt will ever read it… If you were anything like a man you wouldn’t give a monkey’s about your aunt’s feelings or opinion. “I am not straight, or a woman…” So, a gay bloke? What? I can’t keep up. (matron) “The best theory yet about how it arose is so that we could gossip about those in our clan grouping, this being one of the things which reinforces the bonds of said clan and thus enables us to survive this harsh world.” Hence Twitter and Facebook. Enforcing the left-wing consensus, reinforcing the bonds of left-wing society, enabling left-wingers to survive this harsh world. Everyone is always in favour of enforcing social norms when it’s *their* social norms being enforced. “Apparently her aunt started asking “Why’s she dressing like a boy?” This being unforgiveable. Sigh.” I don’t think that was the unforgivable bit. That would probably have been: Having set out the social penalties for open transgression, you force people who are that way inclined to hide it. ‘Here are our rules – follow them and there won’t be any trouble.’ OK, that’s just how society works. But then if someone pushes the limits even *within* the rules, they’ll trigger a public investigation into their possible deviancy, and criticise them for hiding it. Once you accept that you have to hide your right-wing opinions in public – at work, on the non-anonymous bits of the internet, on a night out with friends – people will learn to keep quiet. But then people start to notice you’re not *openly* and *loudly* left-wing, and start asking questions. “Do you want to be a right-winger?” is a quite different question if a known SJW is asking it of you. “Are my private political opinions any of your business?” Not everyone is willing to face the social penalties of being openly right-wing in today’s society. Don’t ask, don’t tell. “If you were anything like a man you wouldn’t give a monkey’s about your aunt’s feelings or opinion.” Start a rumour at school that a typical boy is ‘secretly gay’, or try sending him to school with his books in a pink ‘My Little Pony’ rucksack (“What’s wrong? It carries your books just as effectively, doesn’t it?”), and they’ll usually get quite upset about it. That’s me convinced, NiV. Stevella, Convinced of what? That people with politically incorrect opinions have learned to keep quiet about them at work where HR can hear, or that if you send a boy to school with a pink ‘My Little Pony’ rucksack he’ll get upset about it? A tiny number of weirds can arse about as they like an it hurt none. What they need the shitkicking for is for helping the scum of the left insert their poison subjectivist shite in to law and custom. That is the evil here. Whoever can pretend to be whatever as they like. But frankly death for those trying to undermine objective reality on behalf of socialist terror. Where that leads has cost 150 million lives already. “But frankly death for those trying to undermine objective reality on behalf of socialist terror. Where that leads has cost 150 million lives already.” Authoritarian terror, Mr Ecks. It’s authoritarian terror. And that’s been going on a lot longer than socialism, and killed a lot more than 150 million. As ever, NiV, you talk bollocks. In any society there will always be pressure towards the consensus point of view. For, in essence, that’s what a society is. Without a consensus point of view it isn’t a society. And the pressure to conform will be greater the further the individual strays from the core consensus. And that’s all your “authoritarianism” is. Unlike the other sort of authoritarianism. Where a non-representative group uses it’s power to attempt to change the point of view of the society it distances itself from. Recognise anything? Step 1 toward CM: destroy normalcy. As I’ve said to you before, what a thing is is what the consensus says it it is. A tree is a tree & a dog is a dog because that’s what the consensus says they are. The tree & the dog don’t have any say in the matter. They can think they are whatever they like. But their opinion doesn’t count. It’s not of interest to anyone. It’s not their decision. “In any society there will always be pressure towards the consensus point of view.” Yes. All societies contain authoritarians. It’s a natural human instinct. Libertarian philosophy makes a point of discussing it at length. “Unlike the other sort of authoritarianism. Where a non-representative group uses it’s power to attempt to change the point of view of the society it distances itself from.” First, it’s no different. Even if a *majority* of society approved of slavery and Orwellian thought-crime, that would not make it ‘liberal’. And second, as I’ve repeatedly pointed out, 72% of the British public classify transphobia as “always” (53%) or “mostly” (19%) wrong. *You’re* the non-representative minority! However, *everyone* is in a non-representative minority on *some* of their opinions and habits. Less than 50% smoke. Less than 50% are overweight. Less than 50% are Jewish. *Everyone* has a stake in us not pressuring minorities towards any consensus without need. Go read John Stuart Mill. Maybe he can explain it better than I can. “As I’ve said to you before, what a thing is is what the consensus says it it is.” Do you have that the right way round?! If ‘The Party’ says two plus two is five…? If the popular consensus is that the Emperor is fully clothed…? Things are what they are. But people often don’t see things clearly and get it wrong (we’re all only human), so people need the freedom to be able to point it out when they disagree. Even if they’re the ones who are wrong. Steve: ’>Claims to be a man >Writes a bitchy, passive-aggressive, emotionally free-bleeding essay about xir feelings’ Well, ‘Guardian’, innit? That’s considered a bit macho there. TMB gets it, more or less. The author does have a point, however badly worded. That is, that if your daughter starts dressing like a boy, you try to gently nudge them back in line; you don’t insist that they make a binary choice between girl and boy on the spot. NiV, Tyranny, tranny – men, women – amazing what a difference a Y can make. When the tranny bullies her (or his, if you like) aunt the tranny is the one being authoritarian. And also showing she’s still a girl at heart, cos a real man doesn’t care what people think. Oh, we may shut up at times for an easy life or indeed for fear of punishment, but we don’t care what people think. Tranny talk is to convince the tranny that they are normal. NiV’s principal audience is . . . NiV. And libertarian philosophy, like communist philosophy, is a load of hogwash bollocks. It never survives its collision with the real world. We all want to live as we like. We all want other people to live as we like. If that wasn’t true you wouldn’t be trying to push libertarian bollocks down our throats. All societies are dynamic. Expressing the ever changing tensions between their individual constituents. And you’ll never be able to define liberal as easily as you think you have. Liberal isn’t a point, it’s a vector. A slaveowning society could define itself as liberal. Depends on which directions they believe liberal & illiberal are. They can even define 2+2=5 if they fancy. Although whether they find out that works in practise is another matter. For that’s the only question that’s relevant. Does this work, here & now. JuliaM – Well, ‘Guardian’, innit? That’s considered a bit macho there Touche. George Monbiot and Owen Jones aren’t exactly the Kurt Russell and Sylvester Stallone of journalism. “And libertarian philosophy, like communist philosophy, is a load of hogwash bollocks. It never survives its collision with the real world. We all want to live as we like. We all want other people to live as we like.” Yep. That’s exactly why we got Communism; people thinking like that is how they came to rule. That’s why we’ve always had totalitarian dictators all over the world; why nobody ever thinks ‘we don’t have to keep doing this to ourselves’. And that’s why the SJWs will win. And why the cycle will endlessly repeat. “If you want a picture of the future, imagine a boot stamping on a human face – forever.” We simply take turns wearing the boot. @NiV, August 11, 2018 at 11:26 am eg Taylor Swift attacked for Not commenting-on/condemning Trump. No NiV, you get communism because people think people are better than they really are. That they’ll all subsume themselves for the common good. And libertarianism presumes much the same, but in the opposite direction. In the real, messy world, individuals are not alike but no individual is truly an individual. We are all shaped by our interactions with other people. We are naturally hierarchical. Some will wish to be on the top. Some will wish to defer to others’ leadership. The best we can hope for is a course between totalitarianism & anarchy, changing to meet changing circumstances but resisting extremes. Shooting anyone advocating anything ending in ‘ism’ would be a good move.. “Shooting anyone advocating anything ending in ‘ism’ would be a good move..” Trouble is, you’d have to call that policy “shoot anyone advocating anything ending in ‘ism’ ism”. Life of Brian also had a scene with a suicide squad. Silly sods. “eg Taylor Swift attacked for Not commenting-on/condemning Trump.” Yes! Just one of many examples I was thinking of. “No NiV, you get communism because people think people are better than they really are. That they’ll all subsume themselves for the common good.” … and when they don’t, they consider it reasonable to *make* them do so, for the good of society. There are liberal versions of communism – the voluntary ‘hippy commune’ love-and-peace sort of thing. They still don’t work, because of both the economics and the psychology of justice, and they definitely don’t scale, but they’re relatively harmless because they’re voluntary and when they break down everyone just goes home. They only become dangerous, the sort of thing that killed 150 million people, when they take the next step of enforcing their ways and beliefs on others. Because they believe they’re doing it for those people’s own good, and the good of society. The social morality warriors are much the same. A certain way of life is good and moral, and good people will want to live it. And that often doesn’t work – because people enjoy sin too much to give it up – but is not a problem when membership is voluntary. Some people will voluntarily give up drunkenness, fornication, pornography, greed, sloth, and selfishness – subsuming themselves and their own desires for the common good of society. But then they take that next step – when other people don’t join in, and so endanger the moral fabric and social stability of society, they consider it their right and duty to *make* other people conform to their own idea of virtue. All the historical horrors have this one mindset in common – that society has the right and duty to enforce its own beliefs on its members, for their own good and for the common good. Thus: “In any society there will always be pressure towards the consensus point of view.” The problem word there is “pressure“. It always starts with persuasion, and ends up with shooting people for the policies they advocate. Such as capitalism. Of course, as everyone immediately points out when this view is expressed, a society without any enforced rules at all is impossible – because there would then be no rules to stop murder and slavery. True. Which is why libertarianism doesn’t believe in no enforced rules, but in the absolute minimum of enforced rules needed to guarantee everyone getting the maximum freedom consistent with everyone else getting the same freedoms. Hence JS Mill’s ‘Harm Principle’. It’s obviously more complicated than that when you get to the messy details of implementation – there are no sharp boundaries in reality. But that doesn’t really matter since – like the related policies of free markets – nobody is going to actually implement it any time soon. The authoritarian/regulatory mindset is too ingrained and powerful still. I consider it more an aspiration, and a guide to a direction to move in. I agree with you, in a sense, that: “It never survives its collision with the real world. We all want to live as we like. We all want other people to live as we like.” You can say exactly the same about the free market, low tax, small government, minimal-welfare, minimal-regulation sort of policies advocated here. (Which are really just libertarian principles applied to economics.) They never survive the collision with a real world full of people always ready to vote themselves a slice of somebody else’s pie. Nevertheless, since those Enlightenment philosophers expressed their ideas, the world has moved a hell of a long way in that direction, and is a lot more prosperous and free as a result. I think it does some good to keep on reminding people of the underlying principles that made it all possible. (Mainly, though, I just enjoy arguing about it!)
https://www.timworstall.com/2018/08/im-afraid-i-find-this-amusing/
CC-MAIN-2020-45
refinedweb
2,765
65.93
1st off, apologies to make the question migrate from elsewhere! It became an orphan at the earlier dwelling :bawling: and hence is in the look out for a patron! This place is a haven for all pundits and so here it is: :lol: I read the article Create a Database-Driven Site In 30 Minutes! in WebMasterBase by Corbbmacc O'Connor and wanted to use ssi to call a text file to be icluded in one of my pages. I used the following code snippet mentioned in the article: <!--#set var="which" value="$QUERY_STRING_UNESCAPED" --> <!--#if expr="$which != ''" --> <!--#include virtual="/content/$which" --> <!--#else --> <!--#include virtual="/content/error.txt" --> <!--#endif --> It is working ok so far as to call an existing file (thru a query string), but it doesn't return the "error.txt" file when a non existing file is called, which I intended to be done by these lines : <!--#else --> <!--#include virtual="/content/error.txt" --> But what I get at such occasions is an error message that "[An error has occured while processing this directive]", but not the contents of error.txt file which I expect to be returned. I think the default error message is to be disabled and the customised "error.txt" must be included, which doesn't happen. I have created and named the folders and files correctly. Could you please offer me a solution? Thank you Regards.
http://www.sitepoint.com/forums/printthread.php?t=20235&pp=25&page=1
CC-MAIN-2014-42
refinedweb
231
73.98
MooseX::AutoDestruct - Clear your attributes after a certain time version 0.009 package Foo; use Moose; use namespace::autoclean; use MooseX::AutoDestruct; has foo => ( traits => [ AutoDestruct ], is => 'ro', isa => 'Str', lazy_build => 1, ttl => 600, # time, in seconds ); sub _build_foo { --some expensive operation-- } MooseX::AutoDestruct is an attribute metaclass trait that causes your attribute value to be cleared after a certain time from when the value has been set. This trait will work regardless of how the value is populated or if a clearer method has been installed; or if the value is accessed via the installed accessors or by accessing the attribute metaclass itself. No traits are automatically applied to any metaclasses; however, on use'ing this package an 'AutoDestruct' attribute trait becomes available. Moose will properly deduce what trait you're talking about if you pass AutoDestruct as a string -- e.g.: has foo => (traits => [ 'AutoDestruct' ], ...) However, this is depreciated in favor of the exported trait alias: has foo => (traits => [ AutoDestruct ], ...) Apply the AutoDestruct trait to your attribute metaclass (e.g. "traits => [AutoDestruct]") and supply a ttl value. Typical usage of this could be for an attribute to store a value that is expensive to calculate, and can be counted on to be valid for a certain amount of time (e.g. caching). Builders are your friends :) Please report any bugs or feature requests to bug-moosex-autodestruct at
http://search.cpan.org/dist/MooseX-AutoDestruct/lib/MooseX/AutoDestruct.pm
CC-MAIN-2017-51
refinedweb
230
59.84
webservices Hi, I have a problem in webservices. I have defined a service which shoud read the xml file from the clientside and read the values... for more information.ice in Netbeans webservice in Netbeans hi deepak.. in the tutorial which u hav provided() im getting..... im using netbeans version 6.9.1 .. pls help me out... regards-- Harish Kumar how to insert data from netbeans into databse how to insert data from netbeans into databse how to insert data from netbeans into databse Please visit the following link: Web Service Web Services with NetBeans IDE Creating webservices in NetBeans. In this example program I will show you how you can make webservices in the Netbeans IDE. NetBeans IDE provides necessary GUI index NetBeans NetBeans why Netbeans IDE is not commonly used Today by most of the companies Netbeans Array help Netbeans Array help Ok here is my code- * * To change this template, choose Tools | Templates * and open the template in the editor. */ import... index = 0; index < frequency.length; index++ ) frequency[ index ] = 0 pf webservices tutorials Web services tutorials Webservices Tutorials Web service Web service webservices in JSP WEB-SERVICES-JAXRPC - WebSevices Friend, Please visit the following links: What is Index? What is Index? What is Index Why Web Services? Why Web Services? In this section of WebServices tutorials series we will understand why Web Services are developed and what are the benefits of using Web Services for the development of Enterprise applications. Why netbeans library netbeans library Hi could someone build a program in netbeans for a book library please.The program should provide a menu of options to work with the library, including: 1) Adding a new item to the library 2) Viewing all stock About Webservice - WebSevices About Webservice I wanted to know about WebServices Drop Index Drop Index Drop Index is used to remove one or more indexes from the current database. Understand with Example The Tutorial illustrate an example from Drop Index2ee example programs j2ee example programs can any one tell me how to develop and execute ---------- j2ee entity beans (cmp,bmp) example,message driven bean example ,webservices example in weblogic server with (netbeans or eclipse RMI in netbeans 6.5 RMI in netbeans 6.5 runing client in RMI using netbeans 6.5 Netbeans GUI Ribbon Netbeans GUI Ribbon how to create ribbon task in java GUI using netbeans hibernate on netbeans - Hibernate hibernate on netbeans is it possible for me to run the hibernate program on Netbeans IDE JNDI names in netbeans JNDI names in netbeans how to create a JNDI names in netbeans checking index in prepared statement checking index in prepared statement If we write as follows: String query = "insert into st_details values(?,?,?)"; PreparedStatement ps = con.prepareStatement(query); then after query has been prepared, can we check the index connect netbeans with oracle connect netbeans with oracle how to connect netbeans with oracle Hi Friend, Please visit the following link: Here you will find the steps to connect netbeans JavaScript array index of JavaScript array index of In this Tutorial we want to describe that makes you to easy to understand JavaScript array index of. We are using JavaScript... line. 1)index of( ) - This return the position of the value that is hold "The folder name is not valid" netbeans "The folder name is not valid" netbeans "The folder name is not valid" while crating a jsp,html or any page in netbeans RMI Program in netbeans RMI Program in netbeans pls give me an idea for how to run RMI program in netbeans with detailed example websevices websevices - how to import webservices in eclipse and netbeans hi how to import webservices in eclipse and netbeans.give a detailed step by step... visit the following link: NetBeans - IDE Questions NetBeans Can we use netbeans to create servlet, jsp pages?If yes means can you explain how it can be done? how to use netbeans for creating jsp...:// Hope that it will be helpful alter table create index mysql alter table create index mysql Hi, What is the query for altering table and adding index on a table field? Thanks struts-netbeans - Framework struts-netbeans hai friends please provide some help "how to execute struts programs in netbeans IDE?" is requires any software or any supporting files to execute this. thanks friends in advance alter table create index mysql alter table create index mysql Hi, What is the query for altering table and adding index on a table field? Thanks Hi, Query is: ALTER TABLE account ADD INDEX (accounttype); Thanks index - Java Beginners Regarding Simple Web service example - WebSevices /webservices/netbeans/index.shtml Thanks... in Netbeans IDE using the GlassFish Server . however when i did the same... and my netbeans is not starting up . What should be done to use enterprise buttons in netbeans,java buttons in netbeans,java respected sir, i would like to known how to make coding on a button while working on netbeans, so that a new window will open after clicking on that button? thank you import java.awt. Java arraylist index() Function Java arrayList has index for each added element. This index starts from 0. arrayList values can be retrieved by the get(index) method. Example of Java Arraylist Index() Function import NetBeans IDE NetBeans IDE The NetBeans IDE, product of Sun Microsystems, is a free, open-source.... NetBeans IDE supports developers providing all the tools needed to create all Mysql Date Index Mysql Date Index Mysql Date Index is used to create a index on specified table. Indexes... combination of columns in a database table. An Index is a database structure which - IDE Questions jsp using netbeans java,jdbc,netbeans oracle connectivity problem with netbeans including index in java regular expression including index in java regular expression Hi, I am using java regular expression to merge using underscore consecutive capatalized words e.g., "New York" (after merging "New_York") or words that has accented characters Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/100435
CC-MAIN-2013-20
refinedweb
1,027
51.28
required dependencies information. Optional dependencies are not covered. This port is required by: To install the port: cd /usr/ports/textproc/libxml2/ && make install cleanTo add the package: pkg install libxml2 cd /usr/ports/textproc/libxml2/ && make install clean pkg install libxml2 ===> The following configuration options are available for libxml2-2.8.0_3: MEM_DEBUG=off: Memory debugging (DEVELOPERS ONLY!) SCHEMA=on: XML schema support THREADS=on: Threads support THREAD_ALLOC=off: Per-thread memory (DEVELOPERS ONLY!) XMLLINT_HIST=off: History for xmllint ===> Use 'make config' to modify these settings Number of commits found: 182 (showing only 82 on this page) « 1 | 2 Update to 2.6.0. While this release is a major revision release, it maintains API and ABI backward compatibility. Note, due to enhanced error checking (particularly with namespaces), extra errors might be seen on the command line, but they do not appear to be fatal..5.10 * Clean up the Python installation to obey PREFIX (finally) * Mark some of the more troublesome build options as DEVELOPER ONLY! Update to 2.5.9. Add back python stuff to the pkg-plist. The libxml2 (and libxslt, for that matter) build looks for python under ${PREFIX}, not ${LOCALBASE}. Update to 2.5.8. Utilize USE_GNOME= pkgconfig. Remove REINPLACE commands that were rolled into gnomehack. Fix the pre-everything message to reflect the correct macros. Reported by: Edward Glowacki <glowack2@msu.edu> Disable thread support by default. This was interfering with ports such as mod_php4 with DOMXML support. It also has the potential of affecting other ports on -STABLE that rely on libxml2 to build shared libraries. I have filed a bug with the libxml2 developers to see if we can rectify this situation moving forward. More details can be found at: Add a flag to allow one to disable threading support. Setting LIBXML_WITHOUT_THREADS can fix build problems with apps such as PHP. Update to 2.5.7. Remove USE_GNOMENG. Update to 2.5.6. * Update to 2.5.4 * De-pkg-comment Update to 2.5.3. Update to 2.5.2. Update to 2.5.1. Re-add a patch that was forgotten when libxml2 was upgraded to 2.4.27. This will get us closer to eliminating HTTP traffic when searching for DTDs. However, since we no longer offer the docbook 4.1.2 DTDs in ports, this still doesn't solve the problem. Work is now being done to offer a better overall solution. Fix a bug introduced in 2.4.27 that caused KDE's doc building procedure to virtually hang. This patch has been fed back to the libxml people, and should be integrated in the next release. Reported by: bento and the KDE people Update to 2.4.28. Update to 2.4.27. Undo the SGML_CATALOG_FILES variable breakage introduced in 2.4.26. This caused KDE documentation not to build. This patch has been rolled into libxml CVS, and should be resolved in the next release. See for more details. Submitted by: will Obtained from: libxml CVS Update to 2.4.26. Fix a bug in the DTD validation code that caused a seg fault due to freeing unitialized memory. Update to 2.4.25. GNOME has just changed the layout of their FTP site. This resulted in making all the distfiles unfetachable. Update all GNOME ports that fetch from MASTER_SITE_GNOME to fetch from the correct location. Add various tunables to aid developers using libxml2, most notably adding the ability to turn on schema support. Approved by: knu (mentor) && marcus Update to 2.4.24. `%' has no special meaning for sed(1) in RE, so that there is no need to put in into square brackets. Update to 2.4.23. Set the default XML catalog location to the correct path. Bump PORTREVISION. Update to 2.4.22. Update to 2.4.21. Use USE_LIBTOOL. Update to 2.4.20. PR: 37192 Submitted by: Lev A. Serebryakov <lev@serebryakov.spb.ru> U[date to 2.4.19. PR: 36343 Submitted by: Lev A. Serebryakov <lev@serebryakov.spb.ru>. Update to 2.4.17. Update to 2.4.16. Update to 2.4.13. Update to 2.4.12. Backout previous change - it seems that new revision of the patch doesn't apply everywhere. Don't filter libc_r on 5-CURRENT. Update to 2.4.11. Update to 2.4.10. Don't link in libc - FreeBSD doesn't need this. Update to 2.4.6. Update to 2.4.5. Remove all mi-induced bogons: - Don't honour bogus MAKE_JOBS; - sort pkg-plist and remove bogus `@dirrm share/doc/ja/' from it; - remove useless USE_LIBTOOL. Listen to Jun Kuriama and follow my yesterday's upgrade with an upgrade to 2.4.3. One more executable is installed into bin/ now. Upgrade from 2.4.1 to 2.4.2... I let the maintainers know a couple of days ago, but the entire maintership (gnome@) is quiet... Add WWW. Update to 2.4.1. Update to 2.4.0. Update to 2.3.10 Correct gnome-config configuration file, so gnome-config outputs correct paths. SWitch maintainership of core GNOME ports to a small group of committers (gnome@FreeBSD.org), since this is now definitely too big for just one person. Update to 2.3.8. Update to 2.3.7. Update to 2.2.5. Update libxml2 to 2.3.3 and libxslt to 0.4.0 (updates rely on each other) Use GNU iconv library (converters/libiconv) instead of BSD iconv. Update to 2.3.0. Finally Gnome folks recognized the need to allow libxml2 co-exist with old libxml installed on the same machine, so I was able to happily remove most of my hacks. More style fixes for ports/textproc. Release maintainership.. libxml2 is not likely to be used in the core GNOME system for a "long time". Max, if you don't want the port (I know you've been interested in it in the past), just reassign it back to ports@ Update to 2.2.11 Update to 2.2.10 Update to 2.2.9 Update iconv to 2.0 and reflect shared library version bump. Persuade libxml2 to install into different filesystem space than libxml (cursing the author all the way for having two incompatible versions of their software do this). Update to 2.2.8 Update to 2.2.7 Update to 2.2.5 Convert category textproc to new layout. Update to 2.2.4 and enable iconv support. Update to 2.2.3 Update to 2.2.2 Update to 2.2.1 Bring libxml2 2.1.1 into the fold after a repo-copy. This will eventually replace libxml for GNOME. Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD 10 vulnerabilities affecting 22 ports have been reported in the past 14 days * - modified, not new All vulnerabilities
http://www.freshports.org/textproc/libxml2/?page=2
CC-MAIN-2014-10
refinedweb
1,145
71
I am trying to check to ensure the user entered a number instead of a character for this program. I was thinking of using isalpha and saying if that isalpha is true then tell user and end. But I have reconsidered and think that what I really need to do is use isdigit, and say that if isdigit is false (i.e the user inputs anything other then a number), then tell the user and exit. But I am still stuck with isdigit like I was isalpha. I have tried various combinations on trying to get it to recognize the if statement and have had no luck. Currently, if I put in a character instead of a digit, it ignores my isdigit statement and thinks it has all the data it needs to go to the end instead of exiting. Can someone please sheed some light onto what I am doing wrong here. Or perhaps should I be trying something else entirely for what I am trying to do? My current code is: Thanks for any help on this.Thanks for any help on this.Code: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <conio.h> int main (void) { typedef struct { int hr; int min; int sec; } TIME; TIME sTime; TIME fTime; TIME tTime; printf("Calculate total time between start and finish. Format for data is hh:mm:ss\n"); printf("\nEnter a start time:\t"); scanf("%d:%d:%d", &sTime.hr, &sTime.min, &sTime.sec); if (sTime.hr >24 || sTime.min >60 || sTime.sec >60) { printf("\aInvalid Option\n"); printf("\nPress any key to exit.\n"); getch(); return 0; } if (isdigit(sTime.hr || sTime.min || sTime.sec)) { printf("\aInvalid Option\n"); printf("\nPress any key to exit.\n"); getch(); return 0; } printf("\nEnter a finish time:\t"); scanf("%d:%d:%d", &fTime.hr, &fTime.min, &fTime.sec); if (fTime.hr >24 || fTime.min >60 || fTime.sec >60) { printf("\aInvalid Option\n"); printf("\nPress any key to exit.\n"); getch(); return 0; } tTime.hr = fTime.hr - sTime.hr; tTime.min = fTime.min - sTime.min; tTime.sec = fTime.sec - sTime.sec; if (tTime.hr < 0) tTime.hr += 12; printf("\n\n\nThe total time: %2d hr(s),%2d min(s), and%2d sec(s)\n", tTime); return 0; } DD :confused:
http://cboard.cprogramming.com/c-programming/23043-correct-use-isdigit-printable-thread.html
CC-MAIN-2013-48
refinedweb
381
78.45
Call using Skype and Record the Call in Wave File using .NET In this article, I will explain how to make a call in Skype and record the call in wave file. Using SkypeControl dll we can connect our windows application to Skype and make a call using Skype. Using Interop.SKYPE4COMlib dll helps to record the SKYPE call in wave file. Nowadays connecting Skype for business use widely spread all over the world.Here I used two controls to Connect , Call Skype and Record Skype call in wave file. The controls are as follows: SkypeControl dll is third party control is used to connect skype and call phone no to Skype. Interop.SKYPE4COMlib dll is also third party control used to record skype call in wave file format. Step as follows: First Connect Widows Application to Skype using SkypeControl dll and then Skype will prompt for allow or deny access of third party connection. If you click allow access then the Skype will connect to the Application. Make Call by passing phone no and record Call in wave file format. Using SkypeControl dll we can connect Widows Application to Skype and make a Call in Skype. Using Interop.SKYPE4COMlib dll helps to record the SKYPE Call in Wave file. Full code as Follows using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SKYPE4COMLib; using SkypeControl; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //Intialize SkypeProxy aSkype of SkypeControl which is used to connect and call Skype Call. SkypeProxy aSkype = new SkypeProxy(); private void Form1_Load(object sender, EventArgs e) { //connect method will connect application to the Skype software and it will prompt for allow or deny access aSkype.Conect(); } ); private void btncall_Click(object sender, EventArgs e) { //Assign Phone No to value variable in which call has to be made. string value = "11111110011"; //connecting skype value = "#abc CALL " + value; //Following Command method will call the Phone no of the value string variable aSkype.Command(value); //using SKYPE4COMLib interface is used to track the call status wheather it is InProgress or Finished in order to save it in wave file Skype skype = new Skype(); skype.CallStatus += new _ISkypeEvents_CallStatusEventHandler(Skype_CallStatus); } public void Skype_CallStatus(Call call, TCallStatus status) { //check for the condition callstatus is InProgress if (status == TCallStatus.clsInProgress) { mciSendString("open new Type waveaudio Alias recsound", "", 0, 0); mciSendString("record recsound", "", 0, 0); }//check for the condition callstatus is finished else if (status == TCallStatus.clsFinished) { DateTime currdate = DateTime.Now; string datetime = currdate.ToString(); //declaring wave filename as current datetime with specified path c string wavfilename = @"C:\" + datetime + @".wav"; //Passing wave filename with path inside mciSendString method to save the preferred location mciSendString("save recsound " + wavfilename, "", 0, 0); //close the recording mciSendString("close recsound ", "", 0, 0); } } } } Below image shows the when aSkype.Conect() inside form load event, connect method raises it will prompt user in Skype to allow or deny access to the third party application. Note: I had attached Interop.SKYPE4COMlib dll and SkypeControl dll for reference and also full sample code.
https://www.dotnetspider.com/resources/44335-Call-using-Skype-record-call-wave-file.aspx
CC-MAIN-2020-40
refinedweb
521
57.37
Async, Await and Asyncio in Python Get FREE domain for 1st year and build your brand new site Hello, in this post I will discuss about the async and await keyword introduced in Python 3.5 along with asyncio module. Let's first discuss about execution of code in sequential and concurrent mode. Sequential Computing - Sequential Computing means executing the current instruction before moving onto the next one. Let's understand that through an example - from time import sleep from datetime import datetime # storing the time at which the script start executing start = datetime.now() def func1(): print("func1") sleep(5) print("Complete executing func1") def func2(): print("func2") sleep(5) print("Complete executing func2") # calling both functions func1() func2() print("Total Excecution Time: "+str((datetime.now())-start)) Output - func1 # sleeping for 5 seconds Complete executing func1 func2 # sleeping for 5 seconds Complete executing func2 Total Excecution Time: 0:00:10.007661 In above code you can see, I created two functions and added sleep method with 5 seconds as sleeping time in each function. Then, I called func1 and func2 respectively. Since, func1 was called first. Thus, it will be executed at first and then func2 will be executed. This is sequential computing. It took total time of around 10 seconds to complete the execution. This can be said as First Come First Serve. Concurrent Computing - Concurrent computing means executing several instructions concurrently or at the same time. Let's understand it through an example - import asyncio from datetime import datetime # storing the time at which the script start executing start = datetime.now() async def func1(): print("func1") await asyncio.sleep(5) print("Complete executing func1") async def func2(): print("func2") await asyncio.sleep(5) print("Complete executing func2") # calling both functions async def main(): await asyncio.gather(func1(), func2()) asyncio.run(main()) print("Total Excecution Time: "+str((datetime.now())-start)) Output - func1 func2 # sleeping for 5 seconds Complete executing func1 Complete executing func2 Total Excecution Time: 0:00:05.006706 In above code you can see, I created two functions and added asyncio.sleep() method with 5 seconds as sleeping time in each function. Then, I used asyncio.gather() method to run the coroutines (func1 and func2) concurrently. Then, I used asyncio.run() method to execute the coroutine (main). In contrast with Sequential computing code, this code just took around 5 seconds to complete the execution. So, from the above the two examples, you should have got a basic idea about the difference between Sequential and Cuncurrent computing. Now, let's dive more deeper into Concurrent computing. Asyncio commonly used methods and keywords - Concurrency- Executing several instructions at the same time. Sequential - Executing single instruction at a time. Coroutine - In simple terms, a coroutine is declared using async def keyword and is generalized form of subroutine. It can be entered, exited, and resumed at many different points. Meaning, a coroutine can be exited and then resumed again from that same point like we did in the above code using asyncio.sleep() method. asyncio module - asyncio module is used to write concurrent code using async and await keywords. async keyword - async keyword is used to declare the coroutine. await keyword - await keyword passes the control back to the event loop. It tells the event loop to execute another instructions, coroutine, etc untill it's completion. Like, In the above example we used await keyword before asyncio.sleep() method to tell the event loop to execute other function func2 until it's completion. Thus, it printed func2 first before printing Complete executing func1. asyncio.sleep() method - It is used to suspend the execution of a program for a specific amount of time as passed in the method. In contrast with time.sleep() method, it is non-blocking in nature. Meaning it let's the execution of other code until it completes its suspension time. asyncio.run() method - It runs the passed coroutine and print the result returned by that coroutine. asyncio.gather() method - It runs awaitable objects (objects which have await keyword) concurrently. Like in the above example, we used func1 and func2 within gather method. When all awaitables are completed successfully, the result is an aggregate list of returned values. asyncio.wait() method - It is used to run awaitable objects in the set. asyncio tasks - Tasks are used to schedule the execution of coroutines, since we can't 1000 of coroutines at the same time. Thus, we use tasks to schedule the coroutines. asyncio.create_task() method - It is used to add a coroutine passed into this method to task and schedule its execution. asyncio event loop - Event loop runs asynchronous tasks and callbacks. asyncio.get_event_loop() method - It gets the current event loop. asyncio.new_event_loop() method - It is used to create a new event loop object. asyncio.run_until_complete() method - It is used to schedule to run as a asyncio tasks or runs the instance of asyncio.Future until its completed. asyncio future - It is a special low-level awaitable object which represents an eventual result of an asynchronous operation. Examples - Example 1 - import asyncio async def func1(): print("testing") async def main(): # scheduling func1 execution by adding it as a task task1 = asyncio.create_task(func1()) # awaiting task1 until it's completed await task1 asyncio.run(main()) Output 1 - testing Example 2 - import asyncio # function to generate asynchronous interable range async def a(num): for x in range(num): yield(x) async def func1(q): print(q) await asyncio.sleep(2) print("finished "+str(q)) # list of tasks tasks = [] async def main(): async for x in a(10): # create_task method to schedule # the execution of function func1 task = asyncio.create_task(func1(x)) # adding the task to tasks list tasks.append(task) # to get the current event loop loop = asyncio.get_event_loop() # run until function main complete its execution loop.run_until_complete(main()) # run until all tasks complete their executions loop.run_until_complete(asyncio.wait(tasks)) Output 2 - 0 1 2 3 4 5 6 7 8 9 # sleeping for 2 seconds finished 0 finished 1 finished 2 finished 3 finished 4 finished 5 finished 6 finished 7 finished 8 finished 9 Asyncio isn't a easy topic to learn, it takes time but with time and practice you can get good in this. This was just a basic overview of async, await and asyncio module in Python. If you have any query regarding this, feel free to ask me in the discussion section below. Thank you so much for reading this.
https://iq.opengenus.org/asyncio-async-and-await-in-python/
CC-MAIN-2021-17
refinedweb
1,077
57.77
22 November 2010 15:57 [Source: ICIS news] By John Richardson ?xml:namespace> Behind this perception in the case of polyethylene (PE) is the influence of the Dalian Commodity Exchange’s futures contract in linear-low density PE (LLDPE) film. And more broadly, across many other products, it seems as if Many industry sources now tell us that PE in general (the In other words, its day-by-day and week-by-week price in And so by Friday 19 November, physical pricing for PE had fallen by $70-130/tonne from the previous week - reflecting four consecutive days of declines in the And then there is what appears to be a greater ability to gamble on physical cargoes. "Chinese monoethylene glycol inventories are at 500,000 tonne - close to their maximum level - but prices have still gone up and imports keep arriving,” said a source with a leading producer early last week. "There are supply reasons why MEG has been so strong this year - ie the great supply surge hasn't happened because of problems with running new plants. "But we still do not fully understand why prices have gone up.” There are good supply and demand reasons why fibre intermediate prices in general have rallied. These include the soaring cost of cotton on poor harvests which has boosted the demand for polyester. But purified terephthalate (PTA) now also has a well-established futures market in There have also, though, been paraxylene (PX) and PTA production problems ahead of 1.2m tonne/year of polyester capacity start-ups in Still - with polyester margins under pressure, players down the entire chain need to ask themselves about the sustainability of the price rises. Returning to PE, dividing the speculation from the real strength of demand seems to have become a bigger headache for producers - perhaps explaining why Here are two very contrasting opinions about the key “There have been reports that this is a peak demand season right now. But as far as our analysis over the last ten years shows, business slows down between mid-November and January,” said a senior Asian-based sales and marketing executive with a major global producer last week. "True, this is an agricultural film season that will provide some support for low-density PE (LDPE) and LLDPE demand. "I don't hold with the argument that there is already strong demand in "This is definitely a quiet season overall as everyone is trying to minimise stocks for tax and financial reporting reasons. "What we think is happening is that there is a lot of trader talk to justify higher prices.” Traders were moving PE to "And so we believe that the demand we are seeing is not driven by fundamentals, but it is instead about speculation and we are worried about inventory levels.” A source with a South Korean producer, however, also said last week: “In the field we find that stocks with converters are low and demand from critical applications (auto, home appliances, construction) is not bad. “I believe that the market from December to January will be quite stable. “The futures market is dragging the physical market (down) a little, but polypropylene (PP) is strong while high-density PE (HDPE) and LLDPE are adjusting. I don't think there will be a dramatic price fall like 2008.” His outlook for 2010 demand growth is bullish, suggesting that there are very solid consumption-growth reasons behind strong pricing. Chinese PE demand would reach around 16m tonnes this year compared with 15m tonnes in 2009, he said. PP demand would total approximately 14.5m tonnes in 2010 as against 13m tonnes last year. And interestingly, he added that new Chinese plants had suffered from mechanical problems, resulting in a lower polyolefin self-sufficiency ratio than had been expected at the start of the year. This could have helped keep supply tight, along with big production problems at new Are markets really that hard to fathom these days, though, and, as a result, has volatility actually increased? A source with a second South Korean producer said: “Markets haven’t changed - they have always been as speculative and volatile as they are now. “It is just that people are getting to understand how they behave a little better as there are so many more of us involved in this business.” Perhaps it is down to the mathematicians and the statisticians to try and resolve this argument. Malini Hariharan contributed to this article Bookmark Paul Hodges’ Chemicals & the Economy blog Read John Richardson and Malini Hariharan’s Asian Chemical Connections blog Click here to find out more on the ICIS margin reports
http://www.icis.com/Articles/2010/11/22/9412770/insight-in-china-petchems-some-like-it-hot.html
CC-MAIN-2013-48
refinedweb
775
54.66
Method Overloading Example section explains you how the method overloading is accomplished in Java. AdsTutorials In this section we will read about overloading in Java. Method overloading in Java is achieved due to the Java supports Polymorphism. Overloading of methods specifies the various methods defined with the same name. The concept of method overloading allows the Java programmer to use the method with the same name. But, these methods must be differentiated by their signature. Signature of method specifies the method's return type, number of arguments of method, data type of arguments of method. Constructors in Java is suitable example for understanding the concept of method overloading. Overloading allows the Java programmer to accomplish the compile time polymorphism. Method overloading allows the user to use the various implementations of same name and give the desired output. This feature protects to know about the internal processing system from the external users. Example Here we are giving a simple example which will demonstrate you about the method overloading in Java. In this example we will create a Java class where we will use the concept of method overloading. As we have discussed above constructor of a class is also uses the concept of method overloading so, in this example we will create the various constructors of a class. Then we will create methods with the same name but, with the different return types and number of parameters. MethodOverloading.java public class MethodOverloading { int a; int b; double c; double d; public MethodOverloading() { } public MethodOverloading(int a, int b) { this.a = a; this.b = b; } public void add() { int sum = a+b; System.out.println("Sum Of "+a+" and "+b+" = "+sum); } public int add(int num1, int num2) { return num1+num2; } public double add(double num1, double num2) { return num1+num2; } } MainClass.java public class MainClass { public static void main(String args[]) { int a = 6; int b = 4; double c = 4.5; double d = 5.5; MethodOverloading mo = new MethodOverloading(); MethodOverloading mo1 = new MethodOverloading(2, 4); mo1.add(); double sum1 = mo.add(c, d); System.out.println("Sum Of "+c+" and "+d+" = "+sum1); int sum2 = mo.add(a, b); System.out.println("Sum Of "+a+" and "+b+" = "+sum2); } } Output When you will execute the MainClass.java you will get the output as follows Advertisements Posted on: July 25, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles Advertisements Ads Ads Discuss: Method Overloading Example In Java Post your Comment
https://www.roseindia.net/java/beginners/method-overloading-example-in-java.shtml
CC-MAIN-2017-43
refinedweb
416
57.98
Difference between revisions of "Code snippets" Revision as of 08:21, 2 February 2013 - 12 Adding and removing objects to/from the scenegraph - 13 Adding custom widgets to the interface - 14 Adding a Tab to the Combo View - 15 Opening a custom webpage - 16 Getting the HTML contents of an opened webpage.PrintMessage('Hello, World!')()(0,0,0) n.append(v) v=App.Vector... Adding an arc or a circle import Part doc = App.activeDocument() c = Part.Circle() c.Radius=10.0 f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature f.Shape = c.toShape() # Assign the circle shape to the shape: def logPosition(self, info): down = (info["State"] == "DOWN") pos = info["Position"] if (down): FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n") Adding a Tab to the Combo View) Opening a custom webpage import WebGui WebGui.openBrowser("") Getting the HTML contents of an opened webpage from PyQt4 import QtGui,QtWebKit a = QtGui.qApp mw = a.activeWindow() v = mw.findChild(QtWebKit.QWebFrame) html = unicode(v.toHtml()) print html
https://www.freecadweb.org/wiki/index.php?title=Code_snippets&diff=16739&oldid=16258
CC-MAIN-2019-43
refinedweb
177
51.55
19 April 2012 19:32 [Source: ICIS news] (updates with Canadian and Mexican chemical railcar traffic data) ?xml:namespace> Canadian chemical railcar loadings for the week totalled 12,297, up from 11,266 in the same week in 2011, the Association of American Railroads (AAR) said. The previous week, ended 7 April, saw a year-on-year decline of 14.7%. The weekly chemical railcar loadings data are seen as important real-time measures of chemical industry activity and demand. From 1 January to 14 April, Canadian chemical railcar loadings were down by 11.5% year on year to 156,657. The AAR said weekly chemical railcar traffic in US chemical railcar traffic rose by 3.9% year on year for the week ended 14 April as shipments rebounded after five weeks of declines. There were 31,405 chemical railcar loadings last week, compared with 30,235 in the corresponding week of 2011. In the previous week, ended 7 April, US weekly chemical railcar loadings fell by 3.7%, marking their fifth decline in a row and the ninth decline so far this year
http://www.icis.com/Articles/2012/04/19/9552056/canada-weekly-chem-rail-traffic-rises-after-14-straight.html
CC-MAIN-2014-35
refinedweb
184
64.2
On 06/27, Satyam Sharma wrote:>> Thanks for your comments, I'm still not convinced, however.An perhaps you are right. I don't have a very strong opinion on that.Still I can't understand why it is better if kthread_stop() sends asignal as well. Contrary, I believe we should avoid signals when itcomes to kernel threads.One can always use force_sig() or allow_signal() + send_sig() whenit is really needed, like cifs does.> On 6/26/07, Oleg Nesterov <oleg@tv-sign.ru> wrote:> >> .>> Anyway, I think _all_ usages of kthread_stop() in the kernel *do* want> the thread to stop *right then*. After all, kthread_stop() doesn't even> return (gets blocked on wait_for_completion()) till it knows the target> kthread *has* exited completely.Yes, kthread_stop(k) means that k should exit eventually, but I don'tthink that kthread_stop() should try to force the exit.> And if a workqueue is blocked on tcp_recvmsg() or skb_recv_datagram()> or some such, I don't see how that flush_workqueue (if that is what you> meant) would succeed anyway (unless you do send the signal too),timeout, but this was just a silly example. I am talking about the casewhen wait_event_interruptible() should not fail (unless something badhappens) inside the "while (!kthread_should_stop())" loop.Note also that kthread could use TASK_INTERRUPTIBLE sleep because itdoesn't want to contribute to loadavg, and because it knows that allsignals are ignored.> Note that the exact scenario you're talking about wouldn't mean the> kthread getting killed before it's supposed to be stopped anyway.Yes sure, we can't kill the kernel thread via signal. I meant we can havesome unexpected failure.> >?I think this "if(tsk)" is just bogus, and should be killed.Oleg.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2007/6/27/100
CC-MAIN-2016-22
refinedweb
312
65.01
If you own or have recently purchased Crucial NVMe SSD such as CT1000P1SSD8 (1TB M.2 NVMe SSD) or CT500P1SSD8 (500GB M.2 NVMe SSD), please be aware that these devices may no be recognized by ESXi after upgrading to the latest release. Thanks to Pete Lindley, (OCTO for End-User Computing), who reached out last week regarding the observation as well as a workaround for the problem. This was also quite timely as I recently purchased a Crucial M.2 NVMe SSD and would have also ran into this problem. It turns out these Crucial devices were working fine while running on ESXi 6.5 Update 2 but was no longer recognized in latest release of ESXi 6.7 Update 2. It is unclear whether support for these SSDs were removed intentionally or unintentionally, but in either case, these devices are not officially on VMware's Hardware Compatibility List (HCL). UPDATE (07/29/20) - Over the past few months, I have had a number of folks share feedback that using the trick mentioned below for ESXi 7.0, they have had success of ESXi detecting their NVMe SSD. I wanted to share some of the model and/or vendors that folks have reported success with. I will keep this list updated, so feel free to leave a comment below. - OWC Aura Pro X2 2TB NVMe - ADATA XPG - Sabrent UPDATE (06/13/20) - Thanks to reader Dave, it looks like this trick also works with ESXi 7.0 but the filename has changed. Simply copy nvme.v00 VIB from the ESXi 6.5 Update 2 and replace it on ESXi 7.0 system (either live under /bootbank or part of the installer) but rename the file to nvme_pci.v00 which is the new filename for NVMe driver. UPDATE (05/23/19) - After speaking with a few folks who took a closer look, the issue is due to the fact that we added support for NVMe 1.3 spec in latest ESXi 6.7 Update 2 release, but because these are "consumer" devices, they did not conform to the latest specification and hence the driver is unable to claim the device. This is another good reminder when using components not on VMware HCL, this is always a risk from a home lab perspective. In general, I know Samsung and Intel NVMe SSD usually works quite well without issues but always good to do some research. I think Engineering is looking to see if there are other workarounds for the future, but for now, you can use the workaround below. The easy workaround that Pete found was to simply replace the NVMe driver from ESXi 6.7 Update 2 (1.2.2.27-1vmw.670.2.48.13006603) with one found in ESXi 6.5 Update 2 (1.2.1.34-1vmw.650.2.50.8294253). To so do, simply copy nvme.v00 to /bootbank from either an existing ESXi 6.5 Update 2 system or directly from the ISO. Please note, any future updates or patches to the ESXi host will most likely override the updated driver. For my 1TB HP EX920 I had to downgrade to 6.7 GA driver for NVMe to get 6.7u1 to see my drive. Haven’t checked 67u2, but I recond it will be the same. Maybe 67GA is the same driver as in 65u2? It was discussed here: In my experience, I had the same issue with 6.7U1 and 6.7U2 – I’m assuming its using the same driver. 6.7U1 was when they updated the driver. The 6.7GA driver seems to work fine. I really wish this was resolved, makes homelab stuff kind of a pain. Thanks for this! I got my 1TB back! Does somone have the issue with samsung evo nvme? Turning off “Intel Rapid Storage Technology” worked for me to get a corsair MP510 detected and working How did you do this? I cannot get this to work. Hello mate, thank you for this. It worked for me! I’m running ESXi on an Optiplex 7060 Micro. It managed to detect Crucial NVMe SSD CT1000P1SSD8. I now have 1 NVME and 1 SATA — booting VMware ESXi, 6.7.0, 15160138 on a 32GB USB Thumb Drive! I you giving me the idea appreciate it. To those wondering where can this be found — it’s in the BIOS — I’ve selected AHCI under SATA operation (it was previously set to RAID ON). Works well now. Cheers! I did replace nvme.v00 with the the version from 6.7.0 GA. Now ESXi is no longer booting 🙁 Did you get this working on ESXi 6.7 Update 2? I really don’t need to rebuild ESXi again. were you able to resolve? I cant discover my datastores I also wonder if the samsung evo 970 nvme has the same problem. I just received my adata SX8200 pro and after rolling back the driver version it works fine..but I wonder if I should go for the Samsung after all, if it wouldn’t have these driver issues. Just stumbled across this article. I literally went to best buy after reading this and purchased a Samsung 970 EVO PLUS 500GB to test on a homelab system (ASROCK X470D4U Motherboard w/ AMD 2700x CPU) running a fresh install of ESXi 6.7 U2. ESXi had no issues detecting the drive, creating datastores, and VMs etc. replacing the nvme.00 in the /bootbank per the steps provided will PSOD. You wont be able to boot anymore with error: Failed to verify signatures of the following vib(s): [nvme]. All tardisks validated. I ran into this issue with my own HP Homelab setup. I documented it here: It’s actually funny that you mentioned it, I tweeted at William Lam about this. He updated this post to show that the issue is that his Crucial drive didn’t support NVMe 1.3, however the HP EX920 is listed as supporting NVMe 1.3. I also have the 1TB version. My understanding is that the EX920 gets pretty hot, I’ve never seen mine go offline, but I don’t do a whole ton with it. Running 6.5U3: Samsung 970 EVO = Yes + Intel 660p 1Tb = No. After cloning 6.5U3 image profile using Web Client/Auto deploy, deselect nvme 1.2.2.28 and select nvme 1.2.1.34, then generate install ISO. Shame, 660p officially supports NVMe 1.3 too Thank you! That helped a lot! The only image available for download was the HPE one: The last firmware version of the Crucial P1 seems to fix the problem (P3CR013). Now I can see the disk in my ESXi 6.7u3 Thanks Benoit, much easier than injecting a deprecated driver. Helped me a lot! The workaround Pete found is good! I was going nuts trying to inject the driver into the ISO. /bootbank is /tmp ? inject drivers into ISO steps download ESXi Customizer Powershell script Download NVMe 1.2.1.34-1vmw.650.2.50.8294253 from website below; direct download VIB link also below Create folder C:\VM and copy ESXi650-201908001.zip and copy ESXi customizer script into it Create folder C:\VM\pkg (this is for you VIB files Open Powershell as Admin Goto C:\VM and you execute the following command .\ESXi-Customizer-PS-v2.6.0.ps1 -zip .\ESXi670-201912001.zip -pkgDir c:\VM\pkg -v67 Now download Rufus, select ISO and write to USB, boot off USB Happy to find this!! Thank you!! Just installing it outside the ISO solved my issue. Hopefully it’ll make its way back into 6.7!! The zip file should be ESXi670-201912001.zip going into the C:\VM folder Also, add -nsc to the command line to stop errors from doing a signature check which stops ISO from being written. .\ESXi-Customizer-PS-v2.6.0.ps1 -zip .\ESXi670-201912001.zip -pkgDir c:\VM\pkg -v67 -nsc Also if you have any other package .zip or .vib files, just add them to the Pkg folder and it will add them also. After updating NVMe back to ESXi 6.5 Update 2 (1.2.1.34-1vmw.650.2.50.8294253) driver, when starting to transfer data onto hard drive it goes inaccessible and 0 bytes Anyone else had any luck fixing this issue Have a Samsung 970 Pro 1TB M.2 Hi, anyone know of a 2TB NVMe that is consumer grade and doesn’t suffer from this issue with ESXi 6.7 U1 and later? Preferably not Samsung. Thanks. I did some testing with a few M.2 SSDs I had on-hand to try to help other with this. Installing ESXi 6.7 U3b on an Intel NUC10i7FNH, I had the following results: Samsung EVO 970 Plus (500GB) Unknown firmware version (whatever it shipped with) Detected, fully compatible Corsair MP600 (1TB) Firmware EGFM11.3 (Most recent as of 2020-03-14) Note my test setup only supports PCIe 3.0, no idea if PCIe 4.0 impacts compatibility Detected, fully compatible ADATA XPG SX8200 Pro (2TB) Firmware 42A4SANA (Most recent as of 2020-03-14) NOT detected, NOT compatible I’m disappointed that the ADATA didn’t work since the 2TB is only $269 USD and it’s a really good price for performance SSD. I specifically bought it to use in this ESXi build, but I’d rather return it for a compatible one. I did install the ADATA SSD in a Windows PC and it works fine there, just not in the latest ESXi update. I’d love to hear reports of other compatible/incompatible SSD models! I just bought the SX8200 pro on the island. esxi did not see 6.5 u3 and 6.7 u3. nvme drive saw that i installed old version. but there is a problem. I am testing hdd speed in windows or other operating system I see 3500mb / sec write and 3400mb / sec read values. but i installed windows vm in esxi I did the same test. 1500mb / s read gives 1300mb / s write value. The adata xpg s40 product did not have such a resistance problem or speed issue. I used windows vm in esxi while using xpg s40 I saw 3500mb / s write and 3400mb / s read values. So when the driver sees the old version, he sees the SX8200 pro on the island, but the performance is halved. 🙁 note: the servers I’ve tested: dell r720 and r730 and esxi 6.5u3- 6.7u3 Has anyone tried this with ESXi 7.0? I have an SX8200 installed and working with the drive rollback on 6.7U3, and am holding off on 7.0 for now because of this. Having the same issue with XPG8200 Pro and ESXi 7. Rolled back to 6.7 U3 with older nvme drivers. I hope if there is a way to fix this :/ thanks for testing that, have the same drive. hope there will be a fix soon. To echo Michael, thanks for trying! 🙂 To confirm, you’re saying the 6.5U2 driver referenced in this fix doesn’t work on 7? yeah exactly. I tried to install older nvme drivers at ESXi 7 as I did for 6.7 U3, but once ESXi 7 rebooted, I also noticed my nics couldn’t be detected. I will give it a try again this weekend with “esxcli software profile update” command William mentioned at his latest post. I’m using E200-8D by the way. Good to know – I have the same motherboard series (X10SDV) Still no news with 7.0 and SX8200? I’m facing same isssue. Download ESXi 6.5 U2 Driver Rollup from my.vmware.com and copy nvme.v00 to \bootbank\nvme_pci.v00 (7.0) or \bootbank\nvme.v00 (6.7). I used SCP to do this. My SX8200 works! I just made a request (for Adata SX8200Pro) via to add NGUID and EUI64 NVMe Identifier, just like Please also make the same request to Adata. I doubt they will add.. unless lot of people use ESXi. Did that – thanks for the hint. Though I couldn’t find the sx8200 as a SSD drive on the support page. I need help, I have installed Esxi 7.0 on NUC10i7FNH installed with CORSAIR MP510 1.9TB PCIe NVMe Performance M.2 SSD, when i go in storage adapters it is showing me unknown and performance is not as it should have to be. Please can you suggest what drivers i can use to overcome this issue ? Did you figure this out? I find my NVME drives in my NUC10 (with ESXi 6.7 and 7.0) are being claimed by AHCI and not working well at all. Hi, I try to install EVO 970 plus. in ESXi 6.7u2 don’t see disks but I can see the controller(BOSS-S1), I tried the steps of old driver, but ESXi don’t see them in anyway. Any idea? Hi, I have a Crucial MX 300 MVNe 275 Gb drive, and it is recognized by ESXi 7.0 (displayed under Storage as a local ATA Disk). It used to hold a Windows 10 installation in the same NUC7i3BNH. I have cleared partition table in ESXi. When I attempt to create a new data store, it fails with these log entries in wmkwarnong.log: 2020-06-29T17:07:10.197Z cpu2:526150 opID=33ff0c)WARNING: Vol3: 1410: Crucial 275 GB/5efa1fbe-aee2b6c2-0645-f44d306972ed: Error initializing JB SFD: I/O error 2020-06-29T17:07:10.197Z cpu2:526150 opID=33ff0c)WARNING: Vol3: 1651: Error creating system files: I/O error I have tried the switch of 6.5U2 driver to \bootbank\nvme_pci.v00 and restarted, however it made no difference. I have no reason to believe the drive is faulty as it booted Win10 just fine within the past couple of weeks. Any idea what would cause this behavior? Had to come back and share – updated a few more of my ESXi 6.7 instances to 7 and ran into my storage drivers not showing up again. Come to find out – the nvme_pci.v00 wasn’t listed in the /bootbank/boot.cfg file. (Could have been removed at some point?) I still had to reapply the old 6.5 driver (6.7 wouldn’t work…) – but seemed to help out. I do think I’m getting snagged by the consumer NVME drives that I’m using – as other drives work without the workaround. Of course – sent me into a bit of a panic hoping that I could scrounge up a fix! 1. Upload the following files to esxi “/tmp” directory VMware_bootbank_vmware-esx-esxcli-nvme-plugin_1.2.0.32-0.0.8169922.vib VMW_bootbank_nvme_1.2.1.34-1vmw.670.0.0.8169922.vib (Files can be download from) 2. SSH run the following commands to install 2 files: 3. Reboot > Done !! Enjoy 🙂 Screen Dump: ————————————————————————– login as: root Keyboard-interactive authentication prompts from server: End of keyboard-interactive prompts from server. x-esxcli-nvme-plugin_1.2.0.32-0.0.8169922.vib Installation Result Message: Operation finished successfully. Reboot Required: false VIBs Installed: VMware_bootbank_vmware-esx-esxcli-nvme-plugin_1.2.0.32-0.0.81 69922 VIBs Removed: VMware_bootbank_vmware-esx-esxcli-nvme-plugin_1.2.0.36-2.48.130 06603 VIBs Skipped: 4-1vmw.670.0.0.8169922.vibW_bootbank_nvme_1.2.2.28-1vmw.670.3.73.14320388 VIBs Skipped: Has anyone been able to try PNY XLR8 CS3030? Seeking advice. I am using ADATA XPG, and trying to patch my Lab-ESXi and run into this problem. (again) Sadly it’s my boot drive, so the patching rolls back after 2nd reboot.. (somewhat magical that it even boots up to me) Any one has similar encounter can post a solution? Since you’re using a device that is NOT detected automatically as boot, you could try re-authoring the patch image using Image Builder (UI or CLI) to incorporate the 6.5 NVMe VIB. If not, you may need to consider installing ESXi on USB device Thanks for replying William, Saw this 1 hours late, i ended up installing on another drive, i will definitely look into authoring the patch image in future attempts. I gave up, installed a old intel ssd to replace the NVME as boot drive. I also tried ESXi 7.0 from USB earlier and it’s much easier to replace nvme_pci.v00 (renamed from nvme.v00). For anyone who comes after me who is also new, here’s what i did 1. SCP to the host (you need to enable SSH on host 1st. I used WinSCP) 2. browse to bootbank and replace nvme.v00 @Webster IP: I followed your method. That let me boot (as opposed to PSOD when I simply replaced the NVME file) but then I regressed back to “No network adapter found” (previously I created a USB stick with Intel 219LM (Jacksonville) drivers for the 10th gen Intel CPU motherboards) — I’m guessing that last part did it: Step 1: Installation Result Message: Operation finished successfully. Reboot Required: false VIBs Installed: VMware_bootbank_vmware-esx-esxcli-nvme-plugin_1.2.0.32-0.0.8169922 VIBs Removed: VMware_bootbank_vmware-esx-esxcli-nvme-plugin_1.2.0.37-1vmw.700.1.0.15843807 VIBs Skipped: Step 2:ware_bootbank_native-misc-drivers_7.0.0-1.25.16324942 VIBs Skipped: Does anyone have any advice for how to fix this? Yes, I can reimage the USB stick with the ISO I made, which then gives me back the NIC but I lose the NVME drivers required for my 8200 Pro. If I use this process to put the NVME drivers in the right place, I lose my ability to use my NIC. 🙁 Lenovo M80q. 10th gen Intel i7-10700T with 219LM (Jacksonville) NIC. 🙁 I tried ESXi Customizer v2.81 to do the following: PS C:\esx> .\esxi-customizer281.ps1 .\ESXi7\ESXi-7.0b-16324942-standard.zip -pkgdir c:\esx\pkg -v70 This is ESXi-Customizer-PS Version 2.8.1 (visit for more information!) (Call with -help for instructions) Logging to C:\Users\X\AppData\Local\Temp\ESXi-Customizer-PS-1992.log …-intelnuc 0.8.4-3vmw.670.0.0.8169922 [OK, added] Add VIB nvme 1.2.1.34-1vmw.650.2.50.8294253 [OK, added] Exporting the Imageprofile to ‘C:\esx\ESXi-7.0b-16324942-standard-customized.iso’. Please be patient … …burning that tells me the NIC drivers cannot be found. However, if I then do exactly the same sequence, just without the NVME VIB, the NIC works great – but then, of course, the NVME VIB doesn’t install, and I cannot see my SX8200 Pro. I tried just replacing the file per the 6/13/2020 post at the top of this thread, but the machine PSOD’d at bootup – could not verify drivers, exactly what Wissam Mahmassani wrote. The pkg directory has two files: -a—- 7/28/2020 9:22 AM 184184 VMW_bootbank_ne1000-intelnuc_0.8.4-3vmw.670.0.0.8169922.vib -a—- 9/12/2020 10:40 AM 87418 VMW_bootbank_nvme_1.2.1.34-1vmw.650.2.50.8294253.vib Help!? The stated goal: Working Lenovo M80Q Tiny, which has Intel 10th gen CPU with 219LM (Jacksonville) NIC on it, and an XPG (ADATA?) SX8200 Pro in it. But wait, there’s more! 0.8.4-3vmw.670.3.99.32543355 [OK, replaced 0.8.4-10vmw.700.1.0.15843807] Add VIB nvme 1.2.1.34-1vmw.650.2.50.8294253 [OK, added] Exporting the Imageprofile to ‘C:\esx\ESXi-7.0b-16324942-standard-customized.iso’. Please be patient … …. same result – no NIC found. The change this time: I used the ne1000 843 VIB (ne1000 0.8.4-3vmw.670.3.99.32543355) rather than the newer VIB (ne1000-intelnuc 0.8.4-3vmw.670.0.0.8169922). The feedback from the ESXI-Customizer tool changed a bit ([OK, added] was the old feedback when the VIB was added; this time the feedback was [OK, replaced 0.8.4-10vmw.700.1.0.15843807]) but the end result was the same – NIC not found. 🙁 I face exactly the same problem with ADATA XPG SX8200 Pro and Intel I219-V Onboard NIC. If I add ne1000 VIB, the NIC is recognized by ESXi. However, If I add ne1000 and nvme VIBs, ESXi don’t recognize NIC. I had struggled for several hours, and I gave up ESXi 7.0. Now, it works well on ESXi 6.7. With regards to the ADATA XPG SX8200 Pro, ADATA have said they will never add in the missing attributes to make it fully nvme 1.3 standards compliment. I really guess this will be my only time buying from ADATA WelshWizard.. That’s too bad. Where did you come across this declaration? Their product page does say “supports NVMe 1.3” although I guess that’s different from “fully complies with”. I’m still on 6.7 because I don’t have the time right now to handhold my 8200 Pro through another upgrade after the first round of trouble. @Mark I was told this by someone who asked ADATA for me, i cant really expose who told me. The controller shall specify a globally unique namespace identifier in this field or the EUI64 field when the namespace is created. If the controller is not able to allocate a globally unique identifier then this field shall be cleared to 0h. Refer to section 7.11. The controller shall specify a globally unique namespace identifier in this field or the NGUID field when the namespace is created. If the controller is not able to allocate a globally unique 64-bit identifier then this field shall be cleared to 0h. Refer to section 7.11. The new vSphere 7.0.1 may have issue recognizing NVMe. Did any of you encounter the issue with this release? same problem, im on 7.0.1 and cant detect ADATA XPG SX8200 ssd’s, swapping out the nvme_pci.v00 causes Purple screen of death or no network adapter found error.
https://www.virtuallyghetto.com/2019/05/quick-tip-crucial-nvme-ssd-not-recognized-by-esxi-6-7.html?replytocom=63114
CC-MAIN-2020-50
refinedweb
3,685
76.93
odbx_lo_write man page odbx_lo_write — Writes buffer content into the large object Synopsis #include <opendbx/api.h> ssize_t odbx_lo_write (odbx_lo_t* lo, void* buffer, size_t buflen); Description odbx_lo_write() sends the data supplied in buffer to the server for storing it inside the large object. The function can be called more than once to add subsequent parts of the content to the object. If it isn't a new or empty object, the existing data will be overwritten and truncated to the new size. It's not possible to update only parts of the content as some databases doesn't support to position the internal file position indicator. The lo parameter has to be the large object handle created and returned by odbx_lo_open() via its second parameter. It becomes invalid after it was supplied to odbx_lo_close() and this function will return an error in this case. The data which should be send to the server is read from buffer up to buflen bytes. Return Value odbx_lo_write() returns the number of bytes read from buffer and sent to the database server, which may be up to buflen bytes. It isn't guaranteed that the complete chunk was sent to the server, so the returned size may be less than the value in buflen. write to the large object successfully - - ODBX_ERR_HANDLE lois NULL or the supplied large object handle is invalid See Also odbx_lo_open(), odbx_lo_close()
https://www.mankier.com/3/odbx_lo_write
CC-MAIN-2018-17
refinedweb
230
59.23
Auto-Completing Code This section covers various techniques of context-aware code completion that allow you to speed up the coding process. Basic code completion. Completing names and keywords Basic code completion helps you complete names of classes, methods, and keywords within the visibility scope. When you invoke code completion, RubyMine analyses the context and suggests the choices that are reachable from the current caret position. Code completion covers supported and custom file types. However, RubyMine does not recognize the structure of custom file types and suggests completion options regardless of whether a specific type is appropriate in the current context. If basic code completion is applied to part of a parameter, or a variable declaration, RubyMine suggests a list of possible names depending on the item type. Invoking Basic code completion for the second time shows the list of all declared names. To use basic code completion - Start typing a name. - Press Ctrl+Space or choose Code | Completion | Basic from the main menu. - If necessary, press Ctrl+Space for the second time (this action produces the same effect as pressing Ctrl+Alt+Space). This shows the list of all declared names. To configure automatic code completion You can configure RubyMine. RubyMine supports Smart Type code completion for JavaScript code. tag names RubyMine automatically completes tags and attributes names and values in the following file types: - HTML/XHTML - XML/XSL If there is no schema association, RubyMine will use the file content (tag and attribute names and their values) to complete your input. In XML/XSL files, completion for taglibs and namespaces is available. Completing tag names - Press < and start typing the tag name. RubyMine displays the list of tag names appropriate in the current context. Use the ArrowUp and ArrowDown buttons to scroll through the list. - Press Enter to accept a selection from the list. RubyMine. RubyMine adds the declaration of the selected taglib: Importing a taglib declaration - Start typing a taglib prefix and press Alt+Insert. - Select a taglib from the list and press Enter. RubyMine. RubyMine.
https://www.jetbrains.com/help/ruby/2017.3/auto-completing-code.html
CC-MAIN-2018-34
refinedweb
339
64.71
Created 4 May 2011 Styling and skinning an application - Download the sample code and files (ZIP, 14.2 MB) - You can also view the full source code by right-clicking the Flex application and selecting View Source. Explanation This sample project shows you how to customize the appearance of an application using styling and skinning. To look at the code, right-click on the SWF in the browser and select View Source or download the sample files and view the source files in a text editor or follow the instructions to import the Flash Builder FXP. Multiple application versions are provided: an XML version that does not require a server as well as versions using Flash Remoting with PHP, Java, and ColdFusion servers. With styling, you set component styles inline in MXML (as you have already seen): <s:Label ... or preferably, in a style sheet using selectors (style rules). Each component has a limited number of styles defined for it. For example, for a Label you can set styles including font-size, font-family, and color. For a Button, you can also set a corner-radiusstyle. If you want to change the appearance of a component more drastically then possible with a component's styles, you need to create or edit the associated component skin—the file specifying what the component should look like. There are two families of components in the Flex framework: Spark and MX. The tags that start with s, such as <s:Button>are Flex 4 or later Spark components. The tags that start with mx, such as <mx:PieChart>are the older Flex components. You set the appearance of MX components primarily using styling. The newer Spark components have been re-architected to primarily use a skinning (rather than styling) model in which each component's associated skin file manages everything related to a component's appearance, including its graphics, its layout, and its states. To view the styles available for a component, look at the styles section of its API in ASDocs or look for the members with the blocks symbol in front of them in Flash Builder code-hinting. To include a style sheet, you use the Styletag. <fx:Style Look at the code inside this style sheet. You will see various CSS selectors defined. The first is the global selector whose styles will be applied to all components. global { font-family: Verdana; fontSize: 10; chrome-color: #7F7364; selection-color: #BFB59F; roll-over-color: #E5DFC3; focus-color: #7F7364; } In a style sheet, you can specify styles using camel case ( fontSize) or the more standard CSS hyphenated version ( font-size). In ActionScript and MXML, you have to use the camel case version because ActionScript variables cannot contain hyphens. Styles set more specifically for a component (either inline or using other CSS selectors we'll take a look at next) apply over values specified in the global selector. For example, the XYZ Label still uses a font-sizeof 20 that is set inline in its MXML tag instead of the value of 10 set here. Closer, or more specific style values take precedence. To apply style rules to only certain types of components, you use CSS type selectors. Here is a type selector for the Button component. @namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx"; s|Button { cornerRadius: 5; color:#FFFFFF; font-weight:bold; } Because there are two types of Button components, Spark and MX, a namespace must be declared and the selector must specify a namespace. These styles will automatically be applied to all Spark Button components and they will now all have rounded corners and bold, white text. To apply style rules to only components located in a particular relationship to other components, use CSS descendant selectors. Although not included in the style sheet for this application, here is an example for a style applied to Spark Buttons located within Spark HGroups. s|HGroup s|Button { cornerRadius: 5; color:#FFFFFF; font-weight:bold; } Spark components have multiple states. For example, a Spark Button component has disabled, down, over, and up states. A component's states are listed in the Skin States section of its API. You also saw in the previous samples how to define states for your own custom components. If you want a component to have different styles in different states, you use CSS pseudo selectors. Pseudo selectors are defined by using a colon after the selector name to reference the name of a state. Here is a pseudo selector that sets the label text to black (instead of white) for Button components in their disabled state. s|Button:disabled{ color:#000000; } To apply style rules selectively to only certain components, you use CSS class selectors. To define class selectors, you use a period in front of a custom name. Here is a class selector called navButton. In the code, deptPieCht_itemClickHandler()is called when the user clicks on a pie wedge. .navButton { fontSize: 12; } To apply this style to a component, you set its styleNameproperty to the name of the class selector. This style can be applied to any component. <s:Button id="empBtn" label="Employees" styleName="navButton" .../> Multiple class selectors can be applied by setting styleNameto a list of names separated by spaces. <s:Button If you only want this custom style to be applied to certain types of components, you can preface the selector with the component type. Here is a class selector called bigNavButtonthat can only be applied to Spark Button components. s|Button.bigNavButton{ fontSize: 14; } To apply a style rule to a single component, you use CSS ID selectors. To create an ID selector, you name the selector using a # in front of a component's id. Here is an ID selector: #xyz { color: #403029; fontSize: 20; fontWeight: bold; } for the xyzLabel control. <s:Label Note that the Label no longer has any inline styles set in the MXML tag as it did before. It is a best practice to set all your styles in a style sheet. This application has a toggle button to increase or decrease the size of text at runtime. <s:ToggleButton id="biggerBtn" label="Bigger" click="biggerBtn_clickHandler(event)" .../> The event handler contains code to increase or decrease the text size used in various parts of the application. You can’t change a style at runtime the same way you do a property because styles can be inherited by their children; changing a style's value may affect other components. These style relationships are managed by a StyleManager class. If you look at the Styles section of a component's API, you will see that each style lists its CSS Inheritance as either true or false. There are several ways to change styles dynamically at runtime. You can use a component's setStyle()method: xyz.setStyle("fontSize",24); ... or you can set its styleName property to the name of a different CSS class selector. empBtn.styleName="bigNavButton"; TIf you want to make changes to a style selector instead of making changes to a specific component, you can use the getStyleDeclaration()method of the StyleManager class and the setStyle()method. Every Flex component has a styleManagerproperty you can use to get a reference to the StyleManager class. In this code, the fontSizestyle of the global selector is increased to 12 pixels. this.styleManager.getStyleDeclaration("global").setStyle("fontSize",12); Here is the complete code for the ToggleButton click handler that uses these techniques to increase and decrease font sizes. protected function biggerBtn_clickHandler(event:MouseEvent):void{ if(biggerBtn.selected==true){ xyz.setStyle("fontSize",24); empBtn.styleName="bigNavButton"; this.styleManager.getStyleDeclaration("global").setStyle("fontSize",12); } else{ xyz.setStyle("fontSize",20); empBtn.styleName="navButton"; this.styleManager.getStyleDeclaration("global").setStyle("fontSize",10); } } The ToggleButton also has custom graphics that change to display a plus or minus sign when the button is clicked. We'll look at the code to accomplish this next. As mentioned previously, the new Spark components have been re-architected to primarily use a skinning (rather than styling) model in which each component's associated skin file manages everything related to a component's appearance, including its graphics, its layout, and its states. When you create a new skin class in Flash Builder (File > New > MXML Skin), you get a dialog box to choose a host component (what component the skin will be applied to) and the option to base the skin on an existing skin class. This makes it easy to create new skin classes. Within the skin class, you use tags for graphics classes located in the spark.primitives package (Rect, Line, Ellipse, Path, BitmapImage, and RectangularDropShadow ) to declaratively create the graphics. Instead of writing these tags, you can create the custom graphics using Fireworks CS4 or later, Illustrator CS4 or later, or Photoshop CS4 or later. You use the drawing tools in these products to create the graphics and then select a menu option to save or export the file as FXG, an XML-based graphics interchange format for the Flash Platform. You can then use the generated FXG file as a component in the skin class. The graphics for the ToggleButton in the application were created with Fireworks CS4 or later. The exported FXG files were saved as BiggerButton.fxg and SmallerButton.fxg. Here is the generated code for BiggerButton.fxg, which defines a filled circle and two crossed lines. <?xml version="1.0" encoding="UTF-8"?> <Graphic version="1.0" xmlns="" xmlns: <Group id="Page_1" fw: <Group id="State_1" fw: <Group id="Layer_1" fw: <Path winding="evenOdd" data="M 2 13 C 2 7 7 2 13 2 C 18 2 23 7 23 13 C 23 18 18 23 13 23 C 7 23 2 18 2 13 Z "> <fill> <SolidColor color="#bfb59f" alpha="1"/> </fill> <stroke> <SolidColorStroke color="#403029" weight="3"/> </stroke> </Path> <Path winding="evenOdd" data="M 13 6 L 13 18"> <stroke> <SolidColorStroke color="#403029" weight="2"/> </stroke> </Path> <Path winding="evenOdd" data="M 7 12 L 19 12"> <stroke> <SolidColorStroke color="#403029" weight="2"/> </stroke> </Path> </Group> </Group> </Group> </Graphic> Next, take a look at BiggerButtonSkin.mxml. The base code that specifies the host component and the states was automatically generated from options in the New MXML Skin wizard. The only code added was to create instances of the two classes generated by Fireworks, BigggerButton and SmallerButton located in the skins folder. The includeInproperty is used to specify in which states each graphics should be used. <?xml version="1.0" encoding="utf-8"?> <s:Skin xmlns: <fx:Metadata> [HostComponent("spark.components.Button")] </fx:Metadata> <s:states> <s:State <s:State <s:State <s:State <s:State <s:State <s:State <s:State </s:states> <skins:BiggerButton <skins:SmallerButton </s:Skin> To apply a skin class to a component, you set its skinClassstyle. In MXML, you can just set skinClassto the fully qualified class name of the class. <s:ToggleButton skinClass="skins.BiggerButtonSkin" .../> In a style sheet, you need to use the ClassReferencekeyword to denote you are setting this style to an ActionScript class. s|ToggleButton{ skinClass: ClassReference("skins.BiggerButtonSkin"); } The ToggleButton now shows the plus graphics when it is in one of its normal states and the minus graphics when it has been clicked and is in one of its selected states. This application uses a second skin class to skin the Application container, XYZSkin.mxml. In this skin class, the graphics for the skin are defined using spark.primitives graphics tags. The Rect class is used to create a white rectangle to fill the entire application by setting the top, bottom, left, and right constraint properties to 0. <s:Rect <s:fill> <s:SolidColor </s:fill> </s:Rect> A second Rect instance is used to create a smaller rectangle with rounded corners inside it with a brown stroke and a tan fill. This rectangle's stroke property is set equal to an instance of the SolidColorStroke class and the fill property to an instance of the SolidColor class. Additional stroke and fill classes can be found in the mx.graphics package. Constraint properties are set so the rectangle resizes with the browser window size—if the Flex application is set to resize, which it does by default unless you specify a height and width. It is drawn so that it is 30 pixels from three edges and 35 pixels from the top. <s:Rect <s:stroke> <s:SolidColorStroke </s:stroke> <s:fill> <s:SolidColor </s:fill> </s:Rect> When adding visual objects, the order of declaration in the MXML file determines the order the objects are added to the display list and hence to the drawing surface. In this case, the second rectangle appears on the top of the first because it is defined later in the code; it is added to the display list after the first rectangle. The next tag in the skin class is BitmapImage, another Spark primitive. It is used to fill a rectangular region with bitmap data drawn from a source file. <s:BitmapImage @Embedis a compiler directive used to tell the compiler to embed this graphics file into the application at compile time, not to load it at runtime. This code adds an employee icon in the upper right corner of the application on top of the rectangles. If you associated the skin with the Application and ran the application now, you would see the skin but nothing else, not the Label or the DataGrid—none of the contents of the application. This is because we have not yet specified in the skin where to add and position the contents that get added to the container. Many components are composites of other components. In the API, these subcomponents are listed under Skin Parts. For the Application class, two skin parts are listed: contentGroupand controlBarGroup, both of type Group. This means two Group containers with ID's of contentGroupand controlBarGroupare defined in the Application class as skin parts, and you can set their visual appearance and layout in a skin class. Our application does not have a control bar, so we just need to add the contentGroup, the Group object that the main content children get added to. The last and critical piece of code in the skin is to add this Group container with the name contentGroupand to specify where it should appear. This sets the position of the content within the skinned Application. You could also set the layout by changing and/or modifying the associated layout class and properties for this Group. <s:Group Lastly, the skin sets a minimum size for the skin so the Flex layout manager does not reduce it below this size. <s:Skin xmlns: The complete code for the skin class is included here: <?xml version="1.0" encoding="utf-8"?> <s:Skin xmlns: <fx:Metadata> [HostComponent("spark.components.Application")] </fx:Metadata> <s:states> <s:State <s:State <s:State <s:State </s:states> <!--white background--> <s:Rect <s:fill> <s:SolidColor </s:fill> </s:Rect> <!--brown border and tan fill--> <s:Rect <s:stroke> <s:SolidColorStroke </s:stroke> <s:fill> <s:SolidColor </s:fill> </s:Rect> <s:BitmapImage <s:Group </s:Skin> The skin is applied to the Application container in a style sheet or in the Appliationtag as shown here: <s:Application xmlns:fx="" skinClass="skins.XYZSkin" ...>
http://www.adobe.com/devnet/flex/training/examples/52_complex_app.html
CC-MAIN-2017-39
refinedweb
2,556
61.36
import "github.com/sqp/godock/libs/cdapplet/action" Package action provides actions management for applets. type Actions struct { Max int // Maximum number of concurrent actions (simultaneous). Current int // Current number of active actions. // contains filtered or unexported fields } Actions manages applet internal actions list. Add adds actions to the list. BuildMenu fills the menu with the given actions list. Callback returns a callback to the given action ID. CallbackInt returns a callback to the given action ID. CallbackMenu provides a fill menu callback with the given actions list. Count returns the number of started actions. ID finds the ID matching given action name. Launch starts the desired action by ID. Len returns the number of actions defined. SetBool sets the pointer to the boolean value for a checkentry menu field. SetIndicators set the pre and post action callbacks. SetMax sets the maximum number of actions that can be started at the same time. Package action imports 1 packages (graph) and is imported by 1 packages. Updated 2017-11-29. Refresh now. Tools for package owners.
https://godoc.org/github.com/sqp/godock/libs/cdapplet/action
CC-MAIN-2019-35
refinedweb
175
62.04
Note: This article is written using Visual Studio 2011 Preview and ASP.NET 4.5. Since these are preview versions, this article may change in the future. In my previous article, we explored the new model binding mechanism in ASP.NET 4.5 and how easy it is to perform CRUD operations using it. While developing Data driven applications, a common requirement is the Master-Details filtering. Typically in earlier versions of ASP.NET, to achieve this we needed to write business logic for reading filtered value from the ‘Parent’ DataBound controls and then query the source data and bind the resultant with the ‘child’ Databound control. In this article, we will explore the ASP.NET 4.5 Model binding Value provider and use of Model binding for filtering master-detail or also known as parent-child data . In ASP.NET 4.5, we are provided with the ‘System.Web.ModelBinding’ namespace. This namespace contains value provider classes e.g. ControlAttribute, QueryStringAttribute etc. These classed are inherited from ‘ValueProviderSourceAttribute’. This base class is used to define method parameters to specify source of values for model binding. The means that the parameter passed to the method specifies what value is to be taken for filtering records and what is the source of the value. This source may be Control, QueryString etc. Let’s get started. Make sure you have read the previous article
http://www.dotnetcurry.com/showarticle.aspx?ID=774
CC-MAIN-2014-42
refinedweb
232
59.3
23 March 2009 11:22 [Source: ICIS news] SINGAPORE (ICIS news)--BP Petronas Acetyls (BPPA) has been shutting its 535,000 tonne/year acetic acid plant at Kerteh, Trengganu, Malaysia, intermittently since mid-March due to supply issues with the feedstock carbon monoxide (CO), a company official said on Monday. “Our production has been affected intermittently by electrical trips at the upstream CO unit since mid-March,” the official said. “We are currently operating at reduced rates of 60-70% as operations at the CO unit have been kept at a safe level to prevent further trips.” Acetic acid operations could be interrupted again until the root cause of the problem at the CO plant has been determined and addressed, the source said. The official declined to reveal the output loss resulting from the intermittent shutdowns. BP Petronas Acetyls is a joint venture between BP and Petronas. Major acetic acid producers in ?xml:namespace> For more on acetic acid
http://www.icis.com/Articles/2009/03/23/9202265/bp-petronas-acetic-acid-unit-faces-intermittent-shutdowns.html
CC-MAIN-2015-06
refinedweb
159
60.75
Hello All, I appreciate if you guys could help me. Its been more than 2 months I am trying to figure out how to connect on MongoDB with password and SSL certificate, with out success. I am trying to authenticate on MongoDB using Tableu Mongo BI Connector but I am getting this error: I am using the Mongo DB Connector for BI 2.5 with this connection string to bind the port 3307: mongosqld.exe /auth /u admin /p password --mongo-uri=mongodb://mongodb:27017 /mongo-ssl /mongo-sslPEMKeyFile:C:\temp\mongodb.pem I am using the same SSL PEM key that is configured on MongoDB server. I am getting the following error on mongosqld log file: 2018-10-22T18:47:47.897+1100 I NETWORK [initandlisten] waiting for connections at 127.0.0.1:3307 2018-10-22T18:47:47.897+1100 I SAMPLER [schemaDiscovery] initializing schema 2018-10-22T18:47:47.935+1100 I SAMPLER [schemaDiscovery] sampling MongoDB for schema... 2018-10-22T18:47:47.936+1100 I SAMPLER [schemaDiscovery] no namespaces were sampled 2018-10-22T18:47:52.446+1100 I NETWORK [conn1] connection accepted from 127.0.0.1:57132 #1 (1 connection now open) 2018-10-22T18:47:52.446+1100 E NETWORK [conn1] handshake error: ERROR 1759 (HY000): ssl is required when using cleartext authentication 2018-10-22T18:47:52.447+1100 I NETWORK [conn1] end connection 127.0.0.1:57132 (0 connections now open) That is the connection throw Tableu MongoDB BI Connector option, I using the same SSL certificate of MongoDB server " mongodb.pem " That is my Mongodb environment: MongoDB server with authentication and SSL: I have configured the SSL on MongoDB server ---------------------------------------------------------------------------------------------------------------------------- # network interfaces net: port: 27017 bindIp: 0.0.0.0 ssl: mode: requireSSL PEMKeyFile: /etc/mongodb/ssl/mongodb.pem allowConnectionsWithoutCertificates: true allowInvalidCertificates: true security: authorization: enabled #operationProfiling: ---------------------------------------------------------------------------------------------------------------------------- Thank you in advance Diego Araujo I'd suggest that you start by removing Tableau from the picture. Could you try a couple of things? 1) Try setting up an ODBC connection. Since the MongoDB BI Connector uses the MySQL wire protocol, you'll need to install MySQL drivers if you do not already have them. I use MySQL ODBC 5.3 Unicode Driver. 2) Try connecting to the connector via MySQL Workbench. Once you've done these, can you report back with your results? Become a Viz Whiz on the Forums! Support the Community and master Tableau.
https://community.tableau.com/thread/285433
CC-MAIN-2019-04
refinedweb
407
59.5
Opened 8 years ago Closed 8 years ago #14015 closed enhancement (fixed) Affine and Euclidean groups Description (last modified by ) This ticket implements basic affine groups and Euclidean groups: sage: G = AffineGroup(3, QQ) sage: g = G.random_element(); g [ 2 -1/2 0] [ 0] x|-> [ 1 -1 -1] x + [-32] [ 0 -2 -2] [1/3] sage: g*g [ 7/2 -1/2 1/2] [ 16] x|-> [ 1 5/2 3] x + [ -1/3] [ -2 6 6] [191/3] sage: g*g.inverse() [1 0 0] [0] x|-> [0 1 0] x + [0] [0 0 1] [0] Apply: Attachments (2) Change History (10) Changed 8 years ago by comment:1 Changed 8 years ago by comment:2 Changed 8 years ago by - Dependencies set to #14040, #14014 - Status changed from needs_review to needs_work Changed 8 years ago by comment:3 Changed 8 years ago by - Description modified (diff) - Reviewers set to Travis Scrimshaw - Status changed from needs_work to needs_review Hey Volker, Here's a rebased version with my review changes. I've removed the need for the *_generic classes and made the docstrings be at the class level so that they are visible using introspection. I've also added a method to get the lifted matrix space (representation of affine transformations as linear transformations) as linear_space(), and made a few docstring tweaks. If you're happy with my changes, you can set this to positive review. Best, Travis For patchbot: Apply: trac_14015-affine_groups-ts.patch comment:4 Changed 8 years ago by The _generic suffix was there so that we can later also wrap GAP's affine groups (especially for finite fields) comment:5 Changed 8 years ago by You can have the GAP's affine groups and have the __classcall__() return that class (see sage.combinat.partition.Partitions or sage.combinat.tableau.Tableaux as more complete/complicated examples). IMO this is cleaner since the we the class doesn't have any extra qualifiers, the (single) entry point matches the (base) class, and the classes have the correct naming scheme. Thus it is still extendable. If the input format needs to be changed and exposed to the global namespace, you can implement a __classcall__() on the GAP wrapper parent (and likely the input will still need to standardized). comment:6 Changed 8 years ago by And you need some way to circumvent the enforced argument normalization for internal use where you know that the arguments don't have to be normalized. In terms of complexity / lines of code, I think its pretty much a draw. Which is to say, you end up using a lot of complicated machinery for no real advantage. And it gets even more complicated if you start deriving the class. And it breaks the symmetry between different implementations. If I had seen a real advantage with the __classcall__ mechanism then I would have used it myself. comment:7 Changed 8 years ago by - Milestone changed from sage-5.10 to sage-5.11 - Reviewers changed from Travis Scrimshaw to Travis Scrimshaw, Volker Braun - Status changed from needs_review to positive_review comment:8 Changed 8 years ago by - Merged in set to sage-5.11.beta1 - Resolution set to fixed - Status changed from positive_review to closed Initial patch
https://trac.sagemath.org/ticket/14015
CC-MAIN-2021-04
refinedweb
539
58.21
Introduction Databinding is the communication of dynamic data between view and model layer of your application. View represents template and model could be your business logic defined in the component. Databinding comprises of property and event binding. Components have templates and data is passed to the template in the form of static HTML code snippet. With databinding, you go one step further and pass dynamic data to the template. Your component could also listen to DOM events of your view and accordingly perform some action. There are different ways or approaches to databinding and we will see each of these in the following sections. Databinding can be achieved in any of the following ways: - String Interpolation – expression resolving to a string - Property Binding – binding data to the property of your HTML element - Event Binding – binding event to your HTML element - Two Way Databinding – binding both data and event through the use of ngModel The article assumes you have AngularJs 2 installed and appropriately configured to run the application. String Interpolation It is expressed using {{}} curly brackets. Between these brackets you provide an expression that resolves or evaluates to a string. Let’s write the code that demonstrates string interpolation: import { Component } from '@angular/core'; @Component({ selector: 'app-databinding', templateUrl: './databinding.component.html', styleUrls: ['./databinding.component.css'] }) export class DatabindingComponent { private myName = "Rajeev"; constructor() { } } The above Typescript class is a DataBindingComponent component class. This component simply contains a property named myName which holds the value as ‘Rajeev’. We want to display this value using string interpolation. The component has its own selector and a template file. The selector is a custom HTML element we will use to display the view rendered by this component. The template file databinding.component.html represents the view. It will have the following HTML code snippet: <h1> {{myName}} </h1> As you can see, here we are using string interpolation to the display the value of myName property. The property name is passed to {{}} curly bracket which takes it as an expression and resolves to a string. It also means the value of property myName is passed as a data to the template or view dynamically by the framework. Rendering this component should display the name ‘Rajeev’ Property Binding Let’s consider the same above component class. We will change the code in the template file databinding.component.html to demonstrate property binding: <input type="text" value="Rajeev" /> The above code is fairly straightforward. It just displays the input field with the value hard coded as ‘Rajeev’. Nothing great about it. Now lets remove the hard coding and use property binding instead. To use property binding, we have to define the property in square [] brackets. <input type="text" [value]="myName" /> The value attribute now has the enclosing square [] brackets. It means it is no longer a regular HTML attribute of the input element. But it is now a DOM value property which holds the value called ‘myName’. As you guessed it correctly, the expression inside the quotation mark is the property name we defined in our class component. It effectively means we bound the data or the value of the property ‘myName’ to the DOM value property. You should now see the value ‘Rajeev’ in the input field. Event Binding Let’s again change the template code in the databinding.component.html file to demonstrate event binding: <button (click)="onClick()">Click Me</button> The above code has a button element which has a native DOM click event enclosed with parentheses (). Upon clicking, it makes a call to the onClick() method. The onClick() method will be defined in our DataBindingComponent component class which will simply alert that it was clicked. Let’s change the code in our component to add the onClick() method. import { Component } from '@angular/core'; @Component({ selector: 'app-databinding', templateUrl: './databinding.component.html', styleUrls: ['./databinding.component.css'] }) export class DatabindingComponent { onClick() { alert("I am clicked"); } constructor() { } } This way we achieved what is called as event binding with the native DOM event. So far you have seen native DOM property and event binding. Going ahead with AngularJs 2 series, I will also demonstrate custom property and event binding in my next article. Two Way DataBinding Two way databinding seemed to be very popular at least with Angular 1.x but its not the case now. Its actually a bit performance overhead in using two way databinding and certainly not recommended unless there is a real need for it. But you can still have two way databinding if you love this feature. Let’s tweak our original DataBindingComponent component class. import { Component } from '@angular/core'; @Component({ selector: 'app-databinding', templateUrl: './databinding.component.html', styleUrls: ['./databinding.component.css'] }) export class DatabindingComponent { item = { name: "iPhone", qty: 100, amount: "$200" } constructor() { } } As you can see from the above code, we will create an Item object property that will have item name, quantity and amount. Now we will change the template file databinding.component.html to incorporate two input elements. Lets look at the code: <input type="text" [(ngModel)]="item.name" /> <br> <input type="text" [(ngModel)]="item.name" /> We have two input elements defined so that we can demonstrate the two way databinding feature. Each input element has a ngModel property enclosed with parentheses () and square brackets []. It means ngModel will act both as a property and event binding attribute. We will assign item.name model object property as a value. If you run the app, you will see changes made in one input field is reflected in another and vice versa. This is because changes to view is triggered as an event and the model object which is our component is updated and the moment it is updated it simultaneously reflected on the view. This is all with the magic of ngModel property.
http://techorgan.com/javascript-framework/angularjs-2-series-binding-the-data-with-databinding/
CC-MAIN-2017-26
refinedweb
963
56.45
Details Description Currently Flume guarantees only at least once semantics. This jira is meant to track exactly once semantics for Flume. My initial idea is to include uuid event ids on events at the original source (use a config to mark a source an original source) and identify destination sinks. At the destination sinks, use a unique ZK Znode to track the events. If once seen (and configured), pull the duplicate out. This might need some refactoring, but my belief is we can do this in a backward compatible way. Activity - All - Work Log - History - Activity - Transitions I would recommend thinking carefully about how to manage ZK's garbage. ZK can run happily for quite a while but then slows down dramatically unless given a clean-up. Yep, that is an important aspect of it. We need to come up with a way of handling that. One approach I can think of is to have a configurable period for which the event will not be duplicated. After this period, we go in and clean up older event uuids. Since duplication is primarily due to timeouts etc somewhere in the pipeline, once all agents in the pipeline are up, the event should reach HDFS sinks pretty quickly. Here is an initial stage algorithm I can think of: - Insert uuid at the first agent when the event is received (or when the event is created at the client SDK). - At the destination HDFS (presumably we should be able to support this in all sinks, including custom ones by abstracting this out into another library), at the time of take, do a create for FLUME/<uuid>. - If the create succeeds, this agent "owns" that event and writes it out to HDFS. - If the create fails, it means another agent will eventually write the event out - so drop the event. - After a configured time period for which we guarantee that the event will not duplicate, delete the path which was created (where to do this is a good question - presumably any agent should be able to do it). This algorithm seems to guarantee that an event will eventually be written since there is at least one agent that will not drop it, and barring hdfs reporting false failures (actually writing the events but throwing exceptions) and hdfs timeouts (due to which we don't know if the event really got written or not), this algorithm should not cause duplicates. Also, this algorithm assumes that an agent which dies will eventually come back up and will be able to access the old disk on which it held its file channel (this agent has to eventually come back up to write the event out - it does not matter when it comes back, but it needs to - this brings up the question of what happens if the agent comes back up and tries to write an event out because it took it but never committed the transaction - we need to handle the ownership case). Copying over the discussion from the dev@ list: Hi Arvind, Thanks for your reply. You are right in the fact the global state check and update to the sink will require each sink to explicitly support it. We can, of course have this implementation be in an abstract class which is inherited, but yes, this would also mean that there needs to be code changes. It makes sense to check state in the channels, pretty much the same way as in the sinks. What is a bit concerning is that we will need to do this check at every agent that the event passes through, and probably make some changes in the channel interface to get rid of race conditions (not sure if that is the case, but I think we will need to). Given that an event is likely to pass through 2-3 tiers, each event gets delayed by the time taken by that many ZK round-trips. I am open to this as well, especially considering that it is likely to be a better OOB experience for many users (the ones who have their own custom sinks). Would it suffice to check at the sinks at the terminal agent to make sure that an event gets written out only once? Thinking about this, having a once-only delivery at the channel level also opens up some possibilities with regards to being able to do some sort of processing on events. Having a guarantee of seeing an event exactly once allows us to do some event processing like counters etc. That seems like a good side effect to have. Either way, I am glad we agree on the aspect of checking a global state manager to verify that events are deduped. Thanks, Hari On Tuesday, August 27, 2013 at 2:12 PM, Arvind Prabhakar wrote: Hi Hari, Thanks for bringing this up for discussion. I think it will be tremendously beneficial to Flume users if we can extend once-only guarantee. Your initial suggestion seems reasonable of having a Sink trap the events and reference a global state to drop duplicates. Rather than pushing this functionality to Sinks is there any other way by which we can make it more generally available? The reason I raise this concern is because otherwise this becomes a feature of a particular sink and not every sink will have the necessary implementation opportunity to get this. Alternatively what do you think about this being done at the channel level? Since we normally do not see custom implementations of channels, an implementation that works with the channel will likely be more useful for the broader community of Flume users. Regards, Arvidn On Sun, Aug 25, 2013 at 9:07 AM, Hari Shreedharan <hshreedharan@cloudera.com wrote: Hi Gabriel, Thanks for your input. The part where we use replicating channel selector to purposefully replicate - we can easily make it configurable whether to delete deplicate events or not. That should not be difficult to do. The 2nd point where multiple agents/sinks could write the same event can be solved by namespacing the events into different namespaces. So each sink checks one namespace for the event, and multiple sinks can belong to the same namespace - this way, if multiple events are going to write to the same HDFS cluster, then if a duplicate occurs we can easily drop it. Unfortunately, this also does not work around the who HDFS-writing-but-throwing issue. I agree updating ZK will hit latency, but that is the cost to build once only semantics on a highly flexible system. If you look at the algorithm, we actually go to ZK only once per event (to create, there are no updates) - this can even happen per batch if needed to reduce ZK round trips (though I am not sure if ZK provides a batch API). The two phase commit approach sounds good, but it might require interface changes which can now only be made in Flume 2.x. Alse, if we use a single UUID combined with several flags we might be able to work duplicates caused by this replication. Thanks, Hari On Sunday, August 25, 2013 at 7:24 AM, Gabriel Commeau wrote: Hi Hari, I deleted my comment (again). The mailing list is probably a better avenue to discuss this sorry about that! I can find at least one other way duplicate events can occur, and so what I provided helps to reduce duplicate events but is not sufficient to guaranty exactly once semantics. However, I still think that using a 2-phase commit when writing to multiple channels would benefit Flume. This should probably be a different ticket though. Concerning the algorithm you offered, the case of replicating channel selector should probably be handled, by creating a new UUID for each duplicate message. I hope this helps. Regards, Gabriel (continuing the discussion here instead of email) Thanks Hari. In the spirit of keeping processing components pluggable, it would make sense to have this de-dupe logic pluggable itself. One benefit of doing so would be the choice of different implementations that could provide broader degree of guarantees. For example, the ZK based approach over the enter pipeline could provide complete once-only delivery guarantee but as you pointed out could add latency to delivery. Alternatively there could be locally optimized implementation of this approach that act on subsets of the event stream and thus benefit partitioned deployments where events cannot cross wires. Another use-case to consider would be to locally optimize for multiple channels within the same Agent. That way an Agent that has a File Channel setup as the primary channel and a Memory Channel setup as a fall-back channel in case the primary is full - would need local deduping without having to store state in ZK. Yep, that is what I was thinking about. I was planning to keep these as interfaces which are pluggable, and having no requirement of once-only can easily be done by implementing a pass through dedupe logic. Local dedupe can easily be implemented and we can simply suggest that users configure a ZK based dedupe at the final channel(s). This allows low latency, and local dedupe too. This brings me to another point - having local dedupe can actually allow for some interesting stuff. We could use local dedupes to allow for once only processing of events entering an agent. Putting in a once-only guarantee allows for being able to do some interesting processing on events. For example, if we know that events will always arrive only once (even if there are multiple channels), we could use that to make "accurate" counts of events/event-types. In fact, if we are able to somehow do some processing on the sink side (after dedupe), we could do some simple event processing while still moving the events through. I am thinking whether it makes sense to do something like allowing sinks/sink-based new component to do some processing on events picked up from the channel, and then allow it to write events out to a channel. This sort of creates a workflow that could look like this: AvroSource->Channel->Sink->Channel->Sink->Channel->HDFS. This allows for rolling back some failed processing without losing data (assuming the sink actually duplicates data and does not modify based on references returned by a memory channel). This is sort of how classical processing systems work (with processing code, separated by queues). Allowing the sinks to pull from multiple channels would even allow us to do cartesian product like processing too - like pseudo-joins. Doing this, combined with once-only delivery would allow us to quite reliably do some simple event processing (I agree, the definition of "simple" is different for different people). Thoughts? Hi Hari & team, May I suggest the following idea: instead of assigning a UUID to the events, which I assume would be arbitrary if not random, what about enforcing ordering of events? Each "ingest" agent/client (i.e. first tier) would have a unique identifier (e.g. a random UUID , or host name + agent name), and a local counter, which would increment for every event generated/ingested by that agent. Consequently, each event has an "ingest" ID and a counter value. In ZooKeeper, instead of having a long list of UUID for the events recently gone once, we'd only have as many Z-nodes as ingest agents/clients (let it be N), which contain the highest counter value of events successfully passed through from the corresponding ingest agent/client. If an event has successfully been processed (i.e. the first time), the dedup channel increments the ZK counter to the counter value of that event. If the ZK counter is equal or greater than the counter value of the event, it's a duplicate. The advantage is that a batch of M events successfully processed can be acknowledged in k <= N ZooKeeper operations, and not in M - usually much larger than N. The inconvenient is that if some events get stuck in process, the dedup channels will be waiting on them, and so we'd need a way to resend these events - and therefore, a channel seems like the appropriate place to do that. The "ingest" channel can clear the events that have a counter value below the ZK counter, as they have successfully been through once. On another note, what about grouping the dedup channels for exactly-once-semantics? We would define a namespace for this group of channels, and would guaranty that the events come exactly once in that group of channels; but it could come twice in 2 distinct groups of channels - say one that goes to HDFS and one to HBase for instance. The ZK structure detailed above can be duplicated for each namespace (which would be a parent Z-node); and in order to clear the events, the "ingest" channel needs to check all existing namespaces. I hope this helps. There are cases which we'd have to handle - like what happens if update to ZK fails or if the agent dies before ZK is updated, but after the transaction is committed to the channel.
https://issues.apache.org/jira/browse/FLUME-2173
CC-MAIN-2016-30
refinedweb
2,201
65.66
The QWebView class provides a widget that is used to view and edit web documents. More... #include <QWebView> Inherits QWidget. This class was introduced in Qt 4.4. the Trolltech();. QWebView consists of other objects such as QWebFrame and QWebPage. The flowchart below shows these elements are related. and Browser. This property holds the icon associated with the web page currently viewed. By default, this property contains a null icon. Access functions: text currently selected. By default, this property contains an empty string. Access functions: See also findText() and selectionChanged().(). This property holds the zoom factor for the view. This property was introduced in Qt 4.5. Access functions: Constructs an empty QWebView with parent parent. See also load(). Destroys the web view. Convenience slot that loads the previous document in the list of documents built by navigating links. Does nothing if there is no previous document. It is equivalent to view->page()->triggerPagePageAction(QWebPage::GoForward); See also back() and pageAction(). Returns a pointer to the view's history of navigated web pages. It is equivalent to view->page()->history(); This signal is emitted whenever the icon of the page is loaded or changes. See also icon().().(). view. The parent QObject of the provided page remains the owner of the object. If the current document is a child of the web view, it will be deleted. See also page(). Sets the value of the multiplier used to scale the text in a Web page to the factor specified. See also textSizeMultiplier().PageAction(QWebPage::Stop); See also reload(), pageAction(), and loadFinished(). Returns the value of the multiplier used to scale the text in a Web page. See also setTextSizeMultiplier().().
http://doc.trolltech.com/main-snapshot/qwebview.html
crawl-002
refinedweb
278
53.68
The Java Do While loop will test the given condition at the end of the loop. So, Java Do While loop executes the statements inside the code block at least once even if the given condition Fails. The While Loop tests the condition before entering into the code block. If the condition is True, then only statements inside it will be executed. Otherwise, statements will not execute at least once. There are some situations where it is necessary to perform some operations (execute some statements) first, and then check for the condition. In these cases, we can go for Java Do While loop. Java Do While loop Syntax The syntax of Do While Loop in Java Programming language is as follows: do { statement 1; statement 2; …………. statement n; } While (condition); First, it will execute the statements inside curly brackets, and then after reaching the end, it will check the condition inside the while. If the condition is True, then it will repeat the process. If the condition fails, then Java Do While Loop will be terminated. NOTE: We have to place semi-colon after the While condition. Java Do While Loop Flow Chart The flow chart behind the Java Do While Loop Java do while loop Flow chart sequence is: - First, we initialize our variables. Next, it will enter into the Do While loop. - It will execute the group of statements inside it. - Next, we have to use Increment & Decrement Operator inside the Java do while loop to increment or decrements the value. Please refer to Increment and Decrement Operators article in Java to understand increment and decrement operator. - Now it will check for the condition. If the condition is True, then the statements within the Java Do while loop will execute again. It will continue the process as long as the condition is True. - If the condition is False, then it will exit from it. Java Do While Loop example This program helps us to understand the Do While Loop in Java. This Java program allows the user to enter an integer value below 10. By using this value, the Javac compiler will add those values up to 10. // Java Do While Loop example package Loops; import java.util.Scanner; public class DoWhileLoop { private static Scanner sc; public static void main(String[] args) { int number, sum = 0; sc = new Scanner(System.in); System.out.println("\n Please Enter the any integer Value below 10: "); number = sc.nextInt(); do { sum = sum + number; number--; } while (number > 0); System.out.format(" Sum of the Numbers From the While Loop is: %d ", sum); } } OUTPUT: We are going to enter number = 4. It means, total = 4 + 3 + 2 + 1 = 10 Within this Java example, we used the Do While loop. The Condition inside the While (number > 0) will make sure that the number is greater than 0. In this example, User Entered value: Number = 4, and we initialized the sum = 0 First Iteration sum = sum + number sum = 0 + 4 ==> 4 Next, the number will be decremented by 1 (number –). Next, the condition inside the while is True or Not. Here, 3 > 0 is True Second Iteration: Within the first Iteration, the values of both Number and sum changed as Number = 3 and sum = 4 sum = 4 + 3 ==> 7 After the decrement (number –), check the While Loop condition. Here, 2 > 0 is True Third Iteration Within the Second Iteration of Java Do While Loop, the values of both changed as Number = 2 and sum = 7 sum = 7 + 2 ==> 9 After the decrement, the condition (1 > 0) is True Fourth Iteration After the third Iteration, Number = 1 and sum = 9 sum = 9 + 1 ==> 10 Next, the number will be decremented by 1 (number –). Next, the condition inside the while is True or Not. Here, 0 > 0 is False. Last System.out.format statement in the do while loop example will print the number of digits present in the given number as output. Infinite Do While Loop in Java If you forgot to increment or decrement the value inside the Java do while loop, then it will execute infinite times (also called as an infinite loop). For example: // Infinite Do While Loop in Java Programming example package Loops; public class InfiniteDoWhile { public static void main(String[] args) { int number = 1; do { System.out.format("%d \n", number); }while (number <= 10); } } 1 1 1 1 1 1 ... ... ... Here, in this Java do while loop, the number is always 1, and the number is always less than 10. So, it will go on execute the statements infinite times. Now, let us add an increment operator (number++) inside the. iteration to the above example. // Infinite Do While Loop in Java Programming example package Loops; public class InfiniteDoWhile { public static void main(String[] args) { int number = 1; do { System.out.format("%d \n", number); number++; }while (number <= 10); } } Now, when it reaches 10, the condition will fail. Let us see the output of this program. 1 2 3 4 5 6 7 8 9 10
https://www.tutorialgateway.org/java-do-while-loop/
CC-MAIN-2022-05
refinedweb
834
63.09
This is your resource to discuss support topics with your peers, and learn from each other. 10-29-2012 12:05 AM I'm trying to use the SimCardInfo to get mcc & mnc of the sim card and here's what I have tried: 1. Added to main.cpp #include <bb/device/SimCardInfo> use namespace bb::device; 2. Added to *.pro file LIBS += -lbbdevice 3. Add permission read_cellular_data in bar-descriptor.xml <!-- Request permission to execute native code. Required for native applications. --> <permission system="true">run_native</permission> <permission>read_cellular_data</permission> <env var="LD_LIBRARY_PATH" value="app/native/lib:/usr/lib/qt4/lib"/> 4. A line of code to get MCC in the main method QString mcc = SimCardInfo().mobileCountryCode(); Results: Application compiled and running. Value of mcc is "". So am I missing something in the code or project setting? Or is it the SIM card in the simulator always blank? If so how can i configure the simulator to give me a mock environment? 11-15-2012 12:52 PM
https://supportforums.blackberry.com/t5/Native-Development/How-do-i-use-SimCardInfo-in-Cascades-API-with-simulator/m-p/1967243
CC-MAIN-2017-13
refinedweb
168
54.08
Inflatable Boats Dinghies Rescue Canoes - New Zealandprice: contact company for price design inflatables, high speed Thundercats, inflatable canoes, rescue boats, etc. We DO NOT import from China and resell. We manufacture our boats from scratch using very high marine grade quality Hypalon/PVC. We import our raw material when required from Germany. Our boats are very high quality and built in our very own plant in Auckland, New Zealand. Check out our website and try us out. Blessings Santosh Chandran Inflatable Boats Dinghies Rescue Canoes For any questions and needs please contact us below Company Contact: - Posted By: Elyon Distributors - Phone: 6498375537 - Address: 15A, James Laurie Street, Auckland, New Zealand - Website: Published date: September 7, 2012 - - Business Description: involved in international trade import export of goods, products, and services Si... - 30 07m Patrol BoatBoats - New - Guangdong Jianglong Shipbuilding Co., Ltd. - China - September 7, 2012 - contact company for price 30.07m Patrol Boat, Work Boat Material: FRP (Fiber Reinforced Plastics) L. O. A.: 30.07m Beam: 5.70m Depth: 2.90m Draft: 1.50m Crews: 12 persons Displacement: 88t Engine: 2*788KW Speed: 20 knot Endurance: 1200 nautical miles Navigation zone:"
http://www.worldbid.com/marine/boats-new/inflatable-boats-dinghies-rescue-canoes-i44653.html
CC-MAIN-2017-09
refinedweb
190
58.18
C# is a multi-paradigm programming language which has object oriented, component oriented, imperative and functional program features. It is specifically designed by Microsoft for the Common Language Infrastructure. The language is built on the syntax and semantics of the C++ programming language. The goal of C# is to be a simple, modern, general-purpose, object oriented programming language. It forms an important component of Microsoft’s .NET Framework. You can learn more about C# and the .NET framework in this course. In this tutorial, we’ll walk you through the various aspects of opening and reading a file in C#. We assume that you know the basics of programming. If not, you may want to start with this special C# course, which starts from the basics, and requires no prior programming experience. C# I/O Classes A file is a collection of data stored in a disk having a specific name and a directory path. In C#, the System.IO classes are used to handle all file operations – including creating or opening a file, deleting or closing a file a file, and also reading from or writing to a file. Note that when a particular file is opened for reading or writing, it becomes a stream. In other words the stream is the sequence of bytes passing through the specified communication path. In a nutshell, the input stream is used for reading data from file while the output stream is used for writing into the file. The most common System.IO classes used to handle files are - File: This is kind of the file handle or file name. It used to refer to the file and manipulate it. - FileInfo: This is used to perform any actual operations on the file. - FileStream: This is used for read or write operations on the file. There are also other classes that handle directories, binary byte streams, special string usage and even random memory access. To learn more about these you can check out this C# course. With this introduction to the IO class and FileStreams, let’s now see how they are actually used to open and access a file. C# FileStreams & how to open a file Like we mentioned above, the FileStream class is what’s used to access files. You need to create a new FileStream to create a new file or open an existing one. Here’s the syntax FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>) Let’s take a simple example to see how to use it FileStream myFileStream = new FileStream("myFile.txt", FileMode.Open, FileAccess.Read, FileShare.Read); While opening a file in this manner, you have to specify the mode you want to open it in (via the FileMode parameter), the access you want it to have (via the FileAccess parameter) and whether you want to share it. Notice that we’ve specified the FileMode as Open. The FileMode enumerator defines various options while opening files. Here’s the options you can choose - Open: This opens an existing file. - OpenOrCreate: This specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. - Append: This opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. - Create: This creates a new file. - CreateNew: This specifies to the operating system, that it should create a new file. - Truncate: This opens an existing file and truncates its size to zero bytes. FileAccess enumerators are simpler and have just the following options: Read, ReadWrite and Write. FileShare enumerators have the following options - Read: This allows opening the file for reading - ReadWrite: This allows opening the file for reading and writing - Write: This allows opening the file for writing - Inheritable: This allows a file handle to pass inheritance to the child processes - None: This declines sharing of the current file File.Open Method (String, FileMode) Once you actually have the FileStream, you can finally open the file with the simple Open function. This function is present in the System.IO namespace. Here’s the syntax public static FileStream Open( string path, FileMode mode ) Note that the function has two parameters and one variable value is returned. The function is declared as public. The public keyword is an access specifier which indicates that the function can be accessed from anywhere. The static modifier is used to declare a static member, which belongs to the type itself instead of a specific object. The path variable is of type System.String and indicates which file to open. The mode variable is of type System.IO.FileMode. The value determines whether a file is created in case of non existing file. Also determines whether the contents of the files present are retained or overwritten. The return value is of type System.IO.FileStream. To learn more about how to write your own code with files, with practical examples, you can take this beginners tutorial on C#. Now let’s see how it all comes together to open a file with following program, where we open a file, put some data into it, and then read the data back (detailed explanation after the program). using System; using System.IO; using System.Text; class NewTest { public static void Main() { string newpath = Path.GetTempFileName(); using (FileStream fs = File.Open(newpath, FileMode.Open, FileAccess.Write, FileShare.None)) { Byte[]newinfo = new UTF8Encoding(true).GetBytes("This is some text in the file."); fs.Write(newinfo, 0, newinfo.Length); } using (FileStream fs = File.Open(newpath, FileMode.Open)) { byte[] b1 = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b1,0,b1.Length) > 0) { Console.WriteLine(temp.GetString(b1)); } } } } At the beginning of the program, the ‘using’ operator includes the namespaces (System, System.IO and System. Text) in the code. In other words the program can now use any of the classes present in those namespaces.The variable newtest is declared to be of type class. Now it can contain variables and functions. The main function is the place where the execution of the program starts. The C# Path.GetTempFileName function creates a uniquely named, zero-byte temporary file on the disk and returns the full path of that file. FileMode.Open opens an existing file. FileShare.None declines sharing of the current file. UTF8Encoding is a specific method to handle text that may be in UTF8 encoding. The ‘UTF8Encoding’ function puts the text into a Byte array called ‘newinfo’. The read and write file functions are used to write info into the file and read info from the file respectively. The read operation terminates when the file ends. While writing your own programs, you need to be careful of the parameters you pass to the File Open function. If you pass invalid parameters, ou may get an Exception. The most common exceptions thrown by File Open function are - ArgumentException - ArgumentNullException - PathTooLongException - DirectoryNotFoundException - IOException - ArgumentOutOfRangeException - UnauthorizedAccessException - FileNotFoundException - NotSupportedException The best way to learn to program – is to try it out for yourself. So go ahead and try these examples, and come up with some more of your own. It’s okay if you get a few exceptions in your initial programs. If you need more in depth help on C#, feel free to jump over to our Live Lessons on C# Fundamentals (Part I and Part II)
https://blog.udemy.com/c-sharp-file-open/
CC-MAIN-2017-13
refinedweb
1,231
65.62
Currently I’m working on the book chapter explaining how Angular 2 communicates with the servers. An easy approach would be to use for the data feed a public RESTful API of one of servers (Youtube or something), but I wanted to have my own locally installed server. Using one of the Java servers would be an easiest choice for me, but this would limit the readership to only those who know Java. Can’t do. Let’s stick to JavaScript. Opps, I meant to say TypeScript. Actually what I really meant was using Node.js on the server with the TypeScript. Disclaimer: I’ve been using Node as a runtime for a while, but I’m very new to developing with Node.js framework. After this disclaimer about 50% of the readers should have abandoned this page. Since you’re not one of them, let’s learn together how to start using the Node framework with TypeScript. Creating a Web Server with Node and TypeScript Node.js (a.k.a. Node) allows you to create standalone applications in JavaScript. Node does a great job in the area of communications using HTTP or WebSockets, so let’s start with creating a simple Web server. I assume that you already have both Node and TypeScript compiler installed on your computer, otherwise do it now. We’ll start with creating a standalone Node application implementing the server-side tier of our mini project. In this blog we’re no going to write the Angular client, but if we would our project’s directory could have the following structure: To stay IDE-agnostic lets open a command prompt and create a directory named http_sample with the subdirectory server and configure a new Node project there by running the following command: npm init -y This will create a small npm configuration file package.json with default settings. Now let’s create a file hello_server.ts with the following content: import * as http from 'http'; // 1 const server = http.createServer((request, response)=> { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World!\n'); }); const port = 8000; server.listen(port); // 2 console.log('Listening on:' + port); 1. This code loads the Node’s module using the ES6 syntax “import * as” supported by TypeScript as well. Note that we use const instead of var here. 2. The listen() function is what makes this program run infinitely. Every client’s request will get a response with HTTP code 200 and the text Hello World! The above code need to be transpiled and we’ll create the file tsconfig.json in the project directory to configure the tsc compiler: { "version": "1.7.5", "compilerOptions": { "target": "es5", "module": "commonjs", // 1 "emitDecoratorMetadata": true, "experimentalDecorators": true, "outDir": "build" // 2 }, "exclude": [ "node_modules", // 3 "client" // 4 ] } 1. This will instruct the TypeScript compiler tsc to transpile modules according to the CommonJS spec. In our example the transpiler will convert the import statement import * as http from 'http'; into this: var http = require('http'); 2. The transpiler will put the .js files into the directory build 3. Don’t transpile code located in the directory node_modules that contains the project dependencies 4. When you create the directory client for the Angular (or other) app, but we don’t want to transpile the client’s code because the SystemJS loader will do it on the fly. NOTE: If you decide to copy the content of tsconfig from the listing above, remove the comments as they are not supported in JSON format. I used them here only to provide the code notes with explanations. After running the tsc command the transpiled file hello_server.js will be saved in the build directory and we can start our Web server: node build/hello_server.js Node start the JavaScript engine V8, which in turn will run the script from hello-server.js, which creates a Web server and prints a message “Listening on: 8000”. Open your browser at this URL, and you’ll see a Web page with the text Hello World! NOTE: In your IDE, to get context-sensitive help and the compile-type error check, install the type definition file for Node using the TypeScript Definition Manager tsd (install it first) by running the command tsd install node, which will create the directory typings in your project that will contain the file node.d.ts. In this blog I still use tsd, but it’s in a process of being deprecated in favor of another tool called Typings. Creating a Web Server to Serve JSON Data Now let’s teach our Node Web server to serve JSON data. To send JSON to the browser you need to modify the header to specify the MIME type to be application/json. The following code snippet shows what it takes to send a JSON object: const server = http.createServer((request, response) => { response.writeHead(200, {'Content-Type': 'application/json'}); response.end('{"message": "Hello Json!"}\n');}); While the above code sample suffices as an illustration of how to send a JSON data, real world applications require more functionality on the server side, e.g. reading files, routing based on the provided path, handling various HTTP requests based on the method (GET, POST et al). For our auction example we’ll need to respond with either products or reviews data based on the request. To minimize manual coding we’ll install Express, which is a Node framework. I won’t be using all of the functionality of Express for a simple reason: I don’t know Express. Actually, I should have said, “I’m not an Express expert”, but let’s be honest here. Express will help with creating a RESTful Web service that will send the appropriate JSON file based on the client’s request. To install Express we’ll run the following command from the project directory: npm install express –save This will download Express into the node_modules folder of our project and will update the dependencies section in package.json. To install Express type definition files in the typings directory run the following command: tsd install express Now we can import Express into our application and start using its API. Let’s assume that we want to create a couple of endpoints to serve the product information and reviews. Below is the code of the file my-express-server.ts that shows how you can implement routing based on the URL for the HTTP method GET: import * as express from 'express'; const app = express(); // 1 app.get('/', (req, res) => res.send('Hello from Express')); // 2 . app.get('/products', (req, res) => res.send('Got a request for products')); // 2 app.get('/reviews', (req, res) => res.send('Got a request for reviews')); // 2 const server = app.listen(8000, "localhost", () => { // 3 const {address, port} = server.address(); // 4 console.log('Listening on:' + port); }); 1. Create an object that denotes the Express application. 2. In the above example we’ve illustrated routing only for the GET requests using the method get(), but Express supports all methods required for handling HTTP requests and responses. You can find the declarations (with types) of all of them in the file express.d.ts. 3. Start listening on the port 8000 at the address localhost and execute the code provided in the fat arrow function. 4. We use the destructuring syntax to automatically extract the values of the properties address and port. In the ES5 syntax we’d need to write two lines instead of one: var address = server.address().address; var port = server.address().port; If you transpile the code and start this server (node my-express-server.js), you’ll be able to request either products or services depending on which URL you enter as shown below. Live TypeScript Recompilation and Code Reload Since we write our examples in TypeScript, we need to use tsc to transpile and deploy JavaScript in Node. The TypeScript compiler has the compilation option -w that runs tsc in the watch mode so whenever a TypeScript file changes it gets recompiled automatically. To set the auto-compilation mode for our code we’ll open a separate command window in the directory with the sources and run the following command: tsc -w When no files to compiled are specified, tsc will get the options for compilation from the file tsconfig.json. Now whenever you make a change in the TypeScript code and save the file it’ll generate the corresponding .js file. Accordingly, to start our Web server with Node you can use the following command: node my-express-server.js Live recompilation of the TypeScript code helps, but the Node server won’t automatically pick up code changes after it started. You’d need to manually restart the Node server to see your code changes in action unless you’ll use a handy utility Nodemon that will monitor for any changes in your source and automatically restart your server and reload the code. You can install Nodemon either globally or locally. For global install using the following command: npm install -g nodemon The following command will start our server in a monitoring mode: nodemon my-express-server.js If you want to get fancy, install Nodemon locally (npm install nodemon –save-dev) and introduce npm scripts in your package.json file: “scripts": { "start": "node my-express-server.js", "dev": "nodemon my-express-server.js" }, "devDependencies": { "nodemon": "^1.8.1" } Now you’ll be starting the server as npm run dev in the development mode (auto restart/reload) or npm start in production (no restart/reload). 8 thoughts on “Setting up the Environment for Node.js and TypeScript” The book looks great by the way! Will look out for its completion. The fact that javascript is in every browser is making it more and more apparent that node is going to keep gaining momentum unless something like web assembly comes in the picture soon. Yakov, I think you missed one step in the middle of this article: “npm install tsd -g”, otherwise “tsd install express” won’t work. Is it mandatory to install Node to install/configure Angular[1] ? I think, useful, but not mandatory (for having Npm), correct? Also how to develop Angular[1] apps with TypeScript? Is there a good reference on that? You need npm which comes with Node. Yes, you need tsd installed, thanks. You’ll find all other answers here: I’m trying to follow this tutorial but when I run tsc I run in an error. Searching on google hasn’t helped yet. I have the directory layout as in the tutorial, and both package.json and tsconfig.json files with the same contents as in the tutorial. tsc version is 1.7.5; npm is 2.14.12 and node is 4.3.1 The error goes : $ tsc /usr/lib/node_modules/typescript/lib/tsc.js:31084 var jsonOptions = json[“compilerOptions”]; ^ TypeError: Cannot read property ‘compilerOptions’ of undefined at getCompilerOptions (/usr/lib/node_modules/typescript/lib/tsc.js:31084:35) at Object.parseJsonConfigFileContent (/usr/lib/node_modules/typescript/lib/tsc.js:31074:22) at parseConfigFile (/usr/lib/node_modules/typescript/lib/tsc.js:31351:40) at performCompilation (/usr/lib/node_modules/typescript/lib/tsc.js:31362:45) at Object.executeCommandLine (/usr/lib/node_modules/typescript/lib/tsc.js:31336:9) at Object. (/usr/lib/node_modules/typescript/lib/tsc.js:31635:4) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) Seems like your tsc compiler can’t locate tsconfig where the compiler’s options are. See this: The problem is the comments. I copied the tsconfig.json exactly as you wrote it in the tutorial, comments included, and it turns out that tsc can’t parse the json, this json is undefined. I subùitted a ticket on github because I think there should be a better error message for that.
https://yakovfain.com/2015/12/22/setting-up-the-environment-for-node-js-and-typescript/
CC-MAIN-2018-13
refinedweb
1,990
57.87
On Thu, 17 Jun 2004, Dave S wrote: > Terry Carroll wrote: > > >I use Randy Pargman's progress bar from > > ; I find it > >does the job nicely. > > > > > I will combine this class with backspacing to hopefully produce a static > line with a dynamic progress bar ! Don't sweat the backspacing. Look at the examples on that web page. The line printing the progress bar string looks like this: print prog, "\r", This prints the string named prog, which is your progress-bar, followed by a return ("\r"), which sets up the curser back to column 1, no backspacing needed. Then the newline that's normallt added to a printed statement is supressed, due to the trailing comma. That's one thing I like about this progress bar; you just print it, and that's it, no counting, no backspacing, none of that. Just remember when you're done to do that final bare "print" statement, because otherwise you'll still be poised at the beginning of the line for your next print statement, and your line will look messy, with a progress bar partially overwritten by your next print.
https://mail.python.org/pipermail/tutor/2004-June/030103.html
CC-MAIN-2017-04
refinedweb
188
74.02
5. Remote GPIO Recipes¶ The following recipes demonstrate some of the capabilities of the remote GPIO feature of the GPIO Zero library. Before you start following these examples, please read up on preparing your Pi and your host PC to work with Configuring Remote GPIO. Please note that all recipes are written assuming Python 3. Recipes may work under Python 2, but no guarantees! 5.3. Multi-room motion alert¶ Install a Raspberry Pi with a MotionSensor in each room of your house, and have an class:LED indicator showing when there’s motion in each room: from gpiozero import LEDBoard, MotionSensor from gpiozero.pins.pigpio import PiGPIOFactory from gpiozero.tools import zip_values from signal import pause ips = ['192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6'] remotes = [PiGPIOFactory(host=ip) for ip in ips] leds = LEDBoard(2, 3, 4, 5) # leds on this pi sensors = [MotionSensor(17, pin_factory=r) for r in remotes] # remote sensors leds.source = zip_values(*sensors) pause() 5.4. Multi-room doorbell¶ Install a Raspberry Pi with a Buzzer attached in each room you want to hear the doorbell, and use a push Button as the doorbell: from gpiozero import LEDBoard, MotionSensor from gpiozero.pins.pigpio import PiGPIOFactory from signal import pause ips = ['192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6'] remotes = [PiGPIOFactory(host=ip) for ip in ips] button = Button(17) # button on this pi buzzers = [Buzzer(pin, pin_factory=r) for r in remotes] # buzzers on remote pins for buzzer in buzzers: buzzer.source = button pause() This could also be used as an internal doorbell (tell people it’s time for dinner from the kitchen). 5.6. Light sensor + Sense HAT¶ The Sense HAT (not supported by GPIO Zero) includes temperature, humidity and pressure sensors, but no light sensor. Remote GPIO allows an external LightSensor to be used as well. The Sense HAT LED display can be used to show different colours according to the light levels: from gpiozero import LightSensor from gpiozero.pins.pigpio import PiGPIOFactory from sense_hat import SenseHat remote_factory = PiGPIOFactory(host='192.168.1.4') light = LightSensor(4, pin_factory=remote_factory) # remote motion sensor sense = SenseHat() # local sense hat blue = (0, 0, 255) yellow = (255, 255, 0) while True: if light.value > 0.5: sense.clear(yellow) else: sense.clear(blue) Note that in this case, the Sense HAT code must be run locally, and the GPIO remotely.
https://gpiozero.readthedocs.io/en/master/recipes_remote_gpio.html
CC-MAIN-2020-24
refinedweb
410
53.92
basic framework using an MVC design. you can use it locally or create your own project and import the files. an example is available in the download section. Making your own project:[list=1] []Download the framework and extract it to your root web directory []Create a new folder for your project, for the purpose of this example it is named "Example" []Create three new folders inside of the Example directory named "models", "views", and "controllers" []Still inside of Example, create a new .htaccess file and paste RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ index.php?url=$1 [QSA,L] this will redirect all traffic to index.php with the exception of directories and files that actually exist. you may choose to remove the RewriteCond lines if you want exverything to be redirected [*]Now create an index.php file inside of Example. In order for the framework to know where your project is, you must define a constant called 'USER_ROOT' define("USER_ROOT", dirname(__FILE__)); next you will have to import the framework. require 'PATH/TO/FRAMEWORK/index.php'; where "PATH/TO/FRAMEWORK" is the path to index.php of the file you downloaded in step 1. To test if everything is working properly open a web browser and navigate to the Example folder. You should get something similar to> Controller 'index' doesn't exist! A fatal error has occured :( []Now that the framework has been imported correctly, it will start a bootstrap that will load all the necessary files. Once it has finished that it will look at the url in order to determine what controller to call. it is designed so that will call the method 'search' of the controller 'user' with the arguments of 'array( id => 1)' []With that, to create a very basic home page, make a new file called index.php inside of the controllers folder of Example []Next, create a new class named index that extends the class 'SunPHP\Controller' [note: the use of namespaces in libs is to avoid name collisions, however, res files are part of the global namespace as they are only imported if the user explicitly instructs the framework to include it using App::uses()] After making the class you will now have to create two new functions called 'construct' and 'toString()' []Inside of the construct function make an echo statement that echoes anything you want [*]Inside of the toString function only type 'return CLASS;' [*]Your file should now look something similar to <?php class index extends SunPHP\Controller { public function __construct() { echo "Default page."; } public function __toString() { return __CLASS__; } } ?> [*]Switch back over to your web browser and reload the page you opened in step 5 and you should get a message similar to> Default page. [/list]
http://hawkee.com/scripts/29274880/
CC-MAIN-2018-51
refinedweb
458
59.84
{-# OPTIONS -XFlexibleInstances #-} -- | This module contains the core types, constructors, classes, -- instances, and utility functions common to hspec. -- module Test.Hspec.Core where import System.IO import System.IO.Silently import Control.Exception import Control.Monad (liftM) -- | The result of running an example. data Result = Success | Fail String | Pending String deriving Eq -- | Everything needed to specify and show a specific behavior. data Spec = Spec { -- | What is being tested, usually the name of a type. name::String, -- | The specific behavior being tested. requirement::String, -- | The status of this behavior. result::Result } data Formatter = Formatter { exampleGroupStarted :: Handle -> Spec -> IO (), examplePassed :: Handle -> Spec -> [String] -> IO (), exampleFailed :: Handle -> Spec -> [String] -> IO (), examplePending :: Handle -> Spec -> [String] -> IO (), errorsFormatter :: Handle -> [String] -> IO (), footerFormatter :: Handle -> [Spec] -> Double -> IO () } -- | Create a set of specifications for a specific type being described. -- Once you know what you want specs for, use this. -- -- > describe "abs" [ -- > it "returns a positive number given a negative number" -- > (abs (-1) == 1) -- > ] -- describe :: String -- ^ The name of what is being described, usually a function or type. -> [IO (String, Result)] -- ^ A list of behaviors and examples, created by a list of 'it'. -> IO [IO Spec] describe n = return . map (>>= \ (req, res) -> return (Spec n req res)) -- | Combine a list of descriptions. descriptions :: [IO [IO Spec]] -> IO [IO Spec] descriptions = liftM concat . sequence -- | Evaluate a Result. Any exceptions (undefined, etc.) are treated as failures. safely :: Result -> IO Result safely f = Control.Exception.catch ok failed where ok = silence $ f `seq` return f failed e = return $ Fail (show (e :: SomeException)) -- | Anything that can be used as an example of a behavior. class SpecVerifier a where -- |) -- > ] -- it :: String -- ^ A description of this behavior. -> a -- ^ An example for this behavior. -> IO (String, Result) instance SpecVerifier Bool where it description example = do r <- safely (if example then Success else Fail "") return (description, r) instance SpecVerifier Result where it description example = do r <- safely example return (description, r) -- |") -- > ] -- pending :: String -- ^ An explanation for why this behavior is pending. -> Result pending = Pending failedCount :: [Spec] -> Int failedCount ss = length $ filter (isFailure.result) ss failure :: [Spec] -> Bool failure = any (isFailure.result) success :: [Spec] -> Bool success = not . failure isFailure :: Result -> Bool isFailure (Fail _) = True isFailure _ = False -- | Create a more readable display of a quantity of something. quantify :: Num a => a -> String -> String quantify 1 s = "1 " ++ s quantify n s = show n ++ " " ++ s ++ "s"
http://hackage.haskell.org/package/hspec-0.5.0/docs/src/Test-Hspec-Core.html
CC-MAIN-2015-22
refinedweb
388
50.33
Hello. I've got 2 .Net assemblies, for example, Foo.dll and Boo.dll Boo contains namespace BooModule { public class Boo { public string Speak() { return "Hello from class Boo"; } } public interface IFoo { string Comment(); } } Foo contains namespace FooModule { public class Foo : IFoo { public string Comment() { return "Class Foo inhereted from IFoo"; } } } In IronRuby console I try: IronRuby 1.1.3.0 on .NET 4.0.30319.239 Copyright (c) Microsoft Corporation. All rights reserved. >>> require 'D:\Programs\Univeris\FooBoo\bin\Boo' => true >>> include BooModule => Object >>> require 'D:\Programs\Univeris\FooBoo\bin\Foo' => true >>> include FooModule (ir):1:in `const_missing': uninitialized constant Object::FooModule (NameError) from (ir):1 If I inherit Foo : Boo I get the same error. But if I move the declaration to the Foo propject, so it's like namespace FooModule { public interface IFoo { string Comment(); } public class Foo : IFoo { public string Comment() { return "Class Foo inhereted from IFoo"; } } } Everything works just fine. IronRuby 1.1.3.0 on .NET 4.0.30319.239 Copyright (c) Microsoft Corporation. All rights reserved. >>> require 'D:\Programs\Univeris\FooBoo\bin\Foo' => true >>> include FooModule => Object >>> foo = Foo.new => FooModule.Foo >>> foo.Comment => 'Class Foo inhereted from IFoo' But I've got a really huge program system that consists of several big dll libraries which I want to use via IronRuby and I just can't move all those libraries into one dll file and into one namespace. What am I doing wrong? on 2012-08-14 07:41 on 2012-08-14 23:27 _______________________________________________ Ironruby-core mailing list Ironruby-core@rubyforge.org on 2012-08-15 07:22 Orion Edwards wrote in post #1072378: > I'm not sure exactly why this happens, I think it's something to do with > how the .NET runtime itself delay-loads assemblies and the rules it has > for looking for dependent dll's > There are three ways I know of to work around this: > 1. Use Dir.chdir to switch your working directory to > D:\Programs\Univeris\FooBoo\bin before you start loading the dll's > 2. Add to ruby's load path using $: << 'D:\Programs\Univeris\FooBoo\bin' > 3. Hook the CLR's AssemblyResolve event... this is a bit more complicated, > you can look up how this works on MSDN or I can tell you more if you'd > like > _______________________________________________ > Ironruby-core mailing list > Ironruby-core@rubyforge.org > Thank you very much. Everything worked just fine.
https://www.ruby-forum.com/topic/4404880
CC-MAIN-2017-04
refinedweb
404
56.25
NICE(3P) POSIX Programmer's Manual NICE(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. nice — change the nice value of a process #include <unistd.h> int nice(int incr); The nice() function shall add the value of incr to the nice value of the calling process. A nice value of a process is a non- negative number for which a more positive value shall result in less favorable scheduling. A maximum nice value of 2*{NZERO}-1 and a minimum nice value of 0 shall be imposed by the system. Requests for values above or below these limits shall nice value of the process shall not be changed, and errno shall be set to indicate the error. The nice() function shall fail if: EPERM The incr argument is negative and the calling process does not have appropriate privileges. The following sections are informative. Changing the Nice Value The following example adds the value of the incr argument, -20, to the nice value of the calling process. #include <unistd.h> ... int incr = -20; int ret; ret = nice(incr); None. None. None. exec(1p), getpriority(3p) The Base Definitions volume of POSIX.1‐2017, limits NICE(3P) Pages that refer to this page: unistd.h(0p), nice(1p), exec(3p), getpriority(3p)
https://www.man7.org/linux/man-pages/man3/nice.3p.html
CC-MAIN-2022-27
refinedweb
243
55.34
Package Interview Questions and Answers: In this post let me list down some regularly asked java Package Interview Questions and Answers. we hope these questions will help you to get an idea and improve your knowledge on Java Package concept. Java Packages Interview Questions and Answers What is a package? Ans: The package is a grouping mechanism in which related class files are grouped and made available to other applications and other parts of the same application. So, the package is a collection of related classes and interfaces. The package declaration should be the first statement in a Java class. What is a Java package and how is it used? Ans: A Java package is a naming context for classes and interfaces. A package is used to create a separate namespace for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. What is the first keyword used in a Java application development? Ans: The ‘Package’ is the first keyword used in a Java Application development. Which package is imported, by default? Ans: By default, the ‘Java.lang’ the package is imported, even without a package declaration. Can a class declare as private be accessed outside its package? Ans: No. once declared as private, it is not possible to access the class outside its package. What is the naming convention to be followed for declaring a user-defined package in Java application development? Ans: The Reverse Domain naming convention is to be followed for declaring a user-defined package in Java Application development. For this the syntax is: com.companyname.projectname.module.submodule; Example: com.apache.struts.tiles.login; What are the types of packages in Java? Ans: There are two types of packages in Java - Standard or Built-in packages and - User-defined packages. What is a standard package in Java? Ans: The standard package is the package that contains all libraries or pre-defined class files. There are two types of standard packages: - Core packages (which are starts with Java) - Extension packages (Which are starts with Javax) Example: For Core packages For Extension packages 1. Java.lang Javax.sql 2. Java.util Javax.servlet 3. Java.awt Javax.servlet.http 4. Java.applet Javax.servlet.jsp 5. Java.io Javax.ejb 6. Java.net Javax.swing Does importing a package make sub-packages class files available to the application? Ans: No. Importing a package does not make sub-packages class files available to the application. Example: import Java.awt; class TestPackage { Button b; ActionEvent ae; /*it is an error bcoz.. ActionEvent is available in * Java.awt.event.So we have to import Java.awt.event.*; also*/ public static void main(String args[]) { System.out.println("Hello Packages"); } } What is a user-defined package in Java? Ans: The packages which are created by the users in the Java application development are known as “user-defined package”. How to create a user-defined package? Ans: The ‘Package’ keyword is used for creating a package in Java. Its syntax is: package ; As per industrial standards, the package name should follow the reverse domain naming convention. Example: package org.companyname.projectname.modulename.submodule; package org.softwaretestingo.hrms.leavemangement; //package: org.softwaretestingo.pacakgesprograms.userdefinedpackges; class Employee { int empId=30039; String empName="smith"; float empSal=15000; public void getEmpDetails() { System.out.println("employe id: "+empId); System.out.println("employe name: "+empId); System.out.println("employe salary: "+empId); } } How to compile a source code of Java that is created as a package? Ans: The command for compiling source code with special syntax is: Javac –d . FileName.Java Example: Javac –d . Employe.Java What happens at background when “Javac –d. Employe.Java “is executed? Ans: When this command executed the following things happen: - the org directory is created in the current working directory (or default package). - Employe.class file is stored in: org.talentsprint.pacakgesprograms.userdefinedpackges What happens if we develop another Java class (called Department) and compile the class with the same package name? Does it create a new package with the same name? Ans: No, instead it will store the second.class file in the same package directory. Example: package org.softwaretestingo.pacakgesprograms.userdefinedpackges; class Department { int deptId=1234; public int getDeparmentId() { return deptId; } } After compilation, it will store the Department.class file into the package: org.softwaretestingo.pacakgesprograms.userdefinedpackges; How to use user-defined packages in Java? Ans: There are two fundamental steps to access and use the user-defined packages: Step-1: Set the classpath to user-defined package ,i.e..in which directory the user-defined package is stored up to that directory set the classpath. Example: set classpath =E:\softwaretestingo\myprograms (Assume that our programs are created in the above path) Step-2: Using import keyword we can import all the specific user-defined and standard packages also. Example: import org.softwaretestingo.pacakgesprograms.userdefinedpackges; class RunProgram { public static void main(String args[]) { Employe e1=new Employe(); System.out.println(e1.showEmpDetails(); Department d1=new Department(); System.out.println(d1.getDeptId()); } } Why do we use user-defined packages? Ans: We can use user-defined packages to: - Group related class files into a separate namespace. - Provide the same level of security - Make applications available to other parts of the application and in the same application also. Can a source file contain more than one class declaration? Ans: Yes. A single source file can contain any number of class declarations, but only one of the classes can be declared as public. What restrictions are placed on the location of a package statement within a source code file? Ans: A package statement must appear as the first line in a source code file (excluding blank lines and comments). What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import Java.net.* versus import Java.net.Socket)? Ans: It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. The practical benefit of importing single classes can be realized when two (or more) packages with the same class name, like, java.util.Timer and Javax.swing.Timer. If you import java.util.* and Javax.swing.* and then try to use “Timer”, you will. Can I import the same package/class twice? Will the JVM load the package twice at runtime? Ans: One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. JVM will internally load the class only once no matter how many times you import the same class. Are the imports checked for validity at compile time, like: will the code containing an import such as Java.lang.ABCD be compiled? Yes, the imports are checked for the semantic validity at compile time. The code containing Java.lang.ABCD will not compile. It will throw an error saying, cannot resolve symbol: - symbol: class ABCD - location: package io - import Java.io.ABCD; Does importing a package imports the subpackages as well? Ans: Example: Does import com.MyTest.* also import com.MyTest.UnitTests.*? No, you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of its subpackages. Do I need to import Java?lang package any time? If yes, then why? Ans: No. It is by default loaded internally by the JVM. What is a reflection package? Ans: The java.lang reflect package has the ability to analyze itself in runtime.
https://www.softwaretestingo.com/java-packages-interview-questions/
CC-MAIN-2022-40
refinedweb
1,271
51.75
Simple internationalization package for Dart and Flutter. This package is an permanent fork of another internationalization package. This package now supports hot reload and is tested on latest versions of Flutter. Overview Write your messages into YAML files, and let this package generate convenient Dart classes from those files. Turn this YAML file: lib/messages.i18n.yaml button: save: Save load: Load users: welcome(String name): "Hello $name!" logout: Logout Into these generated Dart classes:!"; } ... and use them in your code - plain and simple. Messages m = Messages(); print(m.users.welcome('World')); // outputs: Hello World! Package is an extension (custom builder) for build_runner (Dart standard for source generation) and it can be used with Flutter, AngularDart or any other type of Dart project.. Solution Write your messages into a YAML file: messages.i18n.yaml (default messages): generic: ok: OK done: DONE invoice: create: Create invoice delete: Delete invoice Write your translations into other YAML files: messages_de.i18n.yaml (_de = German translation) generic: ok: OK done: ERLEDIGT invoice: create: Rechnung erstellen delete: Rechnung löschen ... run the webdev tool, or build_runner directly, and use your messages like this: Messages m = Messages(); print(m.generic.ok); // output: OK print(m.generic.done); // output: DONE m = Messages_de(); print(m.generic.ok); // output: OK print(m.generic.done); // output: ERLEDIGT Messages { const Messages(); InvoiceMessages get invoice => InvoiceExampleMessages(this); ApplesMessages get apples => ApplesExampleMessages(this); } class InvoiceMessages { final Messages _parent; const InvoiceMessages(this._parent); String get create => "Create invoice"; String get help => "Use this function to generate new invoices and stuff. Awesome!"; String get delete => "Delete invoice"; String count(int cnt) => "You have created $cnt ${_plural(cnt, one:'invoice', many:'invoices')}."; } class ApplesMessages { final Messages _parent; const Apples some languages like Czech, we need three: apples: _apples(int cnt): "${_plural(cnt, one:'jablko', few: 'jablka', many:'jablek')}" See also: - - How to use generated classes How to decide what translation to use (ExampleMessages_de?, ExampleMessages_hu?) is up to you. The package simply generates message classes, that's all. import 'messages.i18n.dart'; import 'messages_de.i18n.dart' as de; void main() async { Messages m = Messages(); print(m.apples.count(1)); print(m.apples.count(2)); print(m.apples.count(5)); m = de.Messages_de(); //18n.yaml Add build_runner as a dev_dependency and i18n as a dependency to pubspec.yaml: dependencies: flutter: sdk: flutter i1818n.dart' ... Foo m = Foo(); return Text(m.bar); ... How to use with AngularDart You are probably using webdev tool already, so you just need to add i18.
https://pub.dev/documentation/i18n/latest/
CC-MAIN-2020-34
refinedweb
410
51.55
First example - Ok - In this xample it’s displaying errors - OK: def test(): print(‘function test - line 1’) msg=MIMEMultipart(‘alternative’) print(‘function test - line 3’) print(‘function test - line 4’) print(‘main code - hi’) test() print(‘main code - yeh’) In the example above, python correctly throw a error - “NameError: name ‘MIMEMultipart’ is not defined” (because in the example I don’t put the import commands in the code) BUT I have another python code (a bigger code), in which I have built in the same code above , and Python it’s not giving error message. Python executes just the following lines / output: ‘main code - hi’ ‘function test - line 1’ ‘main code - yeh’ Until some days ago I could get all Python errors in the screen, but now I have this problem above. (evertyhing else it’s working in my bigger code) I am using Python 3.9.4 I tested in another machine, with Python 3.7.4 - the same problem occurs And tested in a third machine, with python 3.5.9 - the same problem occurs
https://discuss.python.org/t/python-started-to-dont-show-errors-and-dont-stop-in-errors/9301
CC-MAIN-2021-31
refinedweb
178
61.19
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site. skip reading and just download Beach E6E65C 3rd line 4th line my house blue NotEnoughItems recipe + usage handler Download + installation Extended mods and texture packs Changelog: For modders: import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; public class EWAPI { private static final Class ecm = getECM(); private static Class getECM() { try { return Class.forName("naruto1310.extendedWorkbench.ExtendedCraftingManager"); } catch(ClassNotFoundException e) { return null; } } private static void addRecipe(ItemStack stack, Object[] input, boolean shapeless) { try { ecm.getMethod("add" + (shapeless ? "Shapeless" : "") + "Recipe", new Class[] {ItemStack.class, Object[].class}).invoke(null, stack, input); } catch(Exception e) { e.printStackTrace(); } } public static boolean getEWInstalled() { return ecm != null; } public static void addRecipe(ItemStack stack, Object[] input) { addRecipe(stack, input, false); } public static void addShapelessRecipe(ItemStack stack, Object[] input) { addRecipe(stack, input, true); } public static List getRecipeList() { try { return (List)ecm.getMethod("getRecipeList").invoke(null); } catch(Exception e) { e.printStackTrace(); return null; } } } if(EWAPI.getEWInstalled()) { EWAPI.addRecipe(new ItemStack(Block.bedrock, 2), new Object[] {"X", "X", "X", "X", ('X'), Block.cobblestone}); } else { System.out.println("This mod requires ExtendedWorkbench."); } "requiredMods": [ "extendedWorkbench" ], "dependencies": [ "extendedWorkbench" ], by Sorenus (v1.2.1.1) by RedstoneNightmare (v1.1.10.1) Credits, Copyright, Modpacks: Quote from Wulfre not sure how many archers we have out there but LONGBOW 50% straighter arrow flight slightly (~10%) longer to pull back I think extended arrows are too much, no? EDIT: This was made before watching the video above ':S Quote from alfmister should add epic tools Eg: Epic diamond pickaxe skip reading and just download. An extended map has 5 layers. You can zoom in and out using the + and - key. You can put it into square update mode by putting it together with a diamond in the crafting grid. When you right click with a map in square update mode, it will become completely explored. This will make the map freeze for a few seconds. On the last layer (zoomed all the way out) it will only explore 1/16 of your map and on the second last 1/4. Exploring a too huge area at once would crash the game. Extended compass: The extended compass allows you to have up to five needles at once. You can open the GUI by right clicking. When you now right click the sign, you will create a needle pointing to the signs location in the selected color. After that you can remove the sign. Examples for valid signs: (#E6E65C or 0xE6E65C works too) or NotEnoughItems recipe + usage handler Download + installation Old versions Source code / dev kits For MC 1.6.4, check out the extended mods section for a tweaked version! Minecraft Forum guidelines require me to inform you that this mod accesses the internet, to check for a newer version. No information is sent during this process. This function can be turned off using the configuration file. Installation (same for client and server): 1. if you are using Java 7 (aka 1.7) or earlier, install Java 8 (JRE) 2. install MinecraftForge 3. place the "[1.x.x]ExtendedWorkbench v1.x.zip" in your mods folder Extended mods and texture packs [1.7.10]UnLogic new blocks and armor [1.7.2]Craft Guide thanks to the great work of Uristqwerty you can view to extended workbench recipes using the CraftGuide mod (the feature is included in main CraftGuide mod, no extra download is required). [1.6.4/1.7.2]TheOldOne's plugins plugins for SimpleOres, Netherrocks, and rbdyck's Mithril. Also some tweaks for the EW mod, including bow zoom for 1.6.4 and configurable values for 1.6.4 and 1.7.2. Texture packs: 32x32 Add-on for Faithful texture pack by Shiiito Outdated: [1.2.5]Super Bows by SoCrazy10 Texture packs: [1.2.5]BDcraft with Extended Workbench patch (x64) by Kingdb707 Your mod/texture pack is missing? PM me or post it in the topic. Changelog: - fixed crash on dedicated server v1.4.1: - fixed item models for tools - compiled using Java 8 v1.4: - compatibility with MC 1.10 - fixed some things - probably broke others - so great it skipped v1.3 - extended map and compass missing for now v1.2.1.1: - fixed some things about shapeless recipes - added Taiwan translation (thanks to sumer16888) v1.2.1.0: - added ore recipes to API - recipes now use OreDicionary for planks - updated NEI handlers to work with ore recipes - updated packet handler to prevent memory leaks - extended map now renders correctly in item frame v1.2.0.6: - added update check (can be disabled in the config) - fixed compatibility across MC versions v1.2.0.5: - improved various aspects of the extended flint and steel v1.2.0.4: - removed strict version check (meaning it will work with MC 1.7.10, 1.7.2 and possibly more) - minor fixes v1.2.0.3: - added NEI handlers again - reduced tool damage against mobs slightly v1.2.0.2: - fixed extended compass crashing - fixed armor blocking unblockable damage v1.2.0.1: - fixed SMP - fixed extended reach - removed some unnecessary stuff from config v1.2: - compatibility with MC 1.7.2 - added empty extended maps + extended map cloning - fixed extended bow not rotation and zooming correctly (finally :)) - fixed extended map icon not adjusting correctly - fixed extended shears not having more durability - adopted the new fishing system to the extended fishin rod - fixed/improved some things concerning the extended flint and steel - change icon of the extended bow to better match the vanilla bow v1.1.10.3: - compatibility with MC 1.6.4 - the mod will crash if some features can not be loaded v1.1.10.2: - fixed mod not working with newer Forge versions (will still work with old ones) v1.1.10.1: - extended tool can reach 50% further - adjusted damage done by swords - added NEI recipe + usage handler again - config file only saves when necessary - fixed extended tool rendering incorrect when enchanted - fixed swords not doing more damage than vanilla swords v1.1.10: - compatibility with MC 1.6.2 - temporary removed NEI recipe + usage handler v1.1.9: - changed default item id from 3983 to 23983, to avoid potental bugs - fixed tools not rendering with latest Forge (now requires Forge 687+) - extended map now centers on player correctly - extended map only shows information about auto update mode if enabled v1.1.8: - compatibility with MC 1.5.2 - fixed shift clicking in extended workbench - fixed extended workbench connection logic - fixed extended items are small in item frames - fixed some blocks rendering wrong v1.1.7: - fixed mobs on fire rendering wrong - extended compass now saves data per item - added help button to extended compass - extended fire can burn in rain v1.1.6: - compatibility with MC 1.5.1 - fixed farmland turning into bedrock - fixed extended recipes involcing wood only work with oak wood - fixed extended workbench interface now showing the labels: "Crafting" and "Inventory" v1.1.5: - compatibility with MC 1.5 - tools will now render bigger (can be turned off in config) - removed "overrideTexture" from config (not needed anymore) - new way of rendering the extended compass (should make no notable difference) v1.1.4: - fixed extended map not updating v1.1.3: - compatibility with MC 1.4.7 - fixed extended compass not working v1.1.2: - fixed crash when no player has an extended compass v1.1.1: - fixed crash without Codechicken core - removed some old stuff v1.1.0: - compatibility with MC 1.4.6 - added extended map again - added auto update mode for extended map - added some color keywords for extended compass - extended compass now works for SMP - extended compass saves needles per world per player instead of per world - extended fishing rod has 50% chance to catch cooked fish - added mcmod.info file - removed old API (replaced by reflection) v1.0.4: - compatibility with MC 1.4.5 - added NEI handlers again v1.0.3: - compatibility with MC 1.4.4 - removed some debug code - removed NEI handlers cause NEI wasn't updated v1.0.2: - fixed extended leather armor not rendering correct - API now works with FML mods (thanks to ShetiPhian) - improved right clicking with extended compass v1.0.1: - fixed crash without NEI - added missing class v1.0: - compatibility with MC 1.4.2 - added SMP support - added recipe and usage handler for NEI - added API again - added extended compass - extended leather armor can be dyed - improved detection of normal recipes in the extended workbench - shift clicking in extended workbench works now like in the normal workbench - fixed some bugs with extended flint and steel v0.7: - compatibility with MC 1.3.2 - removed extended map - removed API v0.6: - added extended map - added configuration file (config/ExtendedWorkbench.cfg) - improved extended armor v0.5b: - improved API - decreased extended hoe durability from +200% to +100% - improved API even more v0.5: - added extended shrears - added extended flint and steel - new recipe for shovels - changed handles of wooden, stone and iron tools to sticks, planks and cobblestone - new icons for these tools - farmland created with an extended hoe will now take longer to turn back into dirt v0.4: - the mod now uses MinecraftForge - added extended armor - fixed bugs when placing workbenches - improved texture of extended workbenches - animation of extended bow is now as good as the one from the normal bow - added super charge for extended bow - increased durability of extended tools from +50% to +100% (hoe: from +100% to +200%) - added increased damage against mobs for extended tools - added extended fishing rod v0.3: - fixed animation of extended bow a bit - fix crash with extended bow, when there's an empty space in the hotbar - the extended bow now needs 20% more time to charge - added extended shovel, pickaxe, axe and hoe v0.2: - no installation in minecraft.jar required anymore - added extended bow v0.1: - initial release For modders: Minecraft and Forge keep changing and it seems like every time I come up with a new and simple way of publishing the source, they break it. So from now on I will just publish the .java files. The easiest way to set the mod up for development is to delete the .class files (naruto1310 folder) from the binary release and place it in the mods folder of your development environment and then copy the sources into the source folder. Older instructions: To develop an extension for the mod you just have to link the source in Eclipse (or whatever you use) and copy the dev version in the /lib folder as well (for recompiling). Installing the dev kits (MC 1.4.4 - 1.6.2): 1. download ExtendedWorkbench dev package 2. place the the dev package in /jars/mods You will now have the mod in your setup. Note that the current dev kits include the source code. So when you use a later version of Forge and the names changed, you can copy the code in your /src folder and update it. Now create a class in your package and copy the folowing code into it: see below If you want to direcly use the mod in Eclipse: right click project -> Properties -> Java Build Path -> Libraries -> Add External Jars... -> select dev packpage If you want to browse the source: right click project -> Properties -> Java Build Path -> Libraries -> expand dev package entry -> Source attachment -> select dev package again Now you can browse the code under the Referenced Libraries entry in your project. Create the following class in your project: Then you can simply add recipes like this: Finally add the following lines to your mcmod.info file: The first line means, that your mod requires EW to run. If it is not present, the game will crash. Don't add this line if you only have optional EW support. The second lines means that, your mod should be loaded after EW (if EW is installed). You always have to add it. If you have any problems or need help using the API, just send me a PM. When your done and published your mod, please tell me and I will add it to the extended mods section. by Sorenus (v1.2.1.1) by RedstoneNightmare (v1.1.10.1) Credits, Copyright, Modpacks: Main idea: - AnimationCraft PG5 Coding + everything not listed otherwise: - Naruto1310 Extended bow (idea + icons): - Wulfre Extended armor (textures + icons): - Toddie1234 This document is Copyright © 2012-2016 Naruto1310. Modpack policity: If you want to include this mod in a modpack you make, you are allowed to do so under the following conditions: - you provide credit in form of my name and a link to this topic - you don't make money using the pack i got a few suggestions: with this you can add a. closet/wardrobe = crafted with wood planks on all edges double furnace = crafted like two furnaces. (has four input-ouput slot) really you can just double vanilla blocks with more functions and style. edit: i'll give you Eg: Epic diamond pickaxe I made a video for the mod - good work I can see this having a lot of potential! LONGBOW 50% straighter arrow flight slightly (~10%) longer to pull back I think extended arrows are too much, no? EDIT: This was made before watching the video above ':S Haha, great minds think alike, awesome design If i had made this mod, i would add: Pies(apple, cocoa?, melon, pumpkin...) and Wulfre's bow would be awesome. Awesome mod, i like it That looks like a Diamond hammer I was just trying to design an extended pickaxe and realized that it would cost waay more iron than a sword, should iron nuggets or iron plated sticks be added? (This is starting to get on that side of modding I hate, but I'm just trying to make it slightly more convenient) Sorry, this mod was just too good for me to resist posting, but it was a stupid idea, I'm going to go play with it now.
http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/1282775-extended-workbench-v1-4-2
CC-MAIN-2017-34
refinedweb
2,349
64.51
Thanks for details Karl. I was looking for something like it. However, I have a question around the warning mentioned in javadoc of parallelReader. It says -. So now, if I want to update one of the index document from my dynamic index, I will have to delete the document and insert it again as Lucene does not allow updating the document. Correct? If this is the case, re-insert of document in dynamic index will change the order of the index with static index, which is not modified. How should we take care of this situation? Am I missing something here? Regards, Rajesh --- Karl Wettin <karl.wettin@gmail.com> wrote: > Hi Rajesh, > > I think you are looking for ParallelReader. > > <> > > public class ParallelReader > extends IndexReader > >:. > > > > karl > > Rajesh parab skrev: > > Hi, > > > > We are using Lucene 2.0 to index data stored > inside > > relational database. Like any relational database, > our > > database has quite a few one-to-one and > one-to-many > > relationships. For example, lets say an Object A > has > > one-to-many relationship with Object X and Object > Y. > > As we need to de-normalize relational data as > > key-value pairs before storing it inside Lucene > index, > > we have de-normalized these relationships (Object > X > > and Object Y) while building an index on Object A. > > > > We have large no of such object relationships and > most > > of the times, the related objects are modified > more > > frequently than the base objects. For example, in > our > > above case, objects X and Y are updated in the > system > > very frequently, whereas Object A is not updated > that > > often. Still, we will need to update Object A > entries > > inside the index, every time its related objects X > > and/or Y are modified. > > > > To avoid the above situation, we were thinking of > > having 2 separate indexes first index will only > > index data of base objects (Object A in above > example) > > and second index will contain data about its > > relationship objects (Object X and Y above), which > are > > updated more frequently. This way, the more > frequent > > updates to Object X and Y will only impact second > > index that stores relationship information and > reduce > > the cost to re-index object A. However, I dont > think, > > MultiSearcher will be helpful if we want to search > for > > data which spans across both indexes (e.g. some > fields > > of Object A in first index and some fields of > Object X > > or Y in second index). > > > > Do we have any option in Lucene to handle such > > scenario? Can we search across multiple indexes > which > > have some relationships between them and search > for > > fields that span across these indexes? > > > > Regards, > > Rajesh > > > > __________________________________________________ > > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around --------------------------------------------------------------------- To unsubscribe, e-mail: java-user-unsubscribe@lucene.apache.org For additional commands, e-mail: java-user-help@lucene.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-java-user/200804.mbox/%3C665397.54440.qm@web52007.mail.re2.yahoo.com%3E
CC-MAIN-2017-04
refinedweb
474
55.34
XML is an acronym for “Extensible Markup Language”. XML is the latest platform-independent and content-dependent technology available for Internet development. XML is the tool of choice for distributing structured information in this age. A working group under the guidance World Wide Web Consortium (W3C) started developing XML to simplify the transmission of documents across the internet. XML is a young meta language. In early 1998, W3C published the XML 1.0 recommendations. Content developers have started developing various applications of XML – for example Mathematical Markup Language(MathML), CML – Chemical Markup Language etc. W3C, while releasing the HTML 4.0 recommendation in early 1998, said that it would approximately take 18 months to develop this transitional language. We have time to learn the basics of XML and develop the future internet language. XML not only fulfills the needs of web authors but also those of anyone interested in publishing. Oracle, IBM and Microsoft are coming out with XML-related software and this gives sufficient indications about the future of XML in the IT industry..{mospagebreak title=SGML, HTML and XML} SGML -Standard Generalized Markup Language SGML is an international standard for describing electronic documents. SGML is a meta language used to write other languages. SGML helps describe text documents in a logical and structural manner. SGML is used primarily for the creation, storage, and distribution of documents and as a source for conversion to other documents. SGML documents have been used in the US military and American aviation industries for many years. It is too complicated for web publishers and this is the reason for the growth of HTML, a simplified subset of SGML. HTML – Hyper Text Markup Language HTML can be considered as the simplest subset of SGML and is simple enough to have Web publishing accessible to anyone. Publishers do not necessarily need knowledge of HTML as a lot of WYSIWYG editors are available in the market. What are the problems with HTML? HTML is too restrictive. Standard tags are predefined by W3C, so HTML is not powerful enough to describe more complex documents. HTML is more presentation oriented than content oriented, so HTML tags do not give an indication of the meaning of the content. You may ask, why can’t W3C introduce more tags to describe content? Doing just that led to another problem: browser companies have introduced new, proprietary tags to attract users to their products. With current HTML, publishers have to do lot of adjustments to their documents to be compatible with popular browsers. Browsers do not check for bad HTML code and hence the Internet has a lot of documents with several HTML mistakes. These issues were raised by content managers and Internet publishers and this problem escalated to such an extent that W3C began to look for alternatives. What is the solution? XML – eXtensible Markup Language XML can be considered as a simplified version of SGML. XML is case sensitive. <p> is different from <P>. though in HTML both would be considered the same. XML is extensible – You can create your own elements to meet your publishing demands. You need not wait for W3C HTML committee to release the next version of HTML to include your required tags. XML is structured – XML documents should adhere to a specific structure. If a document is not structured properly, it is not considered to be XML. XML is a much more accessible language than SGML. Since XML documents are well structured, programmers can easily write software for rendering the XML documents. XML has simple rules to differentiate between the document contents and the XML markup elements. XML markup elements start with either a less than symbol(<) or an ampersand (&) character XML also uses greater than symbol (>), single quote (‘) and the double quotation marks(“) for markup. To use the above markup characters, one should use the corresponding general XML entity (& for &, > for >, < for <, &apos for ‘ and " for “).{mospagebreak title=What is DTD – Document Type Definition} A DTD can be considered the grammar for a markup language. It is a set of regulations that specifies the usage of XML markup. It defines elements, an element’s attributes and its values, and contains specifications about which elements can be contained in others. DTD can also define entities. We will consider an example DTD for email: <!ELEMENT Mail (From, To, Cc?, Date?, Subject, Body)> <!ELEMENT From (#PCDATA) > <!ELEMENT To (#PCDATA) > <!ELEMENT Cc (#PCDATA) > <!ELEMENT Date (#PCDATA) > <!ELEMENT Subject (#PCDATA) > <!ELEMENT Body (#PCDATA | P | Br)* > <!ELEMENT P (#PCDATA | Br)* > <!ATTLIST P align (left | right | justify) "left" > <!ELEMENT Br EMPTY > Description A XML document conforming to the mail DTD has only one From, one To, an optional Cc, an optional Date, one Subject and one body. - A From element has only text. - A To element has only text. - A Cc element has only text. - A Date element has only text. - A Subject element has only text. - A Body element can have text and zero or more of P and Br elements. - A P element can have text and zero or more of Br element - The P element has an align attribute. The attributes possible values are left, justify or right. Its default value is left. - The Br element is empty. A XML parser (discussed in the software section) will use the DTD to parse the document. The DTDs enable you to publish your documents to be used by others. The XML document should have instructions to tell the XML processing programs to find out the DTD. A <!DOCTYPE> element at the start of the XML file will instruct the program about the location of the DTD. For example: {mospagebreak title=Valid and Well-formed XML}{mospagebreak title=Valid and Well-formed XML} <!DOCTYPE Mail system ""> <Mail> .. .. .. </Mail> Two levels of conformance are there in the XML recommendation: valid and well-formed. A well-formed XML file must follow a few key rules: - It should have at least one element. - The document should conform to the XML specification - The root element (<Mail>) should not be contained by any other element. - Proper nesting of elements is a must. - Attribute values should be within quotation marks. - All the entities other than reserved entities should be declared. Refer Even without a DTD, an XML parser should parse a well-formed XML document. If it is not well-formed it can’t be called an XML document. This aspect is good for web applications because the applications need not know the DTD structure used to create the XML document. Valid XML Valid XML files are those which have a DTD reference and conforms to the DTD. A valid XML file must also be well-formed. The availability of DTD along with the document facilitates the XML processing programs and rendering of the document by XML-enabled browsers.{mospagebreak title=Example XML Documents and analysis} Example 1 – A well-formed XML document: <?xml version=”1.0″ standalone=”no”?> <Mail> <From>Author</From> <To>Receiver</To> <Date> Thu, 7 Oct 1999 11:15:16 -0600</Date> <Subject>XML Introduction</Subject> <body><p>Thanks for reading<Br/> this article</p> <br/> <p>Hope you enjoyed this article</p> </body> </Mail> The first line is the XML declaration and it identifies what follows as XML code. It is called the prolog. The attribute version indicates the version of the XML standard. The statement standalone=”no” indicates that markup declarations are external to the document. The XML declaration can be considered as a “processing instruction”. Though this declaration is not compulsory, it is better to include such declaration. This will increase the portability of the document. Example 2 – A valid XML document conforming to mail.dtd. Date element is missing because it is optional in the mail DTD The element P has the attribute justify. After the Body and before P Comments text is allowed, because DTD allows the use of plain text in the Body element. <?xml version="1.0" standalone="no"?> <!DOCTYPE Mail system ""> <Mail> <From>Author</From> <To>Receiver</To> <Cc>Receiver2</Cc> <Subject>XML Introduction</Subject> <body>Comments:<p align="justify">Thanks for reading<Br/> this article</p> <br/> <p>Hope you enjoyed this article</p> </body> </Mail> Example 3 – A valid XML document conforming to “mail.dtd”. Date element and Cc elements are present The element P has the attribute right. <?xml version="1.0" standalone="no"?> <!DOCTYPE Mail system ""> <Mail> <From>Author</From> <To>Receiver</To> <Cc>Receiver2</Cc> <Date> Thu, 7 Oct 1999 11:15:16 -0600</Date> <Subject>XML Introduction</Subject> <body>Comments:<p align = "right" >Thanks for reading<Br/> this article</p> <br/> <p>Hope you enjoyed this article</p> </body> </Mail> An XML document can have comments. XML’s comment syntax is similar to that of HTML. Any text, except double hyphen, “–“, can be placed between <– and –> tags. Processing instruction(PI) can be embedded in the documents. The data components of the PI should be recognized by the processing applications. Publishers may want to include some codes that should not be parsed by the parsers. Those codes can be put in to the ignored sections. An ignored section will have the syntax like this: <[CDATA[Any text to be ignored]]> In simple words, any ignored sections start with <[CDATA[ and end with ]]> {mospagebreak title=Software for XML} XML related softwares can be broadly classified in to three categories: XML Browsers XML Parsers/applications XML Editors XML Browsers Few XML browsers are there now. The XML style sheet specification (XSL)is in the evolution stage. Features like XLink and XPoint are still emerging and has to be incorporated in the browsers. XML Parsers and Applications A parser is a program to check the well-formedness of an XML document. If the document is well-formed, the parser has to read the document’s DTD and should check the conformance of the document to the rules in the DTD. DXP – A parser written in Java Many parsers are written using Java. DXP can be used to check the well-formedness and validity of an XML document. The software, it’s installation and operational documents can be downloaded from MSxml – A parser written in JAVA by Microsoft Download and install form Microsoft Perl Module – A perl module XML parser is available Larry Wall prototyped this Perl module for processing XML documents in Perl scripts. It relies on James Clark’s expat XML parser. This module also requires Perl 5.004 or better. Download and install it from the Perl site. Clark Cooper has provided some sample scripts that demonstrate how to process XML in Perl. XML Editors XML editors give users an environment to create their own tags. One of the popular editors is XML<PRO> from Vervet Logic. Few features of XML<PRO> - Document validation – XML<PRO> can be used as a validator to test the document validity - Entity Palette – A floating palette is available for inserting defined entities - DTD can be associated with the document. {mospagebreak title=Conclusion} XML is still under development stage. It is evolving beyond the draft specifications put forward by w3c. These changes may be rapid and keep yourself updated by visiting related sites. Discussion about XML namespaces, schema, style sheets and XQL – a developing query language are beyond the scope of this introductory article. You can reach the author, Suresh Kumar, at kalakad@yahoo.com.
http://www.devshed.com/c/a/XML/An-Introduction-to-XML/
CC-MAIN-2017-04
refinedweb
1,889
57.27
Steve Langasek <vorlon@debian.org> writes: > I don't have a strong opinion on whether ddebs should be documented in > policy, but I certainly don't agree with requiring dpkg to understand > them as a prerequisite for implementing a general purpose, public > archive for auto-stripped debugging symbols packages. There really is > no reason for dpkg to treat these packages specially - a simple > namespace convention imposed by Policy (i.e., reserving package names > ending in "-ddeb" for use by this archive, which is what has been > proposed) is sufficient, and requires no changes to dpkg, which is as it > should be. Or even just -dbg, since aren't the existing debug packages basically .ddebs, modulo bugs? > I think the .ddeb extension is a red herring. There ought not be > anything new to teach dpkg, here; the only thing of relevance is that > there not be namespace clashes between the ddebs and the debs in the > main archive, and the filename is not relevant to that at all. Yes. -- Russ Allbery (rra@debian.org) <>
https://lists.debian.org/debian-devel/2009/08/msg00273.html
CC-MAIN-2015-40
refinedweb
173
63.29
Data Resampling When data is only available in a single timeframe and the analysis has to be done for a different timeframe, it’s time to do some resampling. “Resampling” should actually be called “Upsampling” given that one goes from a source timeframe to a larger time frame (for example: days to weeks) backtrader has built-in support for resampling by passing the original data through a filter object. Although there are several ways to achieve this, a straightforward interface exists to achieve this: Instead of using cerebro.adddata(data)to put a datainto the system use cerebro.resampledata(data, **kwargs) There are two main options that can be controlled Change the timeframe Compress bars To do so, use the following parameters when calling resampledata: timeframe(default: bt.TimeFrame.Days) Destination timeframe which to be useful has to be equal or larger than the source compression(default: 1) Compress the selected value “n” to 1 bar Let’s see an example from Daily to Weekly with a handcrafted script: $ ./resampling-example.py --timeframe weekly --compression 1 The output: We can compare it to the original daily data: $ ./resampling-example.py --timeframe daily --compression 1 The output: The magic is done by executing the following steps: Feeding the data into cerebro with resampledatawith the desired parameters: timeframe compression The code in the sample (the entire script at the bottom). #) A last example in which we first change the time frame from daily to weekly and then apply a 3 to 1 compression: $ ./resampling-example.py --timeframe weekly --compression 3 The output: From the original 256 daily bars we end up with 18 3-week bars. The breakdown: 52 weeks 52 / 3 = 17.33 and therefore 18 bars It doesn’t take much more. Of course intraday data can also be resampled. The resampling filter supports additional parameters, which in most cases should not be touched: bar2edge(default: True) resamples using time boundaries as the target. For example with a “ticks -> 5 seconds” the resulting 5 seconds bars will be aligned to xx:00, xx:05, xx:10 … adjbartime(default: True)) boundoff(default: 0) Push the boundary for resampling/replaying by an amount of units. If for example the resampling is from 1 minute to 15 minutes, the default behavior is to take the 1-minute bars from 00:01:00 until 00:15:00 to produce a 15-minutes replayed/resampled bar. If boundoffis set to 1, then the boundary is pushed 1 unitforward. In this case the original unit is a 1-minute bar. Consequently the resampling/replaying will now: - Use the bars from 00:00:00 to 00:14:00 for the generation of the 15-minutes bar The sample code for the resampling test script. from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import backtrader as bt import backtrader.feeds as btfeeds def runstrat(): args = parse_args() # Create a cerebro entity cerebro = bt.Cerebro(stdstats=False) # Add a strategy cerebro.addstrategy(bt.Strategy) #') return parser.parse_args() if __name__ == '__main__': runstrat()
https://www.backtrader.com/docu/data-resampling/data-resampling/
CC-MAIN-2019-26
refinedweb
502
52.39
In Java 11 String class introduces lines function to split it into lines with new line separator.In Java 11 String class introduces lines function to split it into lines with new line separator. In this tutorial we are going to explain use the use of new function which is introduced in Java 11 which is used to split lines in Java. Java 11 introduced many new features and improvements to make programming language much useful. In this version of Java (JDK 11) String class introduces a new method String.lines() which splits the string object into lines. The line separator used is \n or \r\n. If your String object contains these new line characters then you can easily and efficiently use the lines() method the string into lines. This method is described in the bug report JDK-8200425, which provides more details about this method. This method is approved and available in current build of JDK 11. In JDK 11 the java.lang.String class comes with a new method lines(), which returns a stream of the lines from the string object. This method is very useful in processing multi-line string in their program. This method makes life easy as in real world programming it is required to process multi-line string very frequently. Today I am trying lines() method of Java 11 to split multi-line string. Here is the full example code: import java.util.stream.Stream; public class StringLinesExample { public static void main(String[] args) { //New line seperator \n String s = "Line 1\nLine2\nLine 3\nLine4"; Stream<String> lines = s.lines(); lines.forEach(System.out::println); lines.close(); //New Line Seperator \r\n s = "Line 1\r\nLine2\r\nLine 3\r\nLine4"; lines = s.lines(); lines.forEach(System.out::println); lines.close(); } } In the above example we have used the lines() method which returns Stream of lines: Stream<String> lines = s.lines(); If you run the example it will print all lines in the String object. Here is the output of the program: C:\java11examples>java StringLinesExample Line 1 Line2 Line 3 Line4 Line 1 Line2 Line 3 Line4 In this tutorial we have learned to use the lines() method which is introduced in Java 11. Check more tutorials at: Ads
http://roseindia.net/java/java11/java-11-string-lines-split-example.shtml
CC-MAIN-2019-35
refinedweb
379
72.76
With the recent release of Bootstrap 5 Beta 1, now is a great time to dip your toes into working with the new major updates and getting your tools ready for when the final release drops. Setting up your project 🗂 1. Set up your environment 🌳 Initialise a new npm package in your directory: $ npm init -y The -y parameter tells npm to accept the default answers for all options. Next, install our packages: $ npm i bootstrap@next react react-dom next sass This will install: - bootstrap@next -- Bootstrap 5 Beta - react -- React - react-dom -- React DOM - next -- NextJS - sass -- SASS/SCSS preprocessor We also need to set up our scripts in package.json as follows: { // ... "scripts": { "dev": "next dev", "build": "next build", "start": "next start" }, //... } 2. Add your SCSS file 👨🎨 Next we need to add our SCSS folder and file: $ mkdir scss $ touch scss/main.scss And add the following content to scss/main.scss: // Import Bootstrap 5 Beta! @import "~bootstrap/scss/bootstrap.scss"; 3. Set up your pages 📄 We need to set up our usual index page, but also a custom App component that lives within the /pages directory. This is so we can ensure that Bootstrap 5 Beta is loaded across the entire NextJs app. Create your pages folder, the index page and custom App component: $ mkdir pages # Your pages folder $ touch pages/index.js # The index page $ touch pages/_app.js # The custom App component In the pages/index.js file, add the following: const IndexPage = () => { return "Hello world!"; }; export default IndexPage; And in your pages/_app.js file, add the following: import "../scss/main.scss"; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default MyApp; At this point you can run npm run dev in your terminal and browse to in your web browser and you'll be greeted with the universal dev message "Hello world!". Now for the fun part... Customising Bootstrap 🎨 So we've got our project up and running, our dependencies are all installed and ready roll, and Bootstrap is being imported into our main SCSS file. Let's add some structure and a little content to our index page: const IndexPage = () => { return ( <div className="container"> <div className="row"> <div className="col"> <h1 className="mt-4">Hello world!</h1> <p>This is Bootstrap 5 Beta + NextJS</p> <button className="btn btn-primary me-2">Read the docs!</button> <button className="btn btn-outline-secondary"> or just get started </button> </div> </div> </div> ); }; export default IndexPage; This will render our new content within Bootstrap's fully-responsive mobile-first grid system: We can then override Bootstrap's SCSS variables to build our our theme: // Change the primary colour $primary: rgb(207, 44, 4); // Set the sans-serif font $font-family-sans-serif: Arial, sans-serif; // Maybe set a difference heading font family $headings-font-family: Georgia, serif; // Make headings bolder! $headings-font-weight: 700; // Thicken up our borders $border-width: 3px; // Remove the border-radius everywhere $border-radius: 0; // Import Bootstrap 5 Beta! @import "~bootstrap/scss/bootstrap.scss"; Which should give you something like this: That should be enough to get your next Bootstrap 5 + NextJS web app kick started. Now get out there and make something beautiful! Discussion (7) Nice and quick setup! I now have my page up and running but i cant get the collapse function to work, is there something more i need to do to get that working? Hello Ted. You can use something like this to collapse the NavBar. Credit to dev.to/johnotu/how-to-toggle-boots... Awesome—nice work! 🥳 Yep, you'll need to include Bootstrap's JavaScript dependencies. There are a couple of different ways to do this—I ended up including them in my <head/>tag using the next/head component: This was my "quick fix" way of getting things like collapse and dropdowns up and running, however I'd recommend looking into properly importing Bootstrap into your project as a module, if you're building something for production. Hi there, have you found an easier and reliable way to import the JS into the app? I searched through the web and bootstrap docs for configuring the webpck was complicated for a guy that never worked with webpack. Any help would be appreciated Its easier than I thought, thanks No worries, my pleasure :) How can I use Popovers and Tooltips which require some additional setup?
https://dev.to/danwalsh/getting-started-with-the-new-bootstrap-5-beta-and-nextjs-51am
CC-MAIN-2022-21
refinedweb
731
53
Continuing: Data binding to a CompositeControl - From: intrader <intrader@xxxxxxx> - Date: Sun, 25 Mar 2007 18:39:40 -0700 intrader wrote: I am very new at using the CompositeControl or CompositeDataBoundControl and at DataBinding in generalRecently I have been reading Espositos "Introducing Microsoft® ASP.NET 2.0" section on CompositeControl and TypeDescriptor. Very worthwhile! My requirement is that I would like to declaratively tell my control to bind to a specific instance of a class; the control then looks at the metadata held in the instance to provide the appropriate control behavior. The syntax follows the 'standard' <tag:controlname. What I want in "here I don't know what to specify" is something like instanceName.someFieldOrProperty, where the field (property) has a metadata to describe the behavior of the field. From within the control I would like to be able to access the field via the DataSource property. I thought of using an event driven approach and have the control.DataBinding event execute an event handler that would take the DataSource of some container (like a panel) and figure out the metadata in the field of the data source; but, this seems overly complex. In a nutshell, given an instance fld containing a reference to someClass.someFieldOrProperty, I would like the more direct approach of using DataSource ="fld". Is 'fld' accessible within the code of the control? Thanks P.S. I have been following the very good examples in the newsgroup, but I have not figured this out yet. I am also studying a very well written article on TypeDescriptors that dwells on their archtecture: "". Wonderful article! I have done some prototype coding that allows me to: 1.Use a Business Object class with properties that are attribute decorated with metadata (similar to the Enterprise Library 3.0): public class Address:BusinessObjectBase{ [StreetAttribute]string Street{...} [StatesAttribute]ReadOnlyNameValues States(...) [ZipCodeAttribute]string ZipCode{...} . . . } 2.Have a panel-like pagelet control to which I attach an instance of Address myAddress (this may act like an ObjectDataSource class): <CAFM:pagelet BO="myAddress" .../> 3. Drop a Field objects in the pagelet; the control takes care of naming appropriately for cases where the BO is within another BO or within an instance of a collection: <CAFM:field <CAFM:field <CAFM:field 4. They render appropriate controls containing a Title, the control displaying the value - TextBox, DropDownList, TextBox respectivelly I have gotten to the point where the rendered code looks OK. The postback seems OK, but the naming of the controls becomes a problem if the BO is within another BO or is part of a collection; the design-time is lacking proper display of the metadata driven fields. So I am investigating TypeDescriptor driven design time modification. I have hoped to get some dialog going on for this thread, but something must be missing in how I phrase or present the thread as no-one has picked up the thread. Thanks for any help. . - References: - Data binding to a CompositeControl - From: intrader - Prev by Date: ITemplate and ControlBuilder - Next by Date: Re: BE-CAREFUL, YOU COULD BE A VICTIM OF SCAM OR FRAUD!!! - Previous by thread: Data binding to a CompositeControl - Next by thread: Re: web.config servercontrol binding problem - Index(es):
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.aspnet.buildingcontrols/2007-03/msg00050.html
crawl-002
refinedweb
536
52.39
When you create a new “Windows Phone Application” project in Visual Studio, you get a complete app that you can instantly compile into a .xap file and deploy to the emulator or a physical phone. The app doesn’t actually do anything other than display some text on the screen, but it sets up a lot of infrastructure that would be difficult and tedious to create from scratch. Before creating the Tally app, let’s understand the main pieces of any new “Windows Phone Application” project: - The application manifest - Images - XAML code: MainPage.xaml and App.xaml - C# code: MainPage.xaml.cs, App.xaml.cs, and AssemblyInfo.cs Visual Studio provides a few types of Windows Phone projects for more complex applications, based on the control that populates the main screen: a databound (list) application, a panorama application, and a pivot application. Almost all of the applications in this book were created from the basic “Windows Phone Application” project, as it’s relatively easy to manually add a databound list, a panorama control, or a pivot control to a project without having to start with a specialized project type. The Application Manifest The file called WMAppManifest.xml (where WM oddly stands for the outdated “Windows Mobile” term) is an application manifest. It describes your app to the operating system—its name, what it looks like, how it starts, what it’s allowed to do, and more. Listing 1.1 shows what Visual Studio generates inside this file when you create a new project and name it “Tally.” You can find this file in your project’s “Properties” folder. .xap Files .xap files, introduced by Silverlight but also used by XNA apps for Windows Phone, are just .zip files. If you rename a .xap file and give it a .zip extension, you can inspect its contents just like any .zip file.A .xap file for a Windows Phone app contains several files: compiled DLL(s), manifests, images, and potentially other assets used by your app that aren’t embedded into a DLL, such as videos or data files. LISTING 1.1 WMAppManifest.xml—The Initial Application Manifest for the Tally Project [code] <?xml version=”1.0” encoding=”utf-8”?> <Deployment xmlns=”” AppPlatformVersion=”7.0”> <App xmlns=”” ProductID=”{2f711986-cfb4-40d3-9b7d-64aa37faf338}” Title=”Tally” RuntimeType=”Silverlight” Version=”1.0.0.0” Genre=”apps.normal” Author=”Tally author” Description=”Sample description” Publisher=”Tally”> <IconPath IsRelative=”true” IsResource=”false”>ApplicationIcon.png</IconPath> > <Tasks> <DefaultTask Name =”_default” NavigationPage=”MainPage.xaml”/> </Tasks> <Tokens> <PrimaryToken TokenID=”TallyToken” TaskName=”_default”> <TemplateType5> <BackgroundImageURI IsRelative=”true” IsResource=”false”> Background.png </BackgroundImageURI> <Count>0</Count> <Title>Tally</Title> </TemplateType5> </PrimaryToken> </Tokens> </App> </Deployment> [/code] The application manifest is a strange file, because most of it gets overwritten by the Windows Phone Marketplace certification process. Therefore, the application manifest inside your app that can be downloaded from the marketplace will be different than the manifest inside your private copy of your app that you manually deploy. The App element contains a ProductID Globally Unique Identifier (GUID) that uniquely identifies your app, and a RuntimeType value that indicates this is a Silverlight app rather than an XNA app. The value for Title is displayed with your installed app (either in the normal app list or the Games hub). The other four attributes are only applicable for listing your app in the marketplace, but these values (as well as Title) get overwritten by the data you enter on the marketplace website (the App Hub). The Genre value affects where your app gets installed on the phone. If you use apps.normal, it gets placed in the normal app list. If you instead use apps.games, it gets placed inside the Games hub. (Yes, Silverlight apps can do this; the Games hub is not limited to apps created with XNA.) You must choose one of the two locations; your app cannot be installed in both. Leaving this as apps.normal is much more convenient at development-time, because the emulator does not expose the Games hub. When submitting an app to the marketplace, this value also gets overwritten by the category you choose on the website. The text overlaid on a tile is defined by the Title element inside the PrimaryToken element.This means that you can use something different than your app name. Although it is best to use your app name to avoid user confusion, shortening it is a good idea when your app name is too long for the tile. You can leave the title element empty to produce a text-free tile (as done by the Facebook app), although the marketplace might reject such a submission unless you provide justification.The marketplace wants to ensure that users are not confused about which tile belongs to which app. The IconPath element points to your icon image file, the Tasks element points to the main Silverlight page where your app begins running, and the Tokens element contains information about your tile (seen by users who pin your app to their start screen). These parts are rarely changed, but these values are preserved when your app is published in the marketplace. The Other Manifest Visual Studio projects contain a second manifest in the “Properties” folder called AppManifest.xml.This is needed by Silverlight infrastructure, but you do not need to touch this file. Capabilities The most interesting part of WMAppManifest.xml is the list of capabilities inside the Capabilities element. These are special permissions for actions that users might not want certain apps to perform, whether for privacy concerns or concerns about data usage charges. The Visual Studio-generated manifest requests all available capabilities. You can restrict this list to test what happens when your app tries to perform an action for which it does not have permission, but that’s a moot point. With one exception described later, the marketplace certification process automatically detects what capabilities your app needs and overwrites your list in the application manifest with the minimal set of required capabilities. Once your app is running, you do not need to check if you’ve been granted any of your requested capabilities. (There’s not even an API to do so!) If your app is running, then all requested capabilities have been granted.They cannot be revoked. In the marketplace, users are told what capabilities your app will be granted before they decide whether to download it. Each capability has a user-friendly name, so ID_CAP_LOCATION in Listing 1.1 is called “location services” in the marketplace, and ID_CAP_NETWORKING is called “data connection.” The user approval is an implicit part of the action of downloading your app. The location services capability, however, requires explicit consent by the user. The marketplace prompts users to agree to the sending of location data before they download the app. ID_CAP_NETWORKING is the one capability you must manually request! There’s one huge exception to the idea that you can let the marketplace certification process worry about the capabilities list for you. Although it can figure out everything else, marketplace certification cannot reliably figure out whether your app needs the phone’s networking capability. If ID_CAP_NETWORKING is present in your manifest, it will be granted even if you don’t need it, and if it is not present, it might not be granted even if you do need it! The key point is that there’s no need for your app to obtain permission from the user for any capability, nor do you have to worry about whether your app has been granted certain capabilities. Just remember: - If your app is running, it has been granted all the capabilities listed in its manifest. - If your app has been downloaded from the marketplace, its manifest automatically lists all the capabilities it needs and no more (except for ID_CAP_NETWORKING, as described in the warning sidebar). You want to restrict the set of capabilities requested by your app, because it is a competitive advantage. For example, users might decide not to buy your Tip Calculator app if it wants permission to use the phone’s data connection! Therefore, be sure to remove the ID_CAP_NETWORKING capability if you don’t need it.Otherwise, your marketplace listing will say that your app “requires access to your data connection.” Although ID_CAP_NETWORKING is currently the only capability to be careful about, the best practice is to use the Windows Phone Capability Detection Tool that ships with the Windows Phone Developer Tools starting with the October 2010 release.This runs the same automatic capability detection done by the marketplace certification process and then tells you what to put in your manifest. Before submitting your app to the marketplace, you should replace your requested capabilities with this minimal set (and, if appropriate, ignore the ID_CAP_NETWORKING capability that is usually falsely reported by the tool). Why can I no longer debug my app on a physical phone after updating its capabilities? That pesky ID_CAP_NETWORKING capability is to blame. Without ID_CAP_NETWORKING, the debugger is unable to communicate with the attached phone. So keep it there during development, but be sure to remember to remove this capability before submitting your app to the marketplace if your app does not require it! How can I write a game that uses Xbox LIVE features? Some capabilities are for specific developers such as mobile operators and phone manufacturers; not for mere mortals like you and me. ID_CAP_GAMERSERVICES is one such capability that does not work for everyone. It grants access to Xbox LIVE APIs, but only to games approved by Microsoft.You can peruse the Xbox LIVE functionality by looking at the Microsoft.Xna. Framework.GamerServices assembly with Visual Studio’s Object Browser, if you want to know what you’re missing.Most of the functionality inside throws a NotSupportedException unless you are a registered Xbox LIVE developer and have gone through a specific process to enable your game for Xbox LIVE. If you believe you’ve developed a game worthy of the ID_CAP_GAMERSERVICES capability (so you can integrate with Xbox LIVE achievements, leaderboards, and more), you can email [email protected] for more information. Just keep in mind that the standards are very high! Look at the current set of Xbox LIVE games in the marketplace to get an idea of the kind of games that have been approved. Of course, anybody can write a great game for Windows Phone without the ID_CAP_GAMERSERVICES capability, and they can do so in XNA or Silverlight.Volume II of this book series shows plenty of examples of Silverlight games.You’ll even see how to take advantage of Xbox LIVE avatar images without needing any kind of special access or arrangement with Microsoft. Images The project generated by Visual Studio includes three images, shown in Figure 1.1: - ApplicationIcon.png—The main icon, used wherever the app is installed. For normal apps (placed in the phone’s app list), the icon should be 62×62 pixels to avoid scaling. For games (placed in the Games hub), the icon should instead be 173×173 pixels. - Background.png—The tile icon (173×173) used when the user pins the application to the phone’s start screen, whether the app came from the app list or the Games hub. This poorly named file is named as such because it’s technically the background for the tile. The Title in the application manifest is automatically overlaid on the tile’s bottom-left corner, so care must be taken in the image to leave room for the text. - SplashScreenImage.jpg—The splash screen (480×800) shown while the application is loading. You can change the name and location of the first two images, and they can be either JPEG or PNG files. Just remember to update your application manifest accordingly. To create an icon that fits in with the Windows Phone built-in apps, it should usually have a transparent background and the drawing inside should: - be completely white - be composed of simple geometric shapes - reuse iconography already used by the phone if possible - use an understandable real-world metaphor The drawing for the 62×62 icon should generally have a 12-pixel margin around all sides. (In other words, the actual content should fit in a 38×38 box centered in the image.) The drawing for the 173×173 icon should generally fit in a 73×73 almost-centered box. It should be nudged 3 pixels higher than center, giving a 47-pixel margin on top, 53-pixel margin on bottom, and 50-pixel margin on the sides. For drawings significantly longer in one dimension, you may want to leave less of a margin. In most cases, the drawing inside Background.png should be the same as the one inApplicationIcon.png, just larger. As with all user interface guidelines, games are generally exempt from these guidelines. Creating these types of images requires some practice and patience.You’ll want to use tools such as PAINT.NET, mentioned in this book’s “Introduction” section. A few of the characters from the Wingdings and Webdings fonts can even be used to help create a decent icon! These are not strict guidelines or even official guidelines from Microsoft, nor does it match what the initial image files contain; it just tends to look right for most cases.Of course, apps with their own strong branding (such as the Facebook, eBay, and iMDb apps) usually do not follow these guidelines, as being consistent with their own identity outweighs being consistent with Windows Phone. In addition, it often makes sense to deviate from this style if you want your app to stand out in the marketplace. How can my icon get the user’s theme accent color as its background, as with the built-in apps? Each tile icon is rendered on top of an accent-colored square when pinned to Start, so using a transparent background color in your PNG file is all you need to do.Unfortunately, each thirdparty app icon in the app list is always rendered on top of a dark grey square, so there’s no way to get the same effect in the app list. Nothing prevents you from using one of the standard theme colors as a hard-coded background inside your image file, but you shouldn’t do this unless it happens to be a color associated with your brand.That’s because it will never change and therefore look out-of-place to users who switch their accent color. Icons for your marketplace listing have different guidelines than your app’s real icons! Whereas using a transparent background is encouraged for your tile icon, it should be avoided for the separate set of icons you upload to the marketplace.The phone’s Marketplace app renders icons on black squares, which looks odd under the dark theme when the icon has transparency. Even worse, the marketplace section of the Zune program leaves its default white background underneath the icon. For typical Windows Phone app icons, the result is a completely invisible icon due to the white-on-white effect! To avoid this, you must choose a background color for your marketplace icons. It’s a good idea to use this same background for your app icon, even if your tile icon uses transparency to fit in with the user’s theme. Leveraging the built-in splash screen support by supplying the SplashScreenImage.jpg file can be useful for boosting the perceived load time of your app. A desirable approach is to make the image look like what your app will look like once fully loaded, perhaps with disabled-looking controls and without text.This gives the appearance of your app being instantly “there,” but not fully loaded.The text is normally omitted from the image because even if you localize your app for multiple languages, you can still only have the single image file per app. Unfortunately, due to the single-file nature of the splash screen support, it’s only worthwhile for apps that use hard-coded colors and support only a single orientation.That’s because a typical Windows Phone app looks radically different under the dark versus light theme (or in a portrait versus landscape orientation), so no single image can provide a seamless experience for one case without being jarring for the other cases. In addition, I’m a big believer in making apps feel the same as the built-in apps unless there’s a good reason not to, and none of the built-in apps use a perceivable splash screen. The good news is that the phone already produces a built-in animated “Loading…” or “Resuming…” user interface when an app is launched or reactivated. If yours is not fast to load, I’d recommend addressing the core issue (such as delaying computationally expensive work) rather than using a sub-standard splash screen. In this book, none of the apps use a splash screen.To remove the splash screen from your app, simply remove SplashScreenImage.jpg from your project. Many apps in the marketplace (such as the Facebook and Twitter apps) do use a splash screen, but not to improve the perceived loading time.They simply use it to help customize the loading process with their own branding. The icon and splash screen images must have a build action set to Content! If you replace any of the three image files with your own, be sure to set each file’s Build Action in Visual Studio to Content, rather than the default Resource, as shown in Figure 1.2.This correctly places the files directly inside your .xap file rather than embedded inside your DLL. Note that the value of Copy to Output Directory does not matter. Even if the file is not copied to the output directory, it still gets copied to the correct place inside the resultant .xap file. FIGURE 1.2 The three image files discussed in this section must be given a build action of Content in Visual Studio’s Properties window. Every app consists of one or more pages. New projects are given a single page called MainPage. This page defines what the user sees once your app has loaded. It is implemented across two files: MainPage.xaml contains the user interface, and MainPage.xaml.cs contains the logic, often called the code-behind. Listing 1.2 shows the initial contents of MainPage.xaml, and Figure 1.3 shows what this XAML produces when you run the app. Remember that MainPage.xaml is referenced in WMAppManifest.xml! If you want to rename this file, you must also change its name inside your application manifest; otherwise your app will stop working. LISTING 1.2 MainPage.xaml—The Initial Markup for the App’s Main Page [code] <phone:PhoneApplicationPage x:Class=”Tally> [/code] At a quick glance, this file tells us: - This is a class called MainPage (in the Tally namespace) that derives from the PhoneApplicationPage control. - It is marked to only support the portrait (vertical) orientation. - It contains two text blocks with boilerplate text that are meant to be the application name and an appropriate page title. - The page leverages Grid and StackPanel controls to arrange the current text blocks, and additional content is meant to be placed in the grid named ContentGrid. - For such a simple page, there are a lot of things in here! We’ll examine the following two aspects of this file more deeply: - The XML namespaces used at the top of the file - Phone theme resources, referenced as “{StaticResource XXX}” XML Namespaces MainPage.xaml contains most of the XML namespaces you’ll see in this book. Table 1.1 explains them. Although some look like URLs that you can view in a Web browser, they are not. They all map to .NET namespaces in specific assemblies. The first three namespaces are almost always used in Windows Phone apps. The shell namespace is only needed when a page uses an application bar via the ApplicationBar class, or when it enables the status bar by setting SystemTray.IsVisible to True. The status bar is the top area of the phone that displays the time and, based on various factors, signal strength, battery charge, and more. As a developer, you can’t do anything with the status bar other than show or hide it. Phone Theme Resources Rather than hardcoding fonts, font sizes, and colors, MainPage.xaml makes use of several phone-specific resources using StaticResource syntax. Windows Phone defines several resources to make it easy for apps to get a look-and-feel consistent with guidelines and with the user’s chosen theme. Appendix C, “Theme Resources Reference,” lists them all and demonstrates what they look like for both user themes (light and dark). These resources not only contain individual colors, brushes, fonts, font sizes, and thicknesses (for borders and margins/padding) but also contain a bunch of styles for text blocks that package individual resources together. The resources used by this initial page are - PhoneFontFamilyNormal—Segoe WP - PhoneFontSizeNormal—20 px (15 pt) - PhoneForegroundBrush—A solid color brush that is white in the dark theme and black in the light theme - PhoneTextNormalStyle—The previous three resources combined: a FontFamily of PhoneFontFamilyNormal, FontSize of PhoneFontSizeNormal, and Foreground of PhoneForegroundBrush - PhoneTextTitle1Style—A FontFamily of PhoneFontFamilySemiLight (Segoe WP Semilight), FontSize of PhoneFontSizeExtraExtraLarge (72 px, which is 54 pt), and Foreground of PhoneForegroundBrush. under the light theme. This explains how Listing 1.2 produces the result from Figure 1.3 when the user’s theme is dark. Figure 1.4 shows the same page when the phone uses the light theme. Listing 1.3 shows the initial contents of MainPage.xaml.cs, the code-behind file for MainPage.xaml. Because this app does not yet do anything, it only contains the required call to InitializeComponent that constructs the page with all the visuals defined in the XAML file. The class is marked with the partial keyword because its definition is shared with a hidden C# file that gets generated when the XAML file is compiled. LISTING 1.3 MainPage.xaml.cs—The Initial Code-Behind for the App’s Main Page [code] using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; namespace Tally { public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); } } } [/code] App.xaml and App.xaml.cs App.xaml is a special XAML file that doesn’t define any visuals, but rather defines an App class that can handle application-level tasks. Usually the only reason to touch this XAML file is to place new application-wide resources, such as custom styles, inside its Application.Resources collection. AssemblyInfo.cs This file is not worth showing in this book. It contains a bunch of attributes where you can put a title, description, company name, copyright, and so on, that get compiled into your assembly. But setting these is unnecessary because all of the information used by the marketplace is separately managed. Still, the AssemblyVersion and AssemblyFileVersion attributes, typically set to the same value, can be useful for you to keep track of distinct versions of your application: [code] [assembly: AssemblyVersion(“1.0.0.0”)] [assembly: AssemblyFileVersion(“1.0.0.0”)] [/code] By using *-syntax, such as “1.0.*”, you can even let the version number auto-increment every time you rebuild your app.
https://www.blograby.com/developer/deconstructing-a-windows-phone-application-visual-studio-project.html
CC-MAIN-2017-47
refinedweb
3,925
54.63
Opened 7 months ago Last modified 2 weeks ago #14013 new bug Bad monads performance Description (last modified by ) Hi! We've been struggling with a very strange GHC behavior on IRC today. Let's consider the following code (needs mtl and criterion to be compiled): module Main where import Prelude import Criterion.Main import qualified Control.Monad.State.Strict as Strict import qualified Control.Monad.State.Class as State import Control.DeepSeq (NFData, rnf, force) import GHC.IO (evaluate) import Data.Monoid ----------------------------- -- === Criterion utils === -- ----------------------------- eval :: NFData a => a -> IO a eval = evaluate . force ; {-# INLINE eval #-} liftExp :: (Int -> a) -> (Int -> a) liftExp f = f . (10^) ; {-# INLINE liftExp #-} expCodeGen :: NFData a => (Int -> a) -> (Int -> IO a) expCodeGen f i = do putStrLn $ "generating input code (10e" <> show i <> " chars)" out <- eval $ liftExp f i putStrLn "code generated sucessfully" return out {-# INLINE expCodeGen #-} expCodeGenBench :: (NFData a, NFData b) => (Int -> a) -> (a -> b) -> Int -> Benchmark expCodeGenBench f p i = env (expCodeGen f i) $ bench ("10e" <> show i) . nf p ; {-# INLINE expCodeGenBench #-} ------------------------------- -- === (a*) list parsing === -- ------------------------------- genList_a :: Int -> [Char] genList_a i = replicate i 'a' ; {-# INLINE genList_a #-} #-} mtlStateListParser_a_typed :: Strict.State [Char] Bool mtlStateListParser_a_typed = State.get >>= \case 'a':s -> State.put s >> mtlStateListParser_a_typed [] -> return True _ -> return False {-# INLINE mtlStateListParser_a_typed #-} mtlStateListParser_a_let :: Strict.MonadState [Char] m => m Bool mtlStateListParser_a_let = go where go = Strict.get >>= \case 'a':s -> Strict.put s >> go [] -> return True _ -> return False {-# INLINE mtlStateListParser_a_let #-} {-# SPECIALIZE mtlStateListParser_a :: Strict.State [Char] Bool #-} {-# SPECIALIZE mtlStateListParser_a_typed :: Strict.State [Char] Bool #-} main = do defaultMain [ bgroup "a*" $ [ bgroup "pure" $ expCodeGenBench genList_a pureListParser_a <$> [6..6] , bgroup "mtl.State.Strict" $ expCodeGenBench genList_a (Strict.evalState mtlStateListParser_a) <$> [6..6] , bgroup "mtl.State.Strict typed" $ expCodeGenBench genList_a (Strict.evalState mtlStateListParser_a_typed) <$> [6..6] , bgroup "mtl.State.Strict let" $ expCodeGenBench genList_a (Strict.evalState mtlStateListParser_a_let) <$> [6..6] ] ] The code was compiled with following options (and many other variations): -threaded -funbox-strict-fields -O2 -fconstraint-solver-iterations=100 -funfolding-use-threshold=10000 -fexpose-all-unfoldings -fsimpl-tick-factor=1000 -flate-dmd-anal Everything in this code has INLINE pragma. The important part we should focus on are these two functions: #-} Which are just "parsers" accepting strings containing only 'a' characters. The former is pure one, while the later uses State to keep the remaining input. The following list contains performance related observations: - For the rest of the points, let's call the performance of pureListParser_aa "good" one and everything worse a "bad" one. - The performance of mtlStateListParser_ais bad, it runs 10 times slower than pureListParser_a. Inspecting CORE we can observe that GHC jumps between (# a,b #)and (a,b)representations all the time. - If we add a specialize pragma {-# SPECIALIZE mtlStateListParser_a :: Strict.State [Char] Bool #-}, the performance of mtlStateListParser_ais good (exactly the same as pureListParser_a). - If we do NOT use specialize pragma, but we use explicite, non-polymorphic type signature mtlStateListParser_a_typed :: Strict.State [Char] Bool, the performance is bad (!), identical to the polymorphic version without specialization. - If we use SPECIALIZE pragma together with explicite, non-polymorphic type, so we use BOTH mtlStateListParser_a_typed :: Strict.State [Char] BoolAND {-# SPECIALIZE mtlStateListParser_a_typed :: Strict.State [Char] Bool #-}we get the good performance. - If we transform pureListParser_ato mtlStateListParser_a_let :: Strict.MonadState [Char] m => m Bool mtlStateListParser_a_let = go where go = Strict.get >>= \case 'a':s -> Strict.put s >> go [] -> return True _ -> return False {-# INLINE mtlStateListParser_a_let #-} we again get the good performance without the need to use SPECIALIZE pragmas. - The performance of all the functions that are not optimized as good as pureListParser_ais a lot worse in GHC 8.2.1-rc3 than in 8.0.2. - The not-yet documented flag -fspecialise-aggressivelydoes NOT affect the results (). - If you do NOT use INLINEpragma on functions mtlStateListParser_aand mtlStateListParser_a_typedtheir performance is good (so INLINEpragma makes it bad until we provide explicit specialization). Moreover, if we use INLINABLEpragma instead of INLINEon these functions (which logically makes more sense, because they are recursive), performance of the polymorphic one mtlStateListParser_ais good, while performance of the explicitly typed mtlStateListParser_a_typedis bad until we provide explicite specialization. The above points raise the following questions: - Why GHC does not optimize mtlStateListParser_athe same way as pureListParser_aand where the jumping between (# a,b #)and (a,b)comes from? - Is there any way to tell GHC to automatically insert SPECIALIZEpragmas, especially in performance critical code? - Why providing very-explicite type signature mtlStateListParser_a_typed :: Strict.State [Char] Booldoes not solve the problem unless we use SPECIALIZEpragma that tells the same as the signature? (GHC even warns: SPECIALISE pragma for non-overloaded function ‘mtlStateListParser_a_typed’but it affects performance.) - Why the trick to alias the body of recursive function to a local variable goaffects the performance in any way, especially when it does NOT bring any variable to the local let scope? We've been testing this behavior in GHC 8.0.2 and 8.2.1-rc3 and several people reported exactly the same observations. Attachments (2) Change History I added new observation - point 8. comment:9 Changed 7 months ago by I have not worked all of this out, but I have learned something. You have this INLINE pragma: {-# INLINE mtlStateListParser_a #-} It does nothing, because the function is recursive. But alas, it harms things a lot. Simply removing that INLINE pragma makes mtlStateListParser_a behave well in all settings, I think. Can you confirm that? I believe that the reason things go bad is this. GHC does this transformation (always): f = e |> co ===> f' = e f = f' |> co Reason: f can now be inlined at all use sites, and co may cancel. But if the original f has an INLINE pragma we get f = e |> co { INLINE = <inline rhs> } ===> f' = e f = f' |> co { INLINE = <inline rhs> } where the { INLINE = <inline rhs> } is the (stable, user-written) inlining for f. Now the point of the transformation is lost, becuase f won't be replaced at its use sites by f' |> co; the INLINE pragma is what gets inlined. Moreover, if <inline rhs> and e both mention f, then f becomes a loop breaker and we get mutual recusion between f and f'. This what ultimately leads to the alternation between (,) and (##) you observed. Solution (I think) don't do this transformation if f has an INLINE pragma. I'll try that. comment:10 Changed 7 months ago by @simon, you are right. Removing INLINE makes these two functions run with fine performance. It is already described in point 8 in the ticket description. Please note, that point 8 tells about probably related problem with INLINABLE pragma. comment:11 Changed 7 months ago by Sigh. This has turned out to be much nastier than I expected. I worked solely on import qualified Control.Monad.State.Strict as Strict import qualified Control.Monad.State.Class as State mtlStateListParser_a :: State.MonadState [Char] m => m Bool mtlStateListParser_a = State.get >>= \case 'a':s -> State.put s >> mtlStateListParser_a [] -> return True _ -> return False {-# INLINE mtlStateListParser_a #-} foo :: [Char] -> Bool foo = Strict.evalState mtlStateListParser_a I'll refer to mtlStateListParser_a as msp. - Yes, comment:9 is right; the right path is to make doFloatFromRhsreturn Falsefor bindings with a stable unfolding. - Even when that is done, the occurrence analyser does a bad job. We get Rec { msp = ... lvl ... {-# INLINE = ..msp.. #-} -- The stable unfolding lvl = ...msp... }The occurrence analyser treats the occurrence of lvlas a "weak" reference, and so sorts into SCCs thus: Rec{ msp }, NonRec { lvl }. So then it stupidly marks mspas a loop breaker, and lvlas a weak loop breaker. In this case they'd be better in one SCC, in which case we'd pick msp(but not lvl) as a loop breaker. The relevant change is in OccurAnal, around line 1280. -- Find the "nd_inl" free vars; for the loop-breaker phase inl_fvs = udFreeVars bndr_set rhs_usage1 `unionVarSet` case mb_unf_uds of Nothing -> emptyVarSet -- udFreeVars bndr_set rhs_usage1 -- No INLINE, use RHS Just unf_uds -> udFreeVars bndr_set unf_udsBut I'm not fully confident of this change. - Even if we fix that, then the strictness analyser fails. We end up with msp = (\ (s::[Char]). case s of p1 -> (False, x) p2 -> (msp |> sym co) s' ) |> coThose casts are enough to kill demand analysis. It was relying on the coercion-floating that we nuked in comment:9! The function looks to the demand analyser as if it has arity zero, and so we get no useful strictness. Yes, we could teach the demand analyser more tricks, but the tail is beginning to wag the dog. - This is all stupid. An INILNE pragma on a recursive function is doing no good at all. Maybe we should just discard it. And indeed that makes things work. - Until you use an INLINABLE pragma! We don't want to discard the INLINEABLE pragama on a recursive function -- it is super-useful. But if we don't the same ills happen as with INLINE. Actually, the specialiser propagates an INLINE pragma to the specialised function, but does not propagate an INLINEABLE pragam. Result: if you give an overloaded signature for msp, the specialiser will create a pragma-free specialised version, which will optimise nicely. But if you give a non-overloaded signature msp :: Strict.State [Char] Bool, the function fails to optimise for the reasons above. Mind you, in the latter case the INLINEABLE pragma is just as useless as the INLINE pragma was. This is ridiculously terrible. The pragmas (which are there to optimise the program) are getting in the way of optimising the function itself. What to do? Here's a simple idea; - Discard INLINE pragmas for recursive, or mutually recursive, functions. (You can do this manually too!) - Peel off a top-level function for INLINEABLE pragmas, thus: Rec { f = e[f] {-# INLINEABLE = e[f] #-} } ===> Rec { f' = e[f'] } Rec { f = f' {-# INLINEABLE = e[f] #-} }The first Recis a pragma-free group. The second has all its pragmas (for later clients), but just indirects to the first group if you actually call it. Alas, you can't do this manually right now. But somehow none of this really feels right. I'm not sure what to do, so I'm just brain-dumping this. Maybe someone else will have better ideas Changed 6 months ago by WIP on floating from stable unfoldings Changed 6 months ago by WIP on occurrence analysis and rules comment:12 Changed 6 months ago by The attached patches are not finished; they were just WIP related to the comments above. comment:13 Changed 6 months ago by comment:14 Changed 2 weeks ago by What is the status of this, Simon? Regardless, presumably nothing will change for 8.4. Very interesting; this will be an interesting thing to mull over tomorrow morning.
https://ghc.haskell.org/trac/ghc/ticket/14013
CC-MAIN-2018-09
refinedweb
1,748
58.79
The Thing About Jetpacks A book about designing wonderful things Background In 2013, I wrote a book of design essays with my friend Lukas Mathis and we sold it as a hardcover book. I thought it’d be fun to share the whole thing on Medium for free. You can also download an epub version here. Enjoy! Preface I’d like to talk to you about three things. First, thing number one. Almost exactly a year ago, I visited Seattle. While there, I met my Internet friend Jon Bell, whom you might know from such things as this book you’re currently holding. It’s funny how you can meet somebody for the first time, but feel like you know at least part of that person very well. We talked about design a lot, and when I left, I knew two things: one, I like this guy. Two, it would be fun working with him on some kind of project. Here’s thing number two: I’m a horrible procrastinator. One of the techniques I use to cheat myself into doing things is something I call “minimum viable goals.” I tend to set huge goals for myself. Stuff like “tomorrow, I want to clean the house, finish two projects I’m currently working on, and vacuum the car.” When I wake up the next day, all of this work seems so daunting that I can’t bring myself to start it. Instead, I just sit on the balcony and read a book. Which isn’t bad, of course. But it’s not what I intended to do. So instead of setting these huge, insurmountable goals that are so big that I don’t even know where to start, I stop myself, and instead find a minimum viable goal. Instead of writing five chapters in a book, I’m merely going to rewrite a single sentence that has been bugging me. Instead of cleaning the whole house, I’m merely bringing out the trash. Instead of finishing that website I’ve been working on, I’m merely going to improve the validation error messages on the contact form. Those are small goals. I can get one of them done easily, and still go read afterwards. So I get one of them done. And then, instead of reading a book, I do another one, because I’m already working on it. And another one. And then I start working on something a bit bigger. And since I’ve already started, I continue doing it for a bit, because I don’t want to leave it unfinished. And before I know it, I’ve done a lot of small things. And some bigger things. Everything considered, I’ve ended up doing quite a huge thing. This is how it often works. Starting with small ambitions is easier than starting with huge ones, but you’ll often end up achieving more that way. Okay, I’m bad at foreshadowing, so I’ll just come right out and say it: Jon writes about this very same concept in his essay “50 Words,” which you’ll find later in this book. Don’t skip ahead, though, I want to finish telling you about my three things first. On to thing number three: writing on the Internet can be, well, a sad experience, especially if you have a reasonably sized audience. If tens of thousands of people read what you write, there’s always a few people who find some tiny detail in your writing that just happens to be one of their pet peeves. So every time I publish something, I get a few emails complaining about things. Some of these complaints are well-reasoned and interesting and useful. Others, less so. To avoid the less-so ones, I started writing more and more defensively. I started hunting for any potentially offensive or even just not entirely bland sections in my essays, and removing them, because I knew people would complain. But that’s no fun. Writing publicly started to become more and more of a chore than something I was looking forward to. When Jon asked me whether I wanted to write some essays for a tiny booklet on design that would only be sent to 100 people (no pressure, he assured me), I said yes, because the three things I mentioned above — I like Jon, and I like to do small things, and I like the idea of limiting the audience of my writing — came together in a perfect blend of… multi-flavored ice cream, I guess. And like in my “minimum viable goal” thing, all of the small things we’ve done together have ended up creating a big thing, which you’re holding in your hands now. We wrote a lot of small essays, and now they’re a big book. Which is awesome. Lukas Mathis Switzerland, somewhere in the Pisces-Cetus Supercluster Complex July 30, 2013 Introduction It was a fun year. There are plenty of websites that get a following, and plenty of websites that stop updating after a month. Fuckjetpacks.com managed to do both. The site launched on August 31, 2012 with the tagline “celebrating the future around us.” That, along with the notable domain name and this essay named “Why” helped explain what I was hoping to achieve: I built this site because I believe the soul of a product can be found in interaction design. Put another way, design is not just how it looks, it’s also how it works. Do you remember the feeling you got the first time you used the iPod click wheel? Or the first time you saw Metro? What about the feeling you have after navigating a phone tree for five minutes before being told to call back during normal business hours? Or when your phone battery dies at 4pm? These are the moments where a product succeeds or fails. But those moments can be difficult to describe in words, or are too subjective, so they don’t get as much publicity. Instead we get facts, which are boring: I can tell you how many gigs a phone has, or the color of a car, or the dollar amount of the latest patent case settlement. But describing how something feels is much harder. More personal. More interesting. And if I do my job right, it’ll be a lot more fun to read. As time went on, I got more convicted about the points in this mini-festo. There really are a lot of sites on the internet that emphasize visuals. Just about any design or tech-oriented site is going to lean towards beautiful renders, discussions of new logos, shaky videos of unboxing videos. Things that are all about the celebration of what you can see, what you can quantify. But I’m not primarily a visual designer, I’m an interaction designer and a developer. I want to make things. I want to craft whole experiences, so I don’t relate to sites that spend more time on the tech specs than the feel of the product. And besides that, I’m a consumer. The cover of a book, the poster for a movie, or stills from a video game don’t tell me anything about an experience. That’s where the good stuff is, and where the best designers are able to make their mark. I wanted to stop fantasizing about jetpacks and start celebrating the little details that are making today’s products delightful and worthy of praise. So I launched the site with four little design essays and almost immediately the site found an audience. A pretty big one. After a month I decided to pull it offline again, and instead started writing a trilogy of books with Lukas Mathis called For 100 Of Our Closest Friends. As the title suggests, we only gave out 100 copies of each volume, which was our way of getting away from the publicity of the internet and back towards something we hoped would be a little more special, a little more traditional, and a whole lot quieter. This book is a compilation of everything we published over the year. We hope you enjoy it :) Jon Bell Seattle August 12, 2013 The Benefits of Isolation I was pleased to discover an essay entitled Solitude and Leadership. As long as there’s been a web, there have been people decrying it. They point to studies that tie it to depression, they cite its isolating effects, and they remind us that nothing is a substitute for face-to-face interaction. And they’re not entirely wrong. But they’re only representing one side of the story. The web, it should go without saying, has brought tremendous value to our lives alongside a lot of garbage. It’s not all revolutions and time wasted, of course. It’s also everything in between. And so this article is particularly poignant to me, as it doesn’t seek to blame the web, or celebrate it. It moves beyond the standard debate entirely and lays its focus on us. Our attention span. Our ability to think. Deresiewicz writes:. There’s plenty of ammunition in the essay for technophobes, but I don’t read this as an anti-technology screed. I read this as a critique about how we learn, create, and grow. An analysis of the time we don’t give ourselves. Later, he writes:. I think this is a good summary of why I left the web for a while, and why I’m back. As I get more and more dissatisfied with conventional wisdom, with soundbites, with tech tabloids, with regurgitated content, I think there’s a greater and greater need for real voices to return to the web. So here I am, doing my small part. Further reading: Solitude and Leadership, by William Deresiewicz Simple.com Has One of the Best Experiences on the Internet [This post was heavy on images, then I converted it to a book, now I’m posting it back on the internet and I lost the original images. Whoops! –Ed] I like my current bank, but I’m moving to Simple.com. It’s a textbook case of strong but understated interaction design. Let’s dive in! Passphrases Banks deal with money, meaning they need to be secure, meaning the bank website should have an awful policy requiring an uppercase letter, a number, a symbol, and changing your password every two weeks, right? Wrong. Say hello to “passphrases.” They’re more secure (because they’re longer) and easier to remember because they’re plain English. Here are some examples of passphrases: - my brother got the dresser - remember to floss! - I will not forget this password Passphrases are awesome, and Simple is awesome for using them. Sort by Size Most financial sites sort your financial activity so that the deposits are at one end of the list, and the biggest charge is on the other end. Simple understands how people really look at money — they want to see the deposits and the largest credits grouped together. Brilliant. Nifty Auto-tags If I tip someone, Bank Simple knows about it. If I pay a fee, they know that too. In both cases, automatic tags appear next to the line item, which is a huge leap forward, interaction-wise. This is on top of their always-right auto-categorization of charges. I don’t know how they made it so good, but they did and it means a lot of saved time. Super simple saved searches Want to know how much you spend at fancy restaurants? Do a search for “restaurants > 30.” It’s that easy. Now let’s say you want to track your spending in a certain area. Easy. Click the big “New Saved Search” button and you can quickly see that data whenever you need it. Per month, per week, per day views Knowing how much you’re spending overall, or in a category is nice. But you know what’s even better? Seeing how much you’re spending per week. It’s a completely new way to think about budgets, long overdue, and executed perfectly. “Safe to Spend” It’s a bit annoying when there’s a difference between your account balance and what you can spend. Simple just highlights the money you can spend after subtracting any savings goals you may have. The best customer support I’ve ever received Simple puts customer support front and center, to the extent that it’s a pane that slides onto the website from anywhere you are. In my experience, responses come in within 5 minutes, and never longer than a day. It’s so good that sometimes I drop into the customer support box just to tell them how much I love their service. And then they write me back within minutes to say thanks. It’s so easy to send money Click the name, choose a dollar amount, whoosh, a check is sent. There’s also an iOS app. Bill pay has never been this delightful. And so There’s more, but I don’t want to give everything away. Simple is part of the reason I kicked off this blog. A lot of people talk about design like it’s magic pixie dust that you sprinkle on a product to succeed in the marketplace. But it’s obvious when a company only understands design at a superficial level. The masthead may be nice, but the actual experience tends to fall apart. Simple has no such problem. Sure, it looks nice, but more importantly, it works right. It’s actually delightful, despite being a banking site. Take notes. This is how it’s done. “Flick to TV” Represents Everything Wrong With Product Design Today. What happens when you have two outputs, a TV and a stereo? Well, you need some way to select which output you’re aiming at. And how do you make the flick gesture discoverable enough for the mainstream? Cutesy gestures are the mystery meat navigation of the touch era. This particular feature may actually suffer from the opposite problem, by being too discoverable. If you want to reserve “swipe up” to mean “flick to another screen,” how does a person scroll up on a website without accidentally triggering the “flick to tv” gesture? You could make it a two step process — tap the share button, then flick in the direction of the screen, then hope there aren’t two screens near each other that would require a “which screen did you mean?” dialog. Or you could remove the gesture, leaving you with a button. A single, understandable, discoverable button that can work for multiple outputs. It’s not sexy and new, but it works. And we need more “it just works” design in the world. Apple Avoids the Temptation of Jetpack Design Since the late 90’s, most of Apple’s product releases have been met with a yawn by industry watchers even as the products themselves sell better year-over-year. This is not a coincidence. A lot of Apple’s success comes from avoiding the temptation of Jetpack Design. Here’s how they do it: - They pick one feature - … that the market is familiar with - … and they do it better - … then they let you know about it Pick One Feature Apple has mastered the art of saying “we did hundreds of things in this release, and here are the highlights” while reserving their massive marketing firepower for a single feature. Don’t Be Too Early. Skip First, Aim for Best By picking a single thing to trumpet, and by making sure the market is ready for it, Apple just needs to focus on a great execution of their highlighted feature. Apple has always been upfront about this facet of their strategy. Tim Cook recently said “[Apple will] participate only in markets where we can make a significant contribution.” Tell the World So you’ve got a new spin on an idea that the market has seen before. You’ve executed on it well. You don’t have a ton of other features cluttering your marketing message. Now to go market. Go big. Let everyone know. Blanket the airwaves with a single, powerful, well-honed message that no one can miss. (Many companies only do this step, and forget about making a product that anyone will care about. This is not recommended.) Watch the Yawns Roll In.” I’m with Gruber on this one: Apple may be on to something. Further reading: How Apple Rolls I Recently Saw a Delicious Interaction That Most Restaurants Could Learn From Imagine a restaurant website that puts special emphasis on whether or not the restaurant is currently open. Instead of describing the open and close times with text, the website checks the current time and speaks to you naturally. For example: “We’re open!” or “Come quick, we’re closing in an hour!” or “Sorry, we just closed. We’re open until 10pm on weekdays, and midnight on weekends. Hope to see you soon!” This is when it becomes clear that the website isn’t just a PSD blindly exported to the web, as so many are. The designer clearly thought about the three most important questions that people ask a restaurant website, which are: - “Are you open?” and/or “What are your hours?” - “What’s your menu?” (PS please don’t link me to a PDF) - “Where are you located?” … and the design employs a tiny bit of software magic to address each of these primary use cases. Take the menu — when you load the page, it slides down to the part of the menu that corresponds with the time of day. In the morning it takes you to breakfast items, in the evening you see dinner. When you look up the restaurant’s location, the site uses HTML5’s location detection to show you the route between you and the restaurant instead of making you type it all in by hand. This is why today’s designers can benefit from learning a bit of code. Software design often needs to flex temporally and present different things based on each visitor’s conditions. And that’s not something Photoshop or traditional visual design education is set up for. Experience design goes beyond PSDs. They Mean Well “Chase your dreams” is loving, well-intentioned, awful advice. It has all the empty promise of something we often hear in product design: “make it awesome.” If only it were that easy. In both cases, people mean well. They’re just trying to help inspire you. And that’s nice, to a point. Thing is, most of us don’t need platitudes. We need help taking the first step. Many of us know where we want to go, but we’re feeling overwhelmed or lost. The key, whether you’re talking about product design, living a fulfilling life, dieting, saving money, starting your own business, finishing a term paper, becoming more organized, cleaning your house, repairing your relationship, or any other daunting task is this: start. Stop chasing “awesomeness,” close all your browser tabs, and figure out your first step. Make it as small and doable as possible. Break it into steps until the first one feels manageable. Then do it. Then figure out your next step. Do that. Repeat. Work hard. And one day, yes, you’ll look around and see you’ve done something. But you won’t get there with idle dreaming. You’ll get there because you stopped chasing, started doing, and kept it up. Your dreams have a way of finding you when you’ve been working hard. Track 8 Is a Joy To Use [For several years, Apple was criticized for their hyper-realistic design aesthetic while Android and Windows Phone embraced a flatter treatment that Microsoft popularized with what was then called “Metro.” The article below was in the midst of this debate, which is now largely rendered moot by iOS7’s new visual style. –Ed.] There’s a music player for iOS called Track 8. It’s one of my favorite apps. And it’s very, um, flat. It’s all the rage to talk about how Apple’s gone off the skeuomorphic deep-end. And for some people, that’s the end of the discussion. In their mind, Apple makes UI look too real-world, therefore their designs are lame. It goes without saying, but it’s a bit more complicated than that. Let’s be honest: Apple’s iCal would be a pain to use even if Apple removed the stitched leather. It’s just not a very strong calendar application, but the design community seems fixated on the skin Apple chose, which I consider to far less glaring of a problem. It’s just more obvious in a screenshot. And on the other hand, I’ve used plenty of Metro apps that are a pain to use. Because at the end of the day, it’s hard to nail an app’s interaction model, whether done in Metro, something skeumorphic, or something in-between. Which brings me back to Track 8. It’s fantastic design, but not because it looks like a Metro app. It’s just a fantastic experience, period. I highly recommend it. What’s Your Cup of Tea? When I was a teenager, my friend and I drove by two people deep in conversation. I pointed at them and said “See, that’s my cup of tea.” I love his response: “It’s so great that you have a cup of tea.” Thinking about how I work best has helped me with my design work. I spend a lot of time listening to my intuition and aligning with processes I know help me to be more creative. It’s how I get to my best designs. Put another way, my “design process” starts with “process design.” Which brings me to the process design I’ve used for this site. Early on, I had some pretty strong gut feelings about how FJP should work, and those decisions affect the experience of reading it. First, I write best when it feels like no one is reading. I’m less cautious and more honest, so it’s more likely that I’ll say something that has some value. Second, I write first drafts quickly, but it takes me multiple drafts to get to an acceptable level of quality. I have a bad habit of hitting publish too quickly. Third, software slows me down and frustrates me. When I write in a CMS, my writing suffers. Writing uses a completely different part of the brain than blogging management requires. And that’s why the site works like it does. I’m anonymous so I can focus. I publish once a week so I give myself time to write multiple drafts. I hand-write the pages in plain text and put them through Markdown so I don’t have to deal with software any more than necessary. I’m inspired by the idea that I can lessen the distance between us by stripping everything away but the writing. I want to present you the best content I know how to write, once a week, with no overhead, and let the content speak for itself. Your Sign-up Form Tells Me All I Need To Know Some designers treat sign-up/sign-in forms as being outside the core experience for a web app. A few necessarily frustrating hoops before getting to the real fun of the site. I disagree. Forms are the handshake, the joke to break the ice, the first impression. Your form tells me everything I need to know about your app, and by extension, your interaction design skills. Each chef cooks roast chicken differently. Comedians all tell the Aristocrats. It’s all there, in plain view, in the way you design your form. One Of My Favorite Buttons Hundreds of millions of people have gone through a flow like this dozens of times: - Take a great photo - Check a social app like Twitter, Facebook, SMS, or email - Decide to share that great photo - Tap “share” - See “‘Choose from library’ or ‘Take photo’” dialog - Tap “Choose from library” - Find most recent photo - Tap most recent photo - Tap “use” to use most recent photo But despite it being a very common flow, despite the fact that the best designers behind smartphone platforms tend to sweat even minor details, despite the fact that it’s not hard to see how to optimize for this scenario, it still took years before someone invented one of my favorite buttons: “Use Last Photo Taken.” So instead of having to dig through your photos or compose a new one from your camera, you just tap that button to get the most recent photo. Yes. It’s so beautiful and clear. So obviously informed by a keen sense of empathy and a study of user behavior. It’s perfect. Of course, it isn’t going to cure male pattern baldness, bring peace to the Middle East, or sell more copies of Tweetbot, the application that invented it. Frankly, I’d be surprised if more than 10% of their user-base ever stops to think about it. But it’s fantastic interaction design all the same. It’s this attention to detail, this relentless drive to add just a little more delight or remove a little pain, this tendency to never be satisfied with the status quo that can lead to great things. It’s just a button, but it’s the result of wonderful thinking. Opening Your Mind So Wide the Ghosts Slip In When I’m designing, I believe in ghosts. Let me explain. I’m an analytical person. I believe in science and logic. I don’t actually believe in ghosts in any serious way. But part of great design is taking lateral leaps of logic, of challenging assumptions, letting the world change your mind, staying receptive to new experiences and ways of thinking, channeling the energy and ideas around you, knowing anything is possible, letting your intuition drive your thinking, not saying no, not shutting things down, re-evaluating your point of view, treating everyone as if they have something to teach you, staying mentally agile, sharp, light, nimble, and quick. And when I’m in that mode, when I’m truly in touch with my creativity, when my mind is necessarily wide open, the ghosts slip in. Of course ghosts might exist, just like of course this design problem has a solution just out of my reach, one I can discover as long as I keep working at it. In that moment of creative inspiration, everything has to be possible. When I’m designing, I believe in ghosts. I have to. “I Wish This App Looked the Same On All Platforms,” Said No One, Ever Every company that ships multi-platform software has gone through it. It’s part of a predictable and natural maturation process, like how teens suffer through bad acne, or how college kids keep falling in love with Ayn Rand. I’m referring to the infamous “Hey, since we ship on multiple platforms, why don’t we make sure our software looks the same everywhere?” idea. It looks good on paper. But it just doesn’t work, and never will, for several reasons. Learning From Word 6.0 Word 6.0 is a fantastic cautionary tale, and it’s such a simple story I can tell it in bulletpoints. - Word 5.0 for Mac was considered some of the best software written by anyone, on any platform. - Microsoft decided to standardize Word 6.0 between Windows and Macintosh platforms. - Word 6.0 for Mac was considered some of the worst software written by anyone, on any platform. - Microsoft was confused. “Isn’t consistency great?” they asked. “We’re Mac users,” came the reply. “To us, consistency means “Mac-like,” not “A Windows app clumsily ported to Mac.” - Microsoft learned their lesson and so the “Mac Business Unit” has formed with a charter to make great Mac software. Implicit in this mission is “don’t just port it, design it.” Expectations Aren’t Portable No one’s arguing Word for Mac should have different features, a different name, significantly different branding, or compatibility issues. These are things the customer rightfully expect to work in an understandable and predictable way. The problem is when you try to port whole interaction models from one platform to another. Mac OS, iOS, Windows, Windows Phone, Android, Blackberry, and web all have different conventions, interaction models, mental models, expectations, and de facto standards. Trying to pretend otherwise will only harm your design. For example, if you put a “close window” button at the top left of a Windows application, you’re not being “consistent.” You’re not “staying true to your brand.” No, Windows users expect it on the top right, so you just designed and shipped a bad software experience. Period. Speaking With An Accent Users don’t often express it verbally, but they struggle to work with software that speaks with an accent. They might not know what the word “port” means, but they feel it when software hasn’t been tuned to their platform. Watch users try to complete tasks. You’ll see them try their standard platform-learned steps, and if they don’t work, you often see them shift in their chair. They furrow their brow. Their voice trails off. That moment, where you make a user think “Uh-oh, this software is going to be hard,” is something to avoid. And it happens a lot when you try to force consistency across platforms. Can Someone Explain the Use Case? So if there are clear experience problems that appear when people fall for this groupthinky boardroom-bubble foolish consistency pipe dream, why does it keep coming up? What’s the use case? What’s the problem we’re trying to solve? I guess the thinking is “when a user moves from platform X to platform Y, we don’t want them to be confused.” Ok, confused how? Presumably they installed the app with your name on it. The icon and logo look the same. The same core functionality is there. What more do you want? Remember, this edge-case of a user has bought into a new platform, so if you align with it, you’ll make the user’s transition easier. Resist it, and your application will stick out like a Java applet. To use another metaphor, users aren’t asking for one-size-fits-all baggy T-shirts. They want tailored. They want custom-fitted. And if you won’t give it to them, your competition will. (A Caveat) There are apps that do look and feel similar across platforms without degrading the experience. Flipboard is a great example. It started on iOS, went to Android, and managed to stay “Flipboardy” without feeling like an inconsiderate port. The key to their success has less to do with user expectation and superior execution. At no point in the Flipboard for Android experience does an average user feel like the app is speaking with a thick iOS brogue. Quantifying exactly why is a topic for another article, but Flipboard pulled it off. Most companies don’t. Further reading: Mac Word 6.0 Drawing Inspiration From Roller Coasters “You know,” he said with a grin, “Walt Disney was one of the first experience designers.” It sounded outlandish at first, nonsense, like mashing together an old thing and a modern one just to be retro-hip. Like “flophouse retweet” or “steampunk.” It was a fun discussion. I learned that before Disneyland, theme parks were seedy and dangerous. The concept of a family-friendly amusement park simply didn’t exist, but Walt had a vision of the whole experience, not just an idea for a ride or two. He thought maybe he could make things better for people. The more I’ve learned about Disney and theme parks in general, the more I’ve learned about the nature of experience design. How it takes a whole network of subsystems to support a single vision. Business types like to talk about “strong vertical integration,” but great experience goes further. It can be awesomely fractal. For example, you could say, “At my park, I want a family to have a fantastic 8-hour day.” That spins up several new conversations around affordability, around appealing to multiple demographics at once, food, bathrooms, transportation, crime, and before you know it you’re designing a city. And even after you’ve got the city humming along to support this vision, now you have to make it fun. How often can you build new rides? How are you going to handle it when people have traveled all day to try your marquee ride and it breaks down? How can you bring more delight, even as the park gets busier and more complex? How do you deal with lines? Each of these are master’s thesis-sized topics. The whole area, this whole way of thinking, is very fun to think about because you can go as blue-sky or detailed as you want. There’s a need for great decisions at every level, so there’s no way to run out of fun design work. I’ve spent a career in experience design feeling distant from the great artists. I’m technically in the same family but I don’t feel closely related. I’ve realized to be a great experience designer, you don’t necessarily need to think like Michelangelo. Think like Disney instead. Because as experience designers, we work every day, in a series of behind-the-scenes subsystems, to realize a simple vision: we just want to make things better for people. Andy Crewdson, Where’d You Go? We all know the story of Harper Lee, the reclusive author who wrote a masterpiece as her debut and never published again. Or Bill Watterson, who put in a tidy ten years writing Calvin & Hobbes before dropping from view entirely. But when Andy moved on, it felt personal. Andy Crewdson Andy started a blog called Lines & Splines in 2000 about typography and it was unanimously considered one of the best, most thoughtful blogs ever created. But after a few years, Andy simply disappeared without any explanation. At the time, we were shocked. These days we call it infocide, and it’s becoming more common. _why Years ago, an enigmatic man who went by the name “why the lucky stiff” (_why for short) became a minor celebrity on the web when he (amongst many other things) wrote a beautifully unique comic about writing code. And then he disappeared, taking all his content with him. Mark Pilgrim Then there was Mark Pilgrim, a well-respected online figure, who dove into writing a fantastic online book on HTML5. Thousands of designers and developers grew to rely on his groundbreaking work. In 2009, his sites were pulled offline. Instead of returning standard 404 errors, they returned the little-known 410 error code, described this way in part: … the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed. That is a man saying, in the geekiest possible way, “please just leave me alone.” The whole thing felt very David Foster Wallace, so friends leapt into action, asked around, called the cops, and held their breath. Word came back shortly: Mark Pilgrim is alive/annoyed we called the police. Please stand down and give the man privacy and space, and thanks everyone for caring. That was a relief, but it still left a lot of questions. Infocide isn’t normal. It just isn’t done. Right? The web is tuned for digital extroversion We often assume that people who produce also want to be famous. Whether they’re actors, writers, designers, or developers, they wouldn’t put themselves into the public eye if they didn’t want recognition, right? With follows, likes, favorites, retweets, pageviews, reblogs, and comments, we’ve provided digital extroverts with everything they need to feel validated for a job well done. And it’s a great feedback loop, one I’m glad we have. (People said some touching things this week about this site. Thank you.) But is there a way to design a creation network for digital introverts? An outlet for people who know what they want to say, are compelled to create, and want to share publicly, but without any of the spectacle? Without any of the hassle? I wonder. Further reading: _why’s poignant guide to Ruby Remember to Ask Why I was working hard on my first website. It was 1994. Someone asked if I was going to use an “under construction” animation. Let’s pause here. It would be easy to turn this into a “Let’s all laugh at the hapless guy from 1994 while we feel superior about our exquisite modern taste and perfect hindsight” story. So let me be very clear about what happened next. I asked why, but not with a grin, or a sneer, or an eye roll. I asked the way you might spot a friend ordering a beer you don’t recognize before earnestly asking “Have you tried that before? Should I order one?” Turns out he didn’t have a good answer. He just sort of shrugged, and I skipped the animation idea. That moment has stuck with me. I remind myself not to be rude about it, but to always ask why. Because, frankly, an under-construction animation sounded SUPER COOL at the time. It and a million other visually rich/usability harming fads comprised the Jetpack Design of the 1994-era web. Turns out “why” served me very well through the years. Trends came and went, and I considered them all. But if I couldn’t explain why I should follow them, I didn’t. Not that it would have been a problem if I had, of course. But by putting each decision through “why,” I was able to bring a high level of intention to my designs. It was one of the best lessons I’ve learned. [This was the last essay of the blog. After the blog, Lukas Mathis and I did a collection of design essays in a trilogy of books called For 100 of Our Closest Friends. That’s what comes next. –Ed.] Opting Out of Military French Toast There’s an episode of M*A*S*H where a soldier tries to talk a chef through preparing his mom’s perfect french toast. As the instructions are multiplied to serve an entire mess hall, something is lost in translation. The soldier describes each step of the recipe until the final one, where the chef is supposed to wait for the bread until “you pinch it with your fingers and it doesn’t bounce back.” The chef takes the soldier’s careful instructions and multiplies them. He dumps huge canisters of powered eggs and powdered milk into a cauldron, dumps hundreds of slices of bread in after them, and unceremoniously sprays the batch with an industrial-strength hose. Then he deadpans, “Would you care to pinch it, or shall I?” It’s a great reminder that some of the best things don’t scale. Designers are well aware that some of the best experiences can be found amongst the small, the intimate, and the heartfelt. Which begs the question: how can we bring this magic into product design? After all, our customers are used to high impact, mainstream experiences. Can any product compete with the heady rush of camaraderie, of kinship, or of first love? And how do we balance this insight against the drive to make the biggest possible impact? If ten people love your stuff, why not go for a hundred. Or a million. Why not? Because sometimes you make military french toast. If you want to change the world, try reducing your audience. See if you can make them feel something. Don’t settle for mere visibility, challenge yourself instead to cultivate love. A Brief History of Love On the Internet Robin Sloan recently asked a provocative question: how can we determine what we really love on the internet, versus what we’re merely liking? If we think back a few decades, the best way to describe love of a digital product or experience has shifted quite a bit. For me, it all started with the ballpoint pen. Pen Before Prodigy, before AOL, before Yahoo!, Google, and Facebook, before widespread internet, there were dial-up “bulletin board systems,” or “BBSes.” You’d call someone’s house with your phone, horrible noises would come screeching out of the modem speakers, and with luck, you’d connect. Early on, the best BBSes were recorded the old fashioned way — you’d scrawl their number on a sticky note, a napkin, or the margins of a magazine article. The amount of excitedly scrawled circles around a phone number demonstrated how much you loved the BBS it belonged to. Bookmarks Then web browsers came on the scene, and with it this great concept of “digital bookmarking.” It allowed people to save great website addresses for later. It didn’t take long for early web surfers to overwhelm their bookmark folders. Social Bookmarks With the rise of delicious and other sites like it, we began collecting bookmarks as a crowd. It drove a fundamental shift away from curating for ourselves to curating for others. And you didn’t need a blog to do it. [this is good] Everything changed with [this is good], which I consider to be one of the greatest inventions of the early web. It was started by Filepile.org, and was nothing more than a bit of metadata denoting quality. Which meant we could uncover good things more easily. By simply sorting by number of [this is good]s, it was easy to find the best content on FilePile. The Like Button Facebook’s Like Button is the moment when [this is good] went mainstream. The concept of favorites was nothing new, but Facebook was able to push the concept further than anyone else, even opening it externally so any site on the internet could tap into the same flagging mechanism. Which lead to some interesting side effects: on one hand, we found a de facto standard for liking something. On the other hand, liking something started losing its meaning. Just because a band has a million “likes” doesn’t mean I’ll love it any more than a band with three. Pinterest is the most popular of a kind of curation website that counts mlkshk, fffffound!, and zootool as contemporaries. These sites aren’t specifically asking if you like something — it’s assumed. As such, these sites are goldmines of higher-than-average quality content. The sites have moved beyond “this is good” and into “this is who I am.” Likes are thumbs up you leave all around the web, Pinterest has turned into a place where you express your tastes through a tapestry of found content. The State of Things And here we are, with two tiers. There’s the infinite sprawl of the Internet that may as well be the universe — too large to fully explore, and expanding exponentially. Then we have the layer on top: a curation layer, an attempt to pull out the best stuff, a way to separate out the wheat from the chaff. A way to say “I like this stuff more than all the other stuff.” But like our bookmarks folders, like the stack of books beside our bedside table, like our bloated Instapaper queue, our curation layer has gotten overwhelmed. For many people it’s so unwieldy that it’s begun to lose meaning as a curation layer at all. Which is why Robin Sloan’s thoughts on love are so timely. Redefining Love on the Internet Robin put out a must-see iOS app called “Fish: a tap essay.” He described it as a […] short but heartfelt manifesto about the difference between liking something on the internet and loving something on the internet. His central tenet is that love on the internet means “something you’ll return to,” a guideline I find refreshing and clear. It sets a high bar for all of us who try to build extraordinary things. Things that people can love. Does anyone return to what you do? Would you rather one million people look at your work once? Or do you want one hundred people to return to what you’ve done? Do you want an vast expanse of followers, or 100 close friends? A Tale of Two Cars (Lukas Mathis) A year ago, I decided that I finally needed to buy myself a car. I came up with some basic requirements: It had to be safe. It had to be practical. It had to be cheap. And it had to be economical. I researched cars. I looked into fuel efficiency and safety ratings, into trunk volume, price lists, leg room, iPod connectivity, insurance costs, resale value, quality ratings, sound insulation. And I found the perfect car. My test drive took five minutes, I drove the car once around the block, because I already knew that the car did exactly everything I wanted. I didn’t need to test-drive it, I knew its specs and stats and numbers. Besides, modern cars all drive pretty much the same anyway, right? I bought the perfect car — and it sucked. Sure, it did everything I wanted it to do, but I felt nothing for it. And when I did start to feel something, it was contempt. At first, I wasn’t entirely sure why this happened. This is a great car! It does its job perfectly! What’s wrong with it? Eventually, it occurred to me: the car had no personality. It was a black subcompact, just like millions of other black subcompacts. Its engine was quietly humming away, just like millions of other engines. Sitting in the car, the seat felt comfortable, the windows were placed to allow the best possible overview of the street around me, and the dashboard was unobjectionably pretty. Just like millions of other cars. My car was obnoxiously pleasing, annoyingly reasonable, and insultingly average. So I sold it and bought another car. An unreasonable car. My new car is the opposite of what I actually need. It’s uncomfortable. It drives like a go-kart. It’s a roadster, so there’s no trunk. It has a soft-top, so there’s no sound insulation to speak of and it sounds as if it is about to take flight as soon as you push down on the pedal. On the highway, you can hardly hear your music playing. Oh, and the car only has room for two people. Slender people. Barely. And I love it. I love driving it. I love looking at it. I love thinking about it. I even love sitting in a traffic jam, because I’m sitting in the most awesome little car in the world listening to Amanda Fucking Palmer singing about doing it with a rock star, while these poor sods around me are sweating away in their soulless stuffy black subcompacts with perfect safety ratings. Both of these cars cost about the same. One of them is very useful and usable. The other isn’t. And yet. And yet. I love the one that isn’t. But it’s also an incredibly annoying car. Now when I go shopping, I have to think carefully about what I buy because there’s only so much room. I can never offer to drive people anywhere, because space is severely limited. These two cars show two extremes of product design, and both of them get it wrong. The subcompact is a purely rational car. It has no emotional appeal at all. It leaves me cold. I wouldn’t ecstatically recommend this car to anyone. I would never rave about how awesome it is to my friends. It does its job, but it does it in the most bland way possible. The roadster is a purely emotional car. I love it. If people ask me about it, I don’t stop talking until they interrupt me (and sometimes, even that isn’t enough to shut me up). I love telling people about it. But it can’t perform the most basic tasks a car should do. I can’t use it to go shopping. If I move house, this car becomes part of the stuff I have to move, not a tool that helps with moving. When designing a product, we need to strike a balance between emotional appeal and rational appeal. Products that check the most checkmarks on a feature comparison list may be the ones that do the job people want done, but are often not the ones that end up providing the best experience. Checkbox comparisons may tell you something useful about a product, but they can’t tell you whether you’ll fall in love with it. Don’t aim for perfection, either. Perfection can be annoying. Which of your friends do you love the most? The perfect ones that get everything right and never make a mistake, or the ones that try something outrageous, screw up, try again, often get it horribly wrong, but at least get it wrong in new and interesting ways? If you think about the products you adore, the applications you love, the clothes that appeal to you, the companies you want to support: are they the perfect, bland ones, or the ones with at least a little bit of personality? During your design process, you spend so much time polishing your product, removing all the blemishes and imperfections and nits and zits. And that’s great. Because in reality, most products need more polish, not less. But sometimes, maybe, it’s possible to go overboard. Sometimes, maybe, it makes sense to stop polishing before all edges turn into perfectly rounded corners. We need to design products that work, that do the job they’re made for. But people don’t make purely rational decisions. Their emotions play an important part. Our designs need to be useful and have emotional appeal. But if you can’t do both, stick with utility. Sure, driving my roadster is emotionally satisfying, while my subcompact was a tool that left me feeling absolutely nothing. But millions of subcompacts are sold every year, while my roadster was discontinued after two years on the market. The Perils of Designing For a Sometimes Myopic Design Community It’s not hard to describe what will get picked up by design blogs. It should be clean and modern, it should use a typeface we all love, it should be on a grid, the tone of the copy should be informal and hip, there should be an app, and it should be shown off in a cool and beautiful product video with an indie band as the supporting track. Information workers see it all day, every day. We know what “great design” looks like, in the myopic way the design community has defined it. It’s become as formulaic and limiting as a romantic comedy. It’s worth remembering that it’s not our job to design for ourselves. It’s our job to understand and design for all people. But when we spend much of our time with fellow designers, both online and off, we run the risk of isolating ourselves from a broader audience. There’s a reason why a lot of “great design” doesn’t succeed in the marketplace. It’s because we’re often in a designer echo chamber that has a set of values that don’t necessarily match what will resonate in the real world. Which is why I’m impressed by great sales numbers, great customer support, and experiences that are aiming beyond the topic of the day discussed around the virtual designer water cooler. There are experiences aspiring for something greater, by doing their best to leap from the design blogs into people’s daily lives. And to do that, your experience can’t just be a nice link you pass around. It has to be both well-designed and far-reaching. If you’re like me, you became a builder of things in order to change the world for the better. I love the idea that I can work on a product or an experience and it can affect people. And if I do my job well, I won’t just be affecting people, I’ll be benefiting them. That’s pretty great. But in order to make a lasting impact, one that really matters, I try not to forget just how insular and myopic the design community can be. When you find yourself on a project where your target demographic isn’t like you, it lights up new areas of your brain. It changes your creative process and helps you steer away from the siren song of design fashion and towards the basics: listening well so you can design something tailor-made for your target demographic. That’s where the most novel designs, and where the biggest surprises come from. We don’t need another site by designers for designers, we need more great design to hit the mainstream. Bad Usability for Good Reasons (Lukas Mathis) When Apple shipped iOS 6, they replaced their previous Maps app, which used data from Google, with a new app that relied on Apple’s own data. In Apple’s presentations, the new Maps app looked great, but when people actually got their hands on it, they quickly found out that in many places, Apple’s data was significantly worse than Google’s. Where they were previously able to accurately find addresses on the map, they now weren’t. People got lost. They missed appointments. And they blamed their iPhones. Apple blogs were quick to point out that Apple had good reasons for this switch. Apparently Google wouldn’t allow Apple to implement turn-by-turn directions in its Maps app without granting Google access to more iOS user data. Predictably, Apple wasn’t too eager to give Google this kind of access to its customers. The same Apple blogs were also quick to point out that it took Google eight years to acquire all of the maps data they now own. Apple, in contrast, was just starting out. Surely, in a few years, Apple’s Maps app would have caught up with Google. Of course, that assumed that Google stopped improving its own data, but it’s certainly plausible that Apple will be able to narrow the gap in time. Sure, these are all good points. It’s certainly possible to rationalize Apple’s decision to replace Google’s maps with its own, inferior data, to find reasons for it, to imply that, perhaps, Apple had no choice at all, and to pontificate about how, in the future, things will be much better. But here’s the problem: when I take my iPhone out of my pocket, enter an address, and my iPhone directs me to a point on the map that’s kilometers away from where I want to go, I don’t particularly care about Apple’s reasons behind the change. I just care that, right now, this damned phone doesn’t work right. As designers, we’re often forced to compromise. There are business reasons and code reasons and legal reasons that influence what we can do. Maybe something we really want to do is patented. Maybe a design change would be great for our users, but bad for our company’s bottom line. Maybe we have an awesome idea for a UX improvement, but it would require wide-ranging code changes that we don’t have time for. Or maybe the boss just really loves his leather sofa and wants the app to use that pattern as its background. And as long as you’re honest with yourself, and don’t delude yourself about the actual incentives involved, that’s okay. As designers, we need to learn to live with such compromises, lest we kill ourselves with a heart attack at the age of 35. Just be aware that your users don’t care about the reasons behind your decisions when they’re sitting in their cars, kilometers away from where they wanted to go, with no idea how to get there. Dogmatic Design (Lukas Mathis) As a kid, I read a book about the ancient Greeks. It was mostly about myths and warfare, because that’s what little boys like, but there was a short section about architecture, and that’s, I think, the first time I heard of the golden ratio. The picture showed a Greek temple, perhaps the Parthenon. Overlaid were lines showing how the proportions between the roof and the pillars on which it rested matched the golden ratio. The same topic, using the same example, came up again in high school. By then, I had become much more jaded, and it occurred to me that the person drawing the boxes showing the golden ratio on top of the Parthenon had taken a few liberties, cutting off parts of the roof, and adding a bit of the foundation below the columns to make everything fit. That seemed a bit weird. Nowadays, of course, you can just type “golden ratio Parthenon” into Google’s image search, and you’ll find hundreds of these pictures. Interestingly, they all add the “golden ratio lines” in slightly different places. Some include the foundation, others don’t. Some include the edges of the roof, others don’t. Some add additional areas where they see golden ratios. Some pictures are taken from slightly different angles, which changes the perspective and causes the golden ratio to appear in different places. Not everybody seems to see it in the same place. In psychology, there’s a concept called “confirmation bias.” It’s the human tendency to perceive things that confirm their ideas, and be blind to things that contradict them. I have no idea whether the ancient Greeks used the golden ratio when designing their temples, but it seems clear to me that the people who see golden ratios everywhere might be seeing a lot of things that nobody ever consciously put there. Worse, the people who use the golden ratio in their designs run the risk of substituting their own good taste with a dogmatic rule. Personally, I have never felt that the golden ratio was particularly beautiful, more so than any other possible ratio. Thinking about this, it occurred to me that interaction designers often have a heavy tendency towards this kind of dogmatic design. Use a different text color for links, and underline them! Don’t use graphics for decoration, only to convey meaning! Add a site description to your site’s title! Search must be in the top right corner! Don’t offer more than seven choices to the user! Use serif fonts for readability! The homepage must look different than the other pages! Don’t be redundant! The passive voice must be avoided! It’s not that these are all bad rules (though some are pretty horrible). They just don’t necessarily give the best possible result in every situation. To produce as good a result as we can, we must avoid dogmatic design. People are weird. They behave in strange ways and they like the most curious things. It’s hard to predict human behavior. And so it’s not a good idea to rely on rules alone. Don’t be dogmatic about design. Question your decisions. Test and validate everything you do. The Uncanny Valley of Assumptions Hidden in Guessware Assumptions often get in the way of a strong user experience. Capacitive buttons assume I meant to touch them even when I didn’t. Voice control assumes what I said and is usually wrong. Most music or movie recommendations are tuned to an average of all people, meaning they almost never appeal to my tastes. I get suspicious when software makes educated guesses on my behalf, because it’s so often wrong. And then I have to double my work to fix it. Which is why I’m raising an eyebrow at all the proposed innovations in smartphone software that revolve around making assumptions. Because smartphones know our current location, the sites we visit, who we text, the Facebook friends we follow most closely, the speed we travel on the highway, when our next dentist appointment is, what’s on our todo list, how many hours we spend playing video games, how much we spend online, our home address, and a million other signals, there’s a belief that the era of “smart recommendations” is here. I’m not sure I agree. I think today’s recommendations go just about as far as they should, and any expansion of them will feel more creepy or frustrating than genuinely useful. Why? Because even after analyzing tons of data, software can never do better than a guess. Sure, assumptions can sometimes lead to valid recommendations, but they carry with them a cognitive burden. People want to search for specifics like “good mexican food,” not tee up a parlor trick by asking “what should I eat tonight?” and hope the software gets it right. There’s a common belief that the march of technology will solve all problems, that the things lacking in software in this year will be figured out next year, or in ten years. But assumptions, no matter how much technology you aim at them, will never feel completely reliable. There will always be some discomfort associated with them, because they’re still just options auditioning for our approval. Not even my close friends or family can predict what I want to do with reasonable accuracy. There’s not an algorithm for what a person may be interested in doing next, and there never will be. No friend can predict it, let alone a computer relying on imperfect data and missing key context. And even if we could trust the results, and even if we were itching for software to make assumptions about our lives, it still leaves one major issue: privacy. People don’t want to be tracked every minute of the day. They don’t want a log of every purchase they’ve made in the off chance that software may be able to present a coupon they may like. What’s the value we’re adding? We’re asking users to give up their privacy so we can give them imperfect recommendations that they then have to tune and sift through so that maybe we land on something they could potentially enjoy. Experience designers should focus their magic after information has been requested, and not a second before. We shouldn’t be trying to give the user what they want before they ask for it. We should be putting our attention into returning exactly the right thing the moment they ask for it. If we don’t, we risk falling into an uncanny valley of assumptions. Users will want to believe that the latest guessware will make them more productive, more happy, entertained, and informed. But it’ll be forever doomed to be just wrong enough, just often enough, to feel like a burden. When you add recommendations to your software, your first assumption should be “my software won’t be right as often as I’d like.” Design with that in mind. [After this was written, Google Now popularized the “When you get to the airport, tell the user their flight is delayed” scenario. A great example of presenting data at precisely the right time, even when a user doesn’t actively request it, with little downside. –Ed.] Bad Tools (Lukas Mathis) Have you ever noticed how bad most of the tools we use are? I bought three different humidifiers until I found one that actually works decently. I have two drills, because when I bought the first drill, I didn’t realize that I should probably get something called a “hammer drill,” because that’s the only type of drill that actually drills into everything you might want to drill into. Nowadays, when I buy furniture I need to assemble myself, I start out by replacing all the screws that came with the furniture with ones that don’t fall apart when I try to tighten them. I’m not sure how much it would cost furniture manufacturers to include working screws with their furniture. Apparently too much, because they don’t. And that brings me to the screwdrivers. If you go to a hardware store and buy the first set of screwdrivers you see, you’ll end up with a set of screwdrivers made of such soft metal that the tips are completely chewed off after two uses and you can throw them away. Why would anyone even manufacture something like this? As a kid, I’d often build things with the tools in my granddad’s garage. He had very, very old tools. The screwdrivers had wooden handles and the things were scratched to hell. They looked terribly abused. But they still worked. The tips still had their original form. These were tools that were built to last. You bought them once, then used them for the rest of your life. Sure, they acquired a patina, but they kept on working just as well as the day you bought them. Let’s talk about software. Whenever I need to do something new on my computer, I end up downloading half a dozen applications that claim to do this new thing. Around four of them don’t work at all. One usually works, but barely, and (if I’m lucky), one gets the job done well. If you’re going to invest the time into making an application, why not make it one that works well? Why not make the screwdriver that people two generations later can still use and love? I don’t like the term “craftsmanship,” because building an application is not the same as building a chair. If it’s a reasonably complex application, it’s much closer to building a bridge, and you don’t have craftsmen building bridges. You have engineers. But when it comes to taking pride in your work, I think the word “craftsmanship” applies. If you’re spending all of that time building something, why not do it right? Don’t be the person who makes yet another one of the four apps that don’t work right, serving only to make it harder to find the one that does. If you’re not proud of the product you’re working on and you don’t want to make it the best damn thing you possibly can, you’re doing your users, and yourself, a disservice. Design Alchemy There was a time when the designer worked in Photoshop while the developer wrote code. They didn’t talk much. They didn’t usually understand the other’s skills and the respect ended at lukewarm statements like “I couldn’t do what they do.” Too often, both the designer and the developer thought the other side was holding the product back. The designer was criticized for undervaluing technological constraints while the developer was criticized for undervaluing aesthetics. I’ve been the developer and the designer in scuffles like these, and I’ve learned they get in the way of creating great experiences. But the industry has gotten better at cross-discipline collaboration, and it’s improving every day. When developers and designers blend Little by little, developers learned some design and designers learned some code. A new kind of product began to hit the market, one that felt delightful, beautiful, fast, and strong. These products came from cross-discipline teams who genuinely appreciated each other, processes that brought developers to the whiteboard for brainstorms while encouraging designers to prototypes their ideas, and an organizational structure that allowed the flexibility to break out of the traditional role silos. A kind of design alchemy began to take place, where by adding a developer and a designer together closely enough, a completely different kind of experience resulted. A better one. It’s gotten to the point where the resulting products have an unmistakable feel. Simply put, if your product isn’t delightful, it’s a sign your team’s various disciplines don’t talk enough. The Marriage of Hardware and Software We’re starting to see the same thing with hardware and software. For decades, Apple’s “control the whole widget” approach was scorned, mocked, and safely ignored as it became clear that their business model was inferior to Microsoft’s “big tent” ecosystem strategy. The conventional wisdom was as strong as anything seen in computing: Macs were too expensive, PCs won because they were cheaper, provided more choice and freedom, and benefitted from an ecosystem where multiple partners contribute.. It took years of struggle, but Steve Jobs’ original vision of “computing as an appliance” has found its way into the mainstream. Microsoft’s following the same model with Surface. Amazon is shipping their own tablets. So is Google. HP. Barnes and Noble. Even Kids R Us! There’s a Better Way And Your Customer Has Seen It Meanwhile, the old “one company designs the software, a different company designs the hardware, and together hopefully we’ll succeed” model is failing. Is it because it can’t realize low enough prices? No. Is it because it can’t scale? No. Too few workers, not enough demand, channels, or materials? Nope. The old model is failing for a more mundane reason: it results in inferior designs, just like when the designer and developer didn’t talk to each other. It results in obvious seams in the overall experience, whether trying to get customer support, trying to figure out how to install supported drivers, or even getting basic software running. Google is selling a lot of Android licenses, but Android’s customer satisfaction trails that of iOS because it’s an objectively worse overall ownership experience. Thanks to Apple and others, consumers have gotten a taste of a more perfect union of hardware and software, or designer and developer. Our products aren’t perfect, of course, but we’ve made huge strides in product quality over the last decade. And customers can tell. Like code and design, hardware and software may be different things, but it’s the careful marriage of the two that results in the best experiences. That’s where the future is heading. That’s where the best experiences will be made. That’s what customers will demand. So what are the next two things that will combine to make a larger whole? What are the two items that are being considered as two different things rather than being envisioned as one cohesive unit? Where’s the next design alchemy surprise going to come from? I think it’s between hardware and the cloud. We’re still treating them as two separate components, and the seams are showing. If history is any guide, change is coming. I can’t wait. Designing for the Cloud: A Manifesto First things first: “the cloud” is as much a marketing term as it is a true technological breakthrough. It’s not as if storing things on servers is new, after all. But as disk space gets cheaper, as people continue to expand the role they’re willing to entrust to the the cloud, and as expectations around networked computing get more robust, it makes sense that we’d call it something new. But while “the cloud” is a newer term, full of boundless promise that we’re marketing to within an inch of its life, we’re still treating it like a dumb connection to the server. There are two things to remember about designing for the cloud: First, it should be treated as a fundamental component for hardware, like a hard drive. Second, it cannot be trusted to actually work when you need it to, since connectivity can’t be guaranteed. These two points seem to contradict, but it’s through fully embracing both realities that we get some truly new ways to think about designing for cloud computing. It’s a fantastic and fun design challenge. 55 Seconds On, 5 Seconds Off Every cloud-enabled application should have a testing mode where the internet connection disconnects for five seconds every minute. This is the only way to spot out all the problems that emerge when your designs assume an always-on, always-connected, always-fast connection to the internet. Most mobile applications and websites go bonkers when they get disconnected. One result is the “could not connect” zombie alert dialog which, upon dismissing, appears again. And again. And again. The application is so flustered with the idea that the network connection cut out that it’s reduced to a stammering mess. It’s assuming the cloud is reliable, which is the first sign that the experience has not been designed with the realities of the cloud in mind. Blurring the Line Between Local and Cloud We currently live in a world with two options: there are apps, and there are websites. Apps can talk to the cloud, of course, but they’re still apps. What we’re missing out on, experience-wise, is the idea that websites should act more like apps. For example, if I land on your blog, it should be storing files locally. If I click through a few blog posts, then backtrack back to your front page, it should know I’ve been there before. It shouldn’t have to ask the server for the data a second time. This goes beyond simple caching: if I turn on airplane mode and go back to your site, the page should still load. Another example is Gmail. If I land on Gmail, it should contact the server to check for new mail, of course. But if my internet connection were to drop out, the site should (and can) continue working exactly the same way. I should be able to compose a new message. I should be able to open anything in my inbox. I should be able to search through my messages. And when I’m reconnected, everything should work as expected. New mail should arrive, outbox items should be sent. The only difference between being online and offline on Gmail should be a little cloud indicator at the top of the window. Everything else should act normally. The technology exists and the need is clear. The only limitation is that our designs haven’t caught up yet. Excessive Bandwidth Is Killing Your Site’s Experience When the iPhone first launched in 2007, it brought with it an intriguing and far-reaching detail: the phone came with an unlimited data plan. Unlimited data was short-lived, of course, and now it’s hard to find it anywhere in the world. Under this new reality, bandwidth is at a premium. So our designs need to adjust accordingly. The average load time of a website has gone up significantly, to the point where a 1 meg website is no longer considered a problem. Indeed, it’s become the norm on many popular sites. This means that mobile devices are loading pages slower (and taking more precious bandwidth) than ever before. If your web app isn’t making tough design tradeoffs regarding bandwidth, it’s not cloud ready. It’s been ported from the desktop experience and it shows. What It All Means Great design in the cloud era doesn’t mean anything particularly shocking or new. It’s the same stuff we’ve always known about, but we may need some reminding. First, it’s still all about speed. If your experience is slow, people notice. They get frustrated. They don’t enjoy themselves. Simply connecting to the cloud is not an excuse to let the experience become laggy. Bad design is bad design, regardless of the reason for it. Next, the Internet connection cannot be assumed to be reliable, cheap, or even present. Wherever possible, websites should try to cache themselves locally, fail gracefully, and accommodate a world where end users are going into bus tunnels, suffering through poor reception, paying too much for data, and just trying to get things done. Alerts that say “internet connection lost” are sure hallmarks of poor design in the cloud era. Right now we’re relying on the cloud like local storage, where a lack of a connection is a shock. You wouldn’t design a house that falls apart in the rain, yet we’re still designing experiences that fall apart when the network isn’t accessible. A Chance for Differentiation In hindsight, the iPhone seemed inevitable. Of course people wanted multi-touch. Of course they wanted (and were willing to pay for) high quality apps. Of course they were willing to sacrifice a keyboard for a bigger screen. Of course they’d sacrifice battery life for a better overall experience. It just took a design team to have the courage to optimize for these assumptions instead of the short-sighted “it’s good enough” design we put up with for a decade of cell phone software design. Cloud is in a similar place now. Eventually we’ll get it right, and we’ll look back and it’ll all feel as inevitable as iPhone. But first some designers are going to get very, very rich being the first to show the world how a real cloud-based application of the future should work. Why not you? Loss Aversion (Lukas Mathis) In their 1983 paper “Choices, Values, and Frames,” Daniel Kahneman and Amos Tversky describe the following experiment. A group of study participants were asked to imagine that they currently held the hypothetical Job A. They were informed about the job’s salary and workplace temperature. A different Job B was then described as having a lower salary but more pleasant workplace temperature. Participants were asked whether they wanted to switch to Job B. Most declined. Here’s the interesting part: a different set of participants were asked to imagine the opposite scenario. Imagine that you’re currently working Job B, with the lower salary, but more pleasant temperature. Do you want to switch to Job A? Interestingly, most of these participants also said no. People in both scenarios didn’t pick the job they would have preferred in a completely objective evaluation. Instead, they simply picked the job they already had. Most people prefer stability over change. They value the things they currently have higher than the things they don’t, for the sole reason that they currently have them. This is called “loss aversion,” and it’s something you can often see in software development. On the Internet there are active communities of professional users of Adobe’s FreeHand, a vector graphics application. That would not, in itself, be unusual. There’s just one problem: FreeHand was discontinued in 2003. Adobe stopped improving the application, and urged its users to switch to Illustrator, a similar vector graphics application. Since then Illustrator has benefitted from a decade of development, while FreeHand has remained completely unchanged. Yet there are still online communities of people trading tips on how to get FreeHand to run semi-properly on their modern computers. When Apple tried to remove the Apple menu in Mac OS X, Mac users whined so loudly that Apple put it back, sans all of the features that made the old Apple menu useful. But people were mostly okay with losing the menu’s functionality, just not with losing the menu itself. They didn’t complain because they actually needed the Apple menu, they complained because they felt that Apple was taking something away from them. They didn’t use it now, but perhaps in the future, right? By bringing back the menu, even in its useless state, Apple allayed these fears. Right now, you can open up pretty much any Windows opinion site on the Internet, and find similar rants about Microsoft’s removal of the classic Start menu in Windows 8. The more things change, the more people complain about wanting the old things back. Keep this in mind when adding a feature to your application: people value new features much less than features they already have. A feature that may not be a huge benefit to many people may turn into something that is jealously guarded by your users, just because they already have it and don’t want to see it go. Most of these users may not even use any of the features they so vigorously defend, but they might want to, at some point in the future, and they don’t want anyone to steal that option from them. So, taking things away from people causes them much more grief than giving things to people gives them happiness. Keep that in mind when deciding which new features to add to your product. Boiling Frogs (Lukas Mathis) When Microsoft released Windows Vista in 2007, users were up in arms. Earlier releases of Windows used to be causes for celebration. People lined up for Windows 95. There were lines in front of stores, launch parties, and the TV news reported favorably about the whole thing. Not so with Vista. Most people preferred to stick with its predecessor, Windows NT, and Microsoft was forced to let hardware manufacturers keep shipping new PCs with NT preinstalled for years after Vista’s release. Apple also released a new OS in 2007. This time, it was Mac users celebrating. People lined up to buy Leopard, Apple’s sixth revision of Mac OS X. Why were users ecstatic about Leopard, but unhappy with Vista? One reason for this discrepancy is that Microsoft hadn’t released a new version of Windows in six years. Windows NT had come out in 2001. Vista packed six years of features into one humongous update, forcing people to re-learn many of the things they had come to take for granted. In contrast, Apple released six different versions of Mac OS X between 2001 and 2007, going from Mac OS X v10.0 (“Cheetah”) all the way to Version 10.5. This allowed Apple to introduce new features gradually, at a slow pace, allowing people to grow their knowledge of the OS alongside Apple’s updates. Like the (hopefully proverbial) frog that’s thrown into boiling water, Vista users immediately wanted to jump out again, while Apple users comfortably sat in the slowly heating water. Admittedly, that’s not a perfect analogy, because you don’t end up cooked after using either operating system, but the general concept applies. It’s often better to update products incrementally and slowly. Between 2001 and 2007, Apple arguably made as many improvements in Mac OS X as Microsoft did in Windows, but to users, it didn’t feel that way, because Apple released updates piecemeal, slowly spoon-feeding changes to its users. You can do the same. Releasing often has other advantages. If you’re on the wrong track, you’ll get feedback sooner. You won’t invest years of your life into something that nobody wants. It’s also more satisfying. Nothing is more stressful than seeing people struggle with an older, obviously inferior version of your app, while you’re using an updated version that doesn’t have any of the issues your users regularly encounter. Releasing early and often doesn’t always work, but if you can make it work, it’s an option with many advantages. Delivering an Opus On a Punk Budget A pottery class was told they’d be graded one of two ways: either by quantity or quality. The incentive for the quantity group was to make as much pottery as possible, and the incentive for the quality group was to make one great piece. To use a musical metaphor, one group thought like punk rockers, and the other thought like master composers composing a magnum opus. A funny thing happened. The punk group ended up with both quantity and quality: they completed the most work, but also ended up with the higher quality pieces. It’s unsurprising in hindsight, of course. Skills take practice, so the group putting in more hours were destined to do better in the long run. Unfortunately, It’s hard to emulate these results in the real world. Designers doing client work are lucky to get a few days to collect their thoughts, let alone a whole three months to explore. Professional designers are expected to design as close to perfection as possible, as quickly as possible, within a budget, and delivered with a smile. Designers are expected to deliver an opus on a punk budget. This is why experience is so important. Early in an designer’s career, he or she should be sketching constantly, keeping an inspiration journal, challenging new ways of thinking, forgetting everything and starting over, and finding the courage to be loose, wild, and adventurous. Short bursts of raw exploration, done over and over again, help a growing designer set a good foundation. If a designer at this level is not experiencing failure, it’s because they’re playing it too safe. It’s likely they will fail later in their career, with much higher stakes, because they’ve tried to become a perfectionist too early. Perfectionism can be earned later in a career when a creative person sets out to make their opus. But trying for perfection too early in a career often points to a designer who’s timid, and too afraid to experiment. On the other hand, a designer with a lot of experience shouldn’t be as sloppy as he or she once was. Not with the client watching. The experiments, the beginner’s mind, the wandering through new knowledge is as important as it ever has been, but it will rarely be marked down as billable time. Experienced designers are on the clock, and clients need to feel that they’re getting all the brilliance of an opus in their allocated time. It’s about wearing the right hat for the situation. It’s about knowing what the client thinks about design work (he’s suspicious of it), what he thinks about your rates (they’re too high) and what he’s expecting in return (a masterpiece). It’s also about knowing how creativity actually works. (it’s sloppy and non-linear) It’s about having a plan. Here’s mine: I’m a punk during expansion, and the master composer during the reveal. It’s the contrast between the two that makes for great theatre, and it’s great theatre that proves to the client that your idea is a masterpiece. Let’s imagine the deal is signed and you’re off and running. Put on your punk hat. You should be going broad, iterating madly, and letting your ideas fail fast. Your project room should look like a disaster but there should be interesting explorations everywhere. Some of them are awful, but that’s ok. You’re in punk mode. You’re in quantity mode. You’re not falling in love with anything. And above all, you’re documenting everything prodigiously. You do this as long as you can, until you hear that your deadline is coming. The client will be here in three days, and they’re expecting to see some fancy design thinking. They want perfection. They want your opus. That’s fine. You’ve got all your raw material gathered, now you contract by channeling the master composer. This is where your meticulous photographic documentation comes in. It’s going to help you find the great ideas, and it’s going to be the backdrop for your theatre piece. Your presentation to the client will be focused on a small handful of brilliant ideas, and you will explicitly call attention to the huge mess of work you used to arrive at them. A lot of it is faked to give a sense of confidence to the client, of course. But you’re not lying. You’re just putting on a show that represents the years of work it took to be able to recognize perfection when you see it. The mess of papers on the wall behind you is saying “I’ve put in my time. I’ve experimented with thousands of different ideas, and when I tell you these three solutions are the ones, you can trust me.” The client will always have revisions, doubts, and concerns, of course. It’s part of the process. But if you frame your presentation correctly, the client will know you did your homework. You can use the quantity as a backdrop to make the quality pop. You can use punk rock to make sure they hear your opus. Solving Problems by Thinking Really Hard (Lukas Mathis) Most people consider themselves to be pretty rational. We assume that, if we just think hard enough, we can solve most problems. In terms of human evolution, this is a pretty novel idea. It mostly started during the times of Descartes. As a rationalist, Descartes thought that reason was the best source of knowledge and that we can get to the truth using our intellect, purely by thinking about things, rather than by evaluating empirical evidence and experience. Though most people still think as Descartes did, history has shown him to be quite misguided. Even people whose whole job is to think about things get it horribly wrong. Greek philosopher Empedocles did nothing but think about things. All this thinking eventually led him to conclude that everything was made up of four elements: earth, water, air, and fire. Later, Aristotle thought a bit more, and eventually argued that clearly, Empedocles was wrong, because he forgot to include aether in his list of elements. In all the centuries of thinking about this, none of these professional thinkers ever came up with the standard model of particle physics. It took scientists to find out how the universe actually works. It took observation and experimentation, experience and evidence. Empedocles and Aristotle didn’t fail because they were stupid or because they didn’t think hard enough. They failed because the premise of their approach, that you can find answers to non-trivial questions about the real world by thinking really hard, was wrong. Why? Because the real world is incredibly complex and weird, much more so than we can imagine. What are things made of? We didn’t figure it out by reasoning about it. We figured it out by doing experiments. This doesn’t just apply to particle physics. How will people react to this user interface? Will they understand this text? Will they read it? Is this button prominent enough? Will people be able to use this tool efficiently? You don’t find valid answers to these kinds of questions by thinking about them, even if you try thinking really, really hard. Instead, you need to do experiments. Try something, test if it works, and, if it doesn’t, try something else. Repeat until problem solved. Release I think a lot about the reputations that creative people have. Most people think of artists and writers as being a little bit crazy. It’s accepted that the craziness is what helps them create. But there are prolific, eccentric, brilliant creators who have led happy, successful lives despite having strong creative impulses. So what have they been doing? I think they’ve learned the art of release. I think of it like an electrical current. The shock of inspiration comes quickly and it absolutely must be released somewhere. A creator should let it charge through their body as briefly as possible and then find its home back on the ground. If they hold onto it too long, unnaturally, that’s when they can get burned. There are parallels with sex, too. I read a book where the author described her libido as something that wasn’t a part of her moment-to-moment thought process, but when the mood was right, nothing else would do. I don’t think it’s a coincidence that the feeling of sexual climax is referred to as a “release.” We’re letting go in that moment, and the feeling is euphoric. Which is the mindset I have around creativity. When inspiration hits, it’s a surge of energy that must be released somehow. Like the athlete who hasn’t been to the gym, like the sexually frustrated teenager, like a person holding onto an electrical current too long, failing to release can be tremendously frustrating. I love all phases of a project. It’s fun to start new, to go blue sky and imagine possibilities. I also love the peace that comes in the middle of a project, where the ideas are flowing and everything makes sense. But the end of the project, the release, is my favorite. I don’t just love it. I need it. The Fear A few years ago, I opted out of writing online. I stopped maintaining my sites, I stopped caring about the latest tech and design news, and I watched from the sidelines. Eventually I got inspired again. I wrote some anonymous essays, ran them by friends, got a new domain, and launched the kind of site I’d be happy to read. Boom. Within days, it was clear I had a hit. I’ve published a lot of content over the years, but I had never experienced the level of attention my little blog got, and I don’t expect to experience anything like it again. I hit the pageview jackpot, completely by accident. And right at the peak of the most flattering response I’ve ever received, right when you’d think I’d have been thrilled, a funny thing happened: I got The Fear. And nothing kills creativity like The Fear. Dancing, Drawing, and Deuce Most people dance the best when they’re in the moment, they’re feeling the music in their bones, and they’re reacting without second-guessing themselves, without caring if anyone’s watching. It’s beautiful because it’s so raw and pure. But self-conscious dancing is completely different. It’s hesitant, it’s restrained, it’s usually half a beat off. It can be painful to witness. Drawing is the same. I like to draw comics, and I know the lines look best when they’re thrown onto the page. I practice drawing the panel several times on scrap paper until I can throw the drawing in bold, confident gestures. If I let my mind go blank, the result is good. But as soon as I slow down, try to get a line just so, or consider tracing the lines, the line wobbles and the sketch loses its soul. I used to play tennis a lot, and in high school I realized if I let my mind wander, even a little bit, I wouldn’t hit the ball well. I’d approach the shot, plant my feet, prepare my racket, twist my body and wrist forward, and- If a thought managed to force its way in — “I wonder if Anne will be here soon” or “I’m thirsty” or “I really need to study for that test” — then the ball would bang into the rim of the racket, impotently hit the net, or go out of bounds. But if I could stay focused and let my arm flow through the movement, it’d be a strong shot. I learned the difference between a successful volley or an unforced error was all in the composition of my mind in that moment. Stifling the Writing The only difference between volume two of For 100 of Our Closest Friends and the first is The Fear. I’m second-guessing its quality. I’m over-thinking how you’ll feel reading it. I’m missing all the publicity I got on the blog. I’m wondering if anyone liked volume one, or if they did, if they’ll be disappointed in this one. If the last volume had a lot to do with love, of cultivating authentic experiences, of going deeper rather than broader, this one is grappling a lot with inspiration. With fear. Of getting stuck in your head, admitting you’re stiff-legged and awkward on the dance floor, and doing something about it. The Fear isn’t your friend, and it’s not kind. It’s not going to get up off your chest after it thinks you’ve had enough, just to pity you. Instead, The Fear will stay on you, stifling your breath, until you finally get tired of it, until you bolt up, push it off, scream it away, and reclaim yourself by asserting something in its place. Here’s Volume Two, Damn It I’m wishing I had never heard the term “sophomore slump.” I’m wishing I were aflame with burning ideas, inspiration coursing through my veins, ideas swelling and dripping from the ends of my fingertips like rain. I’m remembering wistfully how I danced like no one was watching, back before anyone found my little blog. And I’m realizing it was that unconcerned and intuitive posture, that lack of The Fear, those pure strokes of inspiration that sent sixteen shots just over the net, perfectly placed, over the summer. I’ll get back there again. This is me fighting back, a word at a time. Wearing Computers (Lukas Mathis) Books used to be incredibly precious. Each individual page of each book had to be hand-written by a scribe. Only the richest people could afford to own any. Smaller monasteries had only a few of them. Books were so expensive that by the end of the Middle Ages the papal library in Avignon only had about 2000 books. As a result, only the most precious books were copied. And monks did much of the copying. Basically, this meant religious books. In 1450, Johannes Gutenberg invented the printing press, and re-invented movable type (it was previously invented in China 400 years earlier, but never made it to Europe — something unthinkable in today’s connected world, but still pretty common even half a century ago). Movable type allowed typesetters to create “formes” — essentially a huge stamp that would be used to print an individual page. The forme is mounted in the printing press, coated with ink, and pressed on paper to create a printed image. When printing presses were first invented though, they were not used to print books, much less the kinds of books we find in today’s bookstore. Like the monks in the monasteries, Gutenberg used his press to print religious texts: church documents, papal letters, bibles. It took until the 17th century for people to discover that they could do new things with printing presses; things that weren’t possible when you only had scribes. Newspapers and the kinds of modern novels we take for granted nowadays eventually became popular — more than 150 years after Gutenberg first got the ball rolling. In the 1880s, the movie camera was invented. At first, it was used to film simple, static scenes. People in a garden, a person sneezing, a train. “Movies” were less than a minute long, presented by traveling exhibitors. Then people started to film plays, and eventually, they discovered that they need not be constrained by the rigidity of theater. It took less than 30 years for stop-motion animations, moving cameras, continuous scenes with cuts, and other modern movie techniques to become popular. Getting it Wrong We always see new technology in the context of our existing technology. The printing press was used to print bibles. Movie cameras were used to film theater productions. It takes a while for our brains to adjust, for the new possibilities to become apparent. At first, we usually get it wrong. But it also seems that this timespan is getting shorter. It took 150 years from the printing press to the first newspaper, “Relation aller Fürnemmen und gedenckwürdigen Historien,” but only 40 years from the movie camera to D. W. Griffith’s “The Birth of a Nation.” When it comes to wearable computing, we are now squarely in the “we have it, but we’re getting it wrong” phase. Today all of us are walking around with at least one computer on our bodies. The phone you carry with you is more powerful than the most awesome supercomputers I read about in magazines twenty years ago. Your phone would utterly destroy a Cray X-MP, a machine that would fill your bedroom, and was world’s fastest computer in the early 80s. If you’re wearing a watch, it’s likely that it is more powerful than the first PC I owned. Even your Fitbit has more processing power than the first videogame console I owned. We aren’t wearing fancy glasses with built-in screens, but we’ve definitely entered the age of wearable computing. When you listen to people envisioning the way wearable computing will work, they often depict a crazy future where we’re constantly being barraged by notifications and information and ads. Google Glass detects what we’re looking at, and offers additional information. Oh, I see that you’re looking at a poster for a concert, do you want to buy tickets for that? [This article was written before anyone had tried Google Glass, and all indications were that Google was planning on exactly these kinds of scenarios. –Ed.] Can you imagine how long it would take for people to go from, “Wow, that’s neat” to “Shut up! How do I turn this crap off?” I’m betting less than a minute. This doesn’t sound useful; it sounds stressful. The Google Glass video is the equivalent of the traveling exhibitor, putting on a movie of people standing around in a garden. I don’t want to see that. Nobody wants to see that once the novelty is gone. We’re imagining that we’ll use wearable computers in the same way and for the same things as we use our laptops and iPads. We use Wikipedia on our computers, so how about a pair of glasses that shows you Wikipedia entries for the things you’re looking at? We won’t use wearable computers for these things. We’ll use them for new things. I do think, however, that we’re seeing the first hints of how we’re going to use wearable computing. Passive Tracking Right now, the most common thing we use wearable computers for is tracking. We track ourselves with a Fitbit or Nike FuelBand. This data can be correlated with that of our scale and blood pressure monitor; at the end of the month, we get a nice graph, depicting how well we’re doing. Are you gaining weight without noticing? Have you been slacking off? Is there a correlation between these two things? Passive trackers don’t get in your way, but do help you live a healthier life. In the future, we’ll be able to measure more, better. Our computers will know what we eat, what our blood sugar is, what our average heart rate is. It will be able to give us specific suggestions for improving our health. Gamification When I go jogging, I run from Zombies. “Zombies, Run!” on my phone turns running into a real game, with a plot, different levels, and increasing difficulty. It makes running enjoyable, something I look forward to. Since we always carry these devices with us, why not use them to make everyday life more enjoyable? Why not use them to help us keep our resolutions, and to turn us into better people? Human psychology is easily manipulated. Right now, it’s other people who are manipulating us. The ads we see every minute of every day, the unhealthy way women (and men) are portrayed in the media, the way stores are laid out to make us buy the most useless crap in the shortest amount of time: these are just three examples of how we are being manipulated by the media, corporations, and society. Having a computer constantly with us allows us to tilt the balance a little and to use this kind of manipulation for good. Instead of other people manipulating us into doing and thinking things we don’t want or need, we can manipulate ourselves into doing and thinking the things we actually want to do or think. And maybe, one day, when we all wear augmented-reality glasses, perhaps we’ll even have ad blockers for real-life, physical ads. Social Humans are social animals. We require connections to other people. Modern technology has allowed us to be connected to more people, more easily, and wearable computing emphasizes this further. It also makes it more personal. Being able to have video chats, or send movies of what’s happening around us to our friends can allow us to take part in other people’s lives in a way that wasn’t possible before. There are apps that notify you when friends are close, making these kinds of serendipitous encounters more likely. This may be a slight loss of privacy, but it’s a loss of privacy we control. We decide who gets to know where we are. We require human interaction. Wearable computers will help with this fundamental need. Scripting your Life When I’m near my plants and they need water, my phone tells me. When I leave my car keys in a restaurant, my Android device beeps at me, telling me to go back and get them. When I arrive at my car, it automatically opens a special user interface for easy access to apps I commonly use in the car. When my washing machine is done, I receive a message. When I need to take an umbrella with me, my phone tells me as I leave the house. When I’m running to the train because I’m late again, my phone has already bought the tickets I need. Since we always have these devices with us, they know a lot about us. We can use this knowledge to automate things we regularly need to do anyway, to remind us of things we tend to forget (computers are far better at remembering things than humans are) and to generally be the kind of personal assistant that people imagined when they first thought of portable computers. Enhancing your Mind and Memory When I was a kid, people used to tie a knot in their handkerchiefs if they wanted to remember something. When they noticed the knot, it reminded them of whatever it was they wanted to recall. I bet most kids alive today have never even heard of that concept. The devices we carry with us remind us of what we need to know, when we need to know it. Similarly, people used to have expensive sets of encyclopedias. Dozens of weighty books that contained all kinds of nuggets of information. When people needed to learn about something, they’d start out browsing through their encyclopedias. Today, we carry all of mankind’s knowledge in our pockets. In the future, computing devices will augment more of our existing capabilities. Not in an intrusive way, but in the same way they already do: when we need it, how we need it. Piecemeal Popularization When I watch the Google Glass video, my blood pressure starts to go up. This seems overwhelming and overbearing. I don’t want my life to be a constant stream of interruptions. I don’t think that we will one day buy a pair of Google Glass goggles, and suddenly be in the future. Instead, wearable computing will arrive piecemeal, one tiny, useful nugget at a time. This process has already started. Our phones help us find our parked cars. They allow us to get directions. Maybe one day we’ll add glasses to the mix, but even then these glasses will start out modestly, perhaps a tiny screen in the corner of one eye that supports very few useful features. Over time, they will become much more than that. Wearable computing is in the future, but it’s also in the present. It has already started, and we’re starting to see the direction it’s going in. And I don’t think that direction includes constant popups asking us if we want to buy tickets for every concert poster we look at. 50 Words Every successful project in my life has started small. Not only that, the projects that have made the biggest impact were the ones that started even smaller than the others. This not a coincidence. Stephen King is often asked how he’s able to write so much, and his stock response is “one word at a time.” He’s not being coy. That’s actually how it’s done, both literally and in terms of mindset. One word at a time leads to whole pages, which lead to chapters, and if you can keep it up, one day your book is done. The problem is that people too often aim at goals that weigh them down. Writing a book, running a marathon, designing a new application, website, product or feature. These are all good goals, but you probably won’t achieve them unless you start small. Let’s say you want to write more. For starters, promise you’ll write 50 words a day. Yes, just 50. So when it’s 11:47pm, you’re tired, and you just want to go to bed, you’re setting yourself up for success because the goal is almost comically small. Sure, you could still skip it. But 50 words? Ah, you might as well follow through with them. And that’s the worst-case scenario, when you’re not inspired. The days where you are inspired will be magical. Say you wake up, jot down your 50 words, and they’re pretty good. So you keep going, and not out of a dull grey obligation, but feeling the bright illumination you can only feel from true enjoyment. Pause right there. That’s the secret, but if you blink, you might miss it. You need to find some kind of enjoyment in a task or you will not do it. Small goals let you hurdle over the obligation aspect and let you get at the joy of the activity that much faster. Maybe 50% of the time, your 50-word goal is a chore. But the other 50% of the time, you’re genuinely enjoying it. And when you enjoy it, words will turn to pages. Pages into chapters. Then you’ll have your book, or any other goal you’re working towards. Don’t set a goal of a marathon, start with a goal to run around your block every other day. Don’t set a goal of applying to 10 grad schools, set a goal that you’ll read the brochure for one grad school a night. Don’t set a goal to finish all your wireframes in a single day. See when deadlines are coming and police your time so you can give yourself 20% of the work over 5 days. The way to finding your creative muse is to reframe them as a bunch of small, achievable, fun steps. If you can do that, the rest will take care of itself. Mc. Hidden Complexity Isn’t Simplicity (Lukas Mathis) One of the more nebulous goals we strive for is “simplicity.” It’s not always entirely clear what that means. Does a simpler app need to have fewer, simpler features? Or is it enough to just make things look simple, hiding away the actual complexity behind a veneer of straightforwardness? When you’re rethinking a complex application, it’s easy to fall into this trap of superficial simplicity. Take iTunes. This is an application that came out in 2001, and even back then, was based on a longstanding Mac media player called SoundJam MP. When iTunes came out, people loved it. When Apple’s designers turned SoundJam into iTunes, they removed a ton of features, and managed to create a simple, yet sufficiently powerful media player. Time hasn’t been kind to iTunes. In the last ten years, Apple came out with the iPod, the iPhone, the iPad, the Apple TV, and a bevy of other services and gadgets. And for some reason, Apple decided to use iTunes as its integration point for all of these things. Consequently, iTunes has sprouted a complex device synchronization feature for iPods, iPads, and iPhones. And a fully-grown app store. And cloud integration. And a music store. And a movie player. And an ebook management system. And audiobooks. And much more. Today, iTunes is an unwieldy mess. Tasked with the ungrateful job of simplifying iTunes, Apple’s designers took the cheap way out: they decided to not simplify it. They could have, had they wanted to. They could have broken out the App Store and the synchronization feature. They could have removed a ton of the crap iTunes has accumulated over the years. They did not. Instead, in iTunes 11, they hid the sidebar, and replaced it with a tiny header. Also, instead of a list, the default view now shows your music albums. (Note that they couldn’t even bring themselves to actually remove the sidebar. Instead, they merely hid it, and provided a setting for getting it back. Even when attempting to simplify iTunes’ looks, they managed to just add more crap, without removing anything.) iTunes 11 looks simple. But in making it look simple, Apple had to hide much of iTunes’ complexity. This is not an improvement; the complexity is still there. But now, it’s lurking below a pretty, but shallow façade, just waiting for the right moment to jump out and bite your face off. In the old iTunes, you could see the complexity, and try to understand what was going on. Now, it hits you when you least expect it. Let’s say I want to go to the store. Ah, there’s a button called iTunes Store. Wait, that’s the wrong store; I meant the App Store. Or is it really the wrong store? Actually, App Store is a section of the iTunes Store. It’s a bit of complexity, hidden away, so you won’t find it when you need it. They turned two things into one thing, but it’s a sleight of hand; there are still two things, but you can only see one thing. So now I’m in the App Store, but I want to go back to my music. Let’s click on “Music.” Nope, I’m now in the music section of the iTunes Store. Another bit of complexity that just surfaced again. Ah, I can probably click on “Library” to go back. Oh, Library is a menu. I want to see my Music, so instead of just clicking on “Music,” I have to select “Library” -> “Music.” Now I want to go to my Apps. Let’s go back to the Library menu… nope, it just disappeared. To go from the Music section to the App section, I now have to click on “Music.” Apps. That’s hidden complexity, surfacing again. It might look simple, but it’s not. The logic of how an application actually works is called its implementation model. The way the application presents itself to the user is its UI model. The user looks at the UI model and forms her own model of how the application works. That’s the user’s mental model. The closer the user’s mental model is to the application’s implementation model, the better she is able to use the application. In attempting to hide iTunes’ complexity behind a simple UI, Apple introduced discrepancies between how the app pretends to work, and how it actually works, between the UI model and the implementation model. This prevents the user from forming a correct mental model. It makes it hard to learn how iTunes works, because everything seems like a magic show. Menus appear and disappear, they do different things at different times, they combine different things that should have individual UI elements. You can’t learn how magic tricks work by watching a magic show. Likewise, you can’t learn how an application works if you’re looking at a user interface that, like a magician, intentionally misleads you about what is actually going on. The trick to creating a truly simple application is not to make the UI look as simple as possible. It’s to minimize the discrepancies between how an app pretends to work, and how it actually works. Data Design (Lukas Mathis) When designers talk about their process, they often talk about things like sketching and wireframing and usability tests. But it occurs to me that this is not what I usually start out with. The first thing I typically design is the application’s data model. What kinds of things are there in the application? What properties do the things have? How are they related to each other? Can we normalize this structure, make it simpler? If the application grows, can this model accommodate the changes? Recently, I had a very preliminary design meeting about a website that would help people organize soccer matches. This seems like a simple kind of application. You probably have users and teams and matches. Users belong to teams, and teams participate in matches. Well, you probably also need to have events, if there are several matches at the same event. But wait, if you have events, doesn’t that mean that you might not know all of an event’s matches beforehand? Maybe the event has some kind of run-off system where the winners of a set of matches play against each other, so the participants of that match aren’t known in advance. Okay, let’s drop that for now, but still try to design the system so that we might be able to support something like this at a later date. So a typical use case would be for an organizer of an event to create a new event, add some matches, add teams to the matches, and add players to the teams. But some teams probably already exist in the system; perhaps the team members recreated their own teams in-system. Wait, we probably need to let players create their own accounts. But if they do that, can they choose which teams they want to belong to? Or can only team creators invite players to teams? What if a player isn’t yet in the system, but the person who created a team added the player to the team anyway… we need to support something like this, but can the player then claim the spot in the team? What if different people added the same person to different teams, each creating their own player; can the person then consolidate these things into their main account? All of these questions come down to model design. What are the basic entities in the system? How do they relate to each other? This is the first thing I worry about when designing an application. You might think that it’s not really a designer’s job to do that; let the programmers, who very likely attended courses teaching data model design, deal with that stuff. You’d be wrong. The model fundamentally defines how an application behaves, what kinds of features it can support. If your model is an afterthought, if it’s inconsistent with the user interface, if you didn’t communicate everything the app needs to do to your programmers, or if the programmers were lazy and didn’t do the model design correctly, your application will never work right. Start out with the model, and keep it in sight during the whole design process. Collaborate with programmers, but don’t let them take it over. It’s part of your job. Laying a Good Foundation (Lukas Mathis) The house I live in has a bike rack for visitors. It was built alongside the house, solid concrete and metal. People in Switzerland often travel by bike; it’s not unusual to have these covered racks attached to houses, so people have a place to temporarily park their bikes. Our bike rack, though, has two problems. First, it’s about 100 meters away from our entrance (that’s about 300 feet, for those people still living in the Middle Ages and measuring distance in terms of their body parts). Second, the bike rack is not visible from the entrance. Lack of convenience and lack of discoverability have conspired to make this bike rack completely useless. In the two years I’ve lived here, I’ve never seen a single bike in that rack. Instead, people just park their bikes right in front of the house. A few weeks ago, I was sitting in a café, talking to an architect friend of mine. I was thinking about our useless bike rack, and a question occurred to me. “How do you know the house you built will actually work?” I asked. “What do you mean?” she replied. “Well, if I design something, I do all kinds of tests first to ensure that people will get it. For example, I might build a simple prototype, and let people use it, to find out if they can actually figure out how to use it, if they like it, if it does what they expect. But you’re building a house, you can’t build a prototype house and let people live in it for a few weeks, to see if they like how the rooms are laid out. So how do you do it?” “In time, you develop a feeling for how things should work.” “They didn’t teach this? Did you have classes on where stuff should go so it will actually be where people expect it, and convenient?” “Specific classes for this topic? No. I guess we talked about some of these things.” Well, that certainly explains why many houses are built with such shitty design mistakes. The bike rack is too far away. The built-in coat rack is too small for the number of people who might live in a place. The bathroom window is in an inconvenient place. The door to the toilet is placed awkwardly. Buildings where you have to walk twice as far than you would if they had just built the damn stairs slightly differently. Parking space right in front of the entrance, ensuring that you always have to find your way through a bevy of cars to get to the door. Too few electrical wall outlets, placed on the wrong wall. Rooms, doors, windows, walls, stairs, outlets: it’s so easy to put them in a place that doesn’t match how people actually use a house. In comparison, software developers have it good. If something doesn’t work right, if we didn’t catch it during design, it’s almost always possible to fix it later. But not always. Sometimes, you can’t change the existing database layout, because so much depends on the way it currently is. Sometimes, you can’t change a feature, because the file format depends on it, and you want to keep being compatible with earlier versions of the software. Sometimes, you can’t move the foundation without shaking up everything you’ve built on top of it. And this is why it’s important to really get the foundation right. Spend a bit more time doing mockups and prototypes and sketches. Spend a bit more time arguing about the database layout, about how extensible the file format is, about whether you really should allow outside access to your API with the first release, or wait a bit to see if there are any changes you’ll have to make that break how the API works. The earlier you fix a problem, the cheaper it is to fix it. Even though we’re not architects, and even though we can go back and change things, it’s still best to get them right on the first try. The Lesson I Learned in Plano The guidance was clear. We were designing for a profession where browser plugins were not supported, upgrades lagged by years, and security was paramount. In some cases, no browser was available, so the only option was the command line. Imagine my surprise when I saw what we were pitching to the client: infographic-heavy dashboards animated in Flash. Using techniques that were about four years too cutting edge and too clever by half. What we were presenting looked nice, but it was a complete mismatch with what the client and the target demographic would actually be able to use. The 50 field interviews we conducted clearly warned against this kind of approach. We kept writing and underlining phrases like “no plugins?!” and “very conservative upgrade cycle” in our notebooks, and over every lunch, every client meeting, and every internal discussion, we debated how we’d deal with these factors. It was an immovable reality. We knew it. The client knew it. And yet here we were, pitching the big vision anyway. So what happened? What were we doing advocating for a design that we knew wouldn’t work? What was all the ethnographic research for, if we were going to design as if we hadn’t done any? I pulled one of our clients aside and asked what was going on. Was Flash suddenly possible? No. Did they realize we were pitching things only possible in Flash? Of course. Was that a problem? Not at all. All that mattered to the client was one simple word: inspiration. He explained that he needed to be able to show sexy new thinking to his superiors. He needed to show that he was clever for hiring us. He needed to get people in his company thinking more about the future, about what could be possible, not what was currently possible. He needed us to paint him a picture of tomorrow, not merely a prettier vision of today. The way he saw it, his field was stuck in the dark ages, and he had two options. He could inspire people with brilliant futuristic thinking, or he could let things stay the way they were, perhaps forever. Or at least until a competitor shipped something first, and he was left scrambling for an answer. As hired designers, reality wasn’t our responsibility. We weren’t there to write the code, ship the product, or accept facts. We were there to inspire. We were the upstarts trying to spark a revolution. We were the change agents, the unreasonable ones, the ones asked not to let reality stand in the way of a potentially lucrative new way to think about this unique market. Our designs never shipped as software. But our audacity, our coached refusal to accept the status quo, our drive for change had the desired result: we inspired. We affected change. Once we realized what we were there for. That’s the lesson I learned in Plano. Some design jobs aren’t about the design. Sometimes the designer’s role is simply to start a conversation. As strange as it can feel for a traditional production-oriented designer, sometimes inspiration is the deliverable. All or None Design Shepherding design thinking from idea to a shipping product is hard. The project may be canceled, all the best ideas may get cut from it, or it may be buggy. There are a million ways for the product to stray from the original vision, if it gets released at all. This puts designers in an interesting position. They’re expected to come up with big, bold, outside-the-box thinking. They’re expected to shatter the paradigm. The company can’t afford them to have them around if they can’t invent The Next Big Thing, so they shouldn’t artificially limit their vision. But on the other hand, nothing in a team ever gets done without compromise. Designers should be able to dream big, but be ready to negotiate in good faith. We spend a lot of time training designers about the dreaming part, but not enough time on how to fold technical and business realities into a design in the most graceful possible way. And it’s all about attitude. Designers can choose to accept compromise as “settling on a plan B” or “revising their first draft.” Or they can reject compromise outright. But that dooms them to “all or none” design, where a designer dreams up something great, and then grumbles under their breath as the client, the developers, the marketers, and reality chip away at it. This approach isn’t effective. Designers shouldn’t wait to see their designs get watered down, they should anticipate business, technical, and marketing compromise and look forward to the inevitable negotiations. When a designer pushes back against feedback, I watch carefully. There’s a fine line between championing your point of view and missing an opportunity to refine a vision into something better. Technical limitations may be frustrating, but so are yield signs and warning cones. They shouldn’t be ignored outright. I think we need to teach a slight tweak to the “present multiple explorations” model. We should still know how to expand, how to think in multiple directions and present a strong design rationale for each. But we’d do well to know how to “degrade gracefully,” the way web developers do. We shouldn’t just present options 1 through 3. We should know what each looks like if it can do 10%, 20%, or 30% less. We should know what’s required for version one, and what can wait until version two. A designer should know what truly breaks the design, not just insist on the whole design shipping precisely as proposed. A vision cannot collapse into dust after a small adjustment. Designers that assume otherwise are inexperienced, naive, or arrogant. Perhaps all three. Modern product design is an ongoing discussion, a grand compromise across an array of teams and different factors, almost all of which are beyond the designer’s control. Great design needs to be able to flex while still staying true to the original insights and opportunities identified. Great experience design cannot be all or none. If it can’t bend, it’ll break. Airports Made of Cake While studying Albert Einstein’s brain, scientists discovered an abnormality. He was missing an area called the Sylvian fissure, which some theorize led to his non-linear way of thinking. Einstein believed his greatest advantage was his ability to think non-traditionally about problems and their possible solutions, not sheer mental horsepower. Years ago, I was taught the principles of “lateral thinking,” which are designed to encourage exactly the kind of breakthroughs that great thinkers are able to realize. So I use these techniques when I’m leading a group brainstorm to try to recreate some of the Einstein magic. The exercises are simple, effective, and fun, yet I rarely see them in the workplace, even in creative fields. So here are a few pages from my playbook. Call It Design Play If you stand in front of a room and say, “we’re about to think outside of the box,” you’ll probably be booed. Instead, simply say you’d like to lead the room in a round of design play before kicking off the official brainstorm. Labels matter, and “Design Play” has always worked for me. Make It Fun Immediately Breakthroughs happen when people are comfortable and happy, so the first step in any brainstorm is to lighten the mood of the room. It shouldn’t feel like work. No one should feel like they have to look cool. I’ve found that people are very receptive to things that remind them of being a kid again. “What If Airports Were Made of Cake?” I always lead with this question while describing how design play works, with a bit of a preamble about how despite being a sort of goofy activity, this kind of thinking does result in good ideas. Something like: “I’ll walk you through the classic lateral thinking example, and how it actually resulted in some interesting insights. What if I were to ask you what would happen if airports were made out of cake?” Notice how the room reacts to this. There’s going to be a blend of disbelief, a bit of awkward hesitation, and in my experience, some smiles. Then a joke usually comes out, like “really delicious disasters?” followed by laughter. Then another joke. If the jokes don’t come, I make them myself. The mood of the room, in my experience, immediately changes for the better once the laughs start coming. It’s not as casual as grabbing a beer after work, but it’s not like a standard meeting, either. It inspires a third and too uncommon atmosphere, one that reminds me a lot of elementary school. And for most people that’s an awesome feeling. Stress the Results But it’s not just about getting people laughing. This kind of thinking does work. Here’s what I say once the room gets their giggles out: “It sounds totally crazy, I know. But we’re all laughing, we’re enjoying ourselves, and that’s the moment where good ideas get made. Because somewhere between thinking we’re wasting time and making jokes, your mind shifts into a creative mode. So that’s why it’s important to talk about odd things like airports made of cake. Someone will inevitably talk about the floors being soft and padded, which can lead to statements like ‘it would be the quietest airport ever!’” And bingo. That’s the moment of insight. Legend has it that this exercise did lead to a new airport being built with acoustics in mind, in order to be a more pleasing traveling experience. And that’s a great example of how lateral thinking can go into outer space but then return with a powerful, actionable insight. Get The Wheels Turning To begin the brainstorm, I give everyone a pad of sticky notes and a pen, and instruct them to write everything they could possibly do with a brick. I give them 5 minutes. Everyone’s first few sticky notes are the same: throw the brick, prop open a door, make a house, etc. But as the time goes on, people will find themselves forcing their thinking further out. This is where the mind can stretch and come up with novel new ideas. Then everyone should pick one or two of their favorite ideas to share with the group. It’s fun, and it stresses the point that your first ideas are usually not very good. There’s usually more laughter as camaraderie grows. Dive In This is where the brainstorm diverges. Sometimes I lead another “what would you do with a brick” activity but I angle it more towards the actual product we’re designing, and give people more time for the sticky notes. Other times I ask people to imagine they’re famous characters, like “How would Jay-Z design this? Mario? Michael Jordan? A toddler?” And at the end of the day, sometimes we rank our ideas, or map insights, or leave it open for a second brainstorm. It varies. It all depends on the project, and the insights we’re trying to get to. But one thing is the same, no matter how many times I do this, regardless of the client, the team, or the product. People love thinking creatively in design play. Sometimes it’s just your job to build a temporary space for them, just long enough to get to the real work. Sometimes it’s your job to make it ok to think about airports made of cake. Consistency Considered Harmful (Lukas Mathis) “Remove these two buttons and put them into a menu.” “Why?” “This is the only screen with buttons. It’s more consistent if it doesn’t have buttons.” When people talk about what makes for a good user interface, they often mention “consistency.” This app is bad because it’s inconsistent, but this one is good because it’s consistent. There are many different things an app could be consistent with, but usually, the two major ones are the host system, and the app itself. Consistency with the host system is often a good idea because it helps people apply what they learned in one app to another. Internal consistency is often a good idea because it makes it easier to learn how to use an application. But consistency can be dangerous, because it’s so easy to apply, but often doesn’t give the best possible results. If you’re working on a new feature, it’s tempting to take a feature of your app that’s kind of similar, and just do it the same way. Surprisingly often, this is a horrible idea. Designing your new feature so it works exactly like an existing feature may mean that it doesn’t work as well as it could. What’s more, designing it the exact same way communicates to the user that it will behave in the exact same way. Your new feature probably isn’t that similar to your existing feature. Most things are not the same; if they were, you wouldn’t need both of them. So don’t default to using the same user interface for different things. Maybe this is the only screen with buttons, but maybe that’s because it’s the only screen where the user triggers important actions. So even though all other screens hide their actions away inside menus, it makes sense to put a pair of huge, obvious buttons in front of the user on this particular screen. It’s not consistent with the other screens, but it’s good design. The hammer of consistency is often used to pound good design into a pulp of mediocrity. In the end, what matters is how well a user interface works, not how consistent it is with some other user interface. Design the best solution for the problem at hand; don’t start out by copying a solution for a different, similar problem. If consistency truly helps make a user interface better, if you end up concluding that the two really are similar enough that they should look and work the exact same way, awesome. But don’t start out with that assumption. Don’t be consistent solely for consistency’s sake. Figuratively Literally Language (Lukas Mathis) People love to complain about language. “That’s not a word!” “Don’t end a sentence in a preposition!” “Don’t use the passive voice!” “Really? How high did the show have to literally jump to get over the shark?” I know, because I was one of these people (and sometimes, before I catch myself, I still am). But text is a user interface. The writer creates this user interface, and the reader uses it. So, the basic rules of usability apply: make sure the user can figure out what the hell is going on as easily and quickly as possible. That literally means that you need to kill your sacred cows (and by “literally,” I mean “figuratively, but emphatically,” just like pretty much everybody else who uses the term “literally”). It doesn’t matter whether something “isn’t a word” by somebody’s definition of what words are. It doesn’t matter whether a sentence ends in a preposition. It doesn’t matter whether a famous little book listing a number of its authors’ pet peeves contains a vaguely explained “rule” disallowing a particular grammatical construct with some poorly constructed examples that don’t even illustrate the rule they’re meant to support. What matters is that it works. Is your text devoid of ambiguity, complex words, and long sentences? Do people quickly understand what you’re writing? Can they get through your text easily, without getting tired? Language lives. If people understand what you’re writing, if it’s in common use, if it’s a good choice because it’s easy to read and figure out, use it. In language as in all user interface design, go with whatever works. Backstage Not only had I agreed to dress up as a woman for a company party, I was being a good sport about it. And it wasn’t just any game of dress-up, either. I was going to wear a lot of makeup, a wig, a stuffed bra, a sexy outfit, and I was planning on showing midriff. “I can’t believe you’re letting us do this!” six of my co-workers (filling in as my hair and makeup crew) kept saying. But to me it made sense. This was right around the time I had pulled the plug on my design blog because it got too popular. In explaining why the site was going away, I used certain words like “introvert,” “overwhelmed,” and “privacy.” I had gotten an Internet reputation as an anti-social recluse even as I was getting some industry attention for delivering highly energetic and passionate talks at SxSW, the art school where I teach, and the design studio where I work. It doesn’t make sense on paper, but as they put on my hair and makeup, I was right where I wanted to be. I smiled with my eyes closed, the adhesive from fake lashes wetly weighing down my eyelids. I’m a performer. Point me towards the stage and watch me go. “Look how relaxed he is!” my makeup artists exclaimed. “It’s common for performers,” I heard a man’s voice say. “Low-key and calm backstage. He’s saving up his energy for the performance that comes later.” “Mmm-hmmm,” I murmured, my eyes still closed. Exactly. An hour later, I was part of a parade, then part of an all-afternoon competition. I posed for hundreds of silly pictures, many of me kissing co-workers. I was part of a dance flash mob. I leapt into men’s arms. I kept re-applying my lipstick and fixing my bra. I was on all afternoon. I enjoyed helping everyone have a good time. Then I was done. I slipped away from the party a few hours early and climbed onto a waiting bus. Alone. I reveled in the quiet as I watched across the soccer field to the revelry I had just escaped. I opened my sketchbook and drew up some new design ideas. I jotted down a few ideas for essays, including this one. I lay my head against the cool window and fell asleep. I spoke at an AIGA event last year. Backstage I was quiet and alone, because I had to be. Then I bounded onto the stage and did my best to do a good job. Then a few side conversations with students, a few good-natured design debates with other speakers, and I slipped out. I didn’t watch anyone else or stay for drinks afterwards. The same was true for my first SxSW talk. I flew in, stayed in my hotel, woke up late, saw a movie, gave my talk, had dinner, went back to my hotel, then flew out the next afternoon after visiting with an old friend, far from the conference. I barely engaged with anyone. I couldn’t. And of course, the blog. I worked really hard for a month to write as well as I could. And I knew if I left the blog open to comments or interacted with people over Twitter, it would distract me. And I knew from experience that distractions would mean the work would suffer. Some performers are on all the time (though it’s not as common as many believe), but that’s not how I work. I need time to think, to train and practice, hone and refine. I need to do my hair and makeup away from the crowds. And when I’m ready, I’ll go onstage and put everything into the performance. When I do my job right, I can perfectly disappear into the role. And when that happens, you won’t find me backstage. I’ll be long gone. Where We All Sound the Same Dear designer, We need to talk. I’m sure the work on your portfolio site is lovely, but your copy makes a bad first impression. No, there’s not a typo. It’s worse than that. Your problem is that you sound boring. It’s all there in the first line: “Hi, my name is [name] and I live in [city].” Yawn. Listen, it’s not that the words are bad by themselves. They’re casual, friendly, inviting, to-the-point. The problem is, almost every other designer is saying the same thing. And if you were a developer, or a lawyer, or radio host, that would be fine. But you’re a designer, damn it. You invent the future. You do things better. Right? If I’m visiting your site, I’m trying to determine if you’re a great designer. Meaning I’m looking for a great communicator. If your intro line is a throwaway, I’m going to wonder where else your communication skills need work. It’s gotten to the point where if someone says “yo” instead of “hi,” I’m more likely to remember their site because it’s at least a little different than everyone else’s. The differentiation bar has fallen that low. Not to say you didn’t pour your heart into the site, or that there isn’t lots of goodness it it. You picked just the right typeface, just the right color scheme, and maybe your site uses responsive design so it looks great on any device. You’ve clearly worked hard on this, so why lead with a line as stale and overused as a “why did the chicken cross the road” joke? If you’re a designer, you’re a professional communicator. This is your portfolio site, and you can do better. Investment Creates Pride (Lukas Mathis) It’s no secret that people are proud of the things they make on their own. The more you’ve invested in something, the prouder you are. I love the feeling of holding something I’ve built in my own hands; the more work I put into it, the better. I love my own sketches and drawings, even if, objectively, most aren’t that great. I think the food I cook on my own tastes much better than food from a restaurant. This doesn’t just apply to physical things. It also applies to computer work. I love writing code and letting it run, the feeling of having created something that works. I love drawing in ArtRage, creating things in OmniGraffle or Sketch, even writing text in BBEdit. I’m much less fond of Pages, though. When I start Pages and create a new document, it asks me to pick from a template. Usually, I just pick one, and change the text to whatever I need. I’m not proud of that. I don’t own the result, I’m just riding somebody else’s coattails. True, I’m making something, but I’m not making it mine. It’ll never be mine. I love tweaking a photo I’ve shot in iPhoto, messing with the sliders until it looks good. Conversely, I don’t like the photo apps that allow you to pick a predefined filter. I didn’t make that filter. It’s not because of me that the photo looks good. Somebody else put in the work, I just clicked on a button. There’s an oft-repeated anecdote about cake mixes. Supposedly, they didn’t sell well until one manufacturer decided to allow people to add their own eggs, thus giving them the feeling of “owning” the resulting cake, rather than just making somebody else’s cake. The anecdote is false, but the underlying sentiment is real. It’s not your cake if you’re just putting it into the oven. GM offers buyers of certain Corvettes the option of hand-building the engine that powers their new car. Buying a car is already an emotional experience, but imagine how much more invested in your car you become when you yourself have hand-built its engine! When designing creative apps, the line between giving people so much rope that they can’t help but hang themselves, and giving them so little that they can’t even tie a knot in it, is often very fine. Most Corvette owners probably couldn’t build their cars from scratch, but they are perfectly capable of putting together an engine with some help from a Corvette employee. When working on an application, think about this. Are you letting your users own the things they create, or are they just following in somebody else’s footsteps? What’s your application’s hand-built Corvette engine? What You’re Willing To Leave Behind One thing I learned in a year in real estate is everyone wants it all: enough rooms, a yard, beautiful views, great schools, room to expand, not a lot of renovations required, near stores but not too near, next to a park, everything up to code, and all for a price they can afford. But no one gets it all, of course. So it becomes a question of the one thing you’re willing to budge on. Higher crime? Worse schools? A hefty price tag? Fewer rooms than you were hoping for? It’s different for everyone. When my wife and I were home shopping, we wanted a great house, in a great location, for a price we could afford. Like everyone else. So we wrote down what our highest priorities were, and what we were willing to lose in order to get them. It worked. Our exercise made it very clear which houses fit into our criteria and which didn’t, which helped us streamline our process and feel good about the decision we made. This is a technique I’ve learned to rely on when designing. There is no such thing as a “perfect design,” only tradeoffs. Identify the experience you’re working towards and do everything you can get to get there. But don’t fool yourself into thinking you’ll reach success by refusing to compromise. Deft compromise is precisely what makes a design strong. Designing with Placeholders (Lukas Mathis) One of the first projects I worked on was a kind of social network for students (yep, that was way before Facebook). We spent quite a bit of time coming up with a good design. We were proud of ourselves. It was sleek and modern and simple and flat, just the way we liked it in 1998 (and, apparently, also in 2013). Proudly, we launched it. It actually grew very popular surprisingly quickly. Unfortunately people didn’t quite behave the way we intended them to. For example, there was an area for classified ads. When designing the site, we created our own classifieds to test how the layout would look. We didn’t account for the kind of strange ads actual humans would come up with though. People filled their ads with ASCII art. They wrote in all caps or without any caps at all. They wrote insanely long descriptions of the bike they wanted to sell, but forgot to add any paragraphs. Most didn’t upload images of the thing they wanted to sell (digital cameras and scanners were rare back then) but those who did often uploaded broken images — Windows BMPs with a JPG ending, for example. As a result, our pretty layout looked horrid most of the time. We just didn’t account for human ingenuity when designing it. Our placeholder data didn’t measure up to mankind’s chaotic nature. When Facebook launched their new Android home screen, Facebook Home, they showed mockups of it. I hope Facebook Home’s designers didn’t base their designs on the photos used in those mockups. Most people’s Facebook friends aren’t stock image models who love to play frisbee, have the cutest kids in the world, and cook meals that look like they’re straight out of a fancy restaurant run by the latest celebrity chef. I hope they also made sure that Facebook Home works well if you have friends who upload dozens of images of their cat everyday. Friends who love to post pictures of their drunk buddies. Friends who fill their timeline with selfies. And take photos of their grubby McDonald’s burgers. Don’t misguide yourself. Don’t use placeholder data when designing. Get as much real-life data generated by real human beings as possible and design for that. If you don’t, you’re in for a surprise. Overdoing It (Lukas Mathis) Placeholder data was, sadly, not the only mistake we made with that project. Here’s another one. When we first designed it, we basically spent a week in a cottage in the Alps, and brainstormed ideas for what the website would offer. Then we implemented them. Yep, all of them. The website had an area where you could look for people to share a flat with, or, conversely, find people who had rooms they wanted to share. Your flat-sharing community could create profile pages, and, of course, individual users could have profiles, as well (this, by the way, was implemented such that communities and users had different, unconnected logins so the site had two entirely disconnected login systems). There was a forum where people could discuss whatever they wanted. We had a market place where people could buy and sell things (and, of course, we also had an online shop where you could order T-shirts and stuff). We had a section where people could send e-cards (remember, this was in the 90s). We had a section where we published information and editorials about flat sharing. And that’s just the top-level features. (I actually had to go to the Wayback Machine to look up the site; it had so many different features right at launch that I simply couldn’t remember all of them.) Needless to say, people were terribly confused by all of the stuff on our website, and even though the site became very popular for putting out flat-sharing ads, most of the other features never got any traction. In fact, all of the added clutter probably prevented the site from becoming even more popular. Nowadays many designers have internalized the concept that the first version of your product should ship with the smallest feature set you can possibly get away with, polished to the highest sheen you can possibly get away with. But it’s not just the first version you have to be careful with. For every new feature, you need to ask yourself if it really improves your product, if you can implement it so perfectly that it doesn’t drag the rest of your product down. For a long time, I’ve a owned a simple, tiny USB scanner that I scan all my documents with. It works great. You attach it to your computer, insert a page, hit a button, the page is scanned. Then the software OCRs it and sends it to a filing application. Recently, I “upgraded” my scanner to a wireless one. That seemed like a useful feature. It would get rid of the requirement to connect the scanner to the computer. I could scan documents in one place and they’d magically appear over on my computer on the desk. Unfortunately there are problems. First of all, scanning now takes a lot longer. Previously, I’d push the button, wait a few seconds, and the document was on my computer. The new scanner technically scans faster than the old one. But since it then has to transmit the scanned document wirelessly, I have to wait for each scan much longer than before. Even worse, the scanner uses a lot of power. It has an internal battery but that’s only enough for about 50 scans at most. And I can’t just plug it in and keep scanning because the wireless feature of the scanner actually uses more power than its plug provides. This is the worst case scenario for a new feature. The new feature itself doesn’t work perfectly (it’s too slow). Even worse, it’s also dragging down existing features (now I can only scan a limited number of documents before the scanner runs out of power). When adding features to an application, don’t get ahead of yourself. For every feature, ask yourself: - Can I make this work as well as the rest of my product? - Will this new feature work 100% of the time? - Will this feature never interfere with how the rest of my product works? When in doubt, only implement features that tick the box on all three of these points. (By the way, when I asked about battery life, the scanner’s manufacturer sent me a new power plug that puts out enough power to keep the scanner running. I’ve gone back to using the USB version of the scanner though.) The Easiest Version The first 90% of a project is fun and the second 90% will try to kill you. This is why most projects never ship, and even when they do, they can cause chewed fingernails, bankruptcy, late nights, insomnia, relationship problems, laptops thrown in anger, and so on. But never forget that version one, relatively speaking, is a cakewalk. It’s nothing compared to every other version you will attempt to release. Version one is the high point. It is the closest you will get to the design you first envisioned. I know, I know. Everyone thinks version one is just the beginning. But most software isn’t seriously supported after a year, let alone three. Modern software is a gold rush, and there are more abandoned towns than successful cities. Far more. But we can learn a lot from the software that has managed to make it past the first few versions. First, of course your version one is clean, simple, and focused. Everyone’s is. The question is how well it scales up for the inevitable features you’re going to add. That’s a much tougher challenge than shipping a focused v1, and where truly great designers make their mark. Second, do you know what your product stands for? Do you have a point of view regarding what new features you’ll take on? If not, you’ll end up with an “I guess I’ll play it by ear” strategy and it’s likely your software won’t age gracefully. Figure out what you want your product to be the best at, and don’t be afraid to decline to work on anything that distracts from that overall goal. Third, you need to have a plan for supporting people that are using your product. This isn’t as fun as whiteboarding new ideas, but it’s just as much a part of your product’s design as the icon, the copy, the typeface, the color scheme, or the flows. Software design is mostly thinking about how to deal with problems that arise, and customer support is the purest example. Don’t overlook it. So yes, congratulations on version one! It’s clean and pretty, and perfectly suits the needs of your target audience. Pat yourself on the back, but know it’ll age and bloat faster than you think. Version one is a challenge and an achievement, but the best designers can shepherd their vision to version three and still love what they see. Sorting Through the Noise We start with too little, move to too much, and then we need to find the middle. Older generations grew up with a small handful of television stations to choose from. It was a time of a shared broadcast experience, where you could assume your co-workers were watching the same thing as you the night before. Then cable came, and brought with it an explosion of new channels. The “couch potato” was born. Bruce Springsteen wrote “57 Channels (And Nothin’ On),” which sounded quaint a few years later when we became used to packages with hundreds of channels. And then thousands. Eventually, we saw the shift from passive “channel surfing” to proactive “time shifted entertainment.” Innovations like TiVo meant you no longer had to be home by 8pm to catch an episode live. It was easier than ever to “catch up” to a show everyone else was talking about at work. Repeating History With television, we went from experiencing the same thing in a limited way, to an explosion of mostly low-quality content, to a more targeted, curated experience. Now I watch the shows I want to follow, and only them. I haven’t channel surfed in years. I doubt I ever will again. I see a similar story in the way we use our phones. We started on basic and limited devices that no one really loved. Then came the shift to smartphones and our platform and app choices exploded. We all agree that smartphones are better (though more expensive) than the feature phones they displaced. We love the choice of having millions of apps to choose from. But the data tells us that most people use apps a few times, then don’t touch them again. Many home screens show endless screens of apps that the owner hasn’t used in months or years. That’s not a strong ecosystem. That’s an app graveyard. So what’s the smartphone version of TiVo? What’s this generation’s version of focusing only on the areas that matter? It’s not sustainable to support a million app developers when fewer than 1% of them have a significant user base. Which is not to say we should stop making apps. Even in the worst of the cable years, there were always great shows popping up, and that’ll be no different with apps. It’s a numbers game: more apps, more experimentation, more hits. But there came a point where people stopped channel surfing and started guarding their TV time more closely. That moment will arrive in the app space. It will transform how we use our phones, and we’ll all be better for it. Mobile Has Reached Peak Delight [This essay was written before iOS7 was announced. Several of the complaints in this essay were addressed, which was nice to see. –Ed.] I have no doubt that the mobile space will continue to be very profitable for the foreseeable future. There’s clearly a lot of growth left in it. But one of the biggest mistakes people make is over-emphasizing tangibles like financial growth and devaluing intangible but significant factors like happiness, love, and satisfaction. So while I believe that mobile will continue to drive profits in the technology industry, I believe delight on mobile has peaked. I think it’s only downhill from here until the next big thing. Nailing the basics We’ve gotten used to the idea that phones will let us communicate with everyone in the world via any shared protocol. Phone, email, text, and web are built-in, and 3rd party apps like Facebook, Twitter, and WhatsApp are available on every platform. These are the basics of communication, and we’ve gotten them pretty well nailed. Searching for the Next Commercial All the big phone and app makers are searching for the next “wow” idea so they can market it within an inch of its life. But the basics have been addressed, so what’s left is a bunch of space age ideas that aren’t yet palatable to the mainstream. Voice-powered personal assistants, wearable computing, and the ability to blast content from one screen to another are all important improvements. But the mainstream doesn’t yet have a reason to care. Their basics are covered, and these geek technologies looking for a reason to be marketed smell like desperation. While we look for the Next Big Thing, treating mobile like the tech equivalent of the season-driven fashion industry, there are a tremendous number of problems in the mobile space that are eroding delight more every year. Problem #1: Updates Software makers are very proud when they ship product on time and on a schedule. Doubly so if they’re “agile.” Frequent software releases are held up as a common sense feature that customers love. Wrong. Look, Mr. Software Maker, I know you addressed a crasher bug with unicode characters in landscape mode, or changed your settings icon to be less pixelated, or whatever. But no one cares beyond a tiny minority of superfans. And it’s worse than that. It’s not just that people don’t care, you’re actively causing them stress each time you push an update. Seeing an App Store icon with a badge that says “76” is not fun, nor delightful. Increasingly we’re seeing people simply refuse to update. One solution is defaulting to auto-installed app updates. If you’re on a Wi-Fi connection and plugged into power (which many people are when they sleep), the phone should install the latest and greatest software for you. Are there drawbacks to this? Should overriding be possible? Should there be a way to hold back software for three days in the case of a release going out with a bug? Yes, yes, and yes. But these are small tweaks that will going a long way towards fixing a broken system. Updates are a chore, and need to be fixed. Problem #2: SMS Spam 2007 was a magical time when SMS spam wasn’t a problem and email spam had started to be less of a problem. As a result, the ability for a mobile device to block spam wasn’t a critical feature. And a good thing, too, because it’s a multi-step process that’s hard to design well on a small screen. Well, get ready. SMS spam is on the rise and it’s going to get worse before it gets better. Probably a lot worse. Until smartphones come built-in with strong SMS blocking, we’re going to suffer through a lot of frustrating SMS spam that makes our phones less delightful. Problem #3: Notification Spam Notifications have gotten ridiculous. Some notifications are highly important, like receiving a timely text from a good friend. Others, like a game informing you that your character can now afford to buy a new item, are not. But until we come up with a better system for notifications, it’ll be like the boy who cried wolf. We’ll learn to tune them out, and will miss the important ones. I think there should be a tiered system. By default, trusted apps (such as the built-in text messaging app) should be able to notify aggressively. Every other app, such as 3rd party games, should require you to opt-in to the types of notifications you want to see. And not in a blanket “yes/no” way. The app should be forced to prove why every different kind of update it wants to send is worth turning on. Problem #4: Greedy Defaults Software makers know that people don’t change their defaults very often. So if you can choose between a polite setting that makes you less money or a rude one that makes you more money, there’s a big incentive to go with the rude money-making one. If you add up all the user-hostile defaults on mobile, it adds up to an experience that makes mobile less delightful. Problem #5: Website spam As everyone races to release apps, we’re increasingly seeing the “download our app!” banners on websites we’re trying to visit. This is making the browsing experience worse, and to little benefit. When someone sends you a link to an article, it’s becoming common to have to click through the “no, just take me to the content” dismiss links, often in tiny type and hidden in the corner of the page. Problem #6: Spam That Claims It’s Not Spam Somewhere along the way, it became popular to say “we promise not to spam you” on email forms. But little changed. Now almost every site you visit, every product you buy, and every beta you sign up for believes it’s your best friend. “We’ve been hard at work!” the messages chirp. Meanwhile, I don’t even remember who the company is, and I certainly don’t care that they just added some incremental new feature. I think back to their promise not to spam me. I wonder how they’d categorize these relentless status emails. One email from one overzealous company is easy to ignore. It’s the aggregate I get every day that weighs me down, drowns out the messages I care about, and makes sifting though email a chore. And they still don’t admit that any of it is spam, they think it’s “spreading the word about an exciting new feature.” We Know How This Movie Ends In many ways, the decreasing delight in the mobile space mirrors what happened in the PC industry. After the novelty of personal computers and the internet wore off, we were left with these amazing machines that were a pain to use. They broke a lot. They crashed and lost our data. They had viruses on them. But we still loved them. It felt like they could do anything, if only we could make them work right. This is what was so amazing about mobile, for a time. It had none of the window management, viruses, complex configurations, strange incompatibilities, or other problems that plagued the personal computer. The difference between PC and phone was pretty freeing. For a while. It’s All Too Much Things have changed. Mobile is much more reliable, but it’s repeating many of the mistakes that make the desktop computer such a cognitive and emotional burden. But this time, the device isn’t off in a side office somewhere, it’s in our pockets, in our hands, and woven into our lives. This makes its PC-like shortcomings much harder to avoid than in the PC era. The industry’s drive towards providing more features just inflames this problem. If I could choose between a phone that was more respectful of my time or had more features, I’d choose the respectful one. But that’s not an option, so my $20 basic feature phone is looking more appealing by the day. I think we’re entering what will be an interesting era in mobile. And if it’s as frustrating as it looks like it may be, it’ll be ripe for disruption. Maybe sooner than we think. Magical User Interfaces (Lukas Mathis) Apple’s ads portray Siri as a kind of person. Samuel L. Jackson talks to it as if it were a human being, and it responds in kind. That’s magical. My Android phone’s calendar is magical, too. It allows me to enter appointments as natural text. I can type “meet Jon at 5pm” (which I usually don’t, because meeting Jon would involve a day of sitting on a plane). My phone parses that text and creates the appointment. Neither of these two user interfaces work well. Apple wants you to think of Siri as a magical anthropomorphic being that lives inside your iPhone, not as a bunch of algorithms. Siri’s user interface is patterned after human conversation. You say something, Siri thinks, Siri answers. When it doesn’t work, the only thing you can do is randomly guess what went wrong and try again. Likewise, my phone often doesn’t get what I intended to say, so the next step after entering an appointment is looking through the calendar to see if I can actually find the appointment I just created. With both user interfaces, my action and my phone’s response are disconnected. The phone is trying to appear magical. It’s guessing what I’m trying to do. It’s not showing me what’s really happening — that would be revealing the magic trick. But it’s better to expose some of the underlying application logic to the user than to appear magical. “Magical” is usually not a good attribute for a user interface. “Magical” often means “obtuse and hard to learn.” When you’re designing user interfaces, you want things to be predictable and repeatable, not magical. Of Course When people try to design magical interfaces, they’re often aspiring for the “wow” moment, but that’s the wrong focus. Designers should instead be focusing on “of course” moments, as in “of course it works like that.” Most product design should be so obvious it elicits no response. The problem with aiming for “wow” is when you try to innovate, your design process encourages novel new interactions. But by definition, novel and innovative are often not familiar or intuitive, which can easily tip over into “hard to use.” On the other hand, the Nest thermostat, the iPod click-wheel, iOS’s pinch-to-zoom, the Wii controller, the first Google Maps, pull-to-refresh, and many other recent design success stories have a very strong “of course!” sense to them. Think back to using those products the first time. You probably didn’t struggle with them, which is why they succeeded despite employing unfamiliar interactions.. Designers going for “wow” are too often leading with their desire to be recognized for an ability to innovate. Designers going for “of course” are earnestly attempting to fade their design into the background. They want their solutions to feel like they always existed, like there could be no other option. Forget “wow.” You can’t conjure it. Instead, work to incorporate “of course” to your product. Your users will love the result, even if they can’t put their finger on why. Brand is Misunderstood A few weeks into designing an app, my CEO asked why the company logo wasn’t more visible. Branding on the website, the app logo, and the loading screen all made sense to me. But putting it in the chrome of the app itself seemed odd, so I asked for clarification. He liked the idea that when using the application, the company logo was there, presumably logging eyeball time. I said “I’m not sure that’s a reason to clutter up the interface with a marketing element.” “That’s what branding is,” he responded. And that’s when I realized our problem. We both wanted the start-up to succeed. We both believed that a strong brand would strengthen our chances for survival. But we understood brand to mean contradictory things. He believed that making the logo more prominent helped the brand. I believed that brand was nothing more than the reputation of a product. He believed that missing a chance to add the logo weakened the brand. I believe that distracting a user with too many marketing elements can harm the brand. I pointed out that on Windows, the app icon is already in the window of the application, so his plan would lead to two company logos on the screen. The argument didn’t work. I’m pretty sure he would have been fine with three logos. Because that’s how he understood brand. For many people, brand means “put logos everywhere.” Braiding-trip, watching TV, or hitting reload on Facebook. They required hours of effort that from the outside looks a lot more like studying for a test than the backslapping and noisy mental image we get when we think of collaboration. Second, no one is an island, especially not when designing complex product experiences. Yes, there is a time to put your head down and produce. But getting to that point often requires collaboration, iteration, and a ton of dead-ends. Even writers, famously solitary, still run ideas by other people. I think the latter is well understood. Steve Jobs once board discussion, the better! Right? Well, sort of. We may have over-indexed on collaboration. We’re not giving ourselves nearly enough time to think. To produce. To take all the wonderful conversations we’re absorbing at the studio, on Twitter, from inspirational design sites, blog posts, and the like and actually do anything with them. On my teams, I implement something called “braiding,” or scheduled time apart, followed by scheduled time together, back and forth, repeating throughout the project. The idea is that the team brainstorm is made better by people working on their own first. And then the brainstorm gives us some interesting ideas to go push forward on our own. It’s doubly useful if you have someone who can prototype, because you can go from crazy whiteboard ideas, to someone throwing together a rough prototype alone at their desk, to everyone seeing the working example, sometimes all within the same day. The key is knowing when it’s time to stop talking and go build something, which some teams struggle with. Most builders I know do their most productive work at home, away from the office. Or they barricade themselves in a conference room with their headphones on. When they do, they’re done talking. They’re at a place where they just need to produce. It doesn’t make them anti-social, or bad team players, it’s just a realization that the modern office is pretty bad at actually producing work. It’s designed for talking about it. We need to stop worshipping multi-tasking, collaboration, and open offices so we can find ways to give people their headspace back. Find opportunities during the process to get some time to work through ideas, and you’ll find you’ll be much more insightful and thoughtful in meetings. That’s braiding, the best technique I know for creating high quality content in an environment that expects you to be in meetings all day. Things Regular People Do (Lukas Mathis) When you’re working in tech, it’s easy to lose perspective of how strangely most of your friends behave compared to the average person. They care about Dropbox-compatible iOS text editors, they worry about Markdown dialects, and they use Gmail-only email clients. It’s important to keep in mind that most people are not like your friends. Regular people don’t buy music on Amazon, convert the MP3s to smaller AAC files, and synchronize them to their iPhones. In fact, they probably never synchronize their iPhones, and just browse YouTube to listen to music. Also, after they’ve taken so many pictures and movies that their phone’s memory is full, it’s effectively broken to them, with no obvious way of fixing it. Regular people don’t manage their applications. They click on the download link, and then just let the app sit inside the Downloads folder. Can’t find the app anymore? Just download it again. Regular people don’t manage their files. They just save them wherever the Save dialog first suggests, and then access them via the “Recently opened” menu, or by searching. Regular people use Microsoft Word, rather than a plain-text editor. And Microsoft Word, rather than Photoshop. And Microsoft Word, rather than a journaling application. If you ask them to send you a screenshot, they paste it into Word document (because that’s the program they know best) and send the Word document by email, and when the file gets too large for that, they don’t send it at all. How to Design When designing applications, it’s easy to design them assuming that people actually understand how computers work, what a file system is, how to move data between different computers. After all, your friends know that stuff; doesn’t everybody? Meanwhile, in the rest of the world, most people don’t know these things, and shouldn’t have to. As computers become more appliance-like, the inner workings of these devices doesn’t just become less important to users, it also becomes harder to learn. And why should people learn about them? Your users are doctors and car mechanics and carpenters. They’re experts in their own fields. They’re not computer experts. What to Design There’s a bigger issue than how to design for regular people, though. Look at the kinds of products people in the tech industry love to create. Todo lists and Dropbox-compatible plaintext editors are probably at the top of the list; bonus points if it’s a Dropbox-compatible plaintext-based todo list. Meanwhile, people outside of the tech industry couldn’t possibly care less about this stuff if they tried (which they don’t, because they don’t care). Here’s another example. People in the tech industry have been “solving” the problem of setting up meetings pretty much since networked computers were first invented. But they created it for themselves. Setting up meetings requires everybody to use the same calendaring solution. It requires invitations and time slots and reminders. People don’t care about that. What’s the first thing normal people do when they set up a meeting? They try to find a date that works for everybody. How does that work in, say, Exchange? Usually, somebody sets up a meeting, and then half of the invited participants complain because the date doesn’t work for them. This is then followed by a few days of hashing out dates, until eventually another invitation is sent out, at which point the whole thing begins anew. It took until 2007 for somebody to create a solution to this problem that works for regular people. Technically, Doodle.com is so simple that most techies will hesitate to even call it a product. The person who wants to invite others to a meeting sets up a new page on Doodle.com and enters a few dates. Then, participants open that page, enter their name (no accounts needed), and check all of the dates that apply. Eventually, the creator picks the date that works for the most people. Most programmers could implement this in a few hours. But they didn’t. People working in the tech industry create solutions that solve their own problems, that work for themselves and for other people who work in that industry. Not ones that fit the way most other people behave, or that solve their problems. Designing products that non-experts can use and want to use requires knowing about what the heck they do with their computers. It requires empathy for people who, in many ways, are very different from us. The first step towards a better understanding of how people who aren’t like you use computers? Say “yes” the next time some distant relative calls you and says “you know about computers, right? I have this problem, maybe you can help?” Be Bold (Lukas Mathis) Recently, a friend of mine noted that tech user interfaces often innovate for innovation’s sake, not because the new user interface is inherently better. “Cars don’t replace steering wheels with gestural systems,” he said. That got me thinking. Indeed, the car’s user interface hasn’t changed since the 18th century. But honestly, isn’t the car’s user interface pretty terrible? Originally, cars had steering wheels because of mechanical requirements. Today, these requirements aren’t really there anymore. Car manufacturers could put anything they wanted into their cars. Joysticks, perhaps, or W-shaped control yokes, like the ones used in planes. I don’t think we still use steering wheels because they’re inherently awesome user interfaces for controlling cars. I think we use them for some other reasons. - There are safety standards and regulations that govern pretty tightly how cars are allowed to work. - Car manufacturing is extremely cost-intensive. As a result, car companies are comparatively conservative. - Learning to drive a car requires a huge upfront investment. People who’ve spent hundreds of hours to become proficient car drivers don’t want to switch to a potentially better system if that means having to relearn how to use it. - When something is an industry standard, you can learn it once and apply it everywhere. It’s better to learn one crappy user interface, than half a dozen good ones. Now, some of these points apply to some technologies. If you’re writing banking software, for example, you have to put up with tons of regulations. If you’re trying to write a new operating system from scratch, you’re entering a cost-intensive market. If you’re trying to replace the qwerty keyboard layout or the dials on an SLR with something better, people will resist it because of the upfront investment — the Dvorak layout may be better, but who wants to invest all of that time into learning it when the layout they already know works well enough? Worse, if they learn a new layout, they’ll only be able to use it on their personal computer. Everything else will still have a qwerty keyboard. In most situations though, you’re not limited by these things. So why stick to the steering wheel when you can try something new? Be bold. Try new things. Limitations In art school, I was assigned a project meant to get me thinking: “design a webpage as if there are no technical restrictions.” Instead of being inspired, I was puzzled. The more I thought about it, the more frustrated I got. This was the late 90s, where nothing worked right. CSS was barely used, different browsers rendered pages very differently, and of course bandwidth was maddeningly slow. The assignment was meant to help us look into the future. But I wanted to learn how to be better at designing for the challenges we were dealing with every day. For example: how could we compress images so they downloaded faster? Was there a way to write webpages that looked the same in Netscape and Internet Explorer? What techniques could we use to convert the awful mess that was early internet design into something as beautiful and mature as print design? The best way to see the future is to invent it. And the best way to invent it is to improve on the present. Yet here we were playing at the future by pretending the present didn’t exist. This is why I love building products. Inherent in a designer’s job description is that we’ll see what’s wrong, but don’t stop there. We try to improve things, and we strive to push things forward. Not by fantasizing about how great it will be someday, but by rolling up our sleeves and getting there. By working at it, we build the future. I’m concerned that our hand-wavy future worship has, for many, supplanted truly human-centric design. I’m concerned that some genuinely believe that only through stripping away compromise and ignoring realities will we find our creativity and make real progress. That’s exactly wrong. The future will have more limitations, nuances, and caveats than today, and will challenge us in ways we don’t yet realize. The best designers of the next generation won’t have time to dream about the the distant future. They’ll be too busy building it by addressing the problems around them. Design is how it works (Lukas Mathis) There’s still this idea that you can write code first, and design later. Lots of companies work like that. Programmers implement something and put the most basic UI on top of it, then designers swoop in to kiss it and make it all better. That doesn’t work. Here’s an example. Let’s say we’re designing an email client’s undo feature. If the user types something and hits undo, you don’t want to undo his input character by character. But you also don’t want to remove everything she’s written. So you need to store checkpoints while the user is typing, preferably when she’s taking a break. If she doesn’t take any breaks, you still want to add checkpoints every sentence or so. Let’s say the user deletes a message. This command may be sent to the server, where the message is deleted or moved to a Trash bin. If the user undoes the action, the action also needs to be undone on the server, which may involve various different actions. Finally, let’s say the user sends a message, but then decides that it was a terrible idea to quit that job after all. Undo! Undo! Can you undo sending an email? In some systems (Gmail, for example), yes, for a limited period of time. These examples don’t just involve some UI sugar on top of existing code. They influence the system’s architecture. If programmers didn’t think of these cases before writing the backend, implementing them could involve much rewriting of code. Nobody wants that. Design is how it works. Design behavior before writing code. We Are All Builders Interaction design, visual design, and code form the three legged stool of software design. You need all three for balance, they’re each equally important, and they’re all different from each other by the same degree. Visual design and interaction design are just as far apart as code and graphics. A strong understanding of color theory doesn’t mean you know how to write Javascript, and it doesn’t mean you intuitively will know how to structure a great flow. Having an impeccable eye for fashion doesn’t mean you understand interior design doesn’t mean you’re great at lighting doesn’t mean you’re a musician doesn’t mean you’re a natural at game theory doesn’t mean you can design a delightful first-run experience. Being good at one aspect of design does not necessarily translate to other areas. Sure, they’re all technically done by “designers,” but I like the word “builder” more. We’re all building products. We’re all builders, and we all specialize at different parts of the three legged stool. Blended Builders It’s not as if these different fields have nothing to do with each other, of course. A builder benefits tremendously from additional knowledge, whether marketing, engineering, biology, psychology, botany, linguistics, or finance. Every new bit of information can and should spin thinking in new ways. A blended background is something professional builders are increasingly seeking out. Whether it’s fantastic visual designers who have learned interaction or interaction designers who have learned to code, great products require teams of people who can blend skills. A few years ago, the joke was that these blended builders were as rare as unicorns. In the near future, builders who can only do one thing will be the rarities. And they’d better be really, really good at their one specialty if they want to thrive. Blending Takes Work Which isn’t to say it’s easy. Print-inspired screens atop frustrating flows are the hallmark of the visual designer who doesn’t yet understand software design. Their mistakes are not uncommon, but they’re not made by strong interaction designers who understand the limitations of their field. It goes the other way as well — just because someone’s created a novel and useful affordance for interacting with content doesn’t mean the person can make a page look beautiful, delightful, or inviting. It doesn’t mean they understand composition, balance, typography, or style, and it doesn’t mean they have a good eye. Blending skills is valuable, but it takes a lot of work. You Need At Least Two We’re in a field that requires a team to show talent in a lot of different areas, which means the more hats you can wear, the more valuable you are. But don’t assume if you’re wearing one hat that you’re automatically able to wear others just as well, or that other areas matter less. Visual, interaction, and code are all equally important, so pick at least two. And remember that there are people competing for your dream job that are learning all three. Where There Never Was a Hat I don’t really understand the focus some people have on legacy. If I’m good, I’ll want to hear about it while I’m alive. When I’m gone, I won’t care anymore. This excerpt from Penn of Penn and Teller hits closer to home: “Doing beautiful things is its own reward. […], “‘Look,.” I don’t expect you to remember this book for long. Most writing is lucky to be remembered the day after it’s read. But I’m proud that Lukas and I made a hat where previously there was none. It’s what I’ve always wanted to do with my life. So, what about you? What is your next hat? Notes The Thing About Jetpacks by Jon Bell & Lukas Mathis Published in August 31, 2013. by lot23 productions ISBN: 978–0–615–85966–8 Licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License. You are allowed to quote, send, translate, and reuse as much of this as you’d like as long as you kindly respect these two wishes: First, you must give us, Jon Bell and Lukas Mathis, credit. Second, you cannot make money off our work. Please email either of us with any questions: jon@lot23.com and lukas.mathis@gmail.com.
https://medium.com/@jonbell/the-thing-about-jetpacks-a9708207a082
CC-MAIN-2020-34
refinedweb
32,549
73.17
public class InputMap extends Object implements Serializable InputMapprovides a binding between an input event (currently only KeyStrokes are used) and an Object. InputMaps are usually used with an ActionMap, to determine an Actionto perform when a key is pressed. An InputMapcan have a parent that is searched for bindings not defined in the InputMap. As with ActionMap if you create a cycle, eg: InputMap am = new InputMap(); InputMap bm = new InputMap(): am.setParent(bm); bm.setParent(am);some of the methods will cause a StackOverflowError to be thrown. clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait public InputMap() InputMapwith no parent and no mappings. public void setParent(InputMap map) InputMap's parent. map- the InputMapthat is the parent of this one public InputMap getParent() InputMap's parent. InputMapthat is the parent of this one, or null if this InputMaphas no parent public void put(KeyStroke keyStroke, Object actionMapKey) keyStroketo actionMapKey. If actionMapKeyis null, this removes the current binding for keyStroke. public Object get(KeyStroke keyStroke) keyStroke, messaging the parent InputMapif the binding is not locally defined. public void remove(KeyStroke key) keyfrom this InputMap. public void clear() InputMap. public KeyStroke[] keys() KeyStrokes that are bound in this InputMap. public int size() KeyStrokebindings. public KeyStroke[] allKeys() KeyStrokes defined in this InputMapand its parent. This.
https://docs.oracle.com/javase/8/docs/api/javax/swing/InputMap.html
CC-MAIN-2018-13
refinedweb
216
50.02
digitalmars.D - XmlTokenizer review: Features and API - Eric Desbiens <olace.mail gmail.com> Nov 28 2010 I have written an xml tokenizer because I wanted to learn D2 in a sizeable project. It is templated to support any ranges that have character as element (but using any other range than w/d/string is at your own risk for now). It also uses template variables to set different features at compile time. The features control the degree of xml conformance, namespace support, type of entity decoding, default entity collection and support for xml fragment parsing. I liked the experience of programming in D2 and would like to contribute making the language and its library better. If you find the xml tokenizer useful and well written, I would eventually like to replace the current std.xml implementation with it. There is probably still a lot of work to be done on the tokenizer before its inclusion in phobos but the good news is that I have the time to improve it (Around 5 hours each Saturday, this is about the time I spent in the last 5 months writing it). So I want to do a step by step review of the code to know what needed to be change in order for its inclusion in phobos. I think we should simply start with reviewing features&api first. The basic question: - Does it make the easy things easy and the difficult one possible? - Are the different features useful? Does it have too many of them? Is it missing some? - Are the function/field/enum names easily understandable? Do they follow Phobos naming convention? I will try to ask for more review each week depending on the change requested. Other area that will need to be reviewed later: helper code that can be merged in phobos, conformance, performance, code structure, test arbitrary character support, test UTF support for non-english language, etc. You can read the documentation: You can access the code on github: Hoping to become a regular contributor Eric Desbiens Nov 28 2010
http://www.digitalmars.com/d/archives/digitalmars/D/XmlTokenizer_review_Features_and_API_123097.html
CC-MAIN-2014-52
refinedweb
343
62.98
Here we will learn passing parameters by reference or call by reference in c# or ref parameter in c# with examples and how to use c# pass by reference or call by reference to pass a value type parameters by reference with examples. In c#, passing a value type parameter to a method by reference means passing a reference of the variable to the method. So the changes made to the parameter inside of called method will have an effect on the original data stored in the argument variable. By using ref keyword, we can pass a parameters reference-type and it’s mandatory to initialize the variable value before we pass it as an argument to the method in c# programming language. As discussed earlier, value-type variables will contain the value directly on it memory and reference-type variables will contain a reference of its data. Following is simple example of passing parameters by reference in c# programming language. int x = 10; // Variable need to be initialized Multiplication(ref x); If you observe above declaration, we declared and assigned a value to the variable x before we pass it as an argument to the method by using reference (ref). To use ref parameter in c# application, both the method definition and the calling method must explicitly use the ref keyword. Following is the example of passing a value type parameter to a method by reference in c# programming language. using System; namespace Tutlane { class Program { static void Main(string[] args) { int x = 10; Console.WriteLine("Variable Value Before Calling the Method: {0}", x); Multiplication(ref x); Console.WriteLine("Variable Value After Calling the Method: {0}", x); Console.WriteLine("Press Any Key to Exit.."); Console.ReadLine(); } public static void Multiplication(ref int a) { a *= a; Console.WriteLine("Variable Value Inside the Method: {0}", a); } } } If you observe above example, we are passing the reference of variable x to the variable a in Multiplication method by using ref keyword. In this case, the variable a contains the reference of variable x so the changes that made to the variable a will affect the value of variable x. When we execute above c# program, we will get the result like as shown below. If you observe above result, the changes whatever we did for variable in called method has reflected in calling method also. This is how we can pass parameters to the method by reference using ref keyword in c# programming language based on our requirements.
https://www.tutlane.com/tutorial/csharp/csharp-pass-by-reference-ref-with-examples
CC-MAIN-2018-26
refinedweb
416
50.16
I just updated to the latest svn, and unveiled a bug that's evident when using mixed-mode rendering in the PDF backend. I'm suspect I'm the only one running my patch that enables set_rasterized on a per-artist basis, so I'm the only one that's seeing it. Artists that are left in vector mode are plotted correctly, while artists that are rasterized are squished down toward the lower left corner of the axes. Looking at the svn log, I suspect it's the changes to the path simplification code (r6847) doing something funky at the transforms level. Is that the right place to start looking? Any tips on how to track this down? Thanks, Eric Sample code to reproduce the problem: import numpy from matplotlib.pyplot import subplot, get_cmap, scatter, colorbar, show basecolors = get_cmap('gist_yarg') colormap, normer = basecolors, None #LogNorm() x = y = c = numpy.arange(10) +1 dummy = scatter(x,y,c=c,cmap=colormap)#, norm=normer) cbar = colorbar(dummy)#, spacing='proportional',ticks=isolevels.levels) dummy.set_rasterized(True) dummy.figure.savefig('raster_test.pdf')
https://discourse.matplotlib.org/t/rasterized-artists-have-wrong-transform/10755
CC-MAIN-2019-51
refinedweb
178
54.83
Zerosum Dirt(nap) 2015-04-02T00:37:07-04:00 Nick Plante BankLocal: Where You Bank Matters 2015-03-15T00:00:00-04:00 2015-03-15T00:00:00-04:00 <p>I've been a volunteer and board member for a <a href="">local-first non-profit</a> for several years now. I'm kind of a hippie do-gooder like that, you know? Most recently I've been involved in our community capital / entrepreneurship programs, which is kind of a spiritual cousin to the work I was doing with <a href="">Wefunder</a> and the JOBS Act, but at a much smaller community scale. Access to capital and economic support from your neighbors is a critical ingredient to creating the awesome spaces, inventions, and events that make cities and towns of any size worth living in.</p> <a href="">move their money</a>.</p> <p><a href="" style="padding: 20px 0; display: block;"><img src="/images/banklocal.png" alt="BankLocal"/></a></p> <p>This information is all publicly available, thanks to <a href="">data.gov</a>, <a href="">community bank locator</a>, but what we really wanted was something that'd take a bunch of factors into consideration (are they headquartered locally? what percentage of their loan portfolio is small business lending? do they engage in speculative trading?) and give us a sort of local impact score.</p> <p <a href="">BankLocal</a> project. Take a look at data for your current bank and see how it stacks up against other institutions in your area. We'd love to hear what you think.</p> Nick Plante Rails + Angular + Jasmine: A Modern Testing Stack 2014-01-17T00:00:00-05:00 2014-01-17T00:00:00-05:00 <p>When I started on my first <a href="">Angular</a>+<a href="">Rails</a>.</p> <p>This morning the team over at Localytics (hi Raj!) wrote up a good <a href="">retrospective on their use of Angular + Rails</a> over the past year, including lessons they learned and ongoing challenges. They touch on several of the same issues that my colleagues and I have run into, and the writeup inspired me to dust off my old busted blog to document some of my own findings.</p> <h4>Testing Your JavaScript Has Never Been Easier</h4> <p.</p> <p>To see a working example for yourself and hack around with it, go snag the <a href="">sample project</a> I pushed up to GitHub. Bundle and run it, and play around with the shockingly awesome todo list application. Because the world really needed another one of those. When you've had enough of that, take a look at the contents of the <code>spec/javascripts</code> directory.</p> <p>We're using the <a href="">jasmine-rails</a> test runner with CoffeeScript here, because that's what works for me (sorry Karma). Pay close attention to the <code>spec_helper.coffee</code>, which does much of the dependency injection needed to provide clean and intuitively named interfaces in our example controller spec.</p> <script src=''></script> <div><noscript><pre><code></code></pre></noscript></div> <p>This gives us nice ways to interface with the factories and controllers we're defining, as well as Angular's own <a href="">ngMock</a> library (super useful for stubbing server-side endpoints), the event loop, and even template compilation for partials and directives. A couple of these are illustrated in the sample controller spec shown here:</p> <script src=''></script> <div><noscript><pre><code></code></pre></noscript></div> <p <code>flush()</code> are required to fulfill pending requests, preserving the async nature of the backend but allowing the tests to execute synchronously.</p> <h4>Testing Continuously With Guard</h4> <p>Although the Jasmine web interface is nice, but I'm a big fan of using <a href="">Guard</a> in order to watch for filesystem events and kick off automated test runs from the command line. By including the <a href="">guard-jasmine</a> gem and updating our Guardfile we can continuously test both our server-side RSpec logic and the Jasmine unit tests all at the same time through a single interface:</p> <p><img src=""/></p> <p>One thing I haven't addressed here is directive testing, which can be a bit more difficult. I'll try to address that in a future post, or if you have your own recipes, feel free to link em up in the comments.</p> <p>Special thanks to <a href="">Mark Bates</a> for working with me on early versions of this approach, and convincing me that Angular was worth looking at in the first place.</p> Nick Plante The Wefunder Petition 2012-01-31T00:00:00-05:00 2012-01-31T00:00:00-05:00 <p>Kick.</p> <p>Soon, new laws may allow us to do just that.</p> <p><img src="/images/wefunder.png" style="float: right; margin: 0 10px 0 10px;"/></p> <p>To raise awareness of these initiatives, a few friends and I tossed together the <a href="">Wefunder petition</a> to support HR2930 and Brown's Democratizing Access to Capital Act (S.1791) that's currently being debated in the US Senate. Please go sign it (click the "learn more" link on the site for more background information and links).</p> <p>These changes could have huge impacts for both entrepreneurs and investors, allowing bold new ideas to surface and creating a ton of important jobs and opportunities. I know that sounds like marketing speak, but it's true. This matters.</p> <p>We'll be going to DC next week to talk to Senator Brown's people and see what else we can do to push this forward. We've also been fortunate enough to get some great coverage for our efforts at <a href="">BoingBoing</a> and <a href="">ReadWriteWeb</a>.</p> <p>Now go sign it already and help us send a message. And thanks!</p> Nick Plante Building Android Apps with Mirah and Pindah 2011-07-24T00:00:00-04:00 2011-07-24T00:00:00-04:00 <p>I gave a talk earlier today at the Beijing Ruby group today about my experiences building native Android applications with <a href="">Mirah</a> and <a href="">Pindah</a>.</p> <p>Although I generally prefer building mobile web apps over native development when possible, Mirah is a really promising alternative to Java if you have to go native. Check out the <a href="">preso</a> below and get involved in the growing Mirah / Android community.</p> <p> <iframe src="" width="425" height="355" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"> </iframe></p> <p>Make sure to grab the <a href="">code for the example app</a> on the GitHubs.</p> Nick Plante Geeks on a Train 2011-07-21T00:00:00-04:00 2011-07-21T00:00:00-04:00 <p><a href="">Geeks on a Train</a> starts today!</p> <p>This afternoon I'm leaving Dalian, Liaoning, China for a 10-day journey across China's tech ecosystem with a bunch of awesome startup founders. By train. Because <a href="">planes</a> and <a href="">buses</a> are so last year (kidding!)</p> <p.</p> <p><img src="/images/geeksonatrain.png" style="float: right; margin: 0 0 10px 10px;"/></p> <p>Geeks on a Train (affectionately referred to as "GOAT") is part of the Dalian-based <a href="">Chinaccelerator</a> program, which is a Chinese startup accelerator run by program director <a href="">Cyril Ebersweiler</a> and the good folks at SOS Ventures. I was fortunate enough to meet them through <a href="">TechStars</a> in 2010 and am really honored that they invited me over to work with some of the young teams that were accepted into the program this year. How could I say no?</p> <p <a href="">JFDI</a> are key.</p> <p.</p> <p>But I can only imagine what it's going to be like trapped on an overnight train with them :).</p> Nick Plante Rails Rumble Alumni Archive Project 2011-07-02T00:00:00-04:00 2011-07-02T00:00:00-04:00 <p>2011 has been a busy year so far, full of interesting contract work, side projects, research for the next startup biz, upcoming travel plans, and not-so-fun family health issues. It's also been a busy year for the other <a href="">Rails Rumble</a> organizers, and as such there's currently no date set for the 2011 contest. Sorry about that :(.</p> <p><img src="/images/rumble_logo_2010.png" alt="Rails Rumble" style="float: right; margin: 0 0 10px 5px;"/></p> <p>However, I did find a few hours last weekend to design / develop a Rumble-related mini-site that's been long, long overdue...</p> <p>The new <a href="">Rumble Alumni Archive</a> is a searchable archive of websites and applications that were developed during contests past and present. It's a great way to see what entries are still online and browse them by year (2007-2010), country of origin, and award.</p> <p>Over 80 entries that were developed during Rumble events are still online, most of which have evolved pretty significantly since their initial weekend development sprint. For just a couple examples, check out <a href="">Mocksup</a>, <a href="">Awesome Fontstacks</a>, and <a href="">IOU Mate</a> (formerly "nDebted"). Go <a href="">poke around the archive</a> to see others; there's some really great stuff in there. And please let us know (contact organizers <em>at</em> railsrumble <em>dot</em> com) if we've left anybody out.</p> <p>I know I've said it before, but it's really inspiring to me when I think about how many of these polished web apps started off as as disposable weekend experiments. Kick. Ass.</p> Nick Plante Song Lyrics Without the Suck 2011-06-26T00:00:00-04:00 2011-06-26T00:00:00-04:00 <p>Over the past few years I’ve been involved with a number of music-related web projects, including Loudwerkz, <span class="caps">DMOD</span> (<span class="caps">RIP</span>), and <a href="">Ink19</a>. Although I make my living on the web and love what I do, I suppose I’ve always been secretly jealous of those snobby record store employees who hear the latest cuts first, troll naive customers, and argue with their coworkers about song meanings :).</p> <p>Fortunately, the web has lowered the bar to all of that stuff. What would we do without Pandora, Last.fm, and (more recently) <a href="">Turntable</a>? The one missing piece for me has always been a <strong>good</strong>.</p> <p>If you’re like me, this makes you sad. And irritated. So there I was, bitching about this on Twitter one evening, when <a href="">Seth Banks</a> proposed that we actually do something about it. So we did.</p> <p>Last week, Seth and I launched <a href="">Lyricful</a>, which aims to be the first <a href="">classy lyrics site</a>. We started with a nice clean design and paired it with a sizable lyrics database (growing every day), an intuitive search interface, and some <span class="caps">SEO</span> know-how. We’ve also added a few other things we felt fans would find useful, like song previews, concert information, and easy sharing features.</p> <p.</p> <p>Since the soft launch, we’ve started working with a number of artists who were interested in Lyricful and its sister site, <a href="">MusicNewsHQ</a>.!</p> Nick Plante Startup Workaway - Coworking in Costa Rica 2011-05-03T00:00:00-04:00 2011-05-03T00:00:00-04:00 <p>Are you a hacker? Working on a startup? How about coworking and networking with other people who are building inspiring new stuff? Sure you do.</p> <p><img src="/images/costarica.jpeg" style="float: right; margin: 0 0 10px 10px;"/></p> <p>And who doesn’t like the rain forest? See also: <a href="">howler monkeys</a>.</p> <p>StartupWorkaway is something <a href="">Nick</a>, <a href="">Zach</a>, and I have been talking about for quite awhile. We actually built most of the website back in February when we rented a house together up in Quebec City during Winter Carnaval. Nick polished it up and posted it to <a href="">Hacker News</a> the other day and the response has been pretty incredible so far.</p> <p>Visit <a href="">StartupWorkaway</a> for all the gory details. The application deadline is May 6th.</p> Nick Plante Easy Rails OAuth Integration Testing 2011-03-19T00:00:00-04:00 2011-03-19T00:00:00-04:00 <p>A long while back I wrote a post about <a href="">Twitter auth integration testing</a> using <a href="">Cucumber</a>..</p> <p>We’re using <a href="">OmniAuth</a> to handle auth here, which is absolutely awesome. And we’re also using the equally-awesome <a href="">Capybara</a>.</p> <p><img src="/images/capybara.jpg" style="float: right; margin: 0 0 10px 10px;"/></p> <p>On the other hand, if you’re dissatisfied… Capy 1.0 comes with a swanky new <a href="">minimalist RSpec-friendly acceptance testing <span class="caps">DSL</span></a>.</p> <p>If you want OAuth integration testing to be easy, you’ll want to make sure you’re using the OmniAuth 0.2.0 or later. Among it’s many fine features is a new <a href="">integration test_mode</a> that makes testing OAuth logins less sucky than it’s ever been before. Fortunately for us, Capybara and OmniAuth go together like giant chocholate swamp rat and creamy peanut butter. It pretty much works right out of the box.</p> <p>To demonstrate, let’s add a nice little integration auth helper method that we can use in our request specs to log a user in (I like to put this in <code>spec/support/integration_spec_helper.rb</code>):</p> <pre><code>module IntegrationSpecHelper def login_with_oauth(service = :twitter) visit "/auth/#{service}" end end</code></pre> <p>Now, in your <code>spec_helper.rb</code>, add the following:</p> <pre><code>RSpec.configure do |config| # ... config.include IntegrationSpecHelper, :type => :request end</code> <code>Capybara.default_host = ''</code> <code>OmniAuth.config.test_mode = true OmniAuth.config.add_mock(:twitter, { :uid => '12345', :nickname => 'zapnap' })</code></pre> <p>Finally, let’s take a look at an example RSpec request spec that leverages this helper to test a workflow where a user login is required:</p> <pre><code>feature 'testing oauth' do scenario 'should create a new tiger' do login_with_oauth visit new_tiger_path</code> <code> fill_in 'tiger_name', :with => 'Charlie' fill_in 'tiger_blood', :with => 'yes'</code> <code> click_on 'Create Tiger'</code> <code> page.should have_content("Thanks! You are a winner!") end end</code></pre> <p>That’s it. OmniAuth’s test mode automatically mocks out the authentication workflow, allowing us to supply our own auth results hash. Requests made to the usual /auth/provider <span class="caps">URL</span> will redirect immediately to the provider callback, which means we never have to hit the actual provider while testing (which also means that webmock or fakeweb remain happy).</p> <p>This might seem simple, and it is. And that’s kind of a big deal. So now we can get back to writing stuff that isn’t plumbing and focusing on solving real problems ;).</p> Nick Plante Better AWS Access Control with IAM (and Fog) 2011-03-02T00:00:00-05:00 2011-03-02T00:00:00-05:00 <p>Amazon are the undisputed kings of the <a href="">developer plumbing revolution</a>. EC2 and S3 are so ubiquitious to deploying web applications that sometimes it seems difficult to remember when we had to self-host so much of this stuff. But sometimes managing my access keys can be a pain. Or even worse: a security hazard.</p> <p.</p> <p><img src="/images/fog.png" style="float: right; margin: 0 0 0 10px;" /></p> <p>The solution to this problem is <a href="" title="IAM">Amazon’s Identity and Access Management</a> product beta. <span class="caps">IAM</span> allows you to create different users and groups, and attach those to your account. So, for example, if you’re a company or a group of people who needs to share a single <span class="caps">AWS</span> account, you could create separate identities with separate security credentials (access key ID + secret access key) for each individual. Or if you run several different projects and want to segregate those by account, you can do that too.</p> <p>Even better, you can control which <span class="caps">AWS</span>.</p> <p>Anyway, outside of Amazon’s own <a href="">documentation</a>, I couldn’t find a hell of a lot of information about using <span class="caps">IAM</span> in the real world, so I thought I’d demonstrate how I’m using it with <a href="">Fog</a>, which is an absolutely awesome cloud services library for Ruby.</p> <p>Annotated example code seems like the right way to go here. Let’s generate a new <span class="caps">IAM</span> user and a set of keys for him, and give him permission to only a single bucket, which we’ll create (note that your bucket name must be unique so don’t use the sample one shown here).</p> <p>First, we set up the new user name and the bucket name that we want to create, and establish our <span class="caps">AWS</span> credentials:</p> <pre><code>require 'fog'</code> <code>username = 'testuser' bucket = 'uniquebucketname1234'</code> <code>aws_credentials = { :aws_access_key_id => 'YOUR-ACCESS-KEY-ID', :aws_secret_access_key => 'YOUR-SECRET-ACCESS-KEY' }</code></pre> <p>Creating a new S3 bucket is easy with Fog:</p> <pre><code>storage = Fog::Storage.new(aws_credentials.merge(:provider => 'AWS')) storage.put_bucket(bucket)</code></pre> <p>Fog also provides a lightweight wrapper around <span class="caps">IAM</span> <span class="caps">API</span> methods. Using this, we can create the new user and create an access key. Assuming this is successful, we’ll end up with the user <span class="caps">ARN</span> (which we’ll need later) and a new set of credentials.</p> <pre><code>iam = Fog::AWS::IAM.new(aws_credentials)</code> <code>user_response = iam.create_user(username) key_response = iam.create_access_key('UserName' => username)</code> <code>access_key_id = key_response.body['AccessKey']['AccessKeyId'] secret_access_key = key_response.body['AccessKey']['SecretAccessKey'] arn = user_response.body['User']['Arn']</code></pre> <p>We want to give this user the ability to manage their own keys (as shown in Amazon’s <a href="">Getting Started guide</a> so we create our first policy document as they suggest.</p> <pre><code>iam.put_user_policy(username, 'UserKeyPolicy', { 'Statement' => [ 'Effect' => 'Allow', 'Action' => 'iam:*AccessKey*', 'Resource' => arn ] })</code></pre> <p>We also want to grant them access to the bucket we created. But <strong>only</strong> our bucket and no others. If you think constructing policy documents by hand is shitty, you’re right. Fortunately the <a href=""><span class="caps">AWS</span> Policy Generator</a> can help us generate the nasty bits. Check it out.</p> <pre><code}/*" ] } ] })</code></pre> <p>Finally, let’s reset our <span class="caps">IAM</span> access credentials and verify we can access the bucket and upload a file to it:</p> <pre><code>aws_credentials = { :aws_access_key_id => access_key_id, :aws_secret_access_key => secret_access_key }</code> <code>storage = Fog::Storage.new(aws_credentials.merge(:provider => 'AWS')) storage.get_bucket(bucket) storage.put_object(bucket, 'image.png', File.open('/path/to/image.png'))</code></pre> <p <a href="">s3cmd</a> and the <a href="">Firefox S3 Organizer</a> wouldn’t work with my newly generated <span class="caps">IAM</span> keys, and the reason was simply that they were trying to get a list of buckets first, which was returning an access denied message. D’oh. (and thanks to <a href="">crazed</a> for helping me see the light on that.)</p> <p>If you’re not a Ruby developer, or you just need command line access, you can also use the <a href=""><span class="caps">IAM</span> command line tools</a> provided by Amazon, and you should definitely check out their <a href="">Getting Started guide</a>. Hopefully <span class="caps">IAM</span> will find its way into the <a href=""><span class="caps">AWS</span> Console</a> so routine management tasks are a bit easier in the future. In the meantime, creating policy documents by hand is a big pain in the ass, but at least the <a href="">Policy Generator</a> takes a little bit of the suck out of it.</p> <p><a href="">Get the full example source</a></p> Nick Plante Stomp in the Android Market 2011-02-26T00:00:00-05:00 2011-02-26T00:00:00-05:00 <p>My pal and “prolific prototyper” Nick Tommarello just released his latest project into the wild… <a href="">Stomp.io</a> is a social adventure and travel guide that aims to make it easier for you to find fun things to do while at home or on the go. Stomp debuted at the <a href="">Launch conference</a> run by former TC50 founder Jason Calacanis, and has gotten some <a href="">great media coverage</a> over the past couple days. Like pitches? You can watch Nick’s presentation <a href="">here</a>.</p> <p><img src="/images/stomp.png" style="float: right; margin: 0 0 10px 10px;"/></p> <p>If you’re in SF, <span class="caps">NYC</span>, or Boston, make sure to give it a try. Hopefully it won’t take too long to spread to other areas too. Some of the challenges are… <a href="">kind of nuts</a>. Others are a bit more <a href="">laid back</a>. And there’s a lot more in-between so I’m pretty sure you’ll find <a href="">something</a> you like there. You can install the mobile version of the app on both the <a href="">iPhone</a> and <a href="">Android</a></p> <p <a href="">hiding in the woods</a>; Crash reports and feature requests are very welcome :). Thanks in advance!</p> Nick Plante Ohai Tumblr 2011-01-02T00:00:00-05:00 2011-01-02T00:00:00-05:00 <p>At one point in time (affectionately referred to as the “long long ago”) I used to post all kinds of stuff here, both technical / programmery and non-technical / non-programmery. Once I started using <a href="">Twitter</a> on a regular basis, I stopped posting here as much, and when I did, the content was pretty much just technical stuff. Which is a big win if you’re a fan of the signal to noise ratio.</p> <p>“But,” you say, “I like more noise with less signal!”</p> <p>Me too! And thus it was that I set up a <a href="">Tumblr</a> account awhile back, mostly for posting <a href="">stupid pictures</a>. But I figured, what with it being 2011 and all, that I’d maybe I’d also start <a href="">writing a little bit more there</a>. Or maybe not. We’ll see.</p> <p>If you’re interested, <a href="">follow me on Tumblr</a>.</p> <p>Oh, and Happy New Year!</p> Nick Plante Fooling Around with Mirah and Android 2010-12-20T00:00:00-05:00 2010-12-20T00:00:00-05:00 <p>Have you spent any time playing around with <a href="">Mirah</a> yet? You should. It’s developing into a pretty awesome language. Or maybe just a fantastic <a href="">Ruby-like syntax for Java</a>, depending on how you look at it. Mirah as a language (err, compiler) is still a work in progress, but it’s very usable as-is and fun to play around with. <br /> <img src="/images/ruby-android.png" style="float:right; margin: 0 0 10px 10px;"/></p> <p>If nothing else, it certainly makes writing trivial Android applications more enjoyable. Want to write one yourself? Check out <a href="">Protoform</a>, a little Mirah Android app generator that I tossed together a few weeks ago. Install it via Rubygems and get your droid on:</p> <pre><code>gem install protoform protoform -S ~/android/sdk -T "Hello Android" -P org.zerosum.android HelloWorld</code></pre> <p>You’ll want to have JRuby and Mirah installed of course. Get JRuby with <a href=""><span class="caps">RVM</span></a> and then gem install <a href="">Mirah</a>.</p> <p>If you want to do Android work in straight Ruby instead, you can take a look<br /> at <a href="">Ruboto</a>. However, Ruboto runs on Android<br /> via JRuby, which means the runtime needs to be bundled in to the <span class="caps">APK</span>, leading<br /> to large file sizes and slow execution. Mirah, on the other hand, compiles<br /> straight to Java bytecode with no middleman and makes direct use of the Google<br /> Android APIs. Ruboto is under heavy development and coming along nicely though, and the more Ruby-like <span class="caps">API</span> wrappers are a welcome alternative.</p> <p>Both of these projects have the potential to be pretty important stuff. As<br /> does anything else that makes mobile client development less painful<br /> (<a href="">Appcelerator</a>, <a href="">Phonegap</a>, <a href="">Rhomobile</a>, etc).</p> Nick Plante A Pure Git Deploy Workflow (with Jekyll and Gitolite) 2010-11-01T00:00:00-04:00 2010-11-01T00:00:00-04:00 <p>Manually deploying static site updates is so 2003. And <a href="">Capistrano</a> is great, but it’s an extra step you don’t always need (and somewhat overcomplicated). If you’re using <a href="">Jekyll</a> to power your site and already have your data in Git, it’s pretty easy to set up a pure Git deployment workflow. Even if you’re not using <a href="">Heroku</a> ;-).</p> <p>By using either Gitosis or (better yet) <a href="">Gitolite</a>, you can be autodeploying like a boss in just a few minutes. And, because Gitolite allows you to manage repository access across ad-hoc groups, you can easily allow other users to push to your remotes and update the appropriate sites without them needing shell access on your server. And share those users across multiple projects, and so on and so on.</p> <p>Here’s how I set up the deploy recipe that I use for updating this blog and a couple other static sites that I’m hosting on the same box.</p> <h3>Gitolite Installation</h3> <p>First, install Gitolite on the host you want to deploy to. Sitaram’s <a href="">installation instructions</a> are really easy to follow, but I’ll summarize here (I used the root method, which I suspect is what most readers would want to use too):</p> <pre><code>git clone git://github.com/sitaramc/gitolite gitolite-source cd gitolite-source git checkout v1.5.6 (or whatever tagged version you want) mkdir -p /usr/local/share/gitolite/conf /usr/local/share/gitolite/hooks src/gl-system-install /usr/local/bin /usr/local/share/gitolite/conf /usr/local/share/gitolite/hooks</code></pre> <p>You’ll need to add a <code>git</code> user, who will own the repositories on the system. Create one now, and finish the Gitolite installation process:</p> <pre><code>adduser git su - git gl-setup /path/to/your/public-key/id_rsa.pub</code></pre> <h3>Gitolite Administration</h3> <p>Make sure that you gave <code>gl-setup</code> the correct public key from your local (client) system. Now, on your client, you should now be able to check out the gitolite admin repository, through which you can manage users, groups, and repository access.</p> <pre><code>git clone git@my-server:gitolite-admin</code></pre> <p>Next, edit <code>gitolite-admin/conf/gitolite.conf</code>. Gitolite comes with a couple pre-defined group definitions (including one for the admin repository; don’t screw that one up). Adding a user permissions for a new repository goes like this:</p> <pre><code>repo blog RW+ = kyle stan</code></pre> <p>Where <code>blog</code> is the name of the repository you want to create, and <code>kyle</code> and <code>stan</code> are two users who will need to be able to read and write to that repository. We have no way to identify Stan and Kyle yet, but that’s the next step. We’ll add their public keys to the <code>gitolite-admin/keydir</code> directory. Make sure to name them <code>kyle.pub</code> and <code>stan.pub</code>.</p> <p>Add the new files to the git repo (<code>git add .</code>) and commit everything. Push it to the remote with <code>git push origin master</code>. This should push the gitolite admin changes back to your remote server and update the internal configuration, allowing Stan and Kyle to work on the blog project.</p> <h3>Managing a Static Site</h3> <p>For simplicity’s sake, let’s say that you’re Stan (Stan’s public key is your public key). To create the new repository and register it with Gitolite, you should now be able to do the following:</p> <pre><code>mkdir blog cd blog git init touch index.html git add . git commit -a git remote add origin git@my-server:blog git push origin master</code></pre> <p>Instead of just creating an empty index file, make it a simple html file, or drop in <a href="">a basic Jekyll site</a>. Or, instead of creating a brand new repository, just add a remote (call it <code>production</code> perhaps?) to an existing Jekyll repository that you’ve been working on. In any case, when you push those commits up, Gitolite should check that your public key is authorized to perform that operation, and (assuming that it is) create the new bare repository for you automatically. Because it’s cool like that.</p> <p>If you have a problem with this step, check that (a) your public key is indeed mapped to a username that is authorized to RW that repository, and (b) that the name in your gitolite.conf matches the public key filename.</p> <p>If that all appears to be working, your next step will be to create a virtual host entry in your Apache config on the server (or your web server of choice). Here’s a basic Apache vhost:</p> <pre><code><VirtualHost *:80> ServerName blog.superawesomedomainname.com ServerAdmin info@superawesomedomainname.com DocumentRoot /var/www/blog</code> <code> ErrorLog /var/log/apache2/blog-error.log CustomLog /var/log/apache2/blog-access.log combined </VirtualHost></code></pre> <p>And of course, create the docroot destination and make sure the <code>git</code> user owns it and can write to it. Then you can enable the config and restart Apache (or nginx or whatever).</p> <h3>Auto-Update on Deploy</h3> <p>I’m going to assume that we’re working with Jekyll here. And you should be, because it’s awesome. But if you are using some other static site generator, you can customize it pretty easily. The basic idea is that you want a post-receive hook to fire whenever the server receives a new push, and you want to regenerate the site data and redeploy it for everyone to see. This makes creating a new blog post really easy, for example.</p> <p>Navigate to <code>/home/git/repositories/blog.git/hooks</code> and edit the <code>post-receive</code> file. You may also need to <code>chmod ug+x</code> it so it’ll execute properly. Here’s what goes inside:</p> <pre><code>GIT_REPO=$HOME/repositories/blog.git TMP_GIT_CLONE=$HOME/tmp/blog PUBLIC_WWW=/var/www/blog</code> <code>git clone $GIT_REPO $TMP_GIT_CLONE cd $TMP_GIT_CLONE && jekyll --no-auto $TMP_GIT_CLONE $PUBLIC_WWW cd ~ && rm -rf $TMP_GIT_CLONE</code> <code>find $PUBLIC_WWW -type f -print0 | xargs -0 chmod 666 find $PUBLIC_WWW -type d -print0 | xargs -0 chmod 777</code> <code>exit</code></pre> <p>Save that, and then commit a sample change from your client and push it to the remote. The server should fire the post-receive hook automatically when the push has finished, and regenerate the site, dumping the changes into your docroot directory for the world to see. In fact, you should even see the Jekyll generation output in the git push command output, which makes it extra easy to troubleshoot in case you’re having a problem.</p> <p>And voila, git auto-deploy goodness.</p> <p>What’s best about this is that it’s easy to authorize new users to update a group site or blog, and manage those users all through their public keys and a simple config file. This config also makes it easy to spin up new static sites on the same host; just copy a couple configs and you’re good to go (or even better, investigate <a href="">dynamically configured mass virtual hosting</a>).</p> <p>If you’re self-hosting your blog with some custom blog package you should really give this type of setup a look. I like it because it’s simple to manage access, incredibly quick to deploy updates, and everything is naturally stored in Git and in plaintext, so you’ve always got full revision history and never have to worry about vendor lock-in or proprietary formats. Need comments? Use <a href="">Disqus</a>. Less moving parts is almost always better. Simple is good.</p> Nick Plante More Jekyll, Less Hyde 2010-10-30T00:00:00-04:00 2010-10-30T00:00:00-04:00 <p>This blog has been running <a href="">Mephisto</a> since 2007 or thereabouts. And it seems like the Mephisto project has been dead for just about that long too (check that link if you don’t believe me). So that’s awesome. But such is life… and open source.</p> <p><img src="/images/jekyll.jpg" alt="Dr Jekyll" style="float: right; margin: 0 0 10px 0;"/></p> <p <a href="">Jekyll</a> ..</p> <a href="">NH Ruby</a> <a href="">Gitolite</a>, which makes managing access control for such things crazy easy.</p> <p>The only thing that didn’t make the transition is old blog comments. I went with <a href="">Disqus</a>.</p> <a href="">GitWrite</a> guys had to do for their (awesome!) Rails Rumble entry this year. And yeah, I probably could have just used them too. Don’t know why I didn’t think of that earlier ;-).</p> Nick Plante Rails Rumble 2010 2010-10-21T00:00:00-04:00 2010-10-21T00:00:00-04:00 <p>This is the fourth year I’ve helped organize the <a href="">Rails Rumble</a> innovation competition and the entries this year are definitely the best I’ve seen yet. Our <a href="">panel of experts</a> have finished making their finalist selections and <a href="">public voting just opened</a>, so head on over and help us decide who gets to do a victory dance this weekend.</p> Nick Plante Announcing RubyDoc.info 2010-08-30T00:00:00-04:00 2010-08-30T00:00:00-04:00 <p>Last year we launched a little web service called <a href="">rdoc.info</a> for hosting public docs for Ruby libraries. It wasn’t a completely new idea, but there was nothing else out there at the time that was free and open source and worked on Github post-commit hooks, so <a href="">I put something quick together in a day</a> and started using it. A bunch of other people started using it too, which was great, and people started contributing patches, which was even more great (thanks in particular to Jeff Rafter and Brian Turnbull). It grew as more people and organizations like our friends at <a href="">Thoughtbot</a> started hosting their library docs on it.</p> <p><strong>Today it hosts docs for almost 3000 different Ruby projects. And today we’re killing it.</strong></p> <h3>RubyDoc.info is Rdoc.info 2.0</h3> <p>Well, actually, it’s more like we’re replacing it. With something newer and better, of course. That newer, better thing is <a href="">RubyDoc.info</a> (<a href="">source</a> on Github), a project that originally started out as the <a href="">yardoc.org</a> doc server grew into a full-fledged rdoc.info replacement. <a href="">Loren Segal</a> (the author of <span class="caps">YARD</span>, easily the best Ruby documentation engine ever) and I have been working on merging the projects together for awhile now, and it’s finally cooked well enough that we’re ready to swap it over.</p> <p>The new site addresses a number of outstanding issues / feature enhancements that people asked for on the old site, and it’s much more tied into the <span class="caps">YARD</span> ecosystem. Also, in addition to supporting GitHub post-commit hooks, it also hosts documentation for all published RubyGems. We like it, and we hope you do too.</p> <h3>If You’re Already Using Rdoc.info</h3> <p>If your docs are already up on rdoc.info, don’t worry. Your old URLs should still work, so no need to update them right away. Your post-commit hooks will still work too. If you have any problems at all, please <a href="">open a ticket</a> on the project’s Github repository and we’ll do our best to get you squared away. Thanks!</p> <h3>Better Docs == Better Code</h3> <p>Also, in case you’re not already familiar with <span class="caps">YARD</span>, now is a great time to learn about it and how it can help you improve documentation for your code. This new site deployment coincides with the release of the <a href="">brand new <span class="caps">YARD</span> 0.6</a> and Loren’s awesome new <a href="">Yardoc.org</a> site, which has some great <a href="">guides</a> and other resources to get you up to speed fast.</p> Nick Plante Resque Mailer v1.0.0 (with Rails 3 Support) 2010-07-28T00:00:00-04:00 2010-07-28T00:00:00-04:00 <p>I just released a new version of Resque Mailer (1.0.0), my asynchronous email delivery extension for Resque <a href="">gem</a> <a href="">src</a>. If you’re already using it with Rails 2.x, there really aren’t any changes you need to be aware of. Go about your business. However, thanks largely to the efforts of <a href="">Marcin Kulik</a>, the gem now works in Rails 3.x as well. Thanks Marcin!</p> <p>So why go 1.0.0? Because it’s feature complete, used by a number of people in production, and has been stable without any significant feature additions or issues for quite some time. It’s still simple as hell, and I don’t see it getting more complicated any time soon. And now that it works on both Rails 2.x and 3.x, well, that sounds like a 1.0.0 to me.</p> Nick Plante Google Analytics Integration with OAuth 2010-05-28T00:00:00-04:00 2010-05-28T00:00:00-04:00 <p>In case you’re not reading the <a href="">Mogo blog</a>, I posted a tutorial over there yesterday about how we <a href="">integrate Google Analytics with Rails using OAuth</a> and <a href="">Garb </a>. It’s not a terribly arduous process, but if you haven’t done much work with OAuth it can be confusing, and there are a couple unique Googly things about it that might otherwise trip you up.</p> <p>The post includes complete code for an OAuth-backed authorizations controller too, which should help you get up and running quickly. And fwiw, it should actually be applicable to all the Google Data APIs, not just Google Analytics. Just change the request token scope.</p> <p>And yeah, I really need to get back to blogging on a semi-regular basis, too.</p> Nick Plante Rails Camp New England Redux 2010-03-12T00:00:00-05:00 2010-03-12T00:00:00-05:00 <p>Already got plans for this weekend?</p> <p><img src="" style="float: right; margin: 0 0 10px 10px"/><br /> The second <a href="">Rails Camp</a> New England is this weekend, March 12th to the 14th, in West Greenwich Rhode Island. Hope to see some of you there! Ask me about <a href="">my new startup</a> (want an invite?) or help me fix some of the outstanding <a href="">Rdoc.info</a> <a href="">bugs</a> if you’re looking for something to do :).</p> <p>The last camp in <a href="">summer of 2009</a> was a great experience and I’ve been looking forward to a repeat. Thanks to <a href="">Brian Cardarella</a> for putting it together.</p> Nick Plante Resque Mailer 2010-01-09T00:00:00-05:00 2010-01-09T00:00:00-05:00 <p>We've been making heavy use of Chris Wanstrath's <a href="">Resque</a> library in my <a href="">latest project</a>. Resque is a <a href="">Redis</a>-based background job system that Chris built for GitHub. It's easy to use, especially if you're already leveraging Redis in other parts of your infrastructure, and also has a nice Sinatra front-end for monitoring job status.</p> <p>Anyway, Resque jobs are just Ruby classes that respond to the special perform method. They're placed on a queue — you can place different jobs on different queues — and later, a worker polls the queue, pops the jobs off and performs the task.</p> <p>We have a number of different asynchronous jobs happening in Mogo, many of which are domain-specific. But one thing we're doing that's very common is using the background system to process mail delivery asynchronously. Because synchronous mail delivery is for jerks.</p> <p>Outgoing mail in a Rails app is generally handled by <a href="">ActionMailer</a>, which expects you to implement message delivery types as class methods on an ActionMailer "model" (a butchering of the term). So a typical mailer might look like this:</p> <pre><code>class Notifications < ActionMailer::Base def signup(user_id, sent_at = Time.now) @user = User.find(user_id) subject 'Welcome to Mogo' recipients @user.email from 'Mogoterra <noreply@mogoterra.com>' sent_on sent_at end end </code></pre> <p>Then, to send a signup message, you use the following method call from somewhere else in your codebase:</p> <pre><code>Notifications.deliver_signup(@user.id) </code></pre> <p>So this all works good but it's synchronous. You'd like to be able to background these tasks and use Resque. But you don't really want to mess around with the mailer implementation. Right? Me too.</p> <p>So <a href="">ResqueMailer</a> does just that.</p> <p>Following in the footsteps of <a href="">DelayedJobMailer</a>, ResqueMailer allows you to shift processing of your existing mailers to an async Resque worker without doing pretty much anything. Just install the gem in your Rails project (via <a href="">Gemcutter</a>) and then mix the <code>Resque::Mailer</code> module into your mailer.</p> <pre><code>class Notifications < ActionMailer::Base include Resque::Mailer # ... end </code></pre> <p>You'll need to restart your Resque workers and make sure at least one of them is working on the special <code>mailer</code> queue (or * for all queues). Now when you call <code>MyMailer.deliver_signup</code>, the task will be placed on the mailer queue and processed by the first qualifying worker.</p> <p>It's always nice when a tiny amount of code makes a task transparent. Check out the <a href="">project page</a> on GitHub for more information.</p> Nick Plante Rdoc.info Updated 2009-11-22T00:00:00-05:00 2009-11-22T00:00:00-05:00 <p><a href="">Rdoc.info</a> is now serving up fresh docs using <a href=""><span class="caps">YARD</span> 0.4.0</a>. Doesn’t that new template look nice?</p> <p><img src="" style="float: right; padding: 0 0 5px 10px;"/></p> <p>If you’re a Ruby <span class="caps">OSS</span> developer and haven’t checked out <a href=""><span class="caps">YARD</span></a> yet, you really should. It’s easily the best way to generate sexy documentation for your projects and Loren has done a really awesome job with the latest release. The experimental new <a href="">live docs service</a> (with php.net-style user comments) that he’s testing out is swanky too, and we hope to roll this stuff into Rdoc.info shortly.</p> <p>In the meantime, you can enjoy the latest <span class="caps">YARD</span> features and an updated look and feel. Make sure to <a href="">add a post-commit hook</a> to your <a href="">GitHub</a>-hosted project and we’ll automatically rebuild docs whenever you push a new release to your remote. Docs for older versions are maintained as well, and accessible via the usual commit hash url [<a href="">example</a>].</p> Nick Plante EC2 Deployment with Rubber 2009-11-17T00:00:00-05:00 2009-11-17T00:00:00-05:00 <p>At <a href="">NH.rb</a> last night I gave a talk about <a href="">deploying web applications to the EC2 cloud with Rubber</a>. Rubber is an extension to <a href="">Capistrano</a> written by Matt Conway that makes provisioning and managing multi-instance EC2 deployments magically delicious [<a href="">GitHub</a>].</p> <p>Want to bring up an instant multi-role staging server fully loaded with Apache, Passenger, MySQL, and your Rails app? All gem’d up, migrated, and ready to use? Sure you do. First, <a href="">sign up for an EC2 account</a>, generate your keypair, and then…</p> <pre><code>gem install rubber cd my-rails-project script/generate vulcanize complete_passenger_mysql edit config/rubber/rubber.yml cap rubber:create_staging </code></pre> <p>It uses a Ubuntu <span class="caps">AMI</span> and provisions an EC2 small instance by default. If you added your account credentials and the apt packages and gems you needed to rubber.yml (and provided that there weren’t any unexpected problems), you should now have a fully functional staging server for your web app that you can visit at.</p> <p>Since it’s EC2 you only pay for what you use. What’s more is you can horizontally scale this out with relative ease — breaking out the individual roles to separate instances as needed — and/or add your own custom roles as needed (see the other templates available for examples).</p> <p>Want to learn more? Peep my <a href="">slide deck</a> and then check out the <a href="">Rubber Wiki</a>.</p> Nick Plante Reflections on *Camp 2009-11-15T00:00:00-05:00 2009-11-15T00:00:00-05:00 <p>Last weekend I attended the first-ever <a href="">New Hampshire PodCamp</a>, organized chiefly by my friend <a href="">Leslie Poston</a> along with a crew of enthusiastic volunteer co-organizers (myself included). I only made it to the second of the two days due to prior obligations but had a good time and enjoyed meeting everyone.</p> <p>If you’ve never been to a PodCamp (I hadn’t) it’s sort of like a branded <a href="">BarCamp</a> event that focuses more on how people are using technology — such as podcasting, blogging, social networks, video and music on the web — than on straight-up technical topics. I gave a presentation on <a href="">Developing Twitter Micro-Apps</a>, which I think was pretty well received.</p> <p>We talked about why building apps that leverage existing social networks can be advantageous, how you can have fun with it, and how to get going really really quick with easy-to-use Ruby tools like <a href="">Grackle</a>, Rails templates, <a href="">TwitterAuth</a> (a Rails engine), Darcy’s <a href="">BirdGrinder toolkit</a>, and my own simple <a href="">Retweet</a> / Sinatra recipes. You can <a href="">check out the slides</a> if you want to learn more.</p> <p><em>[ Note: The slides were made with <a href="">slidedown</a>. Although it’s still a little rough in places, it’s quickly becoming my favorite tool for creating slideshows in plain text. ]</em></p> <p><img src=""/></p> <p>That’s me looking pretty intense, live-coding some Twittery shit during the talk. Because, I’m hardcore like that. Unfortunately I didn’t have anyone record the live-coding portions of the presentation, in which we built a conversation aggregator as well as a simple faux-popularity reporting service. Ah well. Other attendees gave talks on topics as various as building interactive and community television outlets on the web, Facebook app development, film promotion, digital photography, and creating Firefox add-ons.</p> <p>The event itself was held at the New Hampton school in <del>the middle of nowhere</del> New Hampton, NH, which is about an hour north of Manchester. It was quite isolated but the campus was beautiful and the solitude gave people a chance to get away from everything and kept everyone in one spot, resulting in less distractions and more focus on community. Although I really enjoy urban city-center events a lot — especially when they intelligently integrate other elements of the host city into after-hours events — there’s something really nice about isolated rural events (the first New England <a href="">Railscamp</a> was another example of this)</p> <p>As someone who has never been very involved in organizing non-<a href="">virtual</a> conferences / events before, it was also interesting to observe and assist with the process of venue selection, sponsor lineup, and so on. In short: it’s a lot of work, but the payoff is great if it’s done well. Congrats and a big thank-you to Leslie (and all the other co-organizers) for putting this all together. There’s already talk of scheduling the next one for June 2010.</p> Nick Plante Notes from MIT Startup Bootcamp 2009-10-14T00:00:00-04:00 2009-10-14T00:00:00-04:00 <p>Yesterday (October 12th) I attended MIT’s <a href="">Startup Bootcamp</a>. As someone who is seriously thinking about taking some time off from his consulting lifestyle to work on bootstrapping a product, it was definitely a worthwhile event for me, and I’m glad I took good notes. I thought I’d share some of them in case you’re interested and couldn’t attend.</p> <p>(If you were there, and I got something wrong or you have something else to add, please leave a comment…)</p> <p>1. <a href="">Adam Smith</a> of <a href="">Xobni</a> .”</p> <p>2. <a href="">Alexis Ohanian</a> of <a href="">Reddit</a> .</p> <p>3. <a href="">Ken Zolot</a> of <span class="caps">MIT</span>. Ken is the founder of <a href="">MIT’s Innovations Teams</a> program. He talked briefly about what makes interesting technology the basis of a viable company or business, and how to make that transition. Ken also stressed the importance of good communication and having tangible results to show early on.</p> <p>4. Dan Theobald, <a href="">Vecna</a>..</p> <p>5. Kyle Vogt, <a href="">Justin.tv</a> ]”.</p> <p>6. <a href="">Angus Davis</a> of <a href="">Tellme</a>..</p> <p>7. <a href="">Hemant Teneja</a> of <a href="">General Catalyst Partners</a>..</p> <p>8. Dharmesh Shah, <a href="">Hubspot</a> (and author of the popular <a href="">On Startups</a>.</p> <p>9. <a href="">Robin Chase</a> of <a href="">Zipcar</a> / <a href="">GoLoco</a>.!</p> <p>10. <a href="">Dan Bricklin</a>,.</p> <p>11. <A href="">Aaron Schwartz</a> of Infogami / Reddit (a Y-Combinator company). At 14, Aaron co-authored the original <span class="caps">RSS</span>).</p> <p>12. Drew Houston, <a href="">Dropbox</a> ).</p> Nick Plante Remote Pair Programming Resources 2009-09-15T00:00:00-04:00 2009-09-15T00:00:00-04:00 <p>I usually don’t double-post or call out the articles I write for <a href=""><span class="caps">DDJ</span> Code Talk</a> too much here (links are in the sidebar), but I wanted to make sure that <a href="">this one</a> got noticed.</p> <p>I’ve had the good fortune lately to be working with a client who really appreciates the power of pair programming (something I’ve been admittedly a bit slow to embrace in my role as a freelancer). Since I’m only on-site with their team 2 days a week, I’ve been forced to learn a fair bit about what’s available for remote pairing tools.</p> <p>Here’s the short summary: <a href="">Screen</a> + <a href="">Vim</a> + <a href="">Skype</a> is a recipe for awesome. Read the <a href="">full article</a> if you want to find out about other options.</p> Nick Plante Rumble Results 2009-09-03T00:00:00-04:00 2009-09-03T00:00:00-04:00 <p>The <a href="">results</a> are in for the <a href="">2009 Rails Rumble</a>. Check em out and peep the winners. Some pretty impressive stuff for a single 48-hour sprint, right? Right!</p> <p>I’d like to personally thank all the <a href="">sponsors</a>, <a href="">expert panelists</a>, and especially the <a href="">contestants</a> that made this years contest the best one yet. We’re looking forward to using the feedback we’ve received this year to make the next one even better, and starting to seriously discuss doing some more language/framework-agnostic events too.</p> <p>But first, we need a little bit of a break :). Some downtime next weekend sure will be nice!</p> Nick Plante Rumble Build Weekend 2009-08-22T00:00:00-04:00 2009-08-22T00:00:00-04:00 <p>This weekend is <a href="">Rails Rumble Build Weekend</a>, which means that over 200 teams of 1-4 people are, at this very moment, working diligently (tirelessly!) to build the next <a href="">awesome</a> <a href="">48-hour</a> <a href="">micro-app</a>.</p> <p>This is the third year in a row we’ve run the contest and things seem to be going smoother than ever. Well, so far. Big thanks to <a href="">Darcy Laycock</a>, <a href="">Erin Shine</a>, and <a href="">Jeff Rafter</a> for being incredible co-conspirators, to all our competition <a href="">sponsors</a>, and especially to the participants who are really pouring their everything into this. I can’t wait to see how some of these ideas turn out.</p> <p><img src="" alt="Rails Rumble" style="float:right; padding: 5px 0 10px 10px"/></p> <p>In case you’re curious, we’re running the voting process a little bit differently this year, and have assembled a fine panel of <a href="">expert judges</a> to help qualify the best of the best before they go on to public voting. These people come from all corners of the web startup ecosystem and I’m really amazed that most of them were able to find the time in their busy schedules to help us out — we’re honored! So a big thanks to them, too.</p> <p>The competition wraps tomorrow (Sunday) night at midnight <span class="caps">UTC</span>, and then the expert panelists have a couple days to work their magic. Public voting should probably open on Thursday if all goes to schedule. If you’re not competing you can still <a href="">register for an account</a> and help us judge! For more information, head on over to the <a href="">competition site</a> or check out the <a href="">blog</a>. Make sure to subscribe for updates. Thanks!</p> Nick Plante Testing ActiveRecord Observers 2009-07-25T00:00:00-04:00 2009-07-25T00:00:00-04:00 <p>Need to unit test those pesky ActiveRecord observers you’re using? I don’t use em often, but there are times when they’re definitely useful. Fortunately, since <a href="">AR::Observer</a> leverages Ruby’s <a href="">Observable</a> module all you have to do is call <tt>MyModel.delete_observers</tt> in your test setup or <code>before</code> block.</p> <pre><code>ZombieSighting.delete_observers</code></pre> <p>Better yet, add the exclusions to your test or spec helper file. Then you can unit test your models comfortably in isolation, and write tests for your observers that look like this:</p> <pre><code>describe Observer before(:each) do @obs = ZombieSightingObserver.instance @thing = Factory.build(:zombie_sighting) end it 'should generate a new notification' do lambda { @obs.after_create(@thing) }.should change(Notification, :count) end end </code></pre> <p>We wouldn’t want to couple zombie sightings too tightly with notifications, after all, as that might anger them even further (zombies are known to be crazy about <a href=""><span class="caps">SRP</span></a>).</p> Nick Plante Rails Camp New England 2009-07-22T00:00:00-04:00 2009-07-22T00:00:00-04:00 <p>Last Friday, about 30 people descended on a large house in Bryant Pond, Maine for <a href="">Rails Camp</a> New England. Organizer <a href="">Pat Allan</a> has been running Rails Camp events in the UK and his home nation of Australia for quite some time, but this was the very first North American event (co-organized by Boston.rb’s own <a href="">Brian Cardarella</a>). Personally, I think it was a smashing success and I’m really glad I had the chance to be a part of it.</p> <p>Our <a href="">weekend retreat</a> basically consisted of group hacking and pair programming, lots of lively discussions, gaming, and plenty of R&R. Frisbee was played. Food was eaten. Canoes were canoed. <a href="">Urban Terror</a> was instigated. Werewolves were slain by lakeside campfire light. Alcohol was consumed. In no particular order, of course.</p> <p><img src="" alt="Rails Camp" style="float: right; margin: 0 0 10px 10px;"/></p> <p>In addition to the ever-important extra-curriculars, we had time to work on personal projects and share with others through a series of BarCamp-style sessions. These sessions included topics as diverse as Ruby Gems, <a href="">GemCutter</a>, Internationalization, <a href="">CouchDB</a>, and <a href="">RadiantCMS</a>. There were also a number of app demos and lots of peer consulting and mentoring going on. Experience levels ranged from complete beginners to seasoned professionals, but all egos were checked at the door and everyone seemed to get along like old friends. Social games and sessions really helped people get to know one another, and keeping the event small meant that by the time you left, everyone was on a first-name basis.</p> <p>I’m not sure how (cough) <strong>productive</strong> I was over the course of the weekend, but I sure had a great time, met a lot of interesting people, and learned a lot from them. If you’ve never attended anything like this I strongly encourage you to. It’s a great mix of learning and fun, and the freestyle format allows you to make of it what you want. A far better experience than any conference I’ve attended in the past year, imo, and far less costly at a mere $120 for the entire weekend, including all lodging and food.</p> <p>A big thanks to Pat and Brian for all their hard work, to <a href="">Thoughtbot</a> and <a href="">ZenDesk</a> for sponsoring, and to everyone else that showed up for being full of awesome. Hopefully we’ll do another RC New England event soon. I’m thinking that a mid-winter ski lodge excursion sounds like a damn good idea… Yeh?</p> Nick Plante TwitterAuth Integration Testing 2009-07-13T00:00:00-04:00 2009-07-13T00:00:00-04:00 <p>Michael Bleigh’s <a href="">TwitterAuth gem</a> is truly full of awesome. It’s a complete OAuth authentication and <span class="caps">API</span> access solution for building Twitter apps with Rails. It uses familiar conventions borrowed from the Restful Authentication plugin, too. If you’re building a Rails-based app and you want to allow your users to <a href="">Sign in with Twitter</a> there’s just no better way to go.</p> <p><img src="" alt="TwitterAuth" style="float:right; margin: 0 0 10px 10px;" /></p> <p>For this particular app, I’m using the dynamic duo of <a href="">Cucumber</a> and <a href="">Webrat</a> to whip up integration tests. Since I initially stumbled a little bit when thinking about how to test integrated authentication against an external source like Twitter, I thought I’d doc the solution here in case other people were having the same issue.</p> <p>Ready? Let’s do it.</p> <h3>Setup</h3> <p>First, install the TwitterAuth gem and use the provided generator to whip up the appropriate facilities. You’ll need to <a href="">register your Twitter application accounts</a> too. Or you know what? Screw it. If you want to make this super easy on yourself, Mike wrote a really great <a href="">Twitter app Rails template</a> that does all the setup for you, including walking you through getting the dev accounts. It’s nice, try it out. You’ll be up and writing Twitter apps in no time.</p> <p>For the rest of this I’m going to assume that you have all of that working, and have installed Cucumber too. Don’t have Cucumber? Install it using RubyGems and then just run <code>script/generate cucumber</code> inside your Rails app.</p> <h3>Authentication Feature</h3> <p>So let’s write a Cucumber feature to test authentication in our boilerplate Twitter template application. Put the following in <code>features/authentication.feature</code>:</p> <pre><code>Feature: Authentication In order to create and edit games As a user I want to sign in with Twitter Scenario: Login via Twitter When I go to "the homepage" And I follow "Login via Twitter" And Twitter authorizes me Then I should see "Logged in as" Scenario: Checking login status Given I am signed in When I go to "the homepage" Then I should see "Logged in as" Scenario: Log out Given I am signed in When I go to "the homepage" And I follow "Log out" Then I should see "Login via Twitter" </code></pre> <h3>Step Definitions</h3> <p>Next, you’ll need to write step definitions to satisfy the missing steps. Do that by creating a file called <code>features/step_definitions/auth_steps.rb</code>. The content of the file should define the following two steps:</p> <pre><code>Given /^I am signed in$/ do visit login_path visit oauth_callback_path end When /^Twitter authorizes me$/ do visit oauth_callback_path end </code></pre> <h3>Fake Style</h3> <p>The secret sauce here is <a href="">FakeWeb</a>. We’ll use it to fake out responses from the Twitter auth service so that your integration tests stay local (and reliable). Make sure to <code>gem install fakeweb</code>, and add the following to <code>tests/environments/cucumber.rb</code>:</p> <pre><code>config.gem "fakeweb", :version => ">= 1.2.5"</code></pre> <p>Now edit Cucumber’s <code>features/support/env.rb</code> file:</p> <pre><code>FakeWeb.allow_net_connect = false FakeWeb.register_uri(:post, '', :body => 'oauth_token=fake&oauth_token_secret=fake') FakeWeb.register_uri(:post, '', :body => 'oauth_token=fake&oauth_token_secret=fake') FakeWeb.register_uri(:get, '', :response => File.join(RAILS_ROOT, 'features', 'fixtures', 'verify_credentials.json')) </code></pre> <p>Here we’re stubbing out the interaction with Twitter auth, and responding to all outbound authorization attempts with canned data. Note that this references a fixture file, containing a sample <code>verify_credentials</code> <span class="caps">API</span> response from Twitter. You can obtain a copy using curl from the comfort of your terminal prompt (substitute your own username and password):</p> <pre><code>curl -i -u user:pass "" > verify_credentials.json</code></pre> <p>The last thing you’ll want to do is to check your <code>twitter_auth.yml</code> file and make sure there’s a <code>cucumber</code> environment defined in it. If not, you may need to add it.</p> <h3>And We’re Done</h3> <p>Alright that should do it. Go ahead and run <code>rake features</code>. Everything should be green. And green is good. If you need to write other features that are dependent on a login requirement, you can reuse the same <em>“Given I am signed in”</em> step that we created earlier.</p> <p>Thanks to <a href="">b.kocik</a>, whose original post on using FakeWeb to stub Twitter auth was 80% of the solution I needed here.</p> Nick Plante Rumble Time 2009-07-07T00:00:00-04:00 2009-07-07T00:00:00-04:00 <p>We opened registration for the <a href="">2009 Rails Rumble</a> yesterday. This is the third year in a row that we’re running the contest and it’s sure to be the best one yet. The build weekend is August 22nd-23rd but you need to register this week if you want a seat. If I were you, I’d go register now before it fills up ;-). <img src="" alt="Rails Rumble 2009" style="float: right; margin: 0 0 10px 10px;"/></p> <p>In other news, I’ll be presenting at the second <a href="">Portsmouth Pecha-Kucha Night</a> tomorrow, July 8th. I’ll actually be talking about the creative power of constraints, and describing our experiences organizing the Rumble will be a big part of that. If you’re in town, make sure to check it out. I’ve never done a p-k talk before but it sounds like it’s going to be a lot of fun.</p> Nick Plante The Way They Were Inside 2009-06-23T00:00:00-04:00 2009-06-23T00:00:00-04:00 <p>Last night we headed to Londonderry NH to view our submission to the 2009 <a href="">48 Hour Film Project</a> on the big screen alongside all the other <a href="">New Hampshire submissions</a>. In case you haven’t been following my <a href="">tumblr</a> (where I tend to post less techie things), I thought I’d double-post it here for your viewing pleasure:</p> <p>></p> <p>For those of you that don’t know, the 48HFP is a filmmaking challenge to write, shoot, and edit a short 5-7 minute film in a weekend. It was also probably the biggest single influence in our putting together the <a href="">Rails Rumble</a>, which follows a similar model but is geared towards web development and tech startup bootstrapping.</p> <p>It’d been a couple of years since I last participated in the project (when I was living in Boston, attempting to make bad sci-fi movies). This time around <a href="">John Herman</a>, our director, ran the project like a sea captain leading a battleship to war. It really demonstrated, to me, the power of having a consistent vision and the right people lined up to do the right jobs ahead of time. Although I’m a little bummed that I missed out on being part of the crew due to prior obligations this year, being on the brainstorming / writing team was a great experience, and I probably would have just gotten in the way during production anyway ;-).</p> <p>In filmmaking as with development, constraints are a powerful thing, and the 48HFP is a real showcase of this. It also demonstrates that many of the fundamentals of the <a href="">"Getting Real"</a> philosophy can be applied equally well to all sorts of art forms and mediums. IE, don’t let time limitations or overcommitted schedules stop you from showing off your bountiful awesome.</p> <p>If you’ve got a few minutes, check out <a href=""></a>, where you can watch a bunch of other 48HFP films — I think you’ll be impressed by the creativity in a lot of them, not to mention the production values they achieved under duress. Props to <a href="">John</a>, <a href="">Dan Freund</a>, <a href="">Ryan Plaisted</a>, <a href="">Bodhipaksa</a>, and everyone else who was involved. And thanks for letting me tag along.</p> <p>Winners of the NH competition will be announced at the upcoming “Best of NH” screening, and the winner of that will move on to compete in <a href="">Filmapalooza</a> at <span class="caps">NAB</span> Las Vegas 2010. Many of the other films we saw last night were pretty incredible, including entries from local filmmakers like <a href="">Marc Dole</a> and <a href="">Bill Rogers</a>, so I’m not holding my breath just yet, but it certainly would be cool. Either way, the best part of these things isn’t winning, but rather seeing what you can do, and watching other people bring their A-game too. It’s inspiring.</p> Nick Plante Serious Bizness 2009-06-01T00:00:00-04:00 2009-06-01T00:00:00-04:00 <p>I’m currently available for consulting work. I took a bit of time off for some personal projects and a much-needed spring vacation and now I’m once again ready to dive into an interesting client / startup project. Are you looking for a motivated, opinionated, yet thoughtful Ruby developer who enjoys mountain biking, foreign cinema, and long walks on the beach?</p> <ul> <li><strong>Web Development</strong>: My core expertise is end-to-end web application development for Ruby, Rails, or Sinatra projects – If you’re looking for a project lead or a team to build your next big web application, I can help. Or if you need an additional hand to augment the development speed or best practices of your existing team, I’m happy to do that too.</li> </ul> <ul> <li><strong>Code Reviews</strong>: Concerned about the quality of your codebase or maybe just looking to get an outside perspective? Reviews include analysis of your code organization and structure, test coverage and effectiveness, and overall complexity / runtime efficiency.</li> </ul> <p>In addition to the Ruby skill set, I’m also well-versed in JavaScript, Flash/ActionScript, social media tools, and the other standard systems and services that the web is built on. If you’ve read this blog and browsed my <a href=""><span class="caps">OSS</span> project contributions</a>, you already know that I’m passionate about technology, embrace web standards, and thoroughly enjoy working on innovative new ideas. I’ve also read a lot of comic books, and listen to all sorts of weird music, in case that helps.</p> <p>I can provide references and an expanded portfolio by request; a rather smallish selection of work samples is currently visible on my <a href="">freelance business micro-site</a>. If you’re interested, you can get in touch via email (nap at zerosum dot org) or contact me on <a href="">Twitter</a>.</p> Nick Plante GitHub has an Apps Platform 2009-05-14T00:00:00-04:00 2009-05-14T00:00:00-04:00 <p>After I pooped out the initial version of <a href="">rdoc.info</a> a week or two ago, <a href="">Jeff</a> and I were bullshitting about the kind of stuff we could add to it when he had a bit of an epiphany: “the place for documentation about GitHub projects is on GitHub”. Yes! Of course! Why didn’t we think of that before?</p> <p><img src="" width="232" height="208" style="float: right; padding: 5px 5px 10px 10px;"/></p> <p>So we registered the <a href="">“docs”</a> user on GitHub and went about building an extension to rdoc.info based on the GitHub pages platform. As of now, when you enter a project on rdoc.info, it’ll build docs for them locally and also generate a GitHub-themed set and push them to the docs user account pages on GitHub. In fact, you never even have to visit rdoc.info if you don’t want to (although project documentation will continue to be available there). For an example, see <a href="">Nunemaker’s HTTParty <span class="caps">API</span> Docs</a>. Make sure to play with the methods and namespaces buttons in the header.</p> <p>As far as I know, we’re the first ones to use GitHub pages as an actual “app platform”, which makes me kind of giddy. You can <a href="">read more about what we did and how we did it</a> over on Jeff’s blog. He deserves most of the credit for this one, including that awesome GitHub <span class="caps">YARD</span> theme and more than a fair bit of tricksy JavaScript goodness. Of course, GitHub deserves a lot of credit too, for building an awesome and extensible service. If you run into any issues with the docs stuff (which is still kinda experimental), please report them via the <a href="">GitHub project</a>. Thanks!</p> Nick Plante Railsconf 2009 Recap 2009-05-13T00:00:00-04:00 2009-05-13T00:00:00-04:00 <p>I’m writing this from a cramped airline seat as we jet back from Las Vegas to balmy Manchester, NH (wifi on planes is awesome — thanks Southwest). Amanda and I spent a week in Vegas during which I attended <a href="">Railsconf 2009</a> and caught a couple of pretty <a href="">incredible</a> <a href="">shows</a>. Then we road tripped it out to the Grand Canyon in Arizona and hiked in below the rim. Which was absolutely breathtaking. I wish we could have spent more time there and less in the city, to be honest.</p> <p><img src="" height="85" width="183" style="float: right; padding: 5px 5px 5px 10px"/></p> <p>Anyway, the conference itself had both its high and low points, but it was neither a total stinker nor an overwhelmingly fantastical experience this year. <a href="">Peter Cooper</a>, whom I had the pleasure of meeting there, has done a much better job than I of summarizing over at <a href="">RubyInside</a>. Friends <a href="">Ben Scofield</a> and <a href="">Nick Quaranto</a> also have some great notes at their respective sites. In fact, I’m going to steal Ben’s format for this post.</p> <p><strong>People</strong></p> <p>The best part of a conference is the people and the conversations, and the afterhours activities. Or at least, that’s been my experience thus far. This time around was no different. Greets to <a href="">bcardadella</a>, <a href="">bphogan</a>, <a href="">brupm</a>, <a href="">bryanl</a>, <a href="">bscofield</a>, <a href="">cdwarren</a>, <a href="">croaky</a>, <a href="">cwsaylor</a>, <a href="">danabrit</a>, <a href="">davidcjames</a>, <a href="">defunkt</a>, <a href="">dpickett</a>, <a href="">erebor</a>, <a href="">fowlduck</a>, <a href="">greggpollack</a>, <a href="">graysky</a>, <a href="">jamesgolick</a>, <a href="">jeffrafter</a>, <a href="">jharuska</a>, <a href="">jimweirich</a>, <a href="">joefiorini</a>, <a href="">jnunemaker</a>, <a href="">jremsikjr</a>, <a href="">keavy</a>, <a href="">knowtheory</a>, <a href="">lazyatom</a>, <a href="">linoj</a>, <a href="">mbleigh</a>, <a href="">mojombo</a>, <a href="">patmaddox</a>, <a href="">peterc</a>, <a href="">qrush</a>, <a href="">rbates</a>, <a href="">reinh</a>, <a href="">robertdempsey</a>, <a href="">seanhussey</a>, <a href="">skizzles</a>, <a href="">solaredge</a>, <a href="">techpickles</a>, <a href="">wifelette</a>, <a href="">wycats</a>, <a href="">zachinglis</a> and anyone else whom I might have forgotten to add to the list (sorry!). Thanks guys.</p> <p><strong>Sessions</strong></p> <p>The sessions this year were spotty, but generally I think the content was better than the previous Railsconf. I mistakingly sat through too many introductory talks and many others reported the same; everyone could benefit from session experience level labels. It’s weird that the organizers don’t do this, since they ask speakers about the experience level of their talks as part of the proposal process.</p> <p>In any case, a number of the talks I saw this year stood out as being particularly great:</p> <ul> <li>Jason Rudolph and Larry Karnowski on <a href="">JavaScript integration testing</a> (using the BlueRidge project)</li> <li>Bryan Helmkamp’s <a href="">Webrat</a> talk</li> <li>Michael Bleigh’s <a href="">Twitter app development</a> session</li> <li>Blythe Dunham on her experiences <a href="">integrating <span class="caps">SMS</span> support</a> into Rails apps</li> </ul> <p>There were a lot of talks this year about testing, cache control / optimization, and Rack / Rails Metal. As well as some useful Rails 3 speculation and discussion. All good stuff.</p> <p>Interestingly, I really didn’t care for many of the (very rough) ideas expressed in Yehuda’s <a href="">mountable Rails apps</a> (Rails 3) session — in particular I really had no clue why they kept comparing Rails (a framework) to Drupal (a <span class="caps">CMS</span>). But, that said, the talk did do a great job stimulating discussion about alternative approaches in “CabooseConf” — apparently just a small room with, uh, tables and stuff — between myself, Bryan, Josh, Ted and others. For this reason it definitely belongs in my favorite sessions list.</p> <p>[mountable app slices] are a challenging problem, and there are a lot of issues in terms of sharing application state, resolving cross-app dependencies, and so on. I hope that we’ll have an elegant solution to this soon; but I suspect that the real answer may be in making component-sized micro-apps easier to mount and integrate rather than taking an “app slices” or engines approach (if the latter case prevails, the Radiant extensions system has some stuff we can learn from).</p> <p>The keynotes were mixed also</p> <ul> <li>The opening <span class="caps">DHH</span> keynote teased us with some interesting Rails 3 info but also repeated a lot of mantras we’d heard before with the usual rallying cries</li> <li>The “fireside chat” with Tim Ferriss was a bit of a disaster; although I think there were at least a few interesting nuggets in there somewhere</li> <li>Chris Wanstrath’s “how to be a famous Rails developer” essay was a definite highlight; well written and thought-provoking, it should be a wakeup call to those people in the community who put personal ego before productivity and creativity</li> <li>Uncle Bob was full of energy and was no doubt entertaining, but to be honest, the content was blah to say the least. More repetition of the same rah-rah we’ve had drilled into our heads for eons, without anything new. A little disappointed but almost everyone else seemed to love it</li> <li>The closing Rails core panel… to be honest, I skipped it. I hear it went well, though</li> </ul> <p><strong>The Rails Rumble Panel</strong></p> <p>Speaking of panels, I think our own <a href="">Rails Rumble / productivity panel</a> went fairly well, although it was missing much of the energy present in our pre-panel planning conversations, which was really a shame. It’s doing decent in the ratings but not stellar, hovering around a 3/5. As Ben (one of our panelists) notes on his own blog, the panel format can be a difficult one to get a lot out of, and I definitely felt this myself sitting through other panels last week. However, I think the Rumble panelists did a damn good job discussing the merits of innovation competitions and relaying advice about finding teammates / cofounders, translating their entries into marketable web properties, and noting the tips, tools, and techniques that helped them excel in a severely constrained timeframe.</p> <p><strong>Overall</strong></p> <p>I had a good time, and visiting Vegas for the first time was certainly an interesting experience. I’m glad I went, and happy that we had a chance to participate. It was awesome to see (almost) everyone from the community in the flesh again, especially folks like Jeff and Ben, whom I’ve been working on side projects with on and off. It’s amazing how much easier it is to hash out ideas in person that it is over chat or phone conversations sometimes.</p> <p>Will I go again next year? I don’t know. If it’s in Vegas, probably not. As much as I enjoyed seeing the sites, frankly I felt that it was a bit distracting. If the conference <strong>is</strong> in Vegas again next year, I certainly hope the organizers hold it somewhere other than the Hilton. Although it was easily accessible by monorail it’s relatively removed from the rest of the strip, and the in-venue food and entertainment options there are limited to say the least. If I’m going to be distracted, I at least want those distractions to be convenient! At least a drunk <a href="">Billy Mays</a> was there (at the Hilton, attending another convention). Maybe next year we can get him to show us how to pitch our apps to consumers during a keynote? Maybe?</p> Nick Plante Vegas Next Week 2009-05-01T00:00:00-04:00 2009-05-01T00:00:00-04:00 <p>So yeah, I’m headed off to Vegas this weekend for <a href="">Railsconf 2009</a>. It’ll be my first evar visit to that area of the country, and although it wouldn’t have been my first choice for a conference location, I’m really looking forward to it (also looking forward to a side trip to the grand canyon after the conference wraps).</p> <p>I hope to see some of you there and I know that everybody says this, but if you see me in the hallways, definitely come say hi and introduce yourself. To be honest, I often feel a bit overwhelmed at conferences and the things I remember most are the people that I meet and the discussions that we have in the hallways, during hack sessions, or over dinner and beers.</p> <p>While you’re there don’t forget to check out our <a href="">panel presentation for the Rails Rumble</a> on Wednesday at 4:25. If you’re going to be attending and want to record the presentation for us, please get in touch with me. You would be my personal hero. I’m looking forward to a couple sessions in particular and I’ll likely also be attending the <a href="">community organizers BoF</a>, as a way to make up for the fact that I’m missing out on the <a href="">NE User Group Leader Summit</a> tomorrow.</p> <p>We’ll be staying at the Sahara during the conference and I’ll probably be checking in occasionally on <a href="">BrightKite</a> if you want to stalk me.</p> Nick Plante Rdoc.info 2009-04-29T00:00:00-04:00 2009-04-29T00:00:00-04:00 <p>For the past few months I’ve been trying to roll out a 1 or 2-day micro-app every month. Because, why not — it’s fun and refreshing. In February there was <a href="">tweetdreams</a>, March was <a href="">Mogo</a> madness (in use at <a href="">offrails.org</a>), and in April we spent a few days tossing <a href="">this</a> together.</p> <p><img src="" alt="cthulhu approved" style="float:right; padding-left: 10px;"/></p> <p>The <em>this</em> that I refer to in the previous paragraph is <a href="">Rdoc.info</a>, a simple web service that generates documentation for Ruby libraries that are hosted on GitHub. You can <a href="">add a new project</a> and it’ll clone the repo from the hub of Git, use <a href=""><span class="caps">YARD</span></a> to generate rdocs, and then host them for you. So you can read them. Online. Because it loves you.</p> <p>If you’re the project owner, it’s even better; just add the following simple post-commit hook to your project’s settings in GitHub <tt></tt> and it’ll automatically regenerate documentation for you whenever you push to the remote. So yeah, unlike a random Twitter vanity application, it’s like, actually useful and stuff.</p> <p>I’ve shown this to a few friends and they’ve had some good suggestions for how to make it more useful. <a href="">Jeff</a>, in particular, had some really great ideas that we’ve been looking into (more on that later, hopefully). Anyway, I’ve doc’d feature ideas in the project’s <a href="">GitHub Issues list</a>, and although we plan to get to them sooner or later, I wanted to release it first as-is, in the spirit of “release early, release often”. If you want to help out, the project has been <a href="">open-sourced</a> in the usual place.</p> Nick Plante Rumble Panel Needs Your Help! 2009-04-22T00:00:00-04:00 2009-04-22T00:00:00-04:00 <p><a href="">Railsconf</a> is less than two weeks away. I’m pretty excited because this year we’re doing a Rails Rumble panel with a bunch of swell people who developed some pretty amazing things within the compressed event timeframe (48 hours). Winners and other innovators from both the 2007 and 2008 events will be present. The session is called <a href="">“Starting Up Fast: Lessons from the Rails Rumble”</a> and the point of it is that these guys will be sharing the tips and tricks that let them build great stuff quick with Rails. Hopefully their advice will be applicable to your own startups and hobby projects, in “real life” as well as within the innovation competition atmosphere.</p> <p <a href="">Google Moderator</a>. The event will be recorded and made available afterwards, so you won’t have to be in attendance to get your answers.</p> Nick Plante Why Namespaces Are Important 2009-04-17T00:00:00-04:00 2009-04-17T00:00:00-04:00 <p>Apparently both <a href="">Extlib</a> and the <a href="">Mash</a> library, which the latest version of the <a href="">Twitter</a> gem relies on, both define <tt>Mash</tt> as a top-level class. This is lame.</p> <p>It means that if you're building an app that uses the Twitter gem to poll their API, you can't use DataMapper (which relies on Extlib) for your ORM. This is but one example of an affected application, of course (<a href="">retweet stack trace</a>). Integrity's twitter notification support is another victim. <a href="">Epic namespacing fail</a>.</p> <p>So whose fault is this? The Mash library? Extlib? Which came first? Which is more widely used? OMFG fight!</p> <p>Seriously, who cares? If you're asking yourself these questions you're missing the point.</p> <pre><code>module Org module Zerosum module Util class CollisionPrevention def initialize puts "gtfo" end end end end end </code></pre> <p>Java users, and consumers of other modern programming languages, figured out why namespacing was important a long time ago. In fact, one of the few things I actually liked from the Java world was it's use of hierarchal <a href="">domain names in packages</a>; <a href="">Modules</a> provide a really easy way to accomplish this. So why aren't we taking advantage of it in our libraries?</p> <p <tt>A::B::C</tt> (or <tt>Tld::Domain::Feature::Specification</tt>).</p> <p>Thanks for listening! :)</p> Nick Plante Getting Started with CouchDB 2009-04-06T00:00:00-04:00 2009-04-06T00:00:00-04:00 <p>I’m a little late to the party on this one, but <a href="">CouchDB</a> sure is the new hotness. We’ve been tossing around an idea for a new project and it’s a great fit for so many reasons. Schema-less? Check. Distributed and fault-tolerant? Yup. Document revision-aware? <em>and</em> it speaks <span class="caps">JSON</span> natively via a RESTful <span class="caps">API</span>? Oh yes. It’s easy to see why so many people are getting excited about it.</p> <p>If you’re used to working with relational databases, it definitely requires a bit of mental reprogramming to really grok Couch, particularly when it comes to working with <a href="">views</a> and designing <a href="">document relationships</a> without traditional joins, etc etc. It’s powerful stuff, and after working with it just a little bit, I’m pretty enthusiastic, but still feel like I’ve got a ton to learn.</p> <p><img src="" alt="CouchDB" style="float: right; margin: 10px 0 0 10px;" /></p> <p>Anyway, in terms of Ruby client interfaces… there are a surprisingly large number of options that’ll make your life easier. Candidates include <a href="">ActiveCouch</a>, <a href="">CouchFu</a>, and <a href="">RelaxDB</a>. There’s also a <a href="">DataMapper adapter</a>. My personal pick would have to be jchris’s <a href="">CouchRest</a> library though. The core of it is very simple, modeled around Couch’s own couch.js library. Plus, the ExtendedDocument model stuff gives you most of what you’d want from a traditional <span class="caps">ORM</span> through properties, callbacks, validation mixins (lifted from DataMapper), in-line views (think of them as finder/scopes on steroids), attachments, and so on.</p> <p>Before diving in too deep I figured I’d port a simple project over to Couch in order to familiarize myself with it. So I created a <a href="">branch of the Retweet project</a> that uses CouchRest instead of DataMapper. Check it out if you want to see how the CouchRest::ExtendedDocument stuff works in a simple project — only one model in this case. It’s quite nice. There’s also a <a href="">CouchDB branch of sinatra-template</a>, if you wanna use that to bootstrap your own ideas.</p> <p>Btw, if you’re on a Mac, and using MacPorts, make sure to port selfupdate to the latest and greatest and then port install couchdb-devel to fetch CouchDB 0.9.0. Anything older than that won’t work with CouchRest.</p> Nick Plante New Biz Cards 2009-04-03T00:00:00-04:00 2009-04-03T00:00:00-04:00 <div> <p><img src="" width="210" height="360" style="float: left; padding-right: 10px;"/><img src="" width="210" height="360" /></p> </div> <p>So what do you think?</p> <p>Btw, it’s true about the sci-fi gadgets — they’re made to order :). I’m also available to build web applications, of course. Probably a better investment.</p> <p>And yes, the <a href="">Nth Metal</a> (consulting business) site needs a bit of a makeover. All in due time.</p> Nick Plante Hello Mogo 2009-04-01T00:00:00-04:00 2009-04-01T00:00:00-04:00 <p><em style="font-size: 1.15em; color: #666;">“In brightest day, in blackest night, no feed shall escape my sight!”</em></p> <div style="float: right;"><img src="" alt="mogo" style="margin: 0 0 10px 10px;"/></div> <p><a href="">MogoFeed</a> is a small planet-style feed aggregator built on top of <a href="">Sinatra</a>, leveraging <a href="">DataMapper</a> and Paul Dix’s supa-fast <a href="">Feedzirra</a> library for the actual feed processing. It also teams up nicely with [the all-knowing, all-powerful] <a href="">Sphinx</a>, making feed search a breeze. There’s a working example of Mogo in action installed <a href="">here</a>.</p> <p>Source is <a href="">available on GitHub</a> so feel free to fork away if you’re in need of such a thing. Patches and pull requests happily accepted.</p> Nick Plante Sinatra Isn't Pushy 2009-03-22T00:00:00-04:00 2009-03-22T00:00:00-04:00 <p>I gave a hands-on introductory talk about <a href="">Sinatra</a> at last weeks <a href="">NH.rb</a> meetup. In case anyone is interested, I’m also embedding the slides below. Looks like scribd butchered them a little bit, but you can always download the original set in <span class="caps">PPT</span> format or whatever too (follow the link).</p> <p>As you might expect, my presentation includes a number of borderline awful puns. Probably not as bad as the puns in a typical Git presentation, but still. You have been warned.</p> <p><a title="View A Quick Introduction to Sinatra (NH Ruby);">A Quick Introduction to Sinatra (NH Ruby)</a> <object codebase="" id="doc_217527207806484" name="doc_217527207806484" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" align="middle" height="500" width="100%" rel="media:presentation"17527207806484_object" menu="true" allowfullscreen="true" allowscriptaccess="always" salign="" type="application/x-shockwave-flash" align="middle" height="500" width="100%"></embed> <span rel="media:thumbnail" href=""> <span property="media:title">A Quick Introduction to Sinatra (NH Ruby)</span> <span property="dc:creator">zapnap</span> <span property="dc:type" content="Text"> </object></p> <p>A <a href="">full meetup report</a> is available as well. You can find the <a href="">full source</a> for the sample door prize chooser app that we live-coded during the presentation via GitHub.</p> Nick Plante Design Refresh 2009-03-21T00:00:00-04:00 2009-03-21T00:00:00-04:00 <p>It was about time, I guess. This blog had been in need of a facelift for many many moons. Anyway, let me know what you think. It’s rocking a tweaked-out version of the classic cutline theme that <a href="">I ported to Mephisto/Liquid</a> with some supernatural green custom goodness. The banner image is a photo of some awesome graffiti I found in a bathroom in a Burlington VT bar last October. I know how that guy feels.</p> <p>I also pooped out a tiny personal microsite earlier this week, which you can find over at <a href="">nickplante.info</a> if you’d like to stalk me further. Eye-burning green highlights ftw.</p> Nick Plante Rumble Panel At Railsconf 2009-03-01T00:00:00-05:00 2009-03-01T00:00:00-05:00 <p>I’m happy to report that our panel, <a href="">Starting Up Fast: Lessons from the Rails Rumble</a>, has been accepted for the 4th annual <a href="">Railsconf</a> event in Las Vegas.</p> <p><a href=""><br /> <img src="" width="125" height="125" border="0" alt="RailsConf 2009" title="RailsConf 2009" style="float:left; padding-right: 10px;" /><br /> </a></p> <p>I’ll be moderating a panel of competition winners and participants, and we’ll be discussing how they were able to achieve some impressive feats in the compressed contest timeframe. It should be packed full of useful real-world advice on how to organize and launch Rails applications quickly. We’ll also talk about the event itself, and the nature of innovation competitions in general (and why you should get involved!) I guarantee that it will be fun, but I can make no guarantee about whether or not there will be choreographed mock-fighting. That’s up to you.</p> <p>Panelists include our friends <a href="">Joe Fiorini</a> (grand prize winner 2008), <a href="">Josh Owens</a> (grand prizer winner 2007, design award 2008), <a href="">Ben Scofield</a> (winner, solo division for both 2007 and 2008), <a href="">James Golick</a> (winner, most useful 2008), and <a href="">Darcy Laycock</a>, who participated in the 2007 contest and joined the organizational team for the 2008 event.</p> <p>So if you’re making the voyage to the City of Sin in May, make sure to check us out. I’m excited, and it’ll be great to meet many of you there! Also, you can teach me how to gamble. I hear that I have a pretty bad tell. Whatever that is.</p> <p><strong><span class="caps">UPDATE</span> 3/16:</strong> The panel is scheduled for May 6th from 4:25pm to 5:15pm <span class="caps">PDT</span> in Pavilion 9 – 10</p> Nick Plante Micro App: Tweet Dreams 2009-02-04T00:00:00-05:00 2009-02-04T00:00:00-05:00 <p>I was feeling kind of <i>meh</i> last week, so I decided I’d take a day off from the paid projects and hack out an ‘app-in-a-day’ microapp. If you know me, you know that this is something I talk about doing all the time and publicly advocate, but rarely find the time to actually execute on ;-). I’d really like to change that, and devote more time to my own projects this year.</p> <p>Of course, the hardest part about doing this sort of thing is coming up with a concept that can be created and deployed within the timeframe you have available. For the <a href="">Rumble</a>, we gave teams of 4 people 2 full days, and lots of prep time. But in this case I wanted to see what I could do with a designer in, say, an afternoon, without any advance planning at all. Just for fun. So I chatted up my designer friend <a href="">Ty</a> and we came up with the concept of a really simple <a href="">Twitter</a>-based dream journal, that would display random tweets that had to do with what people were dreaming about. Nothing fancy, sort of a rip off of <a href="">OhMyScience</a> but without the science. Because who needs science, right?</p> <p>Ty whipped up a fun single page <a href="">Goodnight-Moon-inspired</a> design and I wrote a tiny amount of code to morph my <a href="">Sinatra app template</a> into a Twitter keyword aggregator, and about 3 hours later <a href="">tweetdreams.org</a> was ready to go. It may not be the most innovative or featureful website you’ve seen this week, but it’s cute and was fun to build and a few people have said some nice things about it. Frankly, that’s enough for me.</p> <p><img src="/assets/2009/2/3/tweetdreams.jpg" alt="Tweet Dreams"/></p> <p>The moral of the story is that you don’t have to do something earth-shattering, massive, or insanely innovative to enjoy doing it. If you’re feeling kind of down or like your current work projects are <a href="">neverenders</a>, block out a day and bang out a microapp. Just shipping something will often make you feel better about yourself, regardless of the complexity involved. Don’t be afraid to call it ‘v1.0’ and move on to the next one. On the web, nothing is every finished. And that’s a good thing.</p> <p>So yeah, <a href="">check it out</a> if you’re interested. <a href="">The sub-100 lines of source</a>, sans Ty’s awesome theme, is also up on teh GitHubs if you wanna make your own Twitter-fueled microapp.</p> Nick Plante The Way You Wear Your Hat 2009-01-23T00:00:00-05:00 2009-01-23T00:00:00-05:00 <p>So the <a href="">Sinatra</a> guys just kicked out v0.9. Classy and well-dressed, as always. If you haven’t played around with Sinatra before, you should really give it a look. It’s often everything I need for building lightweight micro-apps. Very <a href="">easy to learn</a> and use, too.</p> <p>Of course, Sinatra is intentionally quite small and doesn’t dictate what testing framework, <span class="caps">ORM</span>, or templating language you use. Having choices is great, but using a common set of tools with Sinatra can also cut down on initial configuration time and make it even more appealing for quick tasks.</p> <p>Personally I’ve found that my own ideal application template consists of <a href="">RSpec</a>, <a href="">Haml</a>, <a href="">DataMapper</a>, and a few bits of well-placed glue. If you want to give Sinatra a spin, and just want some sensible defaults baked-in from the get-go, check out the <a href="">application template</a> that I pushed to GitHub earlier today. It should help get you up and running fast. And it might make pancakes for you too (but probably not).</p> <p>Just <a href="">fork the repository</a>, rename it, and start writing specs and code. When you’re done, use the included Rackup script to deploy it via Passenger. Couldn’t be easier. If you have any criticisms, suggestions, or improvements, let me know. Or hey, just send a pull request.</p> <p>Thanks to Ryan Tomayko, Blake Mizerany, and the rest of the Sinatra team for creating such a fun (and truly minimalist) web framework.</p> Nick Plante New Radiant Extensions 2009-01-13T00:00:00-05:00 2009-01-13T00:00:00-05:00 <p>We launched a new <a href="">Radiant</a>-based site for a client last month. It was a small project but involved the creation of a couple new extensions, so I thought I’d take the opportunity to <span class="caps">OSS</span> them. In case anyone is interested…</p> <ul> <li><a href="">Flash Gallery Extension</a> — An extension that works with Todd Dominey’s excellent <a href="">SlideShowPro</a> (<span class="caps">SSP</span>) Flash component to easily create elegant Flash-based media galleries within Radiant (Note that <span class="caps">SSP</span> is a commercial product; however a trial version is available suitable for testing this extension).</li> <li><a href="">Upcoming Events Extension</a> — An uber-simple extension that allows creation and management of important dates within a Radiant <span class="caps">CMS</span> instance.</li> </ul> <p>That is all.</p> Nick Plante NHRuby & the Importance of User Groups 2008-12-27T00:00:00-05:00 2008-12-27T00:00:00-05:00 <p>There are some changes in store for <a href="">NHRuby</a> in 2009. Group founder <a href="">Scott Garman</a> is headed out to the west coast and is therefore stepping down as coordinator, and I’ll be stepping in to fill the void. Over the past 2 years Scott has done a great job getting things started and lining up interesting content. I hope we can keep the momentum going in his absence!</p> <p>Meetings will continue to be held at <span class="caps">RMC</span> Research in Portsmouth (<a href="">directions</a>), but the dates will shift slightly; from this point forward we’ll be meeting on the <strong>third Thursday</strong> of the month. We’ve also set up <a href="">new mailing lists</a> and a <a href="">new website</a> to document group activities and associated shenanigans. I’ll be migrating more archival material over from the wiki shortly.</p> <p>The 2009 event calendar kicks off to a great start with a talk by <a href="">Jon Linowes</a> on January 15th. He’ll be speaking about <a href="">ReviewRamp</a>, his Rails-based startup, <a href="">Cucumber</a> integration testing, and his own DynamicRecord framework. If you’re in the southern Maine, New Hampshire, or northern Massachusetts area I really encourage you to come out and hang with us. We’re a small, friendly group, and new people of all skill levels are always welcome.</p> <p>Never been to your local user group? You’re really missing out. Attending them is a great way to learn firsthand about new ideas and technologies from passionate people who actually give a shit. It’s also a great way to network and <a href="">find other folks to bounce ideas off of or work on projects with you</a>. The Internet is a great place to meet people too, of course, but there’s just something special about meeting someone in person, being able to pop your hand up in the middle of a talk to get clarification, or grabbing a beer or two after an inspiring discussion. Also, it’s easier to tell if they’re trying to manipulate you into sending them money. If you haven’t yet attended your local user group(s), make it part of your new years resolution to change that.</p> <p>And if your area doesn’t have a user group? Then start one. You might be surprised at who shows up.</p> Nick Plante Merb 2 == Rails 3 2008-12-23T00:00:00-05:00 2008-12-23T00:00:00-05:00 <p>Wow. Well, <a href="">this</a> is… somewhat <a href="">unexpected</a>. And <a href="">very</a>, <a href="">very</a> <a href="">cool</a>.</p> <p><img src="/assets/2008/12/23/merbrails.jpg"/></p> <p>No kidding, right? Personally, I’m excited. I think the Merb 2 / Rails 3 announcement makes a ton of sense (read the links above for details); Rails with a modular Merb-like architecture and a set of reasonable Rails-ish defaults is an epic win for both camps, if done right. It’s truly an exciting time to be a Ruby developer. Happy holidays everyone.</p> Nick Plante Why I Love Vim 2008-12-07T00:00:00-05:00 2008-12-07T00:00:00-05:00 <p>Back when I was a Java developer, I knew and really liked me some <a href="">IntelliJ</a>. Later, when I moved over to Ruby full time, <a href="">NetBeans</a> seemed like a damn good choice. After all, I was used to having a “proper” <span class="caps">IDE</span>, it had pretty nice Ruby support and also, much to my joy, it had a <a href="">Vim plugin</a>, which allowed me to use my favorite editor from my pre-IntelliJ days. Win.</p> <p>Fast forward to about six months ago when I decided that I’d ceased to care about heavyweight IDEs. I just didn’t use enough of their features to make their overall (often cumbersome) weight and memory footprint worthwhile. So goodbye NetBeans with Vim plugin and hello Vim. <a href="">MacVim</a>, specifically.</p> <p>Why Vim? Because Vim is universal. Because Vim is love.</p> <p>Dave Thomas and Andy Hunt famously wrote <i>“Choose an editor, know it thoroughly, and use it for all editing tasks”</i> in their seminal masterpiece, <a href="">The Pragmatic Programmer</a>. I couldn’t agree more. There is no tool in a programmer’s toolbox more important than an editor, and the importance of knowing it inside and out cannot be understated. For me, ever since college, that editor has always been Vim. It was just everywhere that I needed it to be. It was ubiquitous. I could use Vim at home on my desktop, at school, at work in the campus <span class="caps">NOC</span>, at the CS lab, and in any number of remote shell sessions, on even the most obscure platforms. One ring to rule them all.</p> <p>Vim is also small, and quick. Once you know what you’re doing, it’s quicker and easier to manipulate text in Vim than any other editor that I’m aware of. Of course, the learning curve is steep, relative to other editors. But it’s worth it. When I’m writing code, switching between files, replacing text, et al, I don’t want to have to use the mouse too frequently. Vim, in all of it’s keyboard-centric glory, delivers. MacVim also provides awesome mouse highlighting and menu option support, for the best of both worlds.</p> <p>There’s also massive value in Vim’s powerful plugins system. Without some of these awesome third party extensions folks have developed for Vim, it wouldn’t be nearly as appealing as a desktop code editor. But by adding plugins like <a href="">NERDTree</a>, <a href="">rails.vim</a>, <a href="">vcscommand.vim</a>, and <a href="">FuzzyFinder</a>, it becomes a full-fledged programmers editor for me, something that easily outguns TextMate, NetBeans, Komodo, and all the other would-be competitors. Customize it to your hearts content.</p> <p>Anyway, I just wanted to put that out there. Vim rules. And <a href="">Tim Pope</a>, author of rails.vim, rules too (even though he looks awful in drag). His plugin, along with NERDTree, vastly simplifies my day to day editing tasks, and reproduces all the functionality I would have actually used from a more fully-featured <span class="caps">IDE</span>. Thanks guys. You’re my heroes.</p> <p>For more information on using Vim as a Ruby developer, see <a href="">Jamis Buck’s</a> post from a few months back about switching back to Vim from TextMate. It’s a well-written argument, but the really amazing thing about the article is the number of comments it generated. It’s great to see so much love for such a great editor and I’m glad to be in such good company.</p> <p>So, what’s your favorite go-to editor? If it’s Vim, I’d be curious to know what plugins you’re using and how you’ve customized it.</p> <p><i>PS If you’re also a MacVim user, make sure you install the <a href="">:Bclose</a> script too!</i></p> Nick Plante Demystifying Rails Plugin Development 2008-11-18T00:00:00-05:00 2008-11-18T00:00:00-05:00 <p>My slides from the <a href="">Voices that Matter</a> (Pro Ruby 2008) conference…</p> <p><a title="View Demystifying Rails Plugin Development;">Demystifying Rails Plugin Development</a> <object codebase="" id="doc_880515275864122" name="doc_88051527586480515275864122_object" menu="true" allowfullscreen="true" allowscriptaccess="always" salign="" type="application/x-shockwave-flash" align="middle" height="500" width="100%"></embed> </object></p> <p>Thanks to everyone who attended and of course to the organizers for putting together a great conference.</p> Nick Plante Vote Or Die 2008-10-26T00:00:00-04:00 2008-10-26T00:00:00-04:00 <p>OK, I’m being a bit overly dramatic. But seriously, go <a href="">sign up</a> to judge and vote in the <a href="">2008 Rails Rumble</a>. Help us decide which of the amazing web applications featured on our <a href="">leaderboard</a> deserves to take home the goods. Oh, and tell your friends. The more opinions the better.</p> <p>If you need extra motivation, we’re giving away a number of Amazon gift certificates to random voters. There’s still time, but hurry up; voting ends November 1st.</p> <p>While we’re on the subject, there’s also another <a href="">important election</a> coming up too ;-). I’m not going to pretend to tell you who to vote for, but (if you’re a US citizen) just make sure you understand the issues at stake and vote responsibly. Thanks!</p> Nick Plante OpenID, Simplified 2008-10-11T00:00:00-04:00 2008-10-11T00:00:00-04:00 <p>The build portion of the <a href="">Rails Rumble</a> is next weekend. Wow, time really flies, eh? It seems like it’s only been a few weeks since we announced it. We filled all 200 seats this year and even had to open up a few more. I’m really amped, and am looking forward to seeing some truly amazing microapps come out of this weekend sprint. I think they’re going to be even better than last years’. I hope you’ll help prove me right.</p> <p>Anyway, I posted earlier today over on the <a href="">Rumble blog</a> about our decision to mandate <a href="">OpenID</a> usage in the registration (and voting) app and <a href="">JanRain</a>‘s involvement in the Rumble as a sponsor. We’re using their new <a href=""><span class="caps">OPX</span> <span class="caps">ASP</span> service</a> to provide branded railsrumble.com OpenIDs to users who don’t have them. It’s pretty great. We really didn’t want to run our own provider and then be saddled with the upkeep of it. It makes much more sense to delegate that to a third party who is an expert in that realm.</p> <p>Personally I think OpenID is, for the most part, pretty swank. Yes, it has its flaws. And maybe it isn’t a proper fit for <strong>every</strong> application. But for an event of this sort, a decentralized identity / login system is absolutely critical. It would be silly to force users to create dozens of different accounts (all with different login names, password criteria, etc) just to evaluate new applications.</p> <p>I’m both excited and relieved that providing OpenID registration services is becoming easier and easier. It’s really about time and SaaS OpenID facilities makes a ton of sense for sites, like us, that want the benefits of providing OpenID without the hassle of operating and maintaining it long-term.</p> <p>I expect a lot of competitors this year to use Jim Neath’s <a href="">Bort</a> or a similar blank slate Rails application to bootstrap their development. This is a good thing and it doesn’t void the rules in any shape or form as long as the kit is just bundling plugins and not providing major application functionality in and of itself (like Radiant or Spree does). One of the best things about Bort is that it supports OpenID right out of the box, in addition to stock Restful Authentication style user accounts. Epic win for you. And your users.</p> <p>If you aren’t using Bort or something similar, you may want to check out our <a href="">OpenID Simplified plugin</a>, which was extracted from the Rumble voting app itself. It’s a combination of the classic OpenID Authentication plugin with some bits from Restful Auth, and a few extras to make adding OpenID-based user accounts to your application dead simple. What it doesn’t do, however, is provide non-OpenID-enabled account creation.</p> <p>“Wait, what? You can’t create accounts with it?,” you ask, “What were you thinking?”</p> <p>First of all, yes, you’re right. OpenID isn’t ubiquitous yet. And maybe it never will be. But it’s certainly better (at least imo) than creating yet another user account with yet another set of credentials (or worse yet, the same set). Options like the free <a href="">MyOpenID affiliate program</a> and JanRain’s branded <span class="caps">OPX</span> service make it just as easy to have users proxy-register with them as it is to create a one-off local user account. By signing up with one of these services you can provide your own logo and copy and have the logged-in user directed back to your site, once they complete the signup process.</p> <p>Also, by integrating the <a href="">ID Selector</a> widget, many of your users even realize that they actually already have an OpenID account – via Flickr, Blogger, Wordpress, etc – and therefore bypass this unnecessary registration situation altogether.</p> <p>My point is that, although it may not yet be perfect, we’re getting to the point with OpenID services where adding support for them is almost as straightforward as implementing our own local accounts system. Many of your users will already have an OpenID account. Sometimes they just need to be made aware of it. For those who don’t, it’s becoming easier and easier to allow them to create an account that they can use anywhere, without placing the burden for maintenance of that on yourself.</p> Nick Plante Testing Workling with RSpec 2008-10-04T00:00:00-04:00 2008-10-04T00:00:00-04:00 <p><a href="">Workling</a> is my current sauce of choice for interfacing with message queues and performing asynchronous background tasks in Rails apps. We’re using it in production in a couple of places (with <a href="">Starling</a>) and it works great. In fact, we liked it so much that we wrote about it in <a href="">Practical Rails Plugins</a>.</p> <p>Anyway, one thing we didn’t discuss there was how to test your workers. I’m an <a href="">RSpec</a> junkie, and I want to make sure that my Workers are behaving the way that I expect at all times. The solution is pretty simple. I modified a code snippet written a while back by <a href="">David Altenburg</a> to spec his BackgroundRB workers…</p> <p>Just add the following to your <code>spec/spec_helper.rb</code>:</p> <pre><code>module Workling class Base class RailsBase def self.register; end end end end</code> <code>worker_path = File.dirname(__FILE__) + "/../app/workers" spec_files = Dir.entries(worker_path).select {|x| /\.rb\z/ =~ x} spec_files -= [ File.basename(__FILE__) ] spec_files.each { |path| require(File.join(worker_path, path)) }</code></pre> <p>Now you can add specs for your workers to <code>spec/workers/my_worker_spec.rb</code>:</p> <pre><code>require File.dirname(__FILE__) + '/../spec_helper'</code> <code>describe MyWorker do it "should manufacture a new widget at the happy castle widget foundry" do Widget.should_receive(:find).with(1).and_return(@widget = mock_model(Widget)) @widget.should_receive(:manufacture) MyWorker.asynch_manufacture_widget(:widget_id => 1) end end </code></pre> Nick Plante Register for the Rails Rumble! 2008-09-29T00:00:00-04:00 2008-09-29T00:00:00-04:00 <p>Registration for the 2008 Rails Rumble opened last Friday. If you haven’t already registered and want to compete, <a href="">you better hurry up</a>. There are only 25 seats remaining (out of a maximum of 200!) at the time of this writing. I’m guessing those will be gone very, very soon.</p> <p><img src="" style="float:right; padding: 0 10px 10px 10px" /></p> <p>We’ve been working hard to make this years competition even better than last year and I think everyone is going to have a lot of fun. In addition to all the great prizes that sponsors are putting on the table, and the insane amount of community goodwill surrounding the event, there are also a number of companies running <a href="">workshare programs</a>. If you’re a fan of the <a href="">coworking</a> concept you may want to check these out. I know I’m wishing there was one in my town.</p> <p>On the other hand, if you’re geographically isolated from the rest of the Ruby world, don’t despair! It’s a virtual competition and you can compete from anywhere. Look at it as a great opportunity to assemble a distributed team of entrepreneurially-minded developers and designers and see how well you can work with each other. If you’re looking for people or ideas, make sure to check out the #railsrumble channel on the Freenode <span class="caps">IRC</span> network or post to <a href="">the blog</a>.</p> Nick Plante Upcoming Speaking Gigs 2008-09-15T00:00:00-04:00 2008-09-15T00:00:00-04:00 <p>I’ve firmed up a few speaking gigs for the next couple months. And I wanted to share.</p> <p>First of all, tomorrow night, September 16th, I’ll be presenting a “casual intro” to every-day <a href="">Git</a> usage at <a href="">NH.rb</a>. Brian Turnbull and Scott Garman will also be presenting, on <span class="caps">HTTP</span> and Rails deployment stacks, respectively.</p> <p><a href=""><img src="" style="float:right; padding: 10px 0 10px 10px;"/></a></p> <p>If you live in the ME/NH/Northern MA area and are interested in Ruby, I really encourage you to come to these meetings. They’re a great way to meet other local developers and learn about new cutting edge topics. If you can’t make this one, the next one is scheduled for October 21st (they’re always on the third Tuesday of the month). I’m scheduled to speak at that one, too. Topic is currently <span class="caps">TBD</span> but I’m sure we’ll come up with something fun.</p> <p>Meeting other Rubyists and learning about hot new tech isn’t enough of a reward in and of itself? Well, there’s free swag too. This month we’ll be giving away a few copies of my new book, Practical Rails Plugins along with some other Apress goodies (thanks Apress!).</p> <p>NH.rb is also giving way a free core conference pass to the upcoming <a href="">Voices That Matter: Professional Ruby Conference</a> (Boston, November 17-20). Pretty great, right? Sounds like this is going to be a great conference and they have a bunch of top notch speakers lined up. I’ll be there too (how was that for a segue?), speaking about Rails Plugin development strategies on the first day of the event. Hope to see you there!</p> Nick Plante jQueryConf 2008 Agenda 2008-09-01T00:00:00-04:00 2008-09-01T00:00:00-04:00 <p>The JQuery team just announced the <a href="">agenda for JQueryConf 2008</a> and it looks pretty solid! I’m happy that I registered early, as it appears to have sold out.</p> <p>Last year’s “camp” was great and I’m sure this year will be even better, with two tracks to cater to both beginning and advanced developers. The only item from my wish list that’s missing from the agenda is unit testing JQuery client code (and plugins). Oh well! If you’re interested in this topic, <a href="">Chad Meyers</a> just wrote up a great intro to using JQuery’s very own <a href="">QUnit</a> testrunner over on his blog. Good stuff!</p> <p><b>Update 9/29</b>: I posted a summary of conference highlights over at <a href=""><span class="caps">DDJ</span> Code Talk</a>.</p> Nick Plante 2008 Rails Rumble Kickoff 2008-08-26T00:00:00-04:00 2008-08-26T00:00:00-04:00 <p>We just set up the new blog site for the <a href="">2008 Rails Rumble</a> contest. This year the event will be held the weekend of October 18th. Registration should open within the next couple weeks. That is to say, we’re working on it. Read the <a href="">faq</a> ’n <a href="">rules</a> for more info.</p> <p>Greets to co-organizers <a href="">Darcy</a>, <a href="">Erin</a>, <a href="">Carter</a>, <a href="">Brian</a>, and <a href="">Rodrigo</a>.</p> Nick Plante Practical Rails Plugins 2008-08-23T00:00:00-04:00 2008-08-23T00:00:00-04:00 <p>Hey wow, author copies of my book just showed up yesterday. That’s pretty cool. My side of things has been finished for a few months now, but it’s nice to finally see it in print!</p> <p><iframe src="<1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;float:right;padding: 0 0 5px 10px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe></p> <p>The book, <a href="">Practical Rails Plugins</a> (Apress 2008), is aimed at the beginning to intermediate Rails developer, featuring a number of recipes for using popular third party plugins in Rails projects. So it’s sort of a recipes book but with a focus on leveraging plugins to accelerate feature development, and on standalone mini-projects rather than code snippets, which I think is much more illustrative for developers who are new to the framework. Topics include video transcoding and asynchronous processing, state machine modeling, payment processing, geocoding, full text search, testing and a whole lot more.</p> <p>I wrote about 50% of the content, <a href="">David Berube</a> (author of Practical Ruby Gems and Practical Reporting with Ruby and Rails) is responsible for the rest. If you want to pick up a copy, you can order it via <a href="">Amazon</a>. We also put up a <a href="">companion site</a> for the book last week, if you wanna check it out.</p> Nick Plante Razume in the News 2008-08-06T00:00:00-04:00 2008-08-06T00:00:00-04:00 <p>Just wanted to take a quick moment to call attention to <a href="">this TechCrunch article</a> which announces the unveiling of LaunchBox Digital’s first nine startups.</p> <p>My favorite of the group is <a href="">Razume</a>, a collaborative resume review service. But hey, I’m a little biased — we know those guys! For the past couple months, we’ve had the pleasure of helping them develop their Rails-based online resume building tools, document management, and peer review features. It’s been a fun ride and it’s great to see them finally launched and seeing some much deserved attention.</p> <p>In any case, congratulations to Sam, Brian, and the rest of the team on the formal launch. Razume is sure to be an indispensable resource for recent college grads, connecting them with professional resume experts and like minded job seekers. Rock on, Wayne.</p> Nick Plante Debugging ActionScript in the Browser 2008-07-31T00:00:00-04:00 2008-07-31T00:00:00-04:00 <p>Alright, <a href="">Carnivore client library for AS 2.0</a> way back in the day). I’ve been more focused on Ruby work these days, but from time to time I still dabble and do the occasional bit of Flash work for a <a href="">badass creative agency</a>.</p> <p>In any case, if you’re developing applications or widgets for browser-based deployment with Flash, you’ve doubtlessly noticed that certain things just don’t work the same way in the ‘Test Movie’ facility as they do in the browser (cough cough <code>MovieClipLoader</code> cough). Fortunately, there’s a way to see your <code>trace()</code> logger messages in a live browser session, too.</p> <p>First, you need to download and install a <a href="">debug version</a> of the Flash Player in Firefox. Next, install Alessandro Crugnola’s <a href="">Flash Tracer</a> plugin. An older version for FF2 is available at the Firefox addons site, so make sure to snag the one from the link in this article if you’re using Firefox 3.</p> <p>After restarting the browser, you can select ‘Flash!</p> Nick Plante NH Merb 2008-07-13T00:00:00-04:00 2008-07-13T00:00:00-04:00 <p>This Tuesday (July 15th), NH Ruby morphs into NH Merb for the night! Guest speaker <a href="">Jeremy Durham</a> is coming up from Boston to give a talk about his journey converting an existing Rails app to <a href="">Merb</a>. Should be good stuff, especially for those of you who are curious about Merb and how it might be of benefit to you as a Rails alternative.</p> <p>If you’re in the seacoast area, make sure to stop by. As always, more details and directions on the <a href="">wiki</a>.</p> Nick Plante Passenger <3 Sinatra 2008-07-04T00:00:00-04:00 2008-07-04T00:00:00-04:00 <p>A couple people have asked me how I’m hosting the <a href="">Sinatra</a>-based <a href="">pastie service</a> we wrote in yesterday’s revised <a href="">tutorial</a>. The previous version ran on a mongrel handler frontended by nginx, but for this version I decided to try something a little different.</p> <p>One of the big announcements at Railsconf last month was that <a href="">Passenger</a> (aka mod_rails) would be releasing a v2.0 with support not only for Rails applications but also for <a href="">Rack</a>, meaning that any Rack-based Ruby web framework can also run on it. Yay for deployment options, right? So anyway, I figured we’d give that a shot.</p> <p>For those of you who haven’t yet mucked with it, Passenger is dead simple to setup. Run <code>gem install passenger</code> to pull down the gem, and execute the <code>passenger-install-apache2-module</code> command to build and install the Apache 2.2 module (you’ll need the proper Apache libraries to be present of course). The command output will show you how to configure Apache to load the module.</p> <p>Getting Passenger to run a Sinatra-based application also turned out to be remarkably easy. All you need to do is create a regular old Rackup script. The file will need to be named <code>config.ru</code> and should contain all the logic necessary to initialize our app:</p> <pre><code>require 'rubygems' require 'sinatra'</code> <code>Sinatra::Application.default_options.merge!( :run => false, :env => ENV['RACK_ENV'] )</code> <code>require 'toopaste' run Sinatra.application</code></pre> <p>Place this file in the folder on your server where <code>toopaste.rb</code> and the <code>views</code> directory reside.</p> <p>Next, create a <code>public</code> directory. This is where any static images, JavaScripts, or stylesheets would be kept (we’re not using any, in this simple example). Point your vhost’s <code>DocumentRoot</code> here:</p> <pre><code><VirtualHost *:80> ServerName paste.zerosum.org DocumentRoot /var/www/apps/toopaste/public ... </VirtualHost></code></pre> <p>You might as well create a <code>tmp</code> directory too. You can place a <code>restart.txt</code> file in this directory to tell Passenger it needs to reload the app without restarting Apache (you can <a href="">use this in your cap restart tasks, too</a>).</p> <p>Couldn’t be much easier. For more information on deploying other Rack-based frameworks (<a href="">Merb</a>, Camping, Ramaze, etc) and various other config options, check Passenger’s <a href="">user guide</a>.</p> Nick Plante Clone Pastie with Sinatra & DataMapper 0.9 2008-07-02T00:00:00-04:00 2008-07-02T00:00:00-04:00 <p>Waaaay back in November I wrote a <a href="">DataMapper and Sinatra tutorial</a>. DM was still pretty immature at the time, and it quickly became outdated. I promised I’d update it once 0.9 was released.</p> <p>Better late than never, right? Anyway, without further ado, here’s Toopaste Tutorial 2.0:</p> <h4>What We’re Building</h4> <p rules, select themes for viewing, and so on. But the core concept itself isn’t a terribly complex one, and our example is going to be about as barebones as they come.</p> <p>The interesting thing isn’t the application we’re going to build here so much as it is the tools we’ll use. That is, we’ll be using the pastie example to introduce you to two cool new pieces of Ruby tech: Sinatra, a Ruby web micro-framework, and the DataMapper <span class="caps">ORM</span> package.</p> <h4>Sinatra</h4> <p><a href="">Sinatra</a>, on the surface, is a lot like <a href="">Camping</a>, another Ruby web all-in-one-file micro-framework. Camping hasn’t seen much active development lately <span class="caps">ORM</span>-agnostic, instead of being married to ActiveRecord like both Rails and Camping are.</p> <p>Sinatra has been making cameo appearances supporting a number of high-profile Ruby-based web apps, including Heroku and GitHub. It runs on top of <a href="">Rack</a>, which means that it plays nice with a wide variety of Ruby web app servers, including Mongrel, Thin, and Ebb. It also means that you can host your Sinatra applications easily with Apache and Phusion <a href="">Passenger</a>, as of Passenger 2.0. For more information, <a href="">check out the ‘official’ Sinatra tutorial</a> (oops dead link). There’s also an <a href="">open source Sinatra book</a> in the works.</p> <h4>DataMapper</h4> .</p> <p>There are a number of reasons why I prefer this approach, but that’s fodder for an entirely separate blog post, so I won’t get into it here. Besides, the team has already written a <a href="">great summary of why DataMapper rocks</a>. Read it. It’s good stuff. Oh, and performance kicks ass too.</p> <p>Take that, non-believers!</p> <h4>Prerequisites</h4> <p>OK, anyway. Tutorial time. Found your plastic hat? Good. Let’s go. First let’s get the gems we’ll need. As of this writing, DM is at v0.9.2 and Sinatra is at v0.2.2. We’re also going to retrieve the <a href="">Syntaxi</a> gem, which we’ll use for syntax highlighting.</p> <pre><code>sudo gem install sinatra data_mapper syntaxi</code></pre> <p>The <code>data_mapper</code> gem is a “meta gem” that includes the most commonly used gems from <code>dm-core</code>, <code>dm-more</code>, and others. We’ll be using a couple of these additional libraries — <code>dm-timestamps</code> and <code>dm-validations</code> — in this tutorial.</p> <p>Since DM uses the <a href="">DataObjects.rb</a> (DO) drivers, you’ll want to install them too. For this tutorial we’ll be using Sqlite3 as a data store. If you want to use MySQL or Postgres or any other database supported by DO, well that’s cool too (just make sure to get <code>do\_mysql</code> or <code>do\_postgres</code>).</p> <pre><code>sudo gem install data_objects do_sqlite3</code></pre> <h4>The Code</h4> <p>Now that our prerequisites are satisfied, let’s get started by creating the file <code>toopaste.rb</code>:</p> <pre><code>require 'sinatra' require 'dm-core' require 'dm-validations' require 'dm-timestamps' require 'syntaxi'</code> <code>DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/toopaste.sqlite3")</code> <code>class Snippet include DataMapper::Resource</code> <code> property :id, Integer, :serial => true # primary serial key property :body, Text, :nullable => false # cannot be null property :created_at, DateTime property :updated_at, DateTime</code> <code> # validates_present :body # validates_length :body, :minimum => 1</code> <code> Syntaxi.line_number_method = 'floating' Syntaxi.wrap_at_column = 80</code> <code> def formatted_body replacer = Time.now.strftime('[code-%d]') html = Syntaxi.new("[code lang='ruby']#{self.body.gsub('[/code]', replacer)}[/code]").process "<div class=\"syntax syntax_ruby\">#{html.gsub(replacer, '[/code]')}</div>" end end</code> <code>DataMapper.auto_upgrade!</code> <code># new get '/' do erb :new end</code> <code># create post '/' do @snippet = Snippet.new(:body => params[:snippet_body]) if @snippet.save redirect "/#{@snippet.id}" else redirect '/' end end</code> <code># show get '/:id' do @snippet = Snippet.get(params[:id]) if @snippet erb :show else redirect '/' end end</code></pre> <p>Next we’ll dissect this code listing to give you a brief look at how DataMapper and Sinatra work. We’ll show the code listings for our views as we get to them.</p> <h4>Code Analysis: DataMapper</h4> <p>The first couple lines require the libraries we’ll be using in this example. <code>dm-core</code> represents the DataMapper core libraries, and <code>dm-validations</code> and <code>dm-timestamps</code> both add extra bits of non-core functionality to DataMapper. In this case, requiring timestamps means that fields such as <code>created\_at</code> and <code>updated\_at</code> automatically get branded with the current Date/Time when a model is created or updated. As for validations, well we’ll see them in use shortly.</p> <p.</p> <pre><code>DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/toopaste.sqlite3")</code></pre> <h5>Persistent Models and Properties</h5> <p>Next we define our model, <code>Snippet</code>. Since we want to persist snippets, we include the <code>DataMapper::Resource</code> module in the class definition. From an end user point of view this is the same as inheriting from <code>ActiveRecord::Base</code> in Active Record. It’s a nice bonus that we don’t have to use inheritance to accomplish this any more.</p> <pre><code>include DataMapper::Resource</code></pre> <p>The property declarations in our model are DataMapper’s way of specifying attributes, which translate to database table columns. This might look a little bit odd at first if you’re coming over from Active Record…</p> <p><em>“<span class="caps">OMG</span> I don’t have to put comments in my source file to remind me what attributes are available on my models?!”</em></p> <p>It’s like a little slice of heaven, isn’t it?</p> <pre><code>property :id, Integer, :serial => true # primary serial key property :body, Text, :nullable => false # cannot be null property :created_at, DateTime property :updated_at, DateTime</code></pre> <p <code>:accessor</code> option to <code>:private</code> or <code>:protected</code> (<code>:reader</code> and <code>:writer</code> options are also supported for even more control).</p> <p>Another interesting DM optimization worth noting: by default, the text field (<code>body</code>) is lazily loaded. Text columns are expensive in databases, and by using lazy loading, we only access them when they’re needed. This speeds things up significantly in most cases. However, if you don’t want to do this for whatever reason, you can just pass a <code>:lazy => false</code> option in the text column property declaration.</p> <h5>Validation</h5> <p>The validators we’re specifying should look relatively familiar to anyone familiar with AR. They’re only available to us because we required the <code>dm-validations</code> library, as mentioned. This is part of DM’s Merb-like minimalist approach; start with just the bare essentials, and allow developers to mix in extra functionality as its desired. The kitchen sink is so fail, right?</p> <pre><code># validates_present :body # validates_length :body, :minimum => 1</code></pre> <p>So why are these lines commented out then, you ask?</p> <p>Well, we could explicitly add the <code>validates_present :body</code> to specify that the body property must be present, but that’s already handled for us in the property declaration since we specified <code>:nullable => false</code>. If <code>dm-validations</code> is not required, the nullable option will simply ensure that the database column isn’t null, but if validations are in use it will augment this behavior to assume that we not only mean ‘not null’, but also ‘not empty’.</p> <p>Likewise, <code>validates_length</code> could be useful in certain situations, but in our case we just want to make sure that the paste body isn’t empty, which is already handled for us by the nullable option on the body property.</p> <p>There are lots of other validations that we can add in this manner, of course. For more information see the <a href="">DataMapper <span class="caps">API</span> documentation</a>.</p> <h5>Syntax Highlighting with Syntaxi</h5> <p>The only custom method we’ve added to our model, <code>formatted_body</code>, is pretty straightforward.> <pre><code>def formatted_body replacer = Time.now.strftime('[code-%d]') html = Syntaxi.new("[code lang='ruby']#{self.body.gsub('[/code]', replacer)}[/code]").process "<div class=\"syntax syntax_ruby\">#{html.gsub(replacer, '[/code]')}</div>" end</code></pre> <p>The <code>replacer</code> stuff just keeps us from stumbling on syntax coloring markup in our output <span class="caps">HTML</span>.</p> <h5>Auto-Migrations</h5> <p <code>DataMapper.auto\_upgrade!</code> method, which checks to see if the database table that corresponds to our model(s) need upgrading and then creates or updates them as appropriate. It’s a non-destructive way to do auto-migrations (the destructive equivalent is <code>auto\_migrate!</code>)</p> <h4>Code Analysis: Sinatra</h4> <p <span class="caps">URL</span> patterns.</p> <h5>The Index Action / New Snippet Form</h5> <p>The first of our actions needs to display a form to create a new paste. It should always be available at <code>'/'</code>, the application root.</p> <pre><code>get '/' do erb :new end</code></pre> <p>This tells Sinatra that when a <span class="caps">GET</span> request for <code>'/'</code> comes in, that we should use the erb helper to render the <em>new.erb</em> template, which is stored in the <code>views/</code> subdirectory by convention and marked up with embedded Ruby (ERb). We can render our responses inline as well, which works for dirt-simple applications, but in most cases you’ll prefer to keep the view templates outside of this file.</p> <p>In any case, the <code>new.erb</code> template is shown below:</p> <pre><code><div class="snippet"> <form action="/" method="POST"> <textarea name="snippet_body" id="snippet_body" rows="20"></textarea> <br/><input type="submit" value="Save"/> </form> </div></code></pre> <h5>The Create Action</h5> <p>Our next action is analogous to a <code>#create</code> 100% RESTful applications with it.</p> <pre><code>post '/' do @snippet = Snippet.new(:body => params[:snippet_body]) if @snippet.save redirect "/#{@snippet.id}" else redirect '/' end end</code></pre> <p>Pretty standard stuff, right? We retrieve the parameter passed to us from the new paste form, instantiate a new model and try to save it. If the validations pass, we redirect to the <code>#show</code> action equivalent. If not, we’re just going to dump you back to the <code>#new</code> form again. Since the only way the action will fail is if the <code>body</code> property is empty, we’re not going to bother with any sort of error message at this time. We’re not rendering anything here (merely redirecting), so no template is required.</p> <h5>The Show Action / Show Me The Snippets!</h5> <p>If our post is successful, we’re going to be taken to the <code>#show</code> action, which lives at <code>/:id</code>, where <code>:id</code> is the primary key of the corresponding database record. This action will also get accessed directly when you paste that <span class="caps">URL</span> to the chat room, and people click to view your code.</p> <pre><code>get '/:id' do @snippet = Snippet.get(params[:id]) if @snippet erb :show else redirect '/' end end</code></pre> <p>In the code listing above, we look up the particular snippet specified in <code>params[:id]</code> and set an instance variable by calling DataMapper’s <code>get</code> method (equivalent to Active Record’s <code>find</code> and one of many ways to do record lookups with DataMapper). If the <code>@snippet</code> is not found we’ll redirect back to the new snippet form. Otherwise we render an ERb template, which of course has access to that instance variable. Here’s the code you’ll want in <code>/views/show.erb</code>:</p> <pre><code><div class="snippet"> <div class="sbody" id="content"><%= @snippet.formatted_body %></div> <div class="sdate">Created on <%= @snippet.created_at.strftime("%B %d, %Y at %I:%M %p") %></div> <br/><a href="/">New Paste!</a> </div></code></pre> <h5>The Layout</h5> <p>We’re pretty much done at this point. However, to dress up our output we’ll use an ERb layout template with some <span class="caps">CSS</span> to handle the syntax highlighting that Syntaxi provides for us. If it exists, Sinatra will render a special view template (just like Rails does) named <code>layout.erb</code> in the <code>views/</code> subdirectory. This layout will be used to wrap the output of the other views rendered when the <code>erb</code> helper method is called.<> <h4>Hallo Pastie!</h4> <p>You can fire up your new Sinatra and DataMapper-powered application by issuing the following command:</p> <pre><code>ruby toopaste.rb == Sinatra has taken the stage on port 4567!</code> <code>Sinatra sits on top of <a href="">Mongrel</a> by default, making it super-easy to use (and thread-safe to boot!). If you open up a web browser and point it at <code></code> you'll see the results. Copy and paste away. You now have a fully functional (albeit slightly retarded) pastie clone with syntax highlighting for Ruby code snippets. And the core logic is all contained in a single file, with a few external ERb templates for cleanliness.</code></pre> <h4>Wrapping Up</h4> <a href="">Merb</a> developers already know this, of course.</p> <p>OK enough blathering for now. Longest blog post. Ever. If you like, you can <a href="">play with the finished app</a> or <a href="">check out the sources on GitHub</a>. Enjoy, and please comment if you have any problems or suggestions for improvements. This code was written and tested on OS X 10.5 and Debian Etch. Special thanks to Jonathan Stott for the early review and fact checking.</p> Nick Plante Radiant Scoped Multi Update 2008-06-24T00:00:00-04:00 2008-06-24T00:00:00-04:00 <p>Blog updates have been pretty infrequent lately. As have my <span class="caps">OSS</span> contributions. Sorry! I haven’t had an awful lot of spare. Between client work and wrapping up my book (more on that soon), things have been a bit… insane.</p> <p>However, I did find some time over the weekend to finally update the <a href="">scoped multi-site Radiant extension fork</a> to work with 0.6.7 and latest edge.</p> <p>Note that the old <span class="caps">URL</span> is no longer accessible, as the <a href="">Radiant</a> Github presence was recently refactored to remove extensions from the core project repo.</p> Nick Plante I'm Back 2008-06-03T00:00:00-04:00 2008-06-03T00:00:00-04:00 <p>I’m back on the east coast after a 1.5 week west coast mini-tour, culminating with Railsconf information overload and a couple of great parties. I’ve written up some session highlights over at <span class="caps">DDJ</span> (parts <a href="">one</a> and <a href="">two</a>) in case you’re interested.</p> <p>Greets to all the fine folks I met at the conference, especially the Offrails crew and <a href="">Jason LaPier</a>, my local guide to Portland nightlife and microbrews (also a badass Rails developer who was recently published in Pragprog’s <i>Advanced Rails Recipes</i>). Thanks dude!</p> <p>If you’ve sent an email and I haven’t gotten back to you yet, my apologies; I’m still a bit jetlagged and trying to catch up on a ton of things.</p> Nick Plante Travel Plans 2008-05-20T00:00:00-04:00 2008-05-20T00:00:00-04:00 <p>I’ve got my itinerary planned out for <a href="">Railsconf</a>..</p> <p>If you’re in any one of those cities and want to grab a beer (or a smoothie), hit me up on <a href="">Twitter</a>. Hopefully I’ll see some of you at Railsconf.</p> <p>Also, I’ll be giving a talk at <a href="">NHRuby tonight</a> (5/20) on <a href="">Rack</a>. If you’re in the area, stop by.</p> Nick Plante Random Passenger Observations 2008-05-05T00:00:00-04:00 2008-05-05T00:00:00-04:00 <p>Played around with <a href="">Passenger</a> (v1.0.4) a bit more last weekend. Deployed a <a href="">Radiant</a> instance with it for staging. Overall, quite happy. However, thought I’d take the opportunity to jot down a few observations:</p> <p>First, Radiant, with a smattering of extensions, takes a while to start up on the vhost we’re playing around on (yes, need to pump up those specs before deploying anything real). Since Passenger cleans up idle Rails instances when they fall into disuse, this can mean a harsh initial request delay for infrequently accessed hosts.</p> <p>Passenger has clearly targeted the shared host market, where hosts have a large memory footprint and a large number of applications. The same strategy doesn’t work quite as well for a small <span class="caps">VPS</span> memory footprint and a single application root, where it would make sense to keep an instance in memory at all times (and clean it up and respawn it, perhaps, on occasion if an idle timeout is reached).</p> <p>The solution in this case is to increase the <a href="">Rails pool idle timeout</a> to something that matches your traffic profile (of course, the tradeoff there is with the growing memory footprint of long-running processes…). And while you’re at it, adjust the maximum number of spawned instances — it defaults to 20, which is great for a dedicated with 2GB but not so good if you’re running a single application on a 512MB <span class="caps">VPS</span>.</p> <p>More information is available in the <a href="">architectural overview</a> and the excellent <a href="">user guide</a> that the Phusion guys have put together. The <a href="">SpawnManager</a> itself is written in Ruby, and has a set of <a href="">RDocs</a> that you might want to take a look at as well.</p> <p>We initially had some process ownership issues, where the Rails production log wasn’t being written to. The Rails server instance is going to be running as whatever user owns config/environment.rb (unless you change this in the config), so make sure to chown/chmod appropriately.</p> <p>Finally, the restart mechanism, although a bit odd, is pretty useful. If you touch a file called restart.txt in the #{RAILS_ROOT}/tmp directory, it’ll reload the application instance on the next request without having to explicitly restart apache. Here’s a Capistrano deploy:restart task for this:</p> <pre><code>namespace :deploy do task :stop, :roles => [:app] do puts "Use the deploy:restart task to restart the Rails application" end task :start, :roles => [:app] do puts "Use the deploy:restart task to restart the Rails application" end task :restart, :roles => [:app] do run "touch #{current_path}/tmp/restart.txt" end end </code></pre> Nick Plante Note To Self (Good Examples Are Hard) 2008-05-03T00:00:00-04:00 2008-05-03T00:00:00-04:00 <p>The).</p> <p>The key to writing good book material is being able to show people how to do things while keeping them entertained. That means coming up with examples that tread the line between being <strong>practical</strong>, being appropriately <strong>demonstrative</strong>, and being <strong>correct</strong>. Good examples are the hard part.</p> <p>When developing an example, you’re trying to come up with something that has the following characteristics:</p> <ul> <li><strong>It’s interesting.</strong> That is, it’s worth writing about in the first place. No one wants to read another blog post creation example (unless there’s something unusual about it). <span class="caps">BORING</span>.</li> <li><strong>It represents best practices.</strong> You’re an author. You have to be right. Or at least able to competently defend your implementation choices, anyway.</li> <li><strong>It illustrates those concepts that you’re trying to write about.</strong> This should be first point, rather than third. See what I mean?</li> <li><strong>It minimizes focus on those elements that you are not writing about.</strong>).</li> </ul> <p><img src="" alt="bears!" style="float: right; margin: 0 0 10px 10px;"/></p> <p <span class="caps">CSS</span> for making it pretty. Leave that to the <span class="caps">CSS</span> books.</p> <p.</p> <p>If your example is a simple web service for sharing geographic location data and you’re using a bunch of RESTful conventions, make sure to explain the basic concepts. But don’t write a dissertation on <span class="caps">REST</span> vs <span class="caps">SOAP</span>. And don’t worry about responding to formats that aren’t part of the main example.</p> <p.</p> Nick Plante Music To Code By 2008-04-18T00:00:00-04:00 2008-04-18T00:00:00-04:00 <p>There’s a good thread going on over at <a href="">Hacker News</a> today regarding music for coding sprints. It’s interesting to see that a number of people, like me, have trouble concentrating when listening to music with prominent lyrics, whereas others thrive on it.</p> <p>A lot of people also seem to really dig electronica. I guess that’s no big surprise. It’s never done much for me, personally, although there are a few electronic pieces I do really like (NIN’s <em>Ghosts</em> being a recent example). Being an ex-hc/metalhead I gravitate more towards melodic post-rock stuff and the occasional poppy masterpiece.</p> <p>Here’s some stuff in my current work playlist:</p> <ul> <li>Explosions in the Sky</li> <li>Mogwai</li> <li>Castor</li> <li>My Bloody Valentine</li> <li>Elliott</li> <li>Pinback</li> <li>Isis</li> <li>On The Might of Princes</li> <li>Jesu</li> <li>Portishead</li> <li>Dredg</li> <li>National Skyline</li> <li>Pelican</li> <li>Low Frequency In Stereo</li> <li>Radiohead</li> <li>There Were Wires</li> <li>Godspeed You! Black Emperor</li> <li>Mouth of the Architect</li> </ul> <p.</p> Nick Plante NHRuby Hackfest 2008-04-14T00:00:00-04:00 2008-04-14T00:00:00-04:00 <p>Yep, that’s right. <a href="">Hackfest tomorrow night</a> in Portsmouth. Bring any code you’re having issues with. Failing that, I’ve got a couple project tickets (DataMapper, Radiant) that we can dig into. We’ll spend 30 minutes or so on a quickie mod_rails demo while we’re there too.</p> <p>In other local news, John Herman has been swell enough to put together an <a href="">NH Media Makers</a> group. The first get-together is May 11th at Crackskulls in Newmarket. Rock out.</p> Nick Plante Mod_Rails Revealed 2008-04-12T00:00:00-04:00 2008-04-12T00:00:00-04:00 <p>The hardworking hackers over at Phusion finally unveiled <a href="">Passenger</a> (mod_rails) earlier today. I just moved one of our staging servers over to it and will be playing around with it a bit more over the weekend. So far I’m happy to report that, as advertised, it’s dead easy to use… and the performance seems solid.</p> <p>I’d write up a tutorial but honestly it’s so simple that it’s completely unnecessary (imagine that!). Check out the <a href="">updated screencast</a> for all you need to know to get up and running and make sure to dig into the provided docs if you need more. They’re very thorough.</p> <p>In summary, it’s great to see more Rails deployment options emerging, and it’ll be interesting to see viable shared hosting options for the low-end market too. Although I’m a strong believer in the app server + frontend web server pairing, there are a whole class of applications for which it just seems like overkill.</p> <p>A hearty ‘nice work’ to everyone involved! Now where’s my mod_rack? :-)</p> <p><b><span class="caps">UPDATED</span> 4/12</b>: this blog is now running on mod_rails and Mephisto 0.8!</p> Nick Plante 2008 Rails Rumble Rumors 2008-04-10T00:00:00-04:00 2008-04-10T00:00:00-04:00 <p>Just to clear up any possible confusion on that matter: Yes. There will be a <a href="">2008 Rails Rumble</a>. And no. It will not be in May. Probably September or October.</p> <p>We have a lot of great ideas (thanks to everyone that participated and commented) that will improve on last year’s experience dramatically and the whole team is looking forward to it, in a big way. More information coming soon, I promise, as well as an announcement, new blog, and specific details prior to Railsconf.</p> <p>Oh, and speaking of Railsconf… Josh Owens, of <a href="">TastyPlanner</a> fame (last year’s grand prize winner), is giving what looks to be a fun talk about their <a href="">experience building a kickass app in a 48 hour timeframe</a>. If you’re going to be there, you ought to check it out. Especially if you’re interested in participating this year. If you haven’t yet registered for the conference, you’re <a href="">running out of time</a>, so get to it.</p> <p>See you there!</p> Nick Plante Radiant Super Multi Go! 2008-04-03T00:00:00-04:00 2008-04-03T00:00:00-04:00 <p>Here at Ubikorp we’ve used <a href="">Radiant</a> as the basis for a number of client projects who needed core <span class="caps">CMS</span>-like functionality. As anyone who’s played with it knows, Radiant is very barebones; this is intentional and a welcome change from most packages, which attempt to throw the kitchen sink of clutter at each and every problem. Fortunately, it’s easy to build on top of the basics by using a well thought-out extensions system — there are a large number of stock <a href="">extensions</a> available (and it’s also really easy to roll your own for custom app logic).</p> <p>One of the more interesting extensions is the <a href="">multi-site extension</a>. To be honest, multi-site capability is something I really feel should be a core feature, but since it’s not, this approach works surprisingly well (at least until you start adding other extensions that would ideally be multi-site-aware). Radiant school headmaster Sean Cribbs wrote an initial version of the extension back in November, but it didn’t quite work for us on a particular project — we needed to be able to scope individual user-level access to particular sites. So we extended it, and thus the scoped multi-site extension was born.</p> <p>Well, actually, it’s just a fork of the multi-site plugin. For now.</p> <p>Features:</p> <ul> <li>scopes user level access to individual sites (admins and developers still have access to all sites)</li> <li>regular users can’t see, edit, or access other user sites that they don’t own</li> <li>optionally scopes layouts to sites</li> <li>snippets usable everywhere, but display and editing of snippets limited to admins/developers</li> </ul> <p>Anyway, if you’re interested in seeing our changes you can check it out on <a href="">github</a> in my fork of Sean’s Radiant repo. Is this a candidate for integration into the existing extension, or should we spin it out as a separate extension? Let me know what you think.</p> <p><b><span class="caps">UPDATED</span> 6/24:</b> The <span class="caps">URL</span> is out of date. See <a href="">this blog post</a> for more details and updates (the latest version requires Radiant 0.6.7 or later).</p> Nick Plante Twittering 2008-04-02T00:00:00-04:00 2008-04-02T00:00:00-04:00 <p>I’ve been bitten by the <a href="">Twitter</a> bug. I know, I’m a little late to the party. But being late is fashionable. And I sure like the fashion.</p> <p>Anyway, go ahead and <a href="">stalk me</a>. If you dare. Or check out the status updates in the blog sidebar if that’s what you’re into. I’ve also added my <a href=""><span class="caps">DDJ</span></a> blog feed to the sidebar. A couple of my recent articles:</p> <ul> <li><a href="">Roll Your Own Web Framework</a> (an introduction to Rack)</li> <li><a href="">Rails: Vendor Everything Just Got Easier</a> (the new config.gem features in Rails Edge)</li> </ul> <p>More soon. Promise.</p> Nick Plante Mod_Rails Teaser 2008-03-20T00:00:00-04:00 2008-03-20T00:00:00-04:00 <p>Well, <a href="">this</a> is sure to stir up some buzz in the Rubyverse…</p> Nick Plante DDJ Code Talk Launches 2008-03-15T00:00:00-04:00 2008-03-15T00:00:00-04:00 <p>The legendary <a href="">Dr Dobb’s Journal</a> just announced the launch of their new blog and forum system, <a href=""><span class="caps">DDJ</span> Code Talk</a>. I was extremely honored when Jon asked me to contribute, as <span class="caps">DDJ</span> has long been one of my favorite industry pubs. Them peoples is hardcore.</p> <p>In the coming months I’ll be contributing articles about Ruby, web application development, and lightweight languages. Head on over to check out my first article for them, a quick survey of <a href="">Alternative Ruby Web Frameworks</a>. There are a few other Ruby geeks hiding in their trees too, and a broad range of topics, including Python, Java, .<span class="caps">NET</span>, D (!), databases and web service architecture and design. Thanks for reading!</p> Nick Plante NHRuby: Django/Rails 2008-03-09T00:00:00-05:00 2008-03-09T00:00:00-05:00 <p>If you’re in the ME/NH/MA area on Tuesday, make sure to stop by the <a href="">NH Ruby <span class="caps">SIG</span></a>; <a href="">Brian Turnbull</a> will be presenting an in-depth talk comparing the philosophies of Rails and Django. I’ve never done any Python work at all myself, so I’m really looking forward to this dissection.</p> <p>If you’re not in the area, you’re still in luck. We’re trying something new this month, and will be <a href="">broadcasting the event live via WebEx</a>. Big thanks to <a href="">Tim Golden</a> and our sponsor <a href=""><span class="caps">RMC</span> Research</a> for hooking this up!</p> <p>(<span class="caps">NOTE</span>: we usually meet on the third Tuesday of the month, but our host had some scheduling problems this time around; we’ll be returning to the normal schedule in April)</p> Nick Plante Git Ur Radiant Extensions 2008-03-05T00:00:00-05:00 2008-03-05T00:00:00-05:00 <p>I published a new <a href="">Radiant</a> extension yesterday: <a href="">Database Form</a>. It provides a new page type and tags for constructing contact and request info forms and will save user responses to a database table. Those responses can then be exported for use in another application (<span class="caps">CRM</span>, etc). See the <span class="caps">README</span> for usage and examples. It was extracted from some client work that we’ll be deploying soon.</p> <p>If this sounds good, you can download or clone it from <a href="">GitHub</a>. While you’re there, spend a few minutes poking around; GitHub is pretty dang cool. They’ve definitely succeeded in making Git repository hosting stupid simple. Just click a button to create a project, follow a few commands on your local system to import your sources, and you’re off and running. You can then view the repo history, browse the source, see diffs, download a tarball (for easy extension installation in your pre-existing Radiant project), and fork it if you want to add your own features. That’s where things get sweet, of course: Fork the project, make some changes, and send me a pull request so we can merge them into the master branch. All this is possible without GitHub, but it sure does a swell job of streamlining things and abstracting the suck away.</p> <p>It also exposes the links between developers and their project contributions in a pretty cool way. See the <a href="">DataMapper</a> project’s “network” page to see what I’m talking about. <a href="">Ryan Tomayko</a> has pointed out that this sort of interaction starts to smell an awful lot like a MySpace for developers, where lines in the social graph are drawn based on <span class="caps">OSS</span> project work. Wow, that’s a cool thought, ain’t it?</p> Nick Plante Principle of Least Surprise 2008-03-04T00:00:00-05:00 2008-03-04T00:00:00-05:00 <p>One of the things I love about Ruby is that it tends to follow <a href="">the principle of least surprise</a>; things just work the way you would expect them to, with precious few exceptions (cough cough <a href="">inject</a> cough). Horray for intuitiveness.</p> <p>On the other hand, I’ve become so spoiled by The Principle that willful violations stand out like the sober guy at the all-inclusive beach resort. I know I’m being a nitpicky ass here, but <a href="">this Rails bug^H^H^H ticket</a> makes me kinda ill. Funny, because in my previous life as a Java/<span class="caps">PHP</span> developer, I wouldn’t have even batted an eyelash at it.</p> Nick Plante OpenID + Client Certs = Win 2008-02-22T00:00:00-05:00 2008-02-22T00:00:00-05:00 <p>I’m a big fan of <a href="">OpenID</a>. Or rather, I’m a big fan of what OpenID and <a href="">data portability</a> mean for the web at large in the coming white days. Single sign on and distributed identity is certainly an idea that’s been long overlooked and it’s time that we changed that. The next time you write a web application, ask yourself: “do my users really need yet another set of login credentials?”. Then implement OpenID. It’s really simple, especially in Rails. I gave a presentation on it at <a href="">NHRuby</a> last month (<a href="">download <span class="caps">PDF</span></a>).</p> <p>So, as gah-gah as I am over single sign on for ease of use, I’m a embarrassed to note that, like almost everyone else, I’ve completely overlooked <a href="">client certificates</a> for web-based authentication. By using client certificates you one-up single sign on by removing the need to use a login/password at all. This isn’t new; it’s something that’s been available in every web browser for pretty much as long as anyone can remember. And yet I’ve never, ever seen a site that supports them for an authentication mechanism. Sad faces abound.</p> <p>But wait! OpenID to the rescue! It turns out that <a href="">MyOpenID</a> (and a host of other OpenID providers) DO make use of them. So if you create a client certificate with your OpenID provider, you can eliminate the need to use a login/pass with any OpenID client sites. Cheers to <a href="">Dr Nic Williams</a> for digging this up. Sometimes old (and ignored) is the new new. Rock on.</p> <p>More details at <a href="">Dr Nic’s blog</a>.</p> Nick Plante Plugins Are Unnecessary 2008-02-20T00:00:00-05:00 2008-02-20T00:00:00-05:00 <p>Plugins really <strong>are</strong> unnecessary — <a href="">Jay Fields is absolutely right</a>. RubyGems is a great package management system and there’s no reason it can’t do double duty here, if we just impose a few extra restrictions on Gem/Plugin structure. There are other benefits too using <a href="">Gems</a> too, such as versioning and dependency management, which is somewhat painful in the world of Rails plugins.</p> <p><a href="">Merb</a> already uses Gems for plugins/extensions. Why doesn’t Rails? Historic reasons, most likely. Rails itself predates the existence of Gems iirc. But seriously, how hard would it be to rewrite `script/plugin` to install a gem and unpack it into `vendor`? That’s the first step.</p> Nick Plante ActiveRecord: Importing YAML 2008-02-20T00:00:00-05:00 2008-02-20T00:00:00-05:00 <p>Backing up ActiveRecord models to <a href=""><span class="caps">YAML</span></a> is easy to do, and can be convenient for creating ‘templates’ that can later be imported to restore basic project structure in a new database. However, the import process can be a little tricky, as the instantiated objects don’t seem to respond correctly to `new_record?`</p> <p>Here’s what our <span class="caps">YAML</span> might look like. Note that it’s a serialized `CustomWidget`, which is an ActiveRecord model that inherits from `ActiveRecord::Base`.</p> <pre><code>--- </code> <code>- !ruby/object:CustomWidget attributes: name: DoSomething updated_at: 2008-01-28 05:02:54 description: Does something. created_at: 2008-01-28 05:02:54 attributes_cache: {}</code></pre> <p>We can automatically instantiate the appropriate Ruby objects from this using the following code:</p> <pre><code>class CustomWidget < ActiveRecord::Base end</code> <code>YAML::add_private_type("CustomWidget") do |type, value| CustomWidget.new(value) end</code> <code>obj = YAML::load(File.open("template.yml"))[0] => #<CustomWidget name: "DoSomething", created_at: "2008-01-28 05:02:54", updated_at: "2008-01-28 05:02:54", description: "Does something."> obj.save => true</code></pre> <p>So what we’ve done is taken <span class="caps">YAML</span> from one project and tried to use it to import the same data into another database (note that IDs are stripped). We define a transfer type for the <span class="caps">YAML</span>, providing a mapping to the class, and then we call `<span class="caps">YAML</span>::load` to load it up. This returns an array, in this case it contains a single `CustomWidget` object. Everything looks swell. We call `save` on the new object and it returns true.</p> <p>However, if we check the `count` of `CustomWidgets` that exist in the database, we’ll find that it’s unaltered; no new record has been saved. It turns out that this is because the imported `CustomWidget` doesn’t report true when `new_record?` is called.</p> <pre><code>obj.new_record? => nil</code></pre> <p>In order to save itself to the database and get a new ID, the `CustomWidget` instance has to first respond correctly to inquiries as to whether or not it’s new. We’d like `new_record?` to return false. The quick-fix secret is to manually toggle the `@new_record` instance variable. If we do that, calling `save` will return true and actually save the object to the database as well this time. Big yay, right?</p> <pre><code>CustomWidget.count => 0 obj.instance_variable_set("@new_record", true) obj.new_record? => true obj.save => true CustomWidget.count => 1</code></pre> <p>Yes, this is an ugly hack. Did I say ugly? I meant <em>gross</em>.</p> Nick Plante Constraint-Driven Development++ 2008-02-08T00:00:00-05:00 2008-02-08T00:00:00-05:00 <p>There was a nice writeup on <a href="">ReadWriteWeb</a> yesterday about Montreal’s upcoming <a href="">Blitzweekend</a> event. Like the Rails Rumble that we organized last September, Blitzweekend is another attempt to give people a “weekend to build a functioning startup from scratch”. Unlike the Rumble, it isn’t a competition, and it places added value on physical proximity.</p> <p.</p> <p>Results, of course, are what makes application development exciting; seeing a movie get automatically reencoded after upload, a search query produce a number of restaurants in my area, plotted on a map, a transaction get authorized and recorded by the third party <span class="caps">API</span>.</p> <p.</p> <p>.)</p> <p>Anyway, I’ve rambled on for a bit and I’m sorry. We’ll do another Rumble, or something like it, later this year. For sure. But the reason I’m writing is this: You don’t have to wait.</p> <p>That is, you don’t need an actual event to prove that this brand of ultra-mega <span class="caps">CDD</span> works.</p> <p.</p> <p>I’m seriously thinking about doing just this, starting at the end of February, maybe at the end of each month. Anybody wanna be on my team?</p> Nick Plante Slacking 2008-01-30T00:00:00-05:00 2008-01-30T00:00:00-05:00 <p>Like my pal bryanl over at <a href="">smartic.us</a>, I too want to apologize for being a bad blogger lately. I’ve just been stupid busy with both personal stuff and lotsa client work, which of course is both a blessing and a curse.</p> <p>In any case, my head is almost back above water and I hope to be back on track writing regular (and hopefully interesting) posts within the next week or two. I’ve been working on some fun projects and I want to talk about it, really, but at the end of the day I’m just tired and don’t know where to begin. I’ll figure it out.</p> <p>In the meantime, if you’ve got free cycles and some cash in your wallet to burn, pick up a copy of Dave Berube’s new book on <a href="">Ruby Reporting</a>, which was just published by Apress. I served as a technical reviewer on it, which was a really great experience. Even though Dave and I don’t see eye to eye on absolutely everything (cue groans about a particular chapter dealing with MS Access integration), it’s full of fun Ruby code and unique reporting tips, including examples that interop with Google AdWords, SugarCRM, and PayPal. Congrats man, nice work!</p> Nick Plante Railsconf Registration Open 2008-01-30T00:00:00-05:00 2008-01-30T00:00:00-05:00 <p>Registration for <a href="">Railsconf 2008</a> opened earlier today. According to the site, there will be more advanced-level sessions this year, which is definitely a good thing. Last year was a fantastic experience, but it felt like I was constantly stumbling into sessions where the subject matter was a bit too noob-centric (thank goodness for the <span class="caps">IRC</span> peanut gallery).</p> <p>Of course, that said, as with all conferences, the discussions you get into in the hallways and after hours are usually more beneficial than any session you could ever attend anyway. But still, I’m really hoping sessions are labeled with a suggested experience level this year.</p> <p>Am I going? Honestly don’t know. I’d like to. It’s really an amazing thing to see 1500+ Ruby developers all descending upon one location at one time. That spectacle alone is probably worth the price of admission. Plus, the microbrews in Portland are top-notch. I’m guessing it will sell out, so I better make up my mind sooner rather than later. How about you?</p> Nick Plante NHRuby 2008 2008-01-14T00:00:00-05:00 2008-01-14T00:00:00-05:00 <p>The Seacoast NH Ruby <span class="caps">SIG</span> (<a href="">NHRuby</a>) will hold it’s first meeting of 2008 tomorrow, Tuesday January 15th in Portsmouth. I’ll be talking about <a href="">OpenID</a> and <a href="">Scott Garman</a> will be doing an overview of some funky stuff he’s doing with ActionMailer. Check out the <a href="">Wiki</a> for directions and other goodies, as usual. Hope to see you there!</p> <p>I also want to send a quick congratulatory note to Scott, who launched his Rails-based startup <a href="">CampaignLever</a> a few weeks ago. CampaignLever is a tool to help grassroots organizations build effective letter writing campaigns. Nice work man!</p> Nick Plante Storing YAML in YAML Fixtures 2008-01-10T00:00:00-05:00 2008-01-10T00:00:00-05:00 <p>If you ever find yourself in a situation where you have an attribute value that needs to be serialized (stored as <a href=""><span class="caps">YAML</span></a>) and used within a (<span class="caps">YAML</span>) fixture, you can do something like:</p> <pre><code>FancyWidget: id: 1 name: FancyWidget serialized_hash: "<%= {:abc => {:xyz => 'foo'}}.to_yaml %>"</code></pre> <p>Or, if you want to embed <span class="caps">YAML</span> directly you can do:</p> <pre><code>FancyWidget: id: 1 name: FancyWidget serialized_hash: | --- :abc: :xyz: foo</code></pre> <p>This is probably old hat to a lot of you, but I figured I’d doc it here since the solution felt somewhat non-obvious at first. Rails stores serialized attributes in your database this way, so you might run into this if you’re using ActiveRecord’s <a href="">serialize</a> method.</p> Nick Plante Coworking Jealousy 2008-01-06T00:00:00-05:00 2008-01-06T00:00:00-05:00 <p>I’m calling it now: <a href="">Coworking</a> spaces are the new startup incubator. No, I’m not talking about shared office space. No way. <a href="">It’s different</a>:</p> <blockquote> <p>Coworking is a movement to create a community of cafe-like collaboration spaces for developers, writers and independents.</p> </blockquote> <p>The whole concept feels very, very right to me. See, I don’t really want coworkers, just like I don’t really want a full-time ordinary run-of-the-mill 40 hour/week job; I’d rather be sharing a space with 4-10 other self-motivated similarly-minded freelancers, who split their days between client work, personal startuppy ideas, and <span class="caps">OSS</span> projects. Especially ones that can hack some mean code, or who have a sick artistic bent.</p> <p>Of course, you need a critical mass to make something like this work, and people who can commit to participation. Those can be hairy obstacles. Coworking spaces usually develop in larger cities because, hey, they have the ecosystem to support it. The numbers are on their side. <a href="">San</a> <a href="">Francisco</a>, <a href="">Washington DC</a>, <a href="">Boston</a> and <a href="">Seattle</a> all have fairly well known coworking spaces. There are a number of entries at <a href="">pbwiki</a> for small cities, but for the most part, those links are just people who are <strong>interested</strong> should something become available.</p> <p>Man, I’m jealous. I want a coworking space in my city. Hrmm.</p> Nick Plante Reading List Update 2007-12-29T00:00:00-05:00 2007-12-29T00:00:00-05:00 <p>So I updated this blog from <a href="">Mephisto</a> 0.7.3 to the latest <a href="">trunk</a> yesterday and I’m happy to report that the process was 100% painless. Edge has a number of nice nuggets missing from 0.7.x, which is over a year old at this point. In any case, thanks to Rick and the rest of the Mephisto team for the smooth upgrade path. I can’t wait for 1.0, which I hear is rumored for a January release ;-).</p> <p>While I was in the blog tweaking mood I also decided to install the <a href="">mephisto_feedreader plugin</a> and wired it up to display my <a href="">shared items</a> from <a href="">Google Reader</a>. This replaces the static “reading list” that was previously in the sidebar. I scan / read a good number of blogs, probably too many, and I often tag 2-3 things a day on average that I feel are useful / interesting / irreverent. Sharing is good and I have <a href="">nothing to hide</a>. For great justice!</p> Nick Plante Holiday Gifts: Ruby 1.9 2007-12-26T00:00:00-05:00 2007-12-26T00:00:00-05:00 <p>Happy holidays everybody. In case you haven’t heard, <a href="">Ruby 1.9</a> was released yesterday. If you’re not exhausted from overeating and traveling, I’d encourage you to spend a few minutes taking it for a spin.</p> <p>Ruby now runs on top of <span class="caps">YARV</span>, and <a href="">these benchmarks</a> indicate that there are some pretty impressive performance increases over 1.8.6. That said, 1.9 is a <strong>development release</strong>; it’s not currently intended for production use and don’t expect Mongrel or Rails (or various other gems) to run on it just yet.</p> <p>For more information, Dave Thomas has written a nice, concise <a href="">list of pros and cons</a> over on his blog, and Mauricio Fernandez has been maintaining a <a href="">full list of changes</a> found in 1.9. Enjoy!</p> Nick Plante DataMapper 0.2.5 Released 2007-12-21T00:00:00-05:00 2007-12-21T00:00:00-05:00 <p>Sam released <a href="">DataMapper</a> 0.2.5 on Wednesday. It includes a bunch of tasty bugfixes before our next leap to 0.3.×. Give it a try if you haven’t, I think you’ll like it. And if you don’t, well, you’re… whatever.</p> <p>One of the changes that I’m particularly fond of is proper method visibility for properties:</p> <pre><code>class Person < DataMapper::Base property :ssn, :private => true property :login, :protected => true property :name property :address</code> <code> has_many :dogs belongs_to :alien_overlord end</code></pre> <p>The private and protected options are really just shortcuts for (`:reader => :public, :writer => :private`) and (`:reader => :public, :writer => :protected`), respectively. In most cases you’ll want your reader to be public, but if you want to apply the same visibility modifier to both reader and writer, there’s an ‘:accessor’ option too. The property visibility is respected for mass assignment, which is a nice natural way to do things imo, unlike the hacky <a href="">attr_protected</a> stuff in ActiveRecord, which never felt right to me.</p> <p>In any case, we’ve also updated the <a href="">Website</a> and <a href="">Getting Started</a> page, which was a little out of date. See those links for installation instructions and feel free to pop into the `#datamapper` channel on <span class="caps">IRC</span>, hit up the mailing list, or even leave blog comments here if you have any issues.</p> <p>Other important changes (see the changelog for a complete list):</p> <ul> <li>`MyModel#[]` only accepts a primary key now, not an options hash (use first, all)</li> <li>`database.get` (equivalent to AR’s `find_by_id`) is approximately 25% faster than before!</li> <li>Persistence module added (you no longer have to inherit from DM::Base, although I still prefer this approach)</li> <li>You can now set indexes with `:index => true` and `:index => :unique`</li> <li>Validatable gem now used for handling validations</li> </ul> Nick Plante To REST Or Not To REST... 2007-12-18T00:00:00-05:00 2007-12-18T00:00:00-05:00 <p>Assaf Arkin is right, and I stand corrected. <a href="">SimpleDB</a> ain’t RESTful. Hell, it’s not really even GETSful. But it sure sounds nice when they put it in the marketing literature. Sigh.</p> <p>From <a href="">Subbu’s blog</a>: “The technology powering SimpleDB is definitely impressive [..] However, as a <span class="caps">REST</span> <span class="caps">API</span>, it is a disappointment. The <span class="caps">API</span> failed (a) to identify resources, and (b) to specify operations on resources in a RESTful way. It uses a single verb <span class="caps">GET</span> to create, delete, update, or get data from the store.”</p> <p>In any case, Assaf whipped up <a href="">DeHorrible</a>, a Rails proxy that appropriately RESTifies (GETStifies) SimpleDB. lol.</p> <p>I’m still psyched about the SimpleDB announcement, and looking forward to trying it out, but I really wish Amazon would clean up their supposedly RESTful APIs. Yes, I’m looking at you, Flexible Payments.</p> <p>Is it really that hard?</p> Nick Plante Links for 12.17.07 2007-12-18T00:00:00-05:00 2007-12-18T00:00:00-05:00 <p>Some git goodies, updates to both Rails and Merb, and other stuff this week. Here’s the breakdown:</p> <ul> <li><a href="">Evan Williams</a> writes about how to evaluate a new product idea<</li> <li><a href="">Giston</a> — a piston lookalike for git</li> <li><a href="">Gitosis</a> — host and manage a git repo, with access control, easily/safely…</li> <li><a href="">RSpec 1.1 is Released</a> — with support for Rails 2.0.1+ and the new RSpec story runner (!)</li> <li><a href="">Rails 2.0.2 is Released</a> — includes sqlite3 as the new default database and an important fix for RubyGems 0.9.5</li> <li><a href="">Merb 0.4.2 is Released</a> — performance enhancements, etc.</li> </ul> Nick Plante SimpleDB is RESTful & Schema-less? 2007-12-16T00:00:00-05:00 2007-12-16T00:00:00-05:00 <p>So the big web service of the week announcement goes to Amazon, for their <a href=""><span class="caps">AWS</span> SimpleDB</a> hosted service. This should place nicely with EC2, which is an interesting service except for the fact that persistent data across sessions is problematic (every time you boot an EC2 node it’s a clean slate).</p> <p>So what is SimpleDB? It’s:</p> <ul> <li>Built in Erlang (wow, maybe Erlang is worth learning after all, right?)</li> <li><strike>RESTful</strike>(see comments); <span class="caps">API</span> returns <span class="caps">XML</span></li> <li>Schema-less</li> <li>Non-relational</li> </ul> <p>Wait, what? Schema-less? Non-relational? Yup. In case you haven’t noticed, there’s been a groundswell of interest in this area lately… Perhaps most buzz-worthy is the <a href="">CouchDB</a> project, which also uses <span class="caps">REST</span> for inserts and queries, storing your data in schema-less databases which Amazon confusingly refers to as “domains” (see <a href="">other differences</a>). CouchDB is pretty neat, and all the cool kids seem to like it. <a href=""><span class="caps">RDDB</span></a> has similar goals. And then there’s <a href="">DBSlayer</a>, which takes the approach of wrapping a <span class="caps">REST</span> <span class="caps">API</span> around traditional relational databases (MySQL, etc).</p> <p>So why the interest in moving away from traditional <span class="caps">RDBMS</span>, which have served us well for so many years? Simplicity. Ease of scaling. The emphasis on removing business logic from the database and keeping it in the application, where it belongs. At least, those are the arguments. I’m no expert, but I’m certainly interested. Assaf Arkin summarizes the argument much better than I can, and his article <a href="">Read Consistency: Dumb Databases, Smart Services</a> should be required reading for anyone who’s interested in the future of (dumb) databases on the web. Assaf also has a follow-up <a href="">article on the merits of CouchDB</a>, specifically. There’s a lot to think about here.</p> <p>Of course, another key value prop with the Amazon service is that it’s <strong>hosted</strong>. By Amazon. They claim it’s fast and reliable (they should know a thing or two about that), and it looks to be relatively <a href="">inexpensive</a>, when you consider that the alternative is clustering your own databases for the same kind of speed and reliability. It’ll be interesting to see how this turns out and I’m anxious to play around with it.</p> <p>All that said, there’s no Ruby library wrapper for SimpleDB yet. However, as Chad Fowler notes, <a href="">there are already three different projects registered with RubyForge</a>. None of them have checked in even a single file as of this writing, but you know that somebody out there is hard at work (hint hint), and I’m sure you’ll see it before too long. Alternatively, you can build one yourself.</p> <p>Me? I’ve already got too much on my plate this week. And I still have to get that DataMapper cheat sheet done, too.</p> <p>/me apologizes again</p> <p>/me goes outside to shovel snow</p> Nick Plante NetBeans: Helpful Plugins 2007-12-13T00:00:00-05:00 2007-12-13T00:00:00-05:00 <p>So, <a href="">NetBeans 6.0 Final</a> was released a few weeks ago. v6.0 is all about the Ruby love, right out of the box. If you haven’t tried it, I implore you to give it a shot. Even if you’re not a fan of traditional “heavyweight” IDEs, I think you’ll be impressed with what they’ve done. There’s even a slimmed-down Ruby-only version. But sometimes, I must admit, I still miss the power and (relative) simplicity of vim.</p> <p>I’m in the process of re-reading The Pragmatic Programmer, and was just pawing through the passage on “power editing”, in which Dave and Andy suggest that you “choose [one] editor, know it thoroughly, and use it for all editing tasks”. For me, that editor is most definitely vim. I’ve used it for quite some time, it’s familiar, I don’t even have to think about the keybindings when I’m working in vi, and I’m spoilt by the easy text manipulations that just aren’t possible with some fancy graphical editing tools. I use vim for practically everything text-related.</p> <p>Everything, that is, except writing Java and Ruby code (and a few random tasks that <em>have</em> to be performed in a word processor, sadly). Yep, you read that right. I use vim for sysadmin tasks, hacking quick scripts, editing config files, and even taking notes, but lately I haven’t been using it where I’d probably see the single largest productivity boost from it.</p> <p>Since switching to NetBeans, my comfort level with having all the tools I need in one place has increased dramatically, including things such as easy access to a console, in-<span class="caps">IDE</span> debugging, test output, solid class introspection, integrated rdocs, and so on. But I also realize that I’ve been doing myself a bit of a disservice when in “heavy edit” mode. Fortunately, that’s easily fixed, as there’s a vi plugin for NetBeans. <span class="caps">YES</span>. No idea why I didn’t bother to search for something like this before.</p> <p>So in any case, if you’re interested, you can retrieve the NetBeans plugin from the <a href="">jVi homepage</a>. The file named <em>nbvi-<span class="caps">FOR</span>-NB-RC1-1.1.2.×6</em> is the one you want (as of this writing, anyway). Once you’ve downloaded the package, you can install it in NetBeans by going to tools => plugins. Choose the downloads tab, click ‘add plugins’, select the vim core and keybindings plugins, install them, and be happy. Thanks guys, this is so awesome.</p> <p>Oh and speaking of plugins, here are a few other helpful Ruby-related plugins for NetBeans that you may be interested in. Most of them are available through the plugins browser built into the <span class="caps">IDE</span>.</p> <ul> <li>Rspec Support (nice!)</li> <li>Ruby dark pastels color scheme (hrmm looks familiar…)</li> <li><a href=""><span class="caps">HAML</span> and <span class="caps">SASS</span> plugin</a> (if that’s the way you roll)</li> <li>Extra Source Code Hints</li> </ul> Nick Plante Emerging Technologies Conference 2008 2007-12-09T00:00:00-05:00 2007-12-09T00:00:00-05:00 <p>I really enjoy the technology conference ritual, make it a point to get to at least a few every year. I particularly enjoy the smaller regional conferences. Where else can you (a) get exposure to new technologies, (b) meet the smart hackers who created your favorite <span class="caps">OSS</span> tools, © get away from home for a long weekend, and (d) get schooled at <a href="">werewolf</a>, all at the same time?</p> <p>Alas, with winter upon us, it appears that the 2007 conference circuit is winding down. That means it’s time to look forward to… Why, the 2008 conference circuit, of course!</p> <p>The Third Annual <a href="">Emerging Technologies for the Enterprise Conference</a> has been announced; it will be held in Philadelphia, March 26-27th. Last year they had some great talks by high-profile Rubyists such as David Black, Geoff Grosenbach, and Amy Hoy. Rod Johnson, father of the Spring framework, also gave a talk last year.</p> <p>This year, Floyd Marinescu of InfoQ will be giving one of the keynotes. Obie Fernandez and Peter Armstrong (the author of <a href="">Flexible Rails</a>, which I’m really looking forward to reading) have already been announced as Ruby community speakers.</p> <p>Got something worth talking about? Tracey asked me to note that there’s an <a href="">open call for presenters</a>. The submission deadline is 1/7/08.</p> <p>Dates for <a href="">RailsConf</a> (5/29-6/1), <a href="">Mountain West RubyConf</a> (3/28-3/29) and GoRuCo (4/26) have already been announced as well. Feel free to mention any other interesting events that I’ve omitted in the comments!</p> Nick Plante Rails 2.0 Released 2007-12-07T00:00:00-05:00 2007-12-07T00:00:00-05:00 <p>It’s official; <a href="">Rails 2.0 was officially released this morning</a>. Gem update rails to snag it. There’s some great stuff in there, if you haven’t been keeping track, including further augmentation to RESTful conventions, multiview, <span class="caps">HTTP</span> authentication, sexy migrations, and on and on and on.</p> <p>You can read all about it <a href="">here</a> and also make sure to check out the <a href="">feature summaries</a> that Ryan Daigle has put together as well as the series of <a href="">Railscasts</a> Ryan Bates has been doing on the new features. Thanks for the hard work everyone.</p> Nick Plante Links For 12.05.07 2007-12-06T00:00:00-05:00 2007-12-06T00:00:00-05:00 <p>Waiting at <span class="caps">IAD</span> for a connecting flight home (en route from Beijing). It’s snowing. That means delays. I’m tired. But at least I have some time to catch up on blog reading and link posting. Here’s the rundown of goodies on my reading list atm:</p> <ul> <li><a href="">A Quick Jaunt Through Merb’s Framework Code</a> — essential reading for anyone looking to get started with Merb.</li> <li><a href="">NetBeans 6.0 Final</a> is officially released — Best Ruby <span class="caps">IDE</span> on the planet imo, nice to see it finally finished and out there.</li> <li><a href="">A Great Interview with Tor Norbye</a> of the NetBeans team — and the difficulties of doing proper Ruby type inference</li> <li><a href="">Loic Le Meur’s Ten Rules For Startup Success</a> — common sense of course, but good reading</li> <li><a href="">Setting Up a New Rails App with Git</a> — good getting started tutorial if you haven’t yet switched over</li> <li><a href="">Rodrigo Kochenburger</a> has a new blog — he’s a smart cat so make sure to add him to your feed reader</li> </ul> Nick Plante Software Development 2.0 China 2007-11-29T00:00:00-05:00 2007-11-29T00:00:00-05:00 <p>Today I’m in Beijing, attending the <a href=""><span class="caps">CSDN</span>-Dr. Dobb’s Software Development 2.0</a> conference. It’s my first time in China and it’s quite an honor to be here. I’ll be giving a Ruby on Rails overview and code analysis talk as part of tomorrow afternoon’s session. Looking forward to talks by Andrei Alexandrescu, Tenni Theurer, Dan Theurer, Jonathan Palley and of course DDJ’s own <a href="">Jon Erickson</a>.</p> Nick Plante Links For 11.24.07 2007-11-24T00:00:00-05:00 2007-11-24T00:00:00-05:00 <p><img src="" style="float: right;"/></p> <ul> <li><a href="">JRails</a> – Drop-in JQuery replacement for Rails prototype/script.aculo.us helpers.</li> <li><a href="">NetBeans 6.0 RC2</a> – Available for download.</li> <li><a href="">Gemtacular</a> – Rate and Review Ruby Gems.</li> <li><a href="">LiveConsole</a> – IRb over <span class="caps">TCP</span> remote console. Cool idea.</li> <li><a href="">Google TV?</a></li> <li><a href="">Rake tasks for QueryTrace</a></li> <li><a href="">Rails 1.2.6</a> – Includes an important security fix. gem update rails -y</li> </ul> Nick Plante Ruby Method Visibility 2007-11-22T00:00:00-05:00 2007-11-22T00:00:00-05:00 <p>In Java (and most OO languages), declaring a method as <strong>private</strong> means that the method can only be accessed within the context of the defining class. Similarly, <strong>protected</strong> means that the method can only be accessed from that class or any of its subclasses.</p> <p>In Ruby, things are a bit different. Both private and protected methods can be called by <em>any instance</em> of the defining class and its subclasses. Inheritance plays absolutely no role in determining the visibility of a method. The difference instead is that private methods can never be called with an explicit receiver, even if the receiver is <code>self</code>. This means that it’s not possible to access another object’s private methods, even if the object is of the same type as the caller. A private method <em>must</em> be called from within the calling object.</p> <p>Consider the following example:</p> <pre><code>class Person def public_method "public" end</code> <code> protected def protected_method "protected" end</code> <code> private def private_method "private" end end</code> <code>class SalesPerson < Person def check_protected_method_explicit_receiver "#{self.protected_method} method OK with explicit receiver" rescue "failure accessing protected method with explicit receiver" end</code> <code> def check_protected_method_implicit_receiver "#{protected_method} method OK with implicit receiver" rescue "failure accessing protected method with implicit receiver" end</code> <code> def check_private_method_explicit_receiver "#{self.private_method} method OK with explicit receiver" rescue "failure accessing private method with explicit receiver" end</code> <code> def check_private_method_implicit_receiver "#{private_method} method OK with implicit receiver" rescue "failure accessing private method with implicit receiver" end end</code></pre> <p>The public method can of course be accessed from anywhere (in this case, outside the class with an explicit receiver) and both private and protected methods of <code>Person</code> will obviously raise a <code>NoMethodError</code>.</p> <pre><code>Person.new.public_method => "public" Person.new.private_method => NoMethodError: private method `private_method' called for #<Person:0x6ec698> Person.new.protected_method => NoMethodError: protected method `protected_method' called for #<Person:0x6ea5c8></code></pre> <p>So the protected method cannot be accessed outside of the class or it’s subclass, but from within the subclass, using it with either an implicit or explicit receiver works fine:</p> <pre><code>SalesPerson.new.check_protected_method_explicit_receiver => "protected method OK with explicit receiver" SalesPerson.new.check_protected_method_implicit_receiver => "protected method OK with implicit receiver"</code></pre> <p>The private method can also be called from the subclass, but note how it only works with an implicit receiver:</p> <pre><code>SalesPerson.new.check_private_method_explicit_receiver => "failure accessing private method with explicit receiver" SalesPerson.new.check_private_method_implicit_receiver => "private method OK with implicit receiver"</code></pre> <p>This also means you can do stuff like:</p> <pre><code>class Person def ==(other) protected_method == other.protected_method end end</code> <code>x = SalesPerson.new y = Person.new x == y => true</code></pre> <p>We’re accessing the <code>protected_method</code> of another class instance that shares our type here, specifying an explicit receiver. If you were to try to use <code>private_method</code> instead, a <code>NoMethodError</code> would be raised. You could also just call <code>other.send("private_method")</code> if you really wanted to, violating our encapsulation and angering the gods of object orientation. This is only a “little sin” though, and can be permissible if the situation calls for it (like, cough cough, my latest commit to DataMapper).</p> <p>In summary, method visibility and access control can be a bit confusing at first, especially if you’re coming over to Ruby from some other OO language. If you’re still confused, there’s more information available <a href="">here</a> and <a href="">here</a>. Do yourself a favor and make sure you understand, cuz it’s important stuff!</p> Nick Plante Steinbeck on Ruby? 2007-11-21T00:00:00-05:00 2007-11-21T00:00:00-05:00 <h4>“Syntax, my lad. It has been restored to the highest place in the republic.”</h4> <div align="right"><strong>— John Steinbeck</strong></div> Nick Plante Book Review: Practical Ruby Gems 2007-11-17T00:00:00-05:00 2007-11-17T00:00:00-05:00 <p>I’ve been meaning to start posting book reviews for some time now. I don’t really have a good excuse as to why I haven’t, so I’ll spare you the overly verbose excuses and get right to the good stuff.</p> <p>The first book in my stack is David Berube’s <a href="">Practical Ruby Gems</a>. Before diving into it I should note that Dave is a friend of mine and that I’m currently working on a book with him for Apress. My opinions here are, of course, my own.</p> <p.</p> <p <span class="caps">RSS</span> news archiving service built using ActiveRecord and FeedTools. Both practical and well-dissected in the text, this sort of thing is sure to help new Ruby developers grasp the concepts for re-use in their own developments.</p> <p>The chapters on creating and distributing gems (with Rubyforge, gem_server, etc) are short and to the point. The one omission, from my point of view, is that Dr Nic’s <a href="">New Gem Generator</a> isn’t mentioned as a resource for bootstrapping gem structure. This is an invaluable tool for creating new gems.</p> <p.</p> Nick Plante Turn On Your Buzzword Filter 2007-11-13T00:00:00-05:00 2007-11-13T00:00:00-05:00 <p>BigLove [12:37am]: my eyes crossed from all the buzzwords zapnap<br/> zapnap [12:38am]: turn on your buzzword filter. <span class="caps">OMFG</span> <span class="caps">WHERE</span> <span class="caps">DID</span> T EH <span class="caps">INTERNETS</span> GO?</p> Nick Plante Digital Comics, Unlimited 2007-11-13T00:00:00-05:00 2007-11-13T00:00:00-05:00 <p>I’m not ashamed to admit that I’m a bit of a comic book geek.</p> <p>When I was a kid, I was a hardcore fanboy who spent pretty nearly all his paper route money on weekly trips to the local comic shop in Dover. I have no apology for that. As a technology geek also, I’ve built a social comic book pull list organizer that <a href="">has yet to officially launch</a> (we’re looking for someone who’s excited about comics and community building, no techie skills required, email me if you’re interested!) and I’ve done a little ancillary plugin work for the geeky folks over at <a href="">Heavy Ink</a> too.</p> <p>These days I buy mostly graphic novels, but I’ve always loved the feel of a floppy, and back when I used to buy titles monthly, there was just something unspeakably awesome about ‘new comic book day’ and the excitement of pouring through the stacks in a local shop looking for that one key back issue…</p> <p>Like most fans, I have mixed feelings about the digitization of comics. On one hand, I’d probably read a lot more of them if they were available (ahem, legally of course) through a cheap, easy to use digital distribution service like iTunes. On the other hand, I’m sort of glad this hasn’t happened, because it would kill a lot of the allure of it for me if the comics on paper were to become a thing of the past.</p> <p>I imagine I’m not the only one who was both excited and, at the same time, just a little tiny bit bummed about the <a href="">announcement</a> of <a href="">Marvel Comics Unlimited</a> yesterday (<em><span class="caps">NOTE</span>: as of right now the site appears to be down for maintenance, coming soon</em>). The basic premise is that Marvel will offer an online archive of over 2500 back issues online in high-resolution format, starting at about $5/mo. They’re also making a free sampler of 250 titles available to wet your appetites.</p> <p>Marvel’s hedging their bets a little though, which is smart. New issues won’t appear on the Marvel Unlimited site until six months after their initial print publication. This is great for those of us who read graphic novels, and aren’t used to picking up books every week anyway, and it keeps the floppies in circulation. After a bit of consternation, I’ve decided that it’s pretty much a win/win. Of course, as it always is on the web, the user experience will determine the ultimate success or failure of the venture. The flash-based digital comics I’ve seen from Marvel up to this point haven’t exactly been the most pleasant things to read, so here’s to hoping this is an entirely new interface to the library.</p> <p>Anyway, I’m looking forward to reading more about this, both as a comic book enthusiast and as a technologist. Welcome to the 21st century, comic fans. For better or for worse.</p> <p>It’s about time, I guess!</p> Nick Plante OS X Leopard Upgrade Notes 2007-11-11T00:00:00-05:00 2007-11-11T00:00:00-05:00 <p>Starting this blog entry to document any possible gotchas I experience on my upgrade to OS X 10.5. So far everything has been relatively clean. My only problem as of this writing has been with <span class="caps">SSH</span> and <a href="">MacPorts</a>. I have <span class="caps">SSH</span> installed via MacPorts and I noticed when doing any SVN+SSH operations, I was getting the following error:</p> <pre><code>percent_expand: NULL replacement svn: Connection closed unexpectedly</code></pre> <p>Hmm, looks like Leopard is expanding some <span class="caps">SSH</span> environmental variable to <span class="caps">NULL</span>. An easy fix is to add the following line to your <em>~/.ssh/config</em>:</p> <pre><code>IdentityFile ~/.ssh/id_rsa</code></pre> <p>This overrides the default search for your private key, and therefore you don’t get the percent_expand error. If anyone has more information about this particular issue, please let me know. Thanks!</p> Nick Plante Links For 11.10.07 2007-11-10T00:00:00-05:00 2007-11-10T00:00:00-05:00 <p><img src="" style="float: right;"/></p> <ul> <li><a href="">FreeBSD 7.0</a> is is going to own scaling. Srsly. RC1 should be available this week.</li> <li><a href="">Rails 2.0 RC1</a> is here. Have you fixed those deprecation warnings in 1.2.5 yet?</li> <li><a href="">Heroku</a> is coming next week. Holy crap those screencasts are cool. So the future of building and hosting webapps looks a lot like Seaside, eh?</li> <li><a href="">More Heroku coverage</a> and commentary by Giles Bowkett.</li> <li><a href="">The Great Merb Speedup</a>. Keep your eyes peeled for 0.4.1, things in this camp keep getting better and better.</li> <li><a href="">Interesting critique of OpenSocial</a> from Tim O’Reilly.</li> <li><a href="">Google’s OpenSocial <span class="caps">API</span> Blog</a>, because it’s the new hotness.</li> <li><a href="">Using OpenSocial with Ruby on Rails</a>, because hey, you’re curious, right?</li> </ul> Nick Plante NH Ruby Next Monday Night 2007-11-09T00:00:00-05:00 2007-11-09T00:00:00-05:00 <p>As Scott notes over on <a href="">his blog</a>, this month’s <a href="">NH Ruby</a> meeting will be off by a week and a day this time around, due to holiday stuff. Instead of the third Tuesday of the month, it’ll be the second <em>Monday</em>. Yessir, that’s this coming Monday.</p> <p>My good friend <a href="">Dave Berube</a> will be the main speaker, and he’ll be discussing reporting techniques with Ruby and Rails. Dave is putting the finishing touches on a <a href="">new book</a> on the subject, so he knows of that which he speaks. It’s sure to be a good conversation and if you’re in the area, you should definitely check us out.</p> Nick Plante Flexible Payments With Rails & REST 2007-11-09T00:00:00-05:00 2007-11-09T00:00:00-05:00 <p>Anyone who’s been playing around with the original Rails version of the <a href="">Amazon Flexible Payments Service</a> sample application has probably spent a fair amount of time swearing and complaining about how incredibly un-idiomatic and ugly it is. I know I have. It’s not that we don’t appreciate Amazon wanting to play ball with us, it’s just that it’s… well… it’s damn ugly.</p> <p>But wait, a few weeks ago, a new <span class="caps">REST</span>-based Rails sample app was posted. This time around it’s a far more basic “hello world”-ish app, but it’s much more idiomatic and clean, a far better starting place for anyone who wants to learn how to make pay calls with <span class="caps">FPS</span> using Ruby and Rails. It’s also thankfully devoid of soap4r dependencies.</p> <p>Just thought I’d note that, in case you’re working with <span class="caps">FPS</span> and haven’t stumbled upon it yet.</p> <p>In related news, there’s a RubyForge project for a library called <a href="">Remit</a>, which purports to be a proper Ruby <span class="caps">API</span> wrapper for <span class="caps">FPS</span>. <a href="">Tyler Hunt</a> is the developer who’s registered the project and is working on it. With no updates since <a href="">early September</a> though, and no files released, I wonder if the project hasn’t maybe been aborted? Tyler, if you’re out there, give a shout and let us know if you need a hand.</p> Nick Plante Merbivore! 2007-11-07T00:00:00-05:00 2007-11-07T00:00:00-05:00 <p><a href="">Merb 0.4</a> was released earlier today, and the men of Montreal were thus elated. For those that are unfamiliar with it, Merb is a Ruby <span class="caps">MVC</span> web framework not unlike Rails, but focused more on speed and minimalism. It’s a lot like a thread-safe closer-to-the-metal reimplementation of ActionPack. This also means it’s <span class="caps">ORM</span> agnostic (big, big win) and JavaScript library agnostic. Plugins are just gems (dependency management ftw), and it’s fast and easily extensible. If you haven’t used it before, now’s the time to get started!</p> <pre><code>gem install merb -y</code></pre> <p>The release announcement on <a href="">Ezra’s blog</a> has a nice summary to some of the more significant improvements, and links to more in-depth coverage. Along with the gem update comes a brand spankin new website, <a href="">merbivore.com</a> to boot. Congrats guys, on what looks like a huge leap forward. I can’t wait to dig in tomorrow.</p> Nick Plante Drop A PID For Monit 2007-11-06T00:00:00-05:00 2007-11-06T00:00:00-05:00 <p>If you ever need to drop a pid from a Ruby process it’s dead simple:</p> <pre><code>File.open('myapp.pid', 'w') { |f| f.write(Process.pid) }</code></pre> <p>Now you can use <a href="">Monit</a> to keep Sinatra alive, for instance ;-). Monit is great for monitoring UN*X processes and keeping them running under ideal conditions, and that means <a href="">it’s great for Mongrel, and anything that runs through Mongrel</a>. Monit can even check the memory consumption of your application and restart it if it seems to be leaking. Not that <em><strong>that</strong></em> ever happens, of course.</p> Nick Plante I Am Not A Freeloader 2007-11-06T00:00:00-05:00 2007-11-06T00:00:00-05:00 <p>So have you heard the new <a href="">Radiohead</a> album yet? What did you think? And more importantly, what did you pay for it? ComScore estimates that 2 out of 5 of you did. They released a study today suggesting that, during the month of October, <a href="">40% of visitors were willing to pay an average of $6.00 for the digital downloads</a>. Click that link for the full details. It’s also interesting to note that US consumers were will to pay more, on average, than the rest of the world.</p> <p>The <a href="">press</a> is having a <a href="">field day</a> with <a href="">this</a>, and opinions are mixed. The ‘glass is half empty’ point of view seems to be that, holy crap, there are a lot of freeloaders on the ’net.</p> <p>No kidding, really?</p> <p>On the other hand, the ‘glass is half full’ folks point out that, hey, people are actually willing to pay for stuff, and that music on the ’net still has a perceived value after all.</p> <p>I’m siding with the latter camp. Official sales figures won’t be released until after the holidays, but shit, I think these initial estimates are fantastic. Moreover, I think they show tremendous potential for non-compulsory tipping for digital goods in the public space. Software and media piracy is only a problem because of how we perceive and hope to profit from selling media on the web. Labels don’t need a new type of <span class="caps">DRM</span>, they need a new approach to what they’re selling. It’s information, and once that information is out there, it’s free, regardless of how much you perceive it’s worth to be. Magazine publishers figured this out a while back, and make their money through online advertising.</p> <p>What Radiohead has done is adapt, and prove that, at least to some extent, a donation-driven model can work here. Of course, public radio beat them to the punch by at least 50 years, and they’re not the first band to sell music online, but it certainly signals a big win for those of us who believe that all web users aren’t freeloading scum. Even if the average user <em>is</em> a freeloader, the point is that the band can make <em>enough</em> from their efforts such that producing art for public consumption is profitable.</p> <p>Anyway, the average worldwide price for all downloads, including freeloaders, was $2.26. I’d love to know what the bands’ actual per-album net was on their previous album, 2003’s Hail To The Thief. I’d be shocked if it was much higher than, say, $6.00 (<em>update:</em> <a href="">this article</a> estimates that it was probably between $3 and $5 <span class="caps">USD</span>). Personally I paid about $7 <span class="caps">USD</span>.</p> <p>Oh, and the album is pretty good too.</p> Nick Plante Clone Pastie in 15 Minutes with Sinatra & DataMapper 2007-11-05T00:00:00-05:00 2007-11-05T00:00:00-05:00 <p>Hey there, put on your tutorial hat. <span class="caps">ORM</span> package.</p> <p><a href="">Sinatra</a>, on the surface, is a lot like <a href="">Camping</a>, <span class="caps">ORM</span>-agnostic, instead of being married to ActiveRecord like both Rails and Camping are. For more information, <a href="">check out the ‘official’ tutorial</a>.</p> <a href="">great summary of why DataMapper rocks</a>. Read it. Oh, and performance kicks ass now too.</p> <p>OK, anyway. Tutorial time. Found your plastic hat? Good. Let’s go. First let’s get the gems we’ll need. As of this writing, DM is at v0.2.3 and Sinatra is at v0.1.7. We’re also going to retrieve the <a href="">Syntaxi</a> gem, which we’ll use for syntax highlighting.</p> <pre><code>sudo gem install sinatra datamapper json syntaxi -y</code></pre> <p>Since DM uses the <a href="">DataObjects.rb</a> drivers, you’ll want to install them. They’re packaged with the distribution. For our purposes here we’re going to assume you’re on MySQL but all the standard drivers are there, so don’t fret. Change to your DM gem directory (mine is <em>/opt/local/lib/ruby/gems/1.8/gems/datamapper-0.2.3</em>) and issue the following command. Ignore any warnings that are generated. If you’re on OS X 10.5, you may want to check out <a href="">Heimidal’s blog</a> for instructions.</p> <pre><code>sudo rake dm:install:mysql</code></pre> <p>Now that our prerequisites are satisfied, let’s get started by creating the file <em>toopaste.rb</em>:</p> <pre><code>require 'rubygems' require 'sinatra' require 'data_mapper' require 'syntaxi'</code> <code>### SETUP</code> <code>DataMapper::Database.setup({ :adapter => 'mysql', :host => 'localhost', :username => 'root', :password => '', :database => 'toopaste_development' })</code> <code>### MODELS</code> <code>class Snippet < DataMapper::Base property :body, :text property :created_at, :datetime property :updated_at, :datetime</code> <code> validates_presence_of :body validates_length_of :body, :minimum => 1</code> <code> Syntaxi.line_number_method = 'floating'</code> <code> def formatted_body html = Syntaxi.new("[code lang='ruby']#{self.body}[/code]").process "<div class=\"syntax syntax_ruby\">#{html}</div>" end end</code> <code>database.table_exists?(Snippet) or database.save(Snippet)</code> <code>### CONTROLLER ACTIONS</code> <code>layout 'default.erb'</code> <code># new get '/' do erb :new, :layout => 'default.erb' end</code> <code># create post '/' do @snippet = Snippet.new(:body => params[:snippet_body]) if @snippet.save redirect "/#{@snippet.id}" else redirect '/' end end</code> <code># show get '/:id' do @snippet = Snippet.find(params[:id]) erb :show, :layout => 'default.erb' end</code></pre> <p>Next we’ll dissect this code listing to give you a feel for how Sinatra and DataMapper work, and show the code listings for our views as we get to them.</p> <p:</p> <pre><code>mysqladmin -u root -p create toopaste_development</code></pre> <p.. <span class="caps">OMG</span> I don’t have to put comments in my source file to remind me what attributes are available on my models?!</p> <pre><code>property :body, :text property :created_at, :datetime property :updated_at, :datetime</code></pre> <p>It’s like a little slice of heaven, isn’t it?</p> .</p> <pre><code>database.table_exists?(Snippet) or database.save(Snippet)</code></pre> <p>The formatted_body method is simple.> <p.</p> <p <span class="caps">URL</span> patterns.</p> <pre><code>get '/' do erb :new, :layout => 'default.erb' end</code></pre> <p>The first action displays a form to create a new paste, and it’s always available at ‘/’, your application root. Note that it’s a <span class="caps">GET</span> request. The body of this action renders the new.erb template, which should be in your views/ subdirectory. Instead of pulling in an external template, you could just stash your <span class="caps">HTML</span> inline here. This may work fine for dirt-simple applications but I prefer to keep it separate. Here’s that first view, <em>/views/new.erb</em>:</p> <pre><code><div class="snippet"> <form action="/" method="POST"> <textarea name="snippet_body" id="snippet_body" rows="20"></textarea> <br/><input type="submit" value="Save"/> </form> </div></code></pre> <p>The next action is analogous to a #create RESTful applications with it.</p> <pre><code>post '/' do @snippet = Snippet.new(:body => params[:snippet_body]) if @snippet.save redirect "/#{@snippet.id}" else redirect '/' end end</code></pre> <p.</p> <p>If our post is successful, we’re going to be taken to the #show action, which lives at /:id, where :id is the primary key of the corresponding database record. This action will also get accessed directly when you paste that <span class="caps">URL</span> to the chat room, and people click to view your code.</p> <pre><code>get '/:id' do @snippet = Snippet.find(params[:id]) erb :show, :layout => 'default.erb' end</code></pre> <p>In the code listing above, we look up the particular snippet specified in params[:id] and set an instance variable. We then render an ERb template, which of course has access to that instance variable. Here’s the code you’ll want in <em>/views/show.erb</em>:</p> <pre><code><div class="snippet"> <div class="sbody" id="content"><%= @snippet.formatted_body %></div> <div class="sdate">Created on <%= @snippet.created_at.strftime("%B %d, %Y at %I:%M %p") %></div> <br/><a href="/">New Paste!</a> </div></code></pre> <p>If you’ve been paying attention you’ve noticed that both of our erb method calls (used to render an embedded ruby <span class="caps">HTML</span> view, you can also use <a href="">haml</a>) have specified a layout. That layout does the sorts of things a layout usually does; it sets up the page body, the title of the page, the styles, and so on. For completeness’ sake, we’ll list it here:<> <p>Save that listing as <em>views/default.erb</em>. The rendered page content will be inserted into this layout where it yields. And that’s pretty much it. You can fire up your new Sinatra and DataMapper-powered application by issuing the following command:</p> <pre><code>ruby toopaste.rb == Sinatra has taken the stage on port 4567!</code></pre> <p>Sinatra sits on top of <a href="">Mongrel</a>,.</p> <p>If you like, you can <a href="">play with the finished app</a> or <a href="">download the sources</a>. Enjoy, and please comment if you have any problems or suggestions for improvement. This code was written and tested on OS X 10.4 and Debian Etch.</p> <p><strong><span class="caps">UPDATED</span> 07/02/08:</strong> I finally got around to updating this tutorial for DataMapper 0.9.2. About time, eh? Click <a href="">here</a> to see the new version.</p> Nick Plante Blog Updates 2007-11-01T00:00:00-04:00 2007-11-01T00:00:00-04:00 <p>So I finally got around to migrating the blog site over to <a href="">Mephisto</a>. I’ve only been planning on doing that for like 9 months. Horray for progress!</p> Nick Plante Links For 10.30.07 2007-10-31T00:00:00-04:00 2007-10-31T00:00:00-04:00 <p><img src="" style="float: right"/>Not-so-random things you need to know about:</p> <ul> <li><a href="">New Ruby Logo Unveiled</a></li> <li><a href="">NetBeans 6.0 Beta 2 Released</a></li> <li><a href="">Datamapper <span class="caps">ORM</span></a> (add Merb, stir, & bake at 300 for gooey goodness)</li> <li><a href="">Git + Sinatra Web Framework</a> (great screencast!)</li> <li><a href="">Using MacPorts Ruby and Rails after Upgrading to OS X Leopard</a></li> <li><a href="">Microplace</a> (eBay-backed microfinance on Rails)</li> <li><a href="">Google OpenSocial</a> to Launch on Thursday?</li> </ul> Nick Plante Startupping Contests 2007-10-30T00:00:00-04:00 2007-10-30T00:00:00-04:00 <p>So Ty and I submitted our startup project’s pitch to the <a href="">Amazon Startup Challenge</a> last night. Wish us luck!</p> <p>The idea (currently implemented as a working prototype, albeit with a number of rough edges) has to do with <a href="">micropatronage</a>, a concept that is near and dear to my heart. In a nutshell we believe that content authors should be rewarded for their efforts, and we think we’re on to a way to make that fun and rewarding for patrons too.</p> <p>It’s something we’ve been developing on and off for months now, in between various other client gigs and open source initiatives. We have no illusions about being chosen (although it sure would be nice if we were!), but if nothing else the contest has given us the kick in the butt that we needed to get back on track with it and formalize a number of principles in writing. Writing things down, and trying to explain them to people whom you’ve never met before, always helps to clarify your vision. It’s quite amazing, really.</p> <p>Anyway, I love seeing contests like this, even when I don’t win (which is most of the time). I thoroughly enjoyed my role as an organizer of the Rails Rumble event we ran in September, and I look forward to similarly-minded events like the upcoming <a href="">BlitzWeekend</a> (hi Heri!), and even the more VC-involved “contests” like <a href="">Seedcamp</a> and of course <a href="">Y Combinator</a>.</p> <p>I particularly enjoy following startup contests and events where creativity is a key factor; where instead of just implementing a common spec to see who can do it fastest or “best”, teams are actually challenged to invent something totally new, implement it, throw it against a wall and see if it sticks. Hey, now that’s entrepreneurial; it’s brave, it’s somewhat reckless (in it’s purest form, anyway), and it’s a great way to hatch new disruptive ideas in front of a live audience.</p> <p>Some of the projects will be great, most of them will suck, but everyone will learn something. It’s important to remember, too, that the “winning” team won’t necessarily be the long term winner — it’s a distance running event, not a short sprint. In the end, it’s all about development — and I mean that in the personal growth sense, not in the geeks-behind-glass sense.</p> <p>Of course, you don’t need a contest or money or really anything at all to go invent something new, especially these days when launching a company doesn’t cost anything more than the skills, free time, and a <span class="caps">VPS</span>. But sometimes a little extra motivation goes a long way.</p> Nick Plante JQueryCamp Is Tomorrow! 2007-10-26T00:00:00-04:00 2007-10-26T00:00:00-04:00 <p>For anyone who’s registered (and presumably in or around the greater Boston area), don’t forget that <a href="">JQueryCamp</a> is tomorrow! I’ll be there, and looking forward to talks by John Resig, Yehuda Katz (whom I probably owe a beer), and many others.</p> Nick Plante Git Your Learn On 2007-10-22T00:00:00-04:00 2007-10-22T00:00:00-04:00 <p>Any post about Git pretty much mandates the use of some lame pun in the title, and this blog entry is no exception. For those of you who are as-of-yet unfamiliar with it, <a href="">Git</a> is a distributed version control system created by Linus Torvalds. It’s been around and usable for about a year now, but I’d only been peripherally aware of it until <a href="">recently</a>.</p> <p>In the past I’ve just used it to check out and occaisionally toy with the latest <a href="">Rubinius</a> sources but now that the <a href="">Offtrac</a> project is using it, it finally looks like I’m going to have to start familiarizing myself with it beyond installation and cloning a remote repository. If that sounds negative it isn’t meant to be; I enjoy being forced to learn new things every once in a while. Srsly.</p> <p>[To be honest I’m still relatively happy with Subversion, but hey, when I started using Subversion I was still at least relatively happy with <span class="caps">CVS</span> too. No wait, scratch that, I hated <span class="caps">CVS</span>.]</p> <p>Anyway, for those of you out there like me who are just getting acquainted with Git and particularly those who are stumbling over the implications of the <em>distributed</em> part of <em>distributed version control</em>, Carl Worth has written a useful <a href="">getting started guide</a> that you should definitely check out. Of course there’s the <a href="">official user guide</a> too.</p> <p>In practice, normal usage really isn’t as different as it seems, and the concept of a distributed repository is a truly powerful one. Everyone has commit access to <em>their own local branch</em>, which means most operations are fast, and the centralized who-gets-commit-rights question becomes a total non-issue. That’s very very cool. Oh, and no .svn folders littered in every folder is another nicety. The jury’s still out for me as of right now, which is to say I’m not rushing to switch all my existing Subversion projects over just yet. But I have to say, I’m very intrigued so far.</p> Nick Plante 718-123-2083 2007-10-22T00:00:00-04:00 2007-10-22T00:00:00-04:00 <p>Someone rings my cell phone at 7AM this morning and asks “is this Nicholas”? I answer “yes”, because well, that’s my name. Then they hang up.</p> <p>Apparently <a href="">I’m not the only one</a> this has happened to. Isn’t it good to know that there are communities for just about everything on teh Interwebs, including strange paranoia-inducing phone spam? But just who the fsck are these people anyway, and what in the world was the purpose of that? Sigh.</p> <p>In unrelated but positive news, the Sox destroyed the Indians last night 11 to 2, winning the <span class="caps">ALCS</span>. Yes, I am a fair weather fan.</p> Nick Plante Where's Nap? 2007-10-12T00:00:00-04:00 2007-10-12T00:00:00-04:00 <p>Things have been kind of crazy lately, and blog updates have been few and far between. Sorry about that, it’s not that I’ve run out of things to say. Honest.</p> <p>The truth of the matter is I’ve just been really busy with a couple client projects, and some other goodies that I’ll (hopefully) be writing about soon. And oh, yeah, I’m getting married this weekend too ;-).</p> <p>So actually, the answer to the titular question is Martha’s Vineyard, where my lovely wife-to-be and I are renting a house for the week. It’s great to get away from (almost) everything for a little while.</p> Nick Plante Rails 2.0 Preview Release Available 2007-10-01T00:00:00-04:00 2007-10-01T00:00:00-04:00 <p>Check it out: a <a href="">Preview Release</a> of Rails 2.0 was made available yesterday. Things are “almost finished” and this is an opportunity for folks (who haven’t been following edge closely) to get a taste of what’s new before the final release. To install the gem:</p> <pre><code>gem install rails --source</code></pre> <p>Or you can freeze edge using the tag “rel_2-0-0_PR”. Make sure to check out that post (linked above) to read about all the good stuff.</p> <p>Note that 1.2.4 will also be released prior to 2.0 and will include a variety of bugfixes as well as the final deprecation warnings for upgrading an application to 2.0. Big thanks to the whole core team (and all the contributors) for their excellent work.</p> Nick Plante Presenting @ Ruby East 2007-09-28T00:00:00-04:00 2007-09-28T00:00:00-04:00 <p>I’m going to be at <a href="">Ruby East</a> on — oh wow, I’m already here. Hrmm, well nevermind then. Obviously things have been much too busy for pro-active blog entries lately. Sorry about that.</p> <p>In any case, if you’re here, make sure to hang around until the end to see my Rails Rumble talk, which will include announcing the winners. We’ll also be showing some of the team screencasts, in order to demonstrate just how much you can accomplish with Ruby in a very short amount of time. Should be a fun way to close out the event.</p> <p>If you’re not lucky enough to be attending this great little regional conference, the winning teams will also be announced on the <a href="">Rumble Blog</a> sometime later today. Great work everyone.</p> Nick Plante NetBeans 6.0 Beta 1 Available 2007-09-19T00:00:00-04:00 2007-09-19T00:00:00-04:00 <p>NetBeans 6.0 Beta 1 is out and ready for download, including a slimmed-down Ruby-only version for those of you who don’t want all the extras. Personally I like having one <span class="caps">IDE</span> for both Java and Ruby but hey, I’m special. As I’ve written about before, I’m quite smitten with NetBeans and this latest release is the best yet. If you’re curious about why I’m gushing over it, read <a href="">here</a>, <a href="">here</a>, and <a href="">here</a>.</p> <p>So yeah, it’s nice. Go <a href="">download 6.0 Beta 1</a> and give it a try. It’s packaged with <a href="">JRuby 1.0.1</a> and Glassfish v2, which is starting to look more and more attractive as a serious deployment option for Rails.</p> <p>PS: those of you who are frustrated with Goldspike may want to take a look at <a href="">Nick Sieger’s Warbler</a>, an alternative for packaging up your <span class="caps">WAR</span> files.</p> <p><span class="caps">PPS</span>: you don’t have to use JRuby as your interpreter of course. Just go to preferences → Ruby and point it at <span class="caps">MRI</span> (/usr/bin/ruby or whatever) if you don’t want / need / like JRuby. And then you can use the fast debugger too. Inline Ruby debugging rocks.</p> Nick Plante Rock The (Rumble) Vote 2007-09-15T00:00:00-04:00 2007-09-15T00:00:00-04:00 <p>We launched the Voting portion of the Rails Rumble on Thursday evening, and so far it’s been a tremendous hit. Almost 4000 unique votes have been recorded in less than two days. If you check out <a href="">vote.railsrumble.com</a> you can view the current top 10 ranked applications as well as a smattering of random entries.</p> <p>I want to reiterate once again that I’ve been overwhelmed with the creativity and polish that are reflected in a lot of these entries. Many of them look like the teams spent two months instead of two days. I’m not going to name any names, but I definitely have my list of favorites.</p> <p>So anyway, get off your butt, register to vote, and help the community choose the best 48-hour app! You don’t even have to go down to the local high school or anything. Woot! The voting period lasts two weeks, and wraps up on the 27th, after which winners will be announced at the <a href="">Ruby East</a> conference. Maybe I’ll see you there?</p> Nick Plante Overlooking The Obvious 2007-09-14T00:00:00-04:00 2007-09-14T00:00:00-04:00 <p>Sometimes we overlook the obvious. This had me scratching my head for a good 15 minutes yesterday. I’ll blame it on the plague (aka nasty cold) that I seem to have contracted.</p> <pre><code>>>> monday = Time.now.beginning_of_week => Mon Sep 10 00:00:00 -0400 2007 >> monday.strftime(format) => "Monday, September 10 2007" >> (monday+6.weeks).strftime(format) => "Monday, October 22 2007" >> (monday+12.weeks).strftime(format) => "Sunday, December 02 2007"</code></pre> <p>Huh? Exactly 12 weeks from Monday is Sunday? <span class="caps">WTF</span>?</p> <pre><code>>> monday + 12.weeks => Sun Dec 02 23:00:00 -0500 2007 >> (monday + 12.weeks).dst? => false >> monday.dst? => true</code> <code>Three letters: <a href="">D S T</a>. Heh. </code></pre> Nick Plante Can You Feel The Rumble? 2007-09-08T00:00:00-04:00 2007-09-08T00:00:00-04:00 <p><img src="" style="float: right;"/>So the <a href="">Rails Rumble</a> is on! We’ve worked pretty hard to hook this up and it’s great to see it alive and breathing, and #railsrumble buzzing with activity. There were some capacity issues at first (ouch!) but things seem to be going pretty smoothly now.</p> <p>Greets to Carter Parks, Rodrigo Kochenburger, and Erin & Tommy Shine, who all poured a lot of precious blood into this beastie. And our friends Chris Aker and Tom Asaro at <a href="">Linode</a>. And our other sponsors too, of course. Oh, and best of luck to all the Rumblers. Launch some cool-ass web properties and win some swag, guys! Hope you’ve got plenty of Red Bull to keep you caffeinated.</p> <p>Me? I’m going to bed. See you tomorrow in <span class="caps">IRC</span>.</p> Nick Plante Moving to Nginx and Cap2.0 2007-08-27T00:00:00-04:00 2007-08-27T00:00:00-04:00 <p>So a few months back I started using <a href="">nginx</a> on my staging server, front-ending for Mongrel, and just recently I’ve stated migrating some production stuff over to it. It’s pretty great as a lightweight Apache replacement. Incredibly simple syntax, very quick and close to the bone. Most of my production stuff still runs on Apache, but that may soon be changing. I also finally made the leap to <a href="">Capistrano 2.0</a>. Loving the new namespaced task hierarchy.</p> <p>Anyway, here’s a simple alternative maintenance page recipe for Capistrano’s deploy:web:disable target and the corresponding Nginx config to make use of it. In case you’re unfamiliar with it, the disable web task basically redirects all requests to a maintenance page until deploy:web:enable is run, which returns things to normal. This recipe assumes you’ve created your own (static) maintenance.html page in public/maintenance.html and that it makes use of existing stylesheets and images — meaning that you don’t want to rewrite those requests.</p> <p>in config/deploy.rb:</p> <pre><code>namespace :deploy do desc "Disable requests to the app, show maintenance page" web.task :disable, :roles => :web do run "cp #{current_path}/public/maintenance.html #{shared_path}/system/maintenance.html" end</code> <code> desc "Re-enable the web server by deleting any maintenance file" web.task :enable, :roles => :web do run "rm #{shared_path}/system/maintenance.html" end end</code></pre> <p>in nginx.conf (within your server block definition):</p> <pre><code># allow requests for images, js, css, and icons to go through # even if cap has been used to disable the site if ($request_filename ~* /(images|javascripts|stylehseets)/) { break; } if ($request_filename ~* \.ico$) { break; }</code> <code># for cap's deploy:web:disable task if (-f $document_root/system/maintenance.html) { rewrite ^(.*)$ /system/maintenance.html last; break; } </code></pre> Nick Plante NHRuby: Shoes. And Belts. And You! 2007-08-21T00:00:00-04:00 2007-08-21T00:00:00-04:00 <p>If you’re in the greater NH/Maine/Mass seacoast area, don’t forget to check out tomorrow’s <a href="">NHRuby</a> group. Sir Brian DeLacey will be visiting us from Boston and talking about <a href="">Shoes</a>, the Ruby desktop UI toolkit from the ever-enigmatic <a href="">_why</a>.</p> <p>If there’s time left to spare, I’ll probably spend some time blathering on about how you should participate in the upcoming <a href="">Rails Rumble</a>. Believe me, after seeing some of the prizes, you’re going to want to get in on the action. I was dead f**king serious about that championship belt. You’ll see.</p> Nick Plante NetBeans Rocks 2007-08-17T00:00:00-04:00 2007-08-17T00:00:00-04:00 <p>NetBeans really is the <span class="caps">BOMB</span>, as <a href="">Charles Nutter</a> notes over on <a href="">his blog</a>. Check out that link. I wanted to make sure I echoed his thoughts here, because for me, NetBeans really is the best Rails <span class="caps">IDE</span> on the planet. I switched over from IntelliJ some time ago and haven’t regretted it even briefly.</p> <p>I really can’t say enough things about NetBeans. What other <span class="caps">IDE</span> makes it painless to debug (yes debug, within the <span class="caps">IDE</span>), refactor, and test your Ruby applications? Plus, the syntax highlighting is rockin and you get all the standard NetBeans goodness out of the box. Don’t want a huge download? No big deal, there’s a <a href="">slimmed-down Ruby-only version</a> available. Give it a shot. Even if you’re a hardcore Textmate geek, I think you’ll at least be able to see why I’m raving about it.</p> Nick Plante Get Ready To Rumble 2007-08-10T00:00:00-04:00 2007-08-10T00:00:00-04:00 <p><img src="" style="float: right;"/>So like everyone else, you probably have a killer web app idea you’ve been sitting on. Maybe you’ve thought about building it, maybe you’ve even drawn out some diagrams on the back of a napkin, but you just haven’t found the time to execute it. The unfortunate reality is that sometimes you just need an excuse, or a little push, to get something awesome started.</p> <p>Sound about right? Then this one’s for you. Enter the <a href="">Rails Rumble</a>, September 8-9, and consider yourself pushed.</p> Nick Plante Ruby, Rails, Micropayments, and Amazon FPS 2007-08-08T00:00:00-04:00 2007-08-08T00:00:00-04:00 <p>Last week Amazon unveiled a beta of their new <a href="">Flexible Payments Service</a>, a potential Paypal-killer and Google Checkout-killer, among other things. At first glance, <span class="caps">FPS</span> seems to be everything that Paypal isn’t: well designed, <span class="caps">API</span>-centric, and built with developers in mind.</p> <p>While everyone is busy barking about how Amazon is going to go head to head with Google Checkout and Paypal for purchases, they seem to be missing the more interesting development here. I’m talking about something that neither Paypal or Google are even attempting to do, as far as I know: micropayments.</p> <p>Ty, Steve, and I spent some serious time putting together a few different iterations of an idea/prototype earlier this year, that involves micropayments and the street performer protocol. And some other stuff, too :-). Unfortunately, when it came time to tie it into a payment gateway, it became painfully obvious that what we needed didn’t really exist, so we compromised. And that compromise led to a bunch of problems and eventually what we felt was an unworkable solution. So it’s been in mothballs since. This looks like it could be what we were maybe waiting for.</p> <p>If you check out Amazon’s rate schedule you can see why I’m excited:</p> <blockquote> <p>For Amazon Payments balance transfers < $0.05: <br /> 20% of the transaction amount, with a minimum fee of $0.0025</p> </blockquote> <p>OK, OK, so 20% is a hefty fee but not when we’re talking about the alternative being somewhere in the neighborhood of $0.30 <span class="caps">USD</span> + 2-3%. So yeah, pfft. This is <span class="caps">HUGE</span>. And yes, it does look like these micropayments only work when you’re using Amazon payments (as opposed to using a credit card, etc) but so what? I’m not so sure that’s an obstacle.</p> <p>Another reason it’s so interesting to me is that they’ve decided to support three languages/platforms in their initial beta rollout: Java, <span class="caps">PHP</span>, and yes, my friends, Ruby. Oh, and the <a href="">sample app</a>? Yep. Rails.</p> <p>Why aren’t we more excited about this?</p> Nick Plante Impressed With Comatose CMS 2007-07-24T00:00:00-04:00 2007-07-24T00:00:00-04:00 <p>Often after I’m finished building the bulk of a web app, I find there are some secondary pages that need to be built. These pages are largely informational, such as an about page, a contact page, an <span class="caps">FAQ</span>, etc. They’re relatively static in terms of the content, but it’s always nice if we can supply our client (or ourselves) with a nice <span class="caps">CMS</span>-style interface to make updating them easy, and within the context of our existing application layouts. Keep it simple, keep it <span class="caps">DRY</span>.</p> <p>The obvious thing is to cook up some sort of PagesController from scratch. This is nice because it’ll make use of your existing facilities, your authentication/authorization system, layouts, etc. It is custom, after all, and a custom fit is almost always the best fit. But it’s a fair bit of work for something that’s probably not ‘core’ to the application, and takes cycles away from other places they could be better spent.</p> <p>On the other hand, you can integrate with a 3rd-party <span class="caps">CMS</span> or blogging package like Typo, Radiant <span class="caps">CMS</span>, or Mephisto. They’re all great packages and do what they do really well. The downside is you’ve got to write a fair amount of glue to hook everything together and make it look (and feel) uniform.</p> <p>Another option is to use Matt McCray’s <a href="">Comatose</a> plugin, a micro <span class="caps">CMS</span>. It’s got all the basic functionality you want for this sort of stuff out of the box and it couldn’t be much easier to use. The real bonus is integration is almost completely seemless, which makes it (imho) the best of both worlds for this sort of project.</p> <p>Installing the plugin gets you a ComatoseController and a ComatoseAdminController. You add an entry (or multiple entries, if you like) in your routes file to tell your application when to invoke the ComatoseController. You might prefer a scheme where all URLs starting with /pages are passed to Comatose, for example. Then you log into the admin controller (which also needs an entry in routes) to create the pages. All the basic management tools we need are here; pages are organized hierarchically and can be edited with great ease, using a variety of markup filters. Each page gets a number of attributes, including a title, keywords, author, etc.</p> <p>Basically it’s everything we need for the bare-minimum no-frills <span class="caps">CMS</span> experience and nothing we don’t. Which is just the way I like it. Check it out for your next project.</p> <p><em><span class="caps">UPDATE</span></em></p> <p>Anyone having issues with Comatose and authentication should check out <a href="">this bug report</a>. If you’re specifying an alternate session key, you should put it in environment.rb instead of ApplicationController.</p> <pre><code>ActionController::Base.session_options[:session_key] = "_your_custom_session_id"</code></pre> <p>Comatose controllers inherit directly from ActionController::Base instead of from your application controller. So if you specify the session key in application.rb, the Comatose-driven sections of your app will be blissfully unaware of it. This means a method like logged_in? (which checks the session for your login status) will always report back as false.</p> Nick Plante Sidebar Login Box Recipe (restful_auth) 2007-07-13T00:00:00-04:00 2007-07-13T00:00:00-04:00 <p>One of the nice features of Rick Olson’s excellent <a href="">restful_authentication plugin</a> is the store_location facility. If you set up a :login_required before filter in your controller, the access_denied method will get called if the user isn’t logged in. The requested <span class="caps">URL</span> will be stored in the session and the user will be redirected to the login page. After logging in, redirect_back_or_default is called by SessionController#create, which pulls the location out of the session and redirects the user back to where they intended to go in the first place. Very slick.</p> <p>However, if you’ve built an application which has a login box in the sidebar (I recommend <a href="">simple_sidebar</a>), restful_auth has no idea where you were coming from before the post to the create action. So you get redirected to the default (usually ‘/’) specified as a parameter to redirect_back_or_default. This isn’t usually what the user expects. They expect to be returned to the page they were looking at before if they log in from the sidebar. Oh noes!</p> <p>Here’s a little recipe you can use to provide that…</p> <p>First, a simple change to authenticated_system.rb in your lib/ directory (this file is created by the authenticated generator). Change the store_location method to this:</p> <pre><code>def store_location(location = request.request_uri) session[:return_to] = location end</code></pre> <p>Before this change, store_location took 0 parameters and always set the return_to location to the current request <span class="caps">URI</span>. Now, we’ve modified it so it can (optionally) take the location to store as a parameter. If this parameter isn’t supplied, it defaults to the old behavior.</p> <p>Next, change the create method in your session controller so it checks the <span class="caps">HTTP</span> referer. Just add one tiny little line to the top of the method:</p> <pre><code>def create check_referer ... end</code></pre> <p>Now let’s write that check_referer method (it should be protected, not public):</p> <pre><code>def check_referer referer = request.env['HTTP_REFERER'] || "" if referer.match(request.domain) && !referer.match(session_url) && !referer.match(login_url) store_location(request.env['HTTP_REFERER']) end end</code></pre> <p>What this little utility method does is check the <span class="caps">HTTP</span> referer. If the referer is from the current domain, and isn’t the session#create <span class="caps">URL</span> or ‘/login’ (in my application, there’s a login_path named route), we go ahead and store the location of the <strong>referer</strong>. This will later be plucked out by redirect_back_or_default. Note that you’ll need to regex match to make sure the referer value isn’t anything you don’t want to store. For instance, if the user navigates to the login page directly and logs in from there, you don’t want to redirect <strong>back</strong> to the login page on success. You probably want to redirect to the default page, which is whatever you’re specifying as the default with redirect_back_or_default.</p> <p>So that’s it! An easy way to handle redirects from sidebar login blocks, without muddying the already elegantly designed redirects that happen when access is denied.</p> <p>If you want to write a functional test for this, try something like this:</p> <pre><code>def test_redirect_to_referer # for login sidebar location = url_for(:controller => 'foo', :action => 'index') @request.env['HTTP_REFERER'] = location post :create, :login => 'quentin', :password => 'test' assert_response :redirect assert_redirected_to location end </code></pre> Nick Plante Swing Reduction Sauce 2007-07-12T00:00:00-04:00 2007-07-12T00:00:00-04:00 <p>JRuby continues to develop in interesting ways. Earlier today, Zed Shaw (Mongrel’s dad) announced the release of <a href="">Profligacy 1.0</a>, which you should take a look at if you’ve got a thing for building cross-platform desktop apps in Ruby. It’s pretty cool.</p> <p>Profligacy is a (wildly extravagant?) library that purports to take the pain out of using Swing components with JRuby. It uses <span class="caps">LEL</span>, <a href="">Layout Expression Language</a>, to bring a sort of wiki-ish flavor to component layout. This is truly bizarre at first glance, but damn cool at the same time. Basically the Ascii art you lay out with <span class="caps">LEL</span> translates into a Swing GroupLayout. Ah-wha? Yep. Check out some <a href="">examples</a>. I told you it was cool.</p> <p>It also does some other neat stuff like auto-converting procs to Listener interfaces, but I won’t go on about that, as you can go check the release notes instead. If you’ve ever worked in Swing before, you know how painful it can be. Profligacy makes it significantly less bitter to swallow. Now stop reading blogs and go build your first cross-platform Ruby desktop app. You know you want to.</p> Nick Plante An Introduction to Scraping with Hpricot 2007-06-30T00:00:00-04:00 2007-06-30T00:00:00-04:00 <p>For one of my hobby projects, I’ve been building a comic book release schedule webapp in Ruby. Obviously, a large part of that involves locating data sources for comic book publishers and importing those sources. Unfortunately, none of the major publishers have seen fit to make their release schedules available in <span class="caps">RSS</span> or Atom or an other structured format for that matter. Sigh.</p> <p>Fortunately, all is not lost. With the Hpricot gem and a little scraping know-how, we can overcome almost any parsing obstacle, as long as the data is in a somewhat predictably arranged state. Let’s see how it works…</p> <p>For our example, we’ll consider <a href="">DC Comics</a>, home of Superman, Batman, Aquaman, and… <a href="">Super-Chief</a> (Apache Chief? No, he’s different). DC makes their weekly release schedule available through their website at <a href="">this <span class="caps">URL</span></a>. That’s nice and convenient. But it’d certainly be more convenient if they had a feed available. (If they <strong>do</strong> have a feed available, hidden deep within their website, and I haven’t found it, please let me know!)</p> <p>As we click through to next/previous weeks and it becomes pretty clear that passing the dat=<year><month><day> parameter gives you the appropriate listing. Note that they display a month at a time, so all you really have to do is ask for dat=<year><month>01 every time. We’re going to build a little scraper that just grabs the current months’ books, but armed with the knowledge of how this works, you should find grabbing 3-4 months worth of books at a time to be no challenge whatsoever (comic book publishers usually solicit about 3 months in advance).</p> <p>OK. So now let’s take a peep at the structure of the document itself. We can do this by just viewing source in a browser. It seems that every comic listed in the release schedule has a link to a full description of the issue, with a cover art previews, a short synopsis, writers/artists listed, etc. And every one of those links seems to have a <span class="caps">CSS</span> class of ‘contentLink’. Oh, lucky day.</p> <p>This is certainly starting to smell like a job for <a href="">Hpricot</a>, the super fast (and delightful!) <span class="caps">HTML</span> parser for Ruby, written by the enigmatic <a href="">why the lucky stiff</a>. Gem install that sucker!</p> <pre><code>gem install hpricot</code></pre> <p>Now let’s fire up IRb and chew on some delicious Ruby syntax:</p> <pre><code>require 'hpricot' require 'open-uri'</code> <code>THE</span> <span class="caps">ALL</span>-<span class="caps">NEW</span> <span class="caps">ATOM</span> #12 –<br /> <span class="caps">BATMAN</span>: <span class="caps">TURNING</span> <span class="caps">POINTS</span> –</p> </blockquote> <p>Each output line lists a title with a <span class="caps">URL</span>, for each comic solicited in a given month. How does it work? Well, first we open the <span class="caps">URL</span> and feed it into Hpricot. Then the line <em>books = (doc/“a.contentLink”)</em> uses a <a href=""><span class="caps">CSS</span> selector</a> to yank out just the elements that match the selector. We could have also used XPath-style syntax to accomplish the same thing. Anyway, those elements we’re selecting are all the links to comics being released this month. Hpricot hands us an array of these elements, and then we iterate over them, calling the read_comic function and passing it the title (the innerHTML of the link, stripped of excess whitespace), and the <span class="caps">URL</span> (an absolute link to the href attribute of the link).</p> <p>Next, let’s beef up the read_comic function to do something useful. We’ll have it make another remote connection, this time to the <span class="caps">URL</span> specified for the detailed comic description, parse out the talent, description, and some other information about the issue and stuff it into a model object. But first let’s examine the source of one of those pages. The <a href=" 7173">Trials of Shazam! #7</a> should do nicely.</p> <p>We note in our examination of the page source that the data we want to scrape is all contained in <span> tags, with different classes, as listed below. Note that this time we’ve chosen to use XPath-style syntax for the selectors. Note also that the span tag with class=“display\_copy” appears twice. The first time, it contains what appears to be the description of the issue, and the second time it lists the publication date. So instead of returning a single element, display\_copy gets an Array of 2 (or possibly more) elements.</p> <pre><code>def read\_comic(title, url) doc = Hpricot(open(url)) display\_talent = (doc/"span[@class=display\_talent]").innerHTML display\_copy = (doc/"span[@class=display\_copy]") # 2 elements puts "=====" puts "title: #{title}" puts "talent: #{display\_talent}" puts "copy (0): #{display\_copy[0].innerHTML} puts "copy (1): #{display\_copy[1].innerHTML} end</code></pre> <p>Now we’re iterating through each book from the remote source, and dumping out it’s title, the writer and artist responsible for it, a quick synopsis, and some other information (publication date, etc). Alright. If we just had a Comic model in our application, we could be somewhere!</p> <p>So let’s make one. In fact, let’s do it in Ruby, with ActiveRecord. First the schema:</p> <pre><code>DROP DATABASE IF EXISTS comics; CREATE DATABASE comics; USE comics;</code> <code>CREATE TABLE comics ( id int(11) NOT NULL AUTO\_INCREMENT, name VARCHAR(255), publisher VARCHAR(255), talent VARCHAR(255), description TEXT, published\_on DATETIME, PRIMARY KEY (id) );</code></pre> <p>Load this up and then add the following code to the top of your comics scraper. In fact, put it in a file called comics.rb so you can execute it on the command line.</p> <pre><code>require 'active\_record'</code> <code>ActiveRecord::Base.establish\_connection( :adapter => 'mysql', :host => 'localhost', :username => 'root', :password => '', :database => 'comics')</code> <code>class Comic < ActiveRecord::Base end</code></pre> <p>Now we’ve established a connection to the database via ActiveRecord and defined a Comic model that inherits from ActiveRecord::Base, thus wrapping our database schema and giving us some handy getters and setters. Our next step will be to trade in the read_comic function in favor of an import class method on the Comic model.</p> <pre>></pre> <p>When Comic.import receives a title and a <span class="caps">URL</span> it makes a connection to the <span class="caps">URL</span> specified and fires up Hpricot. It uses Hpricot to parse out the information we’re looking for, and then instantiates an instance of the Comic class. We set the talent, the description (the first of the display\<em>copy spans) and then parse the date out from the second display\</em>copy span.</p> <p>We’ll remove all the output from there and put it in the book loop, since it’s clearly not the job of the model code to be rendering a view of any sort. Our new book loop will use Comic.import on each element of the books Array, creating the model, saving it, and then printing out some attributes. Here’s the final code for comics.rb:</p> <pre><code>require 'rubygems' require 'active\_record' require 'open-uri' require 'hpricot'</code> <code>ActiveRecord::Base.establish\_connection( :adapter => 'mysql', :host => 'localhost', :username => 'root', :password => '', :database => 'comics')</code> <code>TRIALS</span> OF <span class="caps">SHAZAM</span>! #7 (OF 12)<br /> description: Freddy must find Hercules for his next trial, <br /> which is considerably more difficult than he expected, <br /> since Herc is behind bars!<br /> release date: 2007-06-13</p> </blockquote> <p>Obviously we can do a lot more with this. We can build a series model, that has_many issues or episodes. We can build a publisher model. We can suck in the images and use RMagick to generate thumbnails. We can discriminate between graphic novels, trade paperbacks, and issues of a standard series book. We can roll this into a Rails application, and allow the results to be browsable, users to add comics to their pull lists, create collections, comment on them, rate them, and so on. Actually, that’s exactly what I’m working on for my hobby project (if you’re interested, email me and I’ll let you take a look — I’m hoping to release it relatively soon-ish).</p> <p>To go further with scraping, we’ll need to pay particular attention to handling errors, because it’s an inexact science and, since we have no hard format, things are subject to change or break in weird ways. That’s the obvious downside to scraping. But when you have no other alternative for automating mass import of data like in this scenario, it’s certainly a good thing to know how to do.</p> <p>If you want to learn more, \_why’s Hpricot site is chock full of useful information, and you may also want to check out <a href="">scRUBYt</a>, which combines Hpricot and <span class="caps">WWW</span>::Mechanize into a full-on web scraping “toolkit”.</p> Nick Plante Thanks Akismet! 2007-06-22T00:00:00-04:00 2007-06-22T00:00:00-04:00 <p>I’m probably a bit behind the game on this one, but huge props are due to <a href="">Akismet</a> for making my blog life just a bit more pleasant. Before it was installed last week, I was deleting hoards of comment spam every day. Today, none.</p> <p>In other blog-related news, I’m still planning on moving productions over to Mephisto, but have been hard pressed for time lately. Fortunately (when I get around to it), it has Akismet support baked right in.</p> <p><em><span class="caps">UPDATE</span>: finally moved over to a new blogging platform! About time, eh?</em></p> Nick Plante Tumbleranting 2007-06-18T00:00:00-04:00 2007-06-18T00:00:00-04:00 <p><a href="">Seth Godin</a> is a nicer guy than I am (he’s probably better dressed, too): I would have ballparked <a href="">his quote</a> a little higher. Explanation: there’s a “don’t waste my time” fee.</p> <p>As a freelancer, this happens to me all the time and it’s muy frustrating. I like hearing ideas, I like helping you structure your approach, I love developing solutions, applications, tools for you. I don’t even mind giving estimates and free advice. But in order to do that, you need to tell me what it is you want.</p> <p>And no, “just like digg but with/for xxx” isn’t what I’m talking about :-).</p> Nick Plante JRuby / Goldspike / Glassfish Deployment Diary 2007-06-11T00:00:00-04:00 2007-06-11T00:00:00-04:00 <p>Robert Dempsey has written a pretty solid little <a href="">tutorial on deploying your first JRuby on Rails app with Glassfish</a>. It’s powerful stuff. Go read it now, damnit!</p> <p>The process can still be a bit tricky the first time, especially if you have additional gem dependencies, etc. But once you get it running you’ll be blown away by how simple it is to create a .war and deploy it to any of numerous pre-existing Java application servers (Glassfish).</p> <p>I had a few issues initially (particularly with openssl support), so I figured I’d document them as an addenum to Robert’s tutorial in case you’re interested. Read on to see my notes…</p> <ul> <li>Make sure to set JRUBY_HOME in your environment. It’s used by Goldspike.</li> <li>If both ruby and jruby are in your path, you can specify the ‘version’ of rake to use by doing: <em>jruby -S rake</em>. This will run the specific command in the JRUBY_HOME/bin directory.</li> <li>Edit the goldspike lib/war_config.rb and change the line that reference jruby-complete version 0.99 to read:</li> </ul> <pre><code>add_java_library(maven_library ('org.jruby', 'jruby-complete', '1.0'))</code></pre> <ul> <li>This will look for JRuby 1.0 instead of 0.9.9. As of this writing you’ll also have to manually retrieve <a href="">jruby-complete-1.0.jar </a> as the remote sources don’t seem to have it yet. Put it in JRUBY_HOME/lib.</li> </ul> <ul> <li>I happen to be using <span class="caps">SSL</span> in my app, so I had to gem install it into the JRuby environment using <em>jruby -S gem install jruby-openssl</em> Make sure the gem ends up in your JRUBY_HOME/lib/ruby/gems hierarchy. Tell goldspike it needs to add this gem with the following line: <em>add_gem(‘jruby-openssl’)</em></li> </ul> <ul> <li>If you’re doing the jruby-openssl thing you’ll also have to retrieve the latest version of the <a href="">Bouncy Castle Crypto APIs</a> package for whatever version of Java you’re using (I’m on OS X, Java 1.5). Put this in your JRUBY_HOME/lib directory and then add the library to your war_config.rb file:</li> </ul> <pre><code>add_java_library(maven_library('bouncycastle', 'bcprov-jdk15', '136'))</code></pre> <p><span class="caps">UPDATES</span>:</p> <ul> <li>Make sure to copy jdbc_databases.rake from ActiveRecord-<span class="caps">JDBC</span> to your lib/tasks directory (for ActiveRecord-related rake tasks). Thanks to Ola Bini for pointing me in the right direction there.</li> </ul> <ul> <li>Include the following in environment.rb:</li> </ul> <pre><code>if RUBY_PLATFORM =~ /java/ require 'rubygems' RAILS_CONNECTION_ADAPTERS = %w(jdbc) end </code></pre> Nick Plante JRuby Reaches 1.0 2007-06-10T00:00:00-04:00 2007-06-10T00:00:00-04:00 <p><a href="">JRuby 1.0</a> has been officially released. This is huge news. Complete compatibility with Ruby 1.8 is pretty much a done deal. Rails apps run. You can deploy your Rails apps in Glassfish. I mean, how cool is that?</p> <p>You should check out team member <a href="">Charles Nutter’s blog</a> for more details. In a nutshell, the future looks like tighter integration with Java as an application platform, and a major focus on optimizing performance. Also a lot of interest in Ruby 1.9/2.0. If you attended Railsconf this year, you most likely got pretty excited about JRuby, and for good reason.</p> <p>If you’ve never tried it out before, <a href="">Atlantic Dominion Solutions</a> has put together a great tutorial on getting started with JRuby on OS X. Or, even easier, go get yourself a copy of <a href="">NetBeans 6.0 M9</a>, which comes bundled with JRuby as the default interpreter for in-<span class="caps">IDE</span> development.</p> Nick Plante NHRuby Meeting Tuesday 06.12 2007-06-08T00:00:00-04:00 2007-06-08T00:00:00-04:00 <p>Usually the NHRuby meets are scheduled for the third Tuesday of the month, but we had to change it up this time due to some schedule conflicts.</p> <p>I’ll be speaking about integrating a Flash widget with Rails-based RESTful web services and also giving a brief overview of how to contribute to Rails and other open source projects (I guess you could say Josh Susser’s talk at Railsconf inspired me). <a href="">Scott</a> will be doing an overview of the tabnav plugin and… something else, too.</p> <p>More information and directions can be found at the <a href="">NHRuby Wiki</a>. Also, many thanks to our new host/sponsor for the meetings, <a href=""><span class="caps">RMC</span> Research</a>.</p> Nick Plante LOLCODE 2007-06-06T00:00:00-04:00 2007-06-06T00:00:00-04:00 [3:44pm] strager: <span class="caps">BUKKIT</span> is the array type. [3:44pm] zapnap: O <span class="caps">RLY</span>? Nick Plante has_much :confusion, :about => "string #{interpolation}" 2007-06-05T00:00:00-04:00 2007-06-05T00:00:00-04:00 <p>No matter how flexible ActiveRecord’s associations become, there’s always going to be a time when you want to override it’s baked-in smarts with your own custom <span class="caps">SQL</span> query. Fortunately, we can do just that with the :finder\_sql option. Use it to manually specify the association that should be returned.</p> <p>There’s one gotcha to be aware of though: if you need to do any variable interpolation in the string (and you most likely will), make sure to use single quotes instead of the usual doubles:</p> <pre><code>has_many :transfers, :finder_sql => 'SELECT * FROM transfers ' + 'WHERE sender_id = #{id} or receiver_id = #{id}'</code></pre> <p>When you use double quotes, the string interpolation happens immediately (when the class is first loaded), thus obtaining the object ID of the class in memory. Using single quotes, the interpolation occurs within the context of your object instance, which is what you’re expecting.</p> Nick Plante Caught In The Act 2007-05-31T00:00:00-04:00 2007-05-31T00:00:00-04:00 <p>Wow, <a href="">Google Street View</a> is totally great. And, as expected, some <a href="">funny shit</a> gets frozen in time at street level. Google is watching! Be cautious where you go, what you do! Try to remain calm, don’t <a href="">lose your head</a> over it.</p> Nick Plante ActiveRecord Delegation Pitfalls 2007-05-30T00:00:00-04:00 2007-05-30T00:00:00-04:00 <p.</p> <p>Here’s a simple example of delegation in action:</p> <pre><code>class User < ActiveRecord::Base has_one :homepage, :class_name => "Article" delegate :url, :to => :homepage end</code> <code>my_user.url => url of the home page article for this user</code></pre> <p.</p> <p>Here’s where we get into trouble:</p> <pre><code>new_user = User.new new_user.url</code> <code>NoMethodError: You have a nil object when you didn't expect it! The error occurred while evaluating nil.url</code></pre> <p>O <span class="caps">NOES</span>! What happened?</p> <p.</p> <pre><code>def #{method}(*args, &block) #{to}.__send__(#{method.inspect}, *args, &block) end</code></pre> <p>How can we get around this? Well, court3nay opened a <a href="">ticket</a> to address this a while back. It was recently closed due to inactivity. I just reopened it, and added a small patch. Here’s the difference in the way the mixin creates the delegated methods:</p> <pre><code>- #{to}.__send__(#{method.inspect}, *args, &block) + #{to}.__send__("nil?") ? nil : #{to}.__send__(#{method.inspect}, *args, &block)</code></pre> <p>Pretty simple really. We just test the delegation target to see if it’s nil first. If it is, we return nil instead of trying to send it a message. Otherwise, we call the method on the target object and let the receiver worry about it.</p> <p>Huzzah, we’ve successfully delegated the task of dealing with nil delegation targets! Way special, eh?</p> Nick Plante Sometimes It's The Little Things, pt 2 2007-05-26T00:00:00-04:00 2007-05-26T00:00:00-04:00 <p>So my first patch to Rails core was accepted yesterday. It’s a <a href="">tiny, tiny patch</a>. All it does is add a :method parameter to the auto_complete_field helper so you can do <a href="">RESTful autocompletion</a> (the filter query should be submitted with a <span class="caps">GET</span>, not a <span class="caps">POST</span>, if you want to follow the <span class="caps">REST</span> conventions).</p> <p>No big deal really, but it feels good to finally be able to “give back” to the community in a way other than blogging and <span class="caps">IRC</span> help. You know, with like, actual code that benefits people other than just me. I’ve contributed to a handful of Java and <span class="caps">PHP</span>-based <span class="caps">OSS</span> projects over the years, but this is officially my first contribution to a Ruby-based project, and that certainly feels like a step in the right direction.</p> Nick Plante Railsconf 2007 FTW 2007-05-21T00:00:00-04:00 2007-05-21T00:00:00-04:00 <p>Had a great time at <a href="">Railsconf 2007</a>! Just got back. A little jetlagged, and in need of (another) nap. In summary: lots of good presentations, <a href="">superb microbrews</a>, a hilarious <a href="">zefrank</a> performance, and a number of lurking lolcats.</p> <p>Highlights for me included DHH’s keynote, <a href="">the Rails way</a> ‘live’ performance by Jamis and Koz (although I have to politely disagree with them on the need for private ActiveRecord attributes), Ezra’s <a href="">deployment and scaling session</a>, and the homesteading talk by <a href="">Matthew Bass</a>. Thanks to everyone who helped make it happen.</p> <p>Also got to meet some fellow <span class="caps">IRC</span> peeps in person. Now ur tru idinty is nown to me, bewar!</p> Nick Plante Oregon 2007-05-16T00:00:00-04:00 2007-05-16T00:00:00-04:00 <p>So here I am in sunny Oregon. Around 1PM I hop on a train headed to Portland for <a href="">RailsConf</a> 07. Came out a few days early to catch up with my good buddy <a href="">Ty</a> in Eugene and work on the startup idea we’ve been banging around. And do some hiking, drinking, and dissecting of Heroes too, of course.</p> <p>I kind of love being out here and yet still having my internal clock set to east coast time. I wake up “early” for a change, and bang out a nasty chunk of work before anyone else here is even awake yet. Otoh, I feel like an old man when I begin to falter around 11PM. Heh.</p> <p>Anyway, I’m looking forward to the conference. I’ll be attending the tutorials day tomorrow, specifically the scaling session with Joyent’s Jason Hoffman as well as David Black’s ‘Routing Roundup’. If you see me, say hi.</p> Nick Plante Deconstructing date_select 2007-05-09T00:00:00-04:00 2007-05-09T00:00:00-04:00 <p>date_select and it’s friend datetime_select are handy little helpers for rendering date selection widgets in your form, but what they hand back to your controller is a little bit unintuitive. If you’re just going to go ahead and use update_attributes on your model, then ActiveRecord magically takes care of converting these to an appropriate Date or Time object for you. However, if you’re not doing that, you’ll find yourself staring at keys in your hash named odd things like “attribute(1i)”.</p> <p>Here’s a handy little helper method, in case you ever need to manually reconstruct a Date object from the params:</p> <pre><code># Reconstruct a date object from date_select helper form params def build_date_from_params(field_name, params) Date.new(params["#{field_name.to_s}(1i)"].to_i, params["#{field_name.to_s}(2i)"].to_i, params["#{field_name.to_s}(3i)"].to_i) end</code> <code>date = build_date_from_params(:published_at, params[:article])</code></pre> <p>Put this in your ApplicationController so inherited controller classes can access it, or (better yet) put it in a suite of helper methods to mix in to application.rb. Not exactly brain surgery here, but I’m a little surprised that there isn’t something already baked into the helpers to do this.</p> Nick Plante MyConfPlan: Check Me Out 2007-04-27T00:00:00-04:00 2007-04-27T00:00:00-04:00 <p><a href="">Dr Nic Williams</a> wrote a nice little app to allow folks to plot out the sessions they’ll be attending at <a href="">Railsconf</a> (or any conference, for that matter) and share them with others. In case you’re curious, check out <a href="">my tentative session list</a>.</p> <p>Some of those decisions are tough ones! In particular, I’d like to see both Nutter’s JRuby talk as well as Dan Webb’s javascript-fu presentation. I’d also like to attend both Matthew Bass’ homesteading talk as well as Brian Leonard’s Tooling/NetBeans session. Sigh, decisions decisions.</p> <p>Also of note: Dr Nic built MyConfPlan in <a href="">Hobo</a>, which seems to have come a long way since I last checked it out. Very cool stuff.</p> Nick Plante REST vs AutoComplete 2007-04-18T00:00:00-04:00 2007-04-18T00:00:00-04:00 <p>After struggling with it probably a little bit more than I should have, I’ve totally come around to the <span class="caps">REST</span> way of looking at things. It seems clean and nice, and I’m 100% behind it. That said, I’ve found that once you adopt the mentality, things that don’t gel with it start to stick out like the guy in the fur coat at the <span class="caps">PETA</span> meeting.</p> <p>Case in point: the ever-popular Rails auto_complete_field helper. To back up my accusation here, let’s walk through an example scenario with a <span class="caps">REST</span> app, and examine the issues that arise…</p> <p>Imagine a really simple web application which consists of a collection of Articles. The only user interaction is that guests can comment on articles and tag them with keywords. So in a RESTful world, we have an Articles resource, and a Tags resource. Tags are also nested on Articles such that when you ask for /articles/:article_id/tags you’re asking for the subset of tags which have been applied to article_id. We might present these as a tab you can click on when viewing an article resource in a browser.</p> <p>Now let’s say that there’s a form somewhere (maybe the #new action on an ArticleCommentsController), which can be used to apply new tags to a given article. There’s an auto_complete_field in that form, that will suggest tags to apply to an article, based on the tags that have already been applied. Dumb example, I know, but hear me out.</p> <p>So, given this scenario, it would make sense to point our auto_complete_field helper at article_tags_path(article_id). This is about as RESTful as it gets — we’ve become a client of our own <span class="caps">API</span>. Nice! Our #index action on ArticleTagsController, in a perfect world, would do a couple things above and beyond just displaying the pretty <span class="caps">HTML</span> list of tags on the article:</p> <ul> <li><strong>It would have a respond_to block.</strong> if a browser client is asking for <span class="caps">XHTML</span>, we probably want to render a nice paginated view of the relevant tags, ordered by weight, with a nice layout. On the other hand, if we’re asking for <span class="caps">XML</span> or <span class="caps">JSON</span>, it just returns no-frills data in the appropriate format.</li> </ul> <ul> <li><strong>it would optionally check for a filter query string.</strong> perhaps we set params[:filter] = :attribute_name and then make the actual string filter value (the thing we’re trying to help auto-complete) available via params[:attribute_name]. in the case of our tags example, we’d end up with a params hash that has filter=name and name=zer (or some other text string). If a filter parameter is found, we’d filter the results by the pattern specified. This could all be wrapped up in a nice little helper.</li> </ul> <p>This proposal raises a couple issues. First, the auto_complete_field helper as it exists today expects us to return some <span class="caps">HTML</span> from the <span class="caps">AJAX</span> call that we can plug into an appropriately named <span class="caps">DIV</span>. This is simple and works well, but if we’re really consuming our own web service, we should probably be talking to it via <span class="caps">JSON</span> or <span class="caps">XML</span> and have a JavaScript handler to process the results, converting them into list format or whatever it is that we desire. But I have to admit that this convenient hack works nicely.</p> <p>More importantly, if the auto-complete filter is being applied to the collection of resources, that means it maps to the #index action by way of a <span class="caps">GET</span> request. So our parameters end up encoded in the <span class="caps">URL</span> with a query string like ?filter=name&name=zer. Obviously, <span class="caps">GET</span> params are a little more limiting than <span class="caps">POST</span> params in terms of length and (perceived) security. But for simple filter strings that take a short sequence of characters, I don’t see this as being an issue. And this is always the case when doing an auto-complete, as far as I can figure.</p> <p>Note that the auto_complete_field JavaScript helper doesn’t actually allow you to specify an <span class="caps">HTTP</span> verb other than <span class="caps">POST</span>, although that’s easy enough to change. Surely the core team would accept the one-line fix required to support a :method => :get option if it’s the “right thing to do”. The real problem is more of a philosophical one: are we, as a community, really going to embrace <span class="caps">REST</span> 100% or is it acceptable to add small bits of cruftiness in places where it seems inconvenient?</p> <p>A perfectly legitimate half-way solution is to define a standard #autocomplete action for any resource you want to use in this manner. The advantage to this is that you can easily use a <span class="caps">POST</span> against a custom :collection method on the resource. That way, we continue to work inside the existing box of conventions. But I ask you, is that really RESTful?! What do you think?</p> Nick Plante NH Ruby UG Lightening Talks Tonight! 2007-04-17T00:00:00-04:00 2007-04-17T00:00:00-04:00 <p>Join us tonight at the Portsmouth Public Library for a bunch of lightening talks on Ruby-related subjects. I’ll be speaking on <span class="caps">REST</span>, Rake, and RMagick (if I can manage to put together a preso and demo app in time). <a href="">Scott</a> will be presenting a demo of his Rails-based ProgressPuppy task manager. And there will be other stuff, too.</p> <p>Note that we’re still doing the meeting, despite aftereffects of the nasty coastal flooding. Hardcore, eh? As always, more information (including directions) can be found at the <a href="">NHRuby Wiki</a>.</p> Nick Plante RailRoad Class Visualization 2007-04-10T00:00:00-04:00 2007-04-10T00:00:00-04:00 <p>Just saw <a href="">this InfoQ article</a> about RailRoad and had to check it out. Gotta say, this is by far the best class visualization tool for RoR I’ve seen yet. Set your options, generate those <span class="caps">DOT</span> files, and then run them through <a href="">GraphViz</a> to export your image format of choice. Couldn’t be easier.</p> <p>Check out some of the examples on the <a href="">RailRoad RubyForge site</a>, including the diagrams of the popular Depot example app and the much more complex Typo blog package. The latter is a good illustration of why the <em>brief</em> option is provided, heh. If you’re in the <span class="caps">UML</span> camp, you might be a little disappointed as the diagrams it produces are closer to <a href=""><span class="caps">BON</span></a>, but personally I think they’re very straightforward and natural.</p> <p>Whatever your modeling language preference is, I think we can agree that tools like this go a long way towards legitimizing Rails use in large multi-person projects and are, well, just plain helpful. Big thumbs up.</p> Nick Plante Paginating Associations 2007-04-10T00:00:00-04:00 2007-04-10T00:00:00-04:00 <p>It’s no real secret that the default Rails pagination helpers are kind of awful. Sure, you can use them, but I wouldn’t recommend it if you expect to scale. Instead, go snag yourself the wonderful <a href="">paginating_find</a> plugin. And then, if you’re going to be using them with your model associations, whip up an association extension like this:</p> <pre><code>module PaginationExtension def paginate(current = 1, size = 10, options = {}) options[:page] = {:current => current, :size => size} find(:all, options) end end</code></pre> <p>Now just extend the has_many association on your City class and you can call <em>city.bars.paginate(2)</em> to get the second 10-element page of bars associated with your city.</p> <pre><code>class City < ActiveRecord::Base has_many :bars, :extend => PaginationExtension end</code> <code>city.bars.paginate(2)</code></pre> <p>The good bars are all on the first page though, so consider yourself warned.</p> Nick Plante Rake: Ant Be Gone! 2007-04-02T00:00:00-04:00 2007-04-02T00:00:00-04:00 <p>I spent the better part of my morning today writing some code to do sample data generation within the framework we’re building. I’d originally packaged it as a standalone utility class to be run with the script/runner facility until I realized that it was a perfect candidate for a custom Rake task. And a perfect topic for a blog entry — two for the win!</p> <p>If you’ve never written a Rake task before and are a Ruby pseudo-noob, fear not. If you’ve written Ant or Make scripts before, and have the requisite passing familiarity with Ruby, it’ll be old hat. Of course, the big win with Rake is that you get to write your tasks in Ruby. Sweet, sweet Ruby. No crufty <span class="caps">XML</span> here.</p> <p>What follows is pretty minimalist, but I wanted to record it for posterity. Also, many of the tutorials I looked at didn’t deal with handling parameters, so I figured it might be useful to someone else out there…</p> <pre><code>namespace :foo do desc "Generate sample data for the app" task :sample_data => [:environment] do |t| require 'db/script/sample_data.rb'</code> <code> num_users = ENV.include?('NUM_USERS') ? ENV['NUM_USERS'] : 5 SampleData.generate(num_users.to_i) end end</code></pre> <p>What we’re doing here is defining a task named <em>sample_data</em> within the <em>foo</em> namespace. We declare a dependency on the Rails :environment, which is a little gift from the Rails team allowing you to write code in your tasks that lives within your app’s pre-existing environment. The <em>desc</em> line serves as a comment about what the task does, and will appear alongside the task name when you query it with the —tasks parameter.</p> <p>Within the body of the task we simply require the script we’re going to run, in this case my virtually unmodified utility class, and then we check to see if a parameter named NUM_USERS was passed in. If it was, we use that value to determine the number of users to create. If it wasn’t, we default to 5.</p> <p>Because Rails is smart, and talented in the mystical arts, it auto-loads any files in <em>lib/tasks</em> that have a <em>.rake</em> extension. So just plop this file in that directory and you can then check the available Rake tasks from the top level of your project. You should see our new task definition there:</p> <pre><code>$ rake --tasks | grep sample rake foo:sample_data # Generate sample data for the app</code></pre> <p>Rockin. So let’s run it. As you can see from the output below, it calls the utility calss, creating 10 sample users (and a bunch of other stuff I’ve excluded). Couldn’t be easier.</p> <pre><code>rake foo:sample_data NUM_USERS=10 SampleData: generating 10 users, blah blah blah...</code></pre> <p>I hope this has been helpful, and if you’re looking for more information, make sure to check out <a href="">Martin Fowler’s seemingly definitive reference</a>.</p> Nick Plante Sometimes It's The Little Things... 2007-03-29T00:00:00-04:00 2007-03-29T00:00:00-04:00 <p>With <em>right</em>. I’m down, you’ve won me over.</p> <p <span class="caps">URI</span>, instead of our old friend the slash.</p> <p>And then came <a href="">Changeset 6485</a>, which made everything once again <a href="">right with the world</a>. Thank gawd that’s over. Now I can get back to being productive :-).</p> Nick Plante NH Ruby UG Meeting.003 Tonight! 2007-03-20T00:00:00-04:00 2007-03-20T00:00:00-04:00 <p>If you’re in the seacoast New Hampshire area, don’t forget to attend tonight’s <a href="">NH Ruby User Group</a> meeting. Click on the link for directions.</p> <p>Brian DeLacey will be speaking on <em>Security and Cryptography in Ruby on Rails</em>, and there will be some free book giveaways from O Reilly.</p> Nick Plante AR Model Initialization Notes 2007-03-16T00:00:00-04:00 2007-03-16T00:00:00-04:00 <p>If you’re new to Rails but not to Ruby, you might be surprised to learn that Rails doesn’t use the standard Ruby <em>initialize()</em> method when Model.new is invoked or when a model instance is returned from a find.</p> <p>If you need to add some initialization code to an ActiveRecord model, use the <em>after_initialze</em> callback instead:</p> <pre><code>def after_initialize @thing = SomethingElse.new(self) @foo = 'bar' end </code></pre> Nick Plante March Reading List 2007-03-12T00:00:00-04:00 2007-03-12T00:00:00-04:00 <p>We’ve been hard at work lately, so blog updates have been a little more infrequent than I’d like. But in the meantime, I thought I’d post some books I’ve been reading. All come highly recommended.</p> <ul> <li><a href="">David A Black’s Ruby For Rails</a> – Essential Ruby/Rails reading. How did I get this far without it?</li> <li><a href="">Founders At Work</a> – Working on a startup? You should be.</li> <li><a href="">Seth Godin’s Small Is the New Big</a> – Learn how to be remarkable. Or at least, how to market your remarkability.</li> <li><a href="">Y the Last Man</a> – Damn, Brian K Vaughn rules. Plus, he likes The Eels. And he’s writing for Lost now, too. Read this, even if you don’t read comics.</li> </ul> Nick Plante Tweaking The Rails Logger 2007-03-05T00:00:00-05:00 2007-03-05T00:00:00-05:00 <p>The <a href="">Ruby</a> <a href="">Logger</a> is a simple but pretty flexible tool — hopefully you’re already using it. If not, you should be. The default logger message format is pretty barebones though, so I thought I’d take a few minutes to talk about how to make it more useful by monkey patching format_message.</p> <p>First, make sure to check out TopFunky’s <a href="">‘Hodel 3000 compliant logger’</a> article, posted a couple months ago. Geoffrey’s syslog-friendly modification works great when running in production mode. Customized log messages are just as important in the development environment, where we’ve made our own simple modifications to include the name and line number of the file:</p> <pre><code>class Logger def format_message(severity, timestamp, msg, progname) "#{Kernel.caller[2]}: #{severity.upcase}: #{progname.gsub(/\n/, '').lstrip}\n" end end</code></pre> <p>This little snippet is especially handy if you’re using an <span class="caps">IDE</span> like IntelliJ that’s smart enough to hyperlink the file path. Got an error being logged in users_controller.rb on line 91? Click on the hyperlink and you’re there.</p> <p>It works by accessing the execution stack Array returned by Kernel.caller. caller<sup class="footnote" id="fnr0"><a href="#fn0">0</a></sup> will refer to the line in Logger#add where format_message is called. caller<sup class="footnote" id="fnr1"><a href="#fn1">1</a></sup> is most likely going to point to one of the Logger#<severity> methods, one of [ debug, info, warn, error, fatal ]. This is the next level down in the stack, where the add method was called from. In most “application-level” code (code we actually write in our application, exterior to the benchmarking messages and such that Rails gives us for free), caller<sup class="footnote" id="fnr2"><a href="#fn2">2</a></sup> is going to be something in our application code itself, some place that we called logger.info, or logger.error, or whatever, from.</p> <p>To get this installed in our environment we create a file development_logger.rb, containing the source above. Then, in development.rb (or the initializer block of environment.rb):</p> <pre><code>require 'development_logger.rb'</code></pre> <p>This will “monkey patch” the Rails Logger, effectively overriding it’s format_message method with our own mojo. Sure, it’s not perfect. But it works great for development purposes. A more elegant way to do the same thing would be to subclass Logger and then do something like:</p> <pre><code>config.logger = DevelopmentLogger.new(config.log_path)</code></pre> <p>However, this just doesn’t seem to have any effect when running script/server, which proceeds as if config.logger is set to the standard (unmodified) Rails Logger. I’m at a bit of a loss as to why. If anyone can explain why setting config.logger seems to have no effect, please (please!) let me know.</p> Nick Plante New Ruby/Rails IDE Comparison 2007-03-03T00:00:00-05:00 2007-03-03T00:00:00-05:00 <p>Oh, what an <span class="caps">IDE</span> snob I’ve become over the past couple years. I was an advocate of lightweight text editors for dev work for a long time, and was only truly bitten by the “heavyweight” environment bug once I was introduced to <a href="">IntelliJ</a>, which I can’t say enough nice things about. I was obviously pretty psyched when I found out that the Jetbrains team has decided to put some serious effort into a Ruby plugin. It’s become very usable in a very short amount of time, and I’m very happy with it, but it’s still relatively new and lacking some features.</p> <p>This <a href="">new comparison of Ruby / Rails IDEs</a> does a great job summarizing the features in the three leading “heavyweight” IDEs for Ruby / Rails. Definitely check it out if you’re in the market for a good <span class="caps">IDE</span>. Interestingly, it seems like <a href="">NetBeans</a> is really giving both IntelliJ and RadRails a real run for their money, being the first of The Big Three to get a reasonable level of code completion working, amongst a plethora of other features.</p> <p>Although I’ll probably download it and take a test drive, I’m pretty committed to IntelliJ at this point, so I’ll probably stick it out. But hopefully a little competition will keep things moving along at a good clip :-).</p> <p><em><span class="caps">UPDATE</span>: Switched over to NetBeans months ago and loving it! Nice work guys.</em></p> Nick Plante attr_readonly 2007-02-27T00:00:00-05:00 2007-02-27T00:00:00-05:00 <p>I was really shocked yesterday to discover that there’s literally no baked-in way to declare an ActiveRecord attribute as private or protected. Sometimes I don’t want publicly-accessible ActiveRecord attribute methods. Sorry, but not every field in my database should have a corresponding public mutator.</p> <p>Consider an IP address field on a User model, that’s used to record the last IP the user logged in from. This is something that, although clients outside of the model should be able to access the value, they certainly shouldn’t be able to set it. Only the model itself should be able to update that field in the database. It’s private!</p> <p>As another example, consider the case where a database field is just a cache of calculated relationship data. That cached value should never be set directly via a public instance method. One example is an average_rating as calculated from a bunch of user ratings on an article. Why would you want to expose a mechanism to set this directly? It should only be set through some sort of recalculate_average_rating public method that lives on your article model and fires as an after_save filter on a new rating object.</p> <p>It turns out that counter_cache itself suffers from this same problem. <a href="">Ticket #6896 in the Rails Trac</a> points out this exact issue and proposes a solution in the form of <em>attr_readonly</em>. This is a solid solution, and would go a long ways towards enforcing proper encapsulation in AR.</p> <p>I ranted about this yesterday in freenode and got yelled at a little bit. Yes, I was probably being a bit obnoxious, but I also don’t want the importance of this to be overlooked. The bottom line is that, like it or not, people are largely stupid. Programmers are not excluded from this. Even Ruby programmers, who admittedly are more self-conscious than most. If you give someone the opportunity to do something stupid, be it at the user level in your app, within your <span class="caps">API</span>, or right within the rest of your code base, they’ll do it. If we’re writing for an audience > 1, we should be writing code like we design user interfaces — the public methods available on our classes shouldn’t include things that give our audience permission to twiddle with the guts of that thing. This is a cornerstone of encapsulation and good OO design.</p> <p>So how do you feel about all this? Is it not A Big Deal to you? To me, it’s a significant limiting factor when it comes to organizing large code bases amongst multiple programmers. If you’re the only guy working on a hobby app, then fine, I guess you can police yourself. Go somewhere and do your thing. But if you’re part of a larger team, or hope to build the foundation for something that can grow into a real enterprise-class app, then proper encapsulation is mandatory.</p> <p>I really hope that patch gets committed, or that someone puts together a plugin that delivers the same functionality. In the meantime, sure, there are some things you can do that are better than nothing at all. Try declaring a public mutator in your class to override the AR attribute method of the same name and raise NoMethodError, or write a before_save filter that loads up the model into another variable and replaces the current field with it’s previous value. But just describing those “solutions” makes me feel somewhat ill. Rails is such a clean, elegant platform, and it needs a clean, elegant way to provide non-public methods for AR attributes. Let’s get that patch committed :-).</p> Nick Plante Axiom Of The Empty Set 2007-02-23T00:00:00-05:00 2007-02-23T00:00:00-05:00 <p>A list without any items in it is still a list, I must insist. Just like a box without anything in it is still a box, or a Smurf village without any Smurfs (Smurves?) is still a frickin Smurf villiage..</p> <p>But not according to the <a href="">W3C</a>, apparently. File this one under Rant Of The Day: none of the standard <a href="h"><span class="caps">XHTML</span> doctypes</a> acknowledge the existance of the empty list.</p> <blockquote> <p><!<span class="caps">ELEMENT</span> ul (li)+></p> </blockquote> <p>That is, neither the <ul></ul> or the <ul/> representations are valid <span class="caps">XHTML</span>. This seems pretty broken to me at first glance, although I’m certianly willing to hear a rebuttal if anyone has one. Even if you don’t think it’s busted, it certainly adds complication to a very common web dev scenario…</p> <p>So we have a list of resources in our view and there’s a good possibility that our list is empty. We want to be able to display that list, and have a button on the page that lets me add new items to the list with a little Ajax love so that we don’t have to reload the page. If we can represent an empty list in the page, it’s simple: we can just <em>render :update</em> in Rails…</p> <pre><code>render :update do |page| page.insert_html(:bottom, :my_list, "<li>#{item}</li>") end</code></pre> <p>The code above assumes that there’s a <span class="caps">DOM</span> ID ‘my\_list’ that has 0 or more elements. But since <span class="caps">XHTML</span> won’t let us represent a 0-element list, the obvious thing to do is to bake some extra smarts into the update code.</p> <p>Now it’s the job of the update to determine if a list exists, and if not to create it, but only for the special one-off case of the zero element list? Yuck, bleh. No thanks. This is probably what most people do, but it just strikes me as putting too much intelligence into something that’s supposed to be pretty dumb.</p> <p>The alternate solution listed here also qualifies as a hack, no bones about it. But, at least in my opinion, it’s a somewhat more elegant hack than what was described above. File under simple Workaround Of The Day:</p> <pre><code><ul id="list_things"> <li class="invisible" style="display: none"/> </ul></code></pre> <p>Note that the W3C does support empty list item elements :-). Thanks to azta for the suggestion.</p> Nick Plante Super Mathematics 2007-02-20T00:00:00-05:00 2007-02-20T00:00:00-05:00 <p><img src=""/><br/> Do the math. No matter what you think, nobody’s perfect.</p> Nick Plante NH Ruby UG Meeting.002 Tuesday 2007-02-19T00:00:00-05:00 2007-02-19T00:00:00-05:00 <p>If you’re a Ruby developer (or just an interested outsider) living in southern Maine/NH or the northern Mass area, don’t forget to attend the next meeting of the <a href="">NH Ruby/Rails User Group</a>. Discussion topic this week is <span class="caps">RJS</span> and Ajax. Come hang out with us in Portsmouth tomorrow and make sure to stick around afterwards for drinks, discussion, and merriment.</p> <p>Oh yeah, and <a href="">Scott</a> has some free stuff to give away at the gathering too. You like free stuff, don’t you?</p> Nick Plante 8.5 Minutes 2007-02-17T00:00:00-05:00 2007-02-17T00:00:00-05:00 <p>What were you doing for those eight and a half minutes? <br /> Was it mean, was it petty, or did you realize you were sorry <br /> And that you love them?</p> <p>It’d be nice to think we could get it right down here just once. <br /> G*d bless the Plan.</p> Nick Plante Inheritance vs Relational Databases in RoR 2007-02-16T00:00:00-05:00 2007-02-16T00:00:00-05:00 <p>There are three patterns in common use that deal with mapping object inheritance to relational databases. We didn’t discuss any of them in my graduate databases course (sigh), and our friend <a href="">ActiveRecord</a> implements only one of them: <strong>Single Table Inheritance</strong> (<span class="caps">STI</span>).</p> <p><span class="caps">STI</span> is what you use when you want to represent an object hierarchy by mapping the union of all attributes found in that class hierarchy to a single underlying database table. Yup, it’s a mouthful. And it works great if the attributes available on the subclasses all tend to be very similar. It’s very fast (comparatively), but makes poor use of space since unused fields are just left null. ActiveRecord’s implementation uses a <em>type</em> field in the database to identify the subclass that the row belongs to.</p> <p>So what about alternative approaches? There are a couple…<br /> <!--break--><br /> First up is <strong>Concrete Table Inheritance</strong>, in which there are n database tables for n concrete classes in the hierarchy. Although I’m sure there are cases where this <em>must</em> be useful, I can’t think of a single one. The problem is the silly amount of replication that happens here — fields common to classes will get replicated across tables. This means a lot of replication, more and more as the object hierarchy gets deeper, and a lot of difficulty when it gets to be refactoring time. Bleh, no thanks.</p> <p><strong>Class Table Inheritance</strong>, by contrast, has a table for each class, including interior nodes in the hierarchy (classes that have derivations). A subclass is represented at the database layer as a table that has some number of additive fields plus a foreign key to it’s parent class, which contains the fields that are common to all ancestors.</p> <p>Conceptually, this seems like the cleanest strategy to me, and the most “OO” of the approaches. However, when we think about the implementation, we realize that performance is going to be a big issue: the class-table strategy is going to require n joins for an object nested n levels into a class hierarchy. Ouch.</p> <p>Despite that admittedly ugly problem, there has been some interest in implementing Class Table Inheritance in ActiveRecord. In fact there’s some <a href="">contributed code on the Rails wiki</a> that should allow you to use it as an alternative to <span class="caps">STI</span> in Rails. Someone should plugin-ize it, perhaps.</p> <p>I initially set out to look at alternative DB/object mappings because I was frustrated by the fact that <span class="caps">STI</span> wasn’t “accommodating” enough for me. At one point I thought that Class Table Inheritance might be a better match for a specific problem we were looking to solve. It turns out that wasn’t really the case at all; The problem wasn’t <span class="caps">STI</span>, it was the way our object hierarchy was structured.</p> <p>My Lesson Of The Day for February 16th, 2007: If your object hierarchy is relatively shallow, and the single table strategy produces ugly results for you (lots of null fields on subclasses), take another look at the relationships between your objects. <span class="caps">STI</span> is a great fit for things that are very closely related to the parent class and require few extra attributes to express that. It’s a lousy fit, otoh, for object relations that aren’t tight like rockstar pants. If both CarPart and DogLeash share the parent class Purchase, they’re probably not good candidates for <span class="caps">STI</span> (wink, wink).</p> <p>Embarrassed as I am to admit it, that was sort of the problem. More on that later, maybe.</p> Nick Plante Going Solo: Resources Without The 'S' 2007-02-13T00:00:00-05:00 2007-02-13T00:00:00-05:00 <p>In case you missed it in the release announcement for Rails 1.2.2 last week, singular resources are now available in <a href="">ActionController</a>. You can use them to model singleton resources in your application.</p> <p>So we’re using technoweenie’s <a href="">restful_authentication</a> plugin to handle all things authentication-related in our current project, and decided that a singular resource was a good fit for a Session (login, logout) and Account Controller.</p> <p>Here’s a dumbass-simple example:</p> <pre><code>map.resource :account, :member => { :activate => :any }</code></pre> <p>Note the missing ‘s’. No collections for us here, no sir. But what <em>do</em> we get?</p> <blockquote> <p><span class="caps">GET</span> /account => AccountController#show<br /> <span class="caps">GET</span> /account/new => AccountController#new<br /> <span class="caps">POST</span> /account => AccountController#create<br /> <span class="caps">GET</span> /account;edit => AccountController#edit<br /> <span class="caps">PUT</span> /account => AccountController#update<br /> <span class="caps">DELETE</span> /account => AccountController#delete<br /> (<span class="caps">ANY</span>) /account;activate => AccountController#activate</p> </blockquote> <p>Hey, that’s just what I needed. And of course we get the standard named routes for the resource like account_url, account_path, etc. Yay for Resources. Yay for <span class="caps">REST</span>.</p> Nick Plante ActiveRecord Association Extensions 2007-02-08T00:00:00-05:00 2007-02-08T00:00:00-05:00 <p>So this is probably old hat to a lot of you, but for those that don’t know, ActiveRecord Association Extensions are a seriously useful widget to have in your <a href="">Batman Fantasy Camp</a> utility belt.</p> <p?</p> <p>Why we can extend our associations to define our own methods, of course. Let’s see how…</p> <p>Okay, so we have a relationship defined between two models: articles and opinions. An article has_many opinions. An opinion has a score on it, which is an integer between 1 and 10 representing how a user felt about the article.</p> <p>Using Association Extensions we can define our own method on the association itself, called total_score:</p> <pre><code>class Article < ActiveRecord::Base has_many :opinions do def total_score sum(:score) end end end</code></pre> <p>Now you can access this information by writing something like:</p> <pre><code>article.opinions.total_score</code></pre> <p>Damn, that’s intuitive. Maybe we want to add another method on the association to retrieve the average opinion of users who voted on this article today:</p> <pre><code>has_many :opinions do def average_opinion_today find(:all, :conditions => ["created_at >= current_date()"]).average end end</code> <code>article.opinions.average_opinion_today</code></pre> <p>And it gets better. If we find ourselves using the same extensions in more than one place, in true <span class="caps">DRY</span> spirit we can build a module and reuse it. When we use the :extend option in an association, we get all the methods in that module mixed in.</p> <pre><code>module MiscellaneousExtensions def average_opinion_today find(:all, :condition => ["created_at >= current_date()"]).average end</code> <code> def total_score sum(:score) end end</code> <code>class Article < ActiveRecord::Base has_many :opinions, :extend => MiscellaneousExtensions end</code></pre> <p>I put this module in a subdirectory of lib called extensions. You’ll have to add that path to the config.load_paths in environment.rb in order for it to be recognized.</p> <p>Using these sorts of extensions on my own project earlier today really helped me clean up some troublesome model code. I was just so amped up about it that I had to share.</p> <p>For more information, see the <a href="">ActiveRecord::Associations <span class="caps">API</span> Reference</a>. Oh and a big shout out to <a href="">Brian Hogan</a> for pointing me in the right direction.</p> Nick Plante Blog Package Ponderings 2007-01-28T00:00:00-05:00 2007-01-28T00:00:00-05:00 <p><a href="">Drupal</a> has served me pretty well for a number of projects in the past. But as we shift our development focus towards Ruby-based projects, it seems like an ideal time to consider migrating my own blogging platform to something Rails-driven. Nothing against Drupal itself of course. Hell, for a <span class="caps">PHP</span> project it’s pretty slick.</p> <p>But it still just leaves me feeling like I’m flirting with an old (and somewhat unattractive) ex-girlfriend. It’s not you, it’s me.</p> <p>The obvious candidates seem to be <a href="">Typo</a> and <a href="">Mephisto</a>. Another option would be to, of course, roll my own. But does the world really need another half-baked blogging engine? Probably not. If anyone has other recommendations let me know. Looks like I’m leaning towards Mephisto at this point.</p> Nick Plante Markaby vs Haml vs ERB for Page Templates 2007-01-25T00:00:00-05:00 2007-01-25T00:00:00-05:00 <p>I’ve been spending some time lately looking at different templating packages for Rails, in hopes of finding something cleaner and sexier than the standard <span class="caps">ERB</span> (rhtml) recipe, that also helps avoid common <span class="caps">HTML</span> pitfalls that cause pages not to validate.</p> <p>My search has pretty much boiled down to two candidates at this point. The first is <a href="">Markaby</a>, which has been around for a while now and lets us represent our <span class="caps">XHTML</span> in Ruby code. The other candidate is the new kid on the block, <a href="">Haml</a>, which just reached a 1.0 last week and has it’s own proprietary <span class="caps">CSS</span>-ish syntax. Let’s take a look at brief look at both of them…</p> <p>Here’s some <span class="caps">ERB</span>:</p> <pre><code><div class="column" id="content"> <h2 class="entry_title"><%= h @thing.name %></h2> <div class="entry_link"><%= link_to('link', @thing.link) %></div> </div></code></pre> <p>This is probably what we’re all used to and there’s no arguing that it works well enough, but… Well, it’s kind of ugly, isn’t it? To represent this same thing in Markaby, we install the plugin and create a template with a <em>.mab</em> extension and stick this in it:</p> <pre><code>div.column.content! { h2.entry_title @thing.name div.entry_link link_to 'link', @thing.link }</code></pre> <p <span class="caps">XHTML</span>. Slick.</p> <p>The downside is, of course, performance. It requires rendering for every single tag and property, which makes it slow in comparison to <span class="caps">ERB</span>, since just the inline Ruby snippets in the rhtml file have to be processed and inserted into a mostly pre-rendered <span class="caps">HTML</span> template. I also have some minor gripes about the use of bang instead of pound for representing element IDs, and the fact that it <a href="">blows up</a> when I put a yield in my Markaby layout code (I have to use @content_for_layout, which is deprecated now).</p> <p>Anyway, enough about that. Let’s talk about Haml for a second. Install the plugin, and create a view with a <em>.haml</em> extension. Here’s the same chunk of code we saw before written in Haml:</p> <pre><code>.column#content %h2.entry_title= @thing.name .entry_link= link_to('link', @thing.link)</code></pre> <p>Haml defines it’s own syntax, which borrows from familiar <span class="caps">CSS</span> markup, and takes advantage of whitespace sensitivity for nesting. This latter bit is great news if you’re one of those undercover Python people hiding amongst us (I’m not one of you, now go away). It generates really nice clean appropriately nested <span class="caps">HTML</span> for output too.</p> <p.</p> <p>I can see why people like Haml, it’s compact and kind of fun (see the <a href="">tutorial</a>.</p> <p “<span class="caps">HTML</span>” markup. Still, the performance issues give me pause. An even bigger issue is that of fragment caching, which sadly seems to be <a href="">currently busted</a> in Markaby. So, all things considered, I guess I’m sticking with <span class="caps">ERB</span> in my view templates, coupled with <a href="">assert_valid_markup</a> for my validation testing needs. At least for now. Even thought it makes me cringe a bit.</p> <p>If I’ve missed anything worth considering about either of these templates, or if there are other options, please drop me a line. I’d love to hear what the rest of the community is using for their high-volume web apps…</p> Nick Plante IntelliJ Ruby Plugin 0.1 Beta Released 2007-01-22T00:00:00-05:00 2007-01-22T00:00:00-05:00 <p>The kind folks over at JetBrains have finally got around to releasing a 0.1 Beta of their Ruby Plugin to the <span class="caps">IDEA</span> Repository. If you’re an <a href="">IntelliJ</a> user, it’s now as easy as going to the plugin manager in Preferences and selecting the Ruby plugin for installation. The workflow is the same as <a href="">I described earlier</a> but this release brings some important bugfixes; console output is now available, starting/stopping the WEBrick server now works as expected, etc.</p> <p>In case you haven’t checked it out, the integrated Rails generators and Rake tasks rock, there’s an RDoc toolbar with lookup, goto class functionality, code formatting, and a bunch of other goodies, all detailed in the <a href="">Release Notes</a>. I got all excited when I saw <em>keyword completion</em> in the list; but it turns out that it’s really just that — although a ticket for proper code completion is listed in the <a href="">issue tracker</a> it looks like it’ll still be awhile before we get to feel that love. Syntax highlighting in rhtml/builder templates will be huge also (in the roadmap).</p> <p>I’ve been using RadRails as my RoR <span class="caps">IDE</span> so far, but now that the IntelliJ plugin is mature enough to work with I’ll probably start migrating over. Don’t get me wrong; RadRails is a <em>great</em> project (and free!), but IntelliJ is my <span class="caps">IDE</span> of choice for Java dev, and I’m psyched to see it evolving into a platform for Ruby development too.</p> Nick Plante Rails 1.2.1, Prototype 1.5, Other Goodies... 2007-01-19T00:00:00-05:00 2007-01-19T00:00:00-05:00 <p>Wow what a big day. Immediately after the release of Rails 1.2.0, we get a quickie bugfix bump to 1.2.1 and a great <a href="">post by <span class="caps">DHH</span> summarizing the features in the release</a>. On top of this, we get <a href="">Prototype 1.5.0, complete with a new web presence and some surprisingly good documentation</a>.</p> Nick Plante Rails 1.2 Released 2007-01-18T00:00:00-05:00 2007-01-18T00:00:00-05:00 <p>Looks like 1.2 has been officially released. I’m sure that I’m not the first to notice :-p. To update your gems:</p> <pre><code>gem update rails --source --include-dependencies</code></pre> <p>Enjoy!</p> Nick Plante Seacoast Ruby UG First Meeting Tonight! 2007-01-16T00:00:00-05:00 2007-01-16T00:00:00-05:00 <p>If you’re in the seacoast NH area (north of Boston), don’t forget to attend the first meeting of the Seacoast Ruby/Rails User Group tonight from 7-9 at the <span class="caps">UNH</span> campus. Apparently there was such an overwhelming response that Scott had to move the location to Morse Hall in order to accommodate the additional heads. Wow, cool. <a href="">More information and directions are on Scott’s blog</a>. See you there!</p> Nick Plante FreeBSD 6.2 Released 2007-01-15T00:00:00-05:00 2007-01-15T00:00:00-05:00 <p>FreeBSD 6.2 was released this morning. Lots of <a href="">bugfixes and new features</a>, including official support for binary updates with freebsd-update. Cvsup away!</p> Nick Plante RailsConf 2007 Registration Opens 1st Week Of February 2007-01-14T00:00:00-05:00 2007-01-14T00:00:00-05:00 <p><a href="">This time around</a> the event runs from May 17th to the 20th. Am I gonna go? I’m debating. It seems like a great opportunity to hear a bunch of great speakers, absorb some mad knoweldge, and meet like-minded Rubyists. Plus it’s in Portland Oregon (the <em>other</em> Portland), a city I’ve always wanted to visit, and a mere 2 hours from a good friend of mine in Eugene.</p> <p>The thing that gives me pause is, of course, the cost. Registration is rumored to be a whopping $800 for the 4-day event this year, roughly double the 2006 event price. Ouch. Does this dramatic price hike reflect significantly increased offerings, or is it just because Rails has moved a bit closer to the mainstream — meaning that more corporate entities are capable of coughing up the usual exorbitant conference fees to send employees? Sigh. In either case, as a self-employed developer type that’s painful. Only half as painful as <span class="caps">WWDC</span>. But still, painful.</p> <p>Of course, if you have the time and the skills, <a href="">CD Baby is sponsoring a HackFest</a> to send the top 20 patch contributors free of charge (inc hotel). You’ve got until the 22nd to make your impact <a href="">as measured here</a>. And yes, I’m a bit late in posting that news.</p> Nick Plante Stupid JavaScript Hacks 2007-01-07T00:00:00-05:00 2007-01-07T00:00:00-05:00 <p>I’m usually not prone to <span class="caps">MLP</span> (mindless link propagation) but sometimes I just can’t help it. Case in point: <a href="">this cool l’il bit of JavaScript</a>. Good for a quick chuckle.</p> Nick Plante New Years Resolutions 2007-01-03T00:00:00-05:00 2007-01-03T00:00:00-05:00 <p>Back from my requisite holiday visitations and feeling refreshed. Now it’s time to get back to work. Here’s some tentative goals for the new year:</p> <ul> <li>Get up earlier in the morning. Start work earlier in the morning. Finish work earlier in the evening.</li> <li>Focus more on Ruby this year, less on Java. Delete <span class="caps">PHP</span> from resume.</li> <li>Get a gym membership and actually go on a regular basis.</li> <li>Take a break from client (ie paid) work for a change and get one of my own ideas off the ground before summer.</li> <li>Print some damn business cards. Stop coming up with cute excuses about why they’re lame and learn to conform. Just a little.</li> <li>Go to at least one conference. Go to at least one UG semi-regularly.</li> <li>Bathe the dog more often. He is a stank factory.</li> </ul> Nick Plante NH Seacoast Ruby/Rails UG 2006-12-28T00:00:00-05:00 2006-12-28T00:00:00-05:00 <p>I just got word that there’s a Ruby on Rails user group starting up in my area. It’s being organized by Scott Garman and the first meeting will be January 16th at the <span class="caps">UNH</span> Library in Durham, NH. More details at <a href="">Scott’s Blog</a>. It’ll be great to meet some other local Ruby dorks — most of my contract work is non-local and the other devs I know in the Portsmouth area have sadly yet to be bitten by the bug. I’m psyched that someone has taken the initiative to set this up. Thanks Scott!</p> <p>On completely unrelated news, I’ll be afk for a few days. Heading northbound to visit relatives and then some college friends for a New Years’ extravaganza of sorts. Hopefully I can remember how to play beer die — it’s been awhile. See y’all in 2007!</p> Nick Plante Singin' Hobo (Not The Stabbin' Kind) 2006-12-26T00:00:00-05:00 2006-12-26T00:00:00-05:00 <p>So it’s the holidays, and I’ve got some time “off” from “work” to recoup and think about my next project, play around with a few ideas, new toys… The first thing on that list of toys is Tom Locke’s <a href="">Hobo</a> framework.</p> <p>The Hobo 0.4.0 Gem was released late last week and it’s pretty slick, although we’re warned not to use it in production webapps yet :-). Hobo extends Rails in a number of ways, but the crux of it is that it lets you get up and running with a real, usable (and cleanly coded) Ruby-based webapp quicker than ever before. Hobo bundles in a working user system (acts_as_authenticated), permisisons, and a bunch of other goodies — take a look at the <a href="">screencast</a> for a quickie walk-through. There also seem to be some interesting ideas here regarding tag libraries, but that’s not covered in this first screencast. Anyway, definitely worth checking out.</p> Nick Plante count_on counter_cache 2006-12-24T00:00:00-05:00 2006-12-24T00:00:00-05:00 <p>Counter cache is my new friend. It’s a very important little feature available on <a href="">ActiveRecord</a> that makes counting associations efficient by maintaining a cache on the model.</p> <p>Although it’s documented in <span class="caps">AWDWR</span> (p359 in my shiny new copy of the second edition), I guess it slipped my mind until now, so I thought I’d blog about it just in case anyone else was looking for a solution…</p> <p>So why does it rock so hard, you ask? Let’s say that I’m building <span class="caps">YADRC</span> (Yet Another Digg/Reddit Clone). I need to count the votes that users make to determine the popularity of an article, display that number, and use it to rank the order of the stories. So we set up our models: a story model, a vote model, and a user model, and we create the appropriate associations. Our <em>vote.rb</em> is going to look something like this:</p> <pre><code>class Vote < ActiveRecord::Base belongs_to :user belongs_to :story end</code></pre> <p>Predictably, Story has_many votes and User has_many votes. Now we can do something like this to find the number of votes on a story object:</p> <pre><code>Story.find(4).votes.size</code></pre> <p>This will work nicely right out of the box. However, once we have a significant amount of stories logged in our system and a reasonable number of votes on each story, performance goes straight to poop. The reason is that each time we’re generating a score for a story (and remember, we’ve got N stories), we’re running a query like this against our database:</p> <pre><code>SELECT count(*) AS count_all FROM votes WHERE (votes.story_id = 4) </code></pre> <p>If we have any real amount of data in our system, this is going to get really ugly. Counter caching is one way to help counteract this problem. Let’s rewrite our model to use it:</p> <pre><code>class Vote < ActiveRecord::Base belongs_to :user belongs_to :story, :counter_cache => true end</code></pre> <p>We also have to add a column, called votes_count, to the stories table in our database. Make sure to specify a default value of 0 in your <span class="caps">DDL</span>. Then we generate a migration, run it, and now we’re ready to try again. The difference should be pretty dramatic. If we tail -f our development log, we’ll notice that those count(*) queries aren’t getting run anymore. So what’s happening?</p> <p>ActiveRecord is using our counter cache column (called <em>votes_count</em> in this case) on the stories table to store the number of belonging objects on the associate class. This value is incremented when an object of this class is created, and decremented when it’s destroyed. The result is that we have a local “cached count” on the Story instance so we don’t have to constantly query the votes table directly. Good deal, eh?</p> <p>There are two additional things worth noting about counter caching. As Dave Thomas points out in <span class="caps">AWDWR</span>, the counter won’t get updated if entries are added by setting the link to the parent directly in the child like this:</p> <pre><code>vote = Vote.new vote.story = story vote.save</code></pre> <p>If you’re doing it this way, you’ll have to force the parent class to refresh the collection. The right approach is to add a Vote through the Story object, which makes the parent aware of the increment (or decrement) and update the counter cache accordingly:</p> <pre><code>story.vote.create</code></pre> <p>The other point I wanted to make was that if you call the <em>count</em> method on object instead of using <em>size</em>, it will always run the actual count query on the underlying database, instead of using our cached shortcut. Thanks for the tip on that one, technoweenie.</p> Nick Plante The Quest For The Perfect RoR IDE... 2006-12-22T00:00:00-05:00 2006-12-22T00:00:00-05:00 <p>Ruby itself doesn’t directly support multiple inheritance (yay for mixins) but the community sort of does. If you survey a random group of RoR developers, about half of them seem to come from a structured (oftentimes strongly-typed) OO language like Java, and the other half comes from the scripting world. One of the best things about Ruby is that it appeals equally to both camps. It’s a common ground of sorts, a compromise, maybe the best of both worlds. I dig that.</p> <p>But as everyone knows, different backgrounds beget different toolsets. In the case of Ruby on Rails, it raises the question: do we need a real <span class="caps">IDE</span> for this kind of work, or is a simple text editor good enough?</p> <p>I’ve gravitated back and forth between the two coding camps over the years. It’s a “right tool for the task” sort of thing if you ask me. You want a lightweight project management application that runs on the web? <span class="caps">PHP</span> please. You want a robust scalable service for the delivery of digital media and have some money to spend? Let’s do that one in Java. There’s a religious war to be had here for sure, and I don’t want to get into that… The interesting thing (and the point I’m trying to make) is that the tools you come to use and respond to differ depending on that background.</p> <p>When I’m working in <span class="caps">PHP</span>, I use vim. No, really. I tried PHPEclipse and the pluses just didn’t outweight the minuses for me. I also tried Komodo. I’m an old school vi hacker, and I do all my sysadmin work in vi, so it became the natural choice. I don’t regret it. Well, not often, anyway. After all, <span class="caps">PHP</span> is a scripting language, right?</p> <p>When I’m working in Java, I’m spoiled to death by <a href="">IntelliJ</a>. Yes, it’s expensive. Yes, there’s a learning curve. And yes, it’s worth every damn penny/hour spent. I’ve tried <a href="">Eclipse</a>. And it’s alright, but it’s not <span class="caps">IDJ</span>. The JetBrains guys have delivered what is by far the most intelligent, usable <span class="caps">IDE</span> I’ve ever used. That’s my story, and I’m sticking to it.</p> <p>So is Ruby a scripting language, or is Ruby a proper OO “enterprisey” language? I’d argue that it’s both and that it’s use dictates the classification. But when you’re building Rails apps, you’re firmly entrenched in OO/<span class="caps">MVC</span> proper webapp territory, and therefore, imho, that demands the use of a proper <span class="caps">IDE</span>. Particularly once a project becomes sufficiently large.</p> <p>So what do <em>I</em> use when it comes to Rails work then? Well, up until now I’ve been using <a href="">RadRails</a> with <span class="caps">RDT</span> and Eclipse. It works pretty well for the most part. But it’s no IntelliJ. We don’t, of course, have auto-complete yet, but the syntax highlighting is getting there, the generators and rake tasks are wrapped up nicely, as is run output, test execution, etc etc. It’s better, for me, than using vi, by leaps and bounds and it seems to be getting better and better (nice job guys!).</p> <p>RadRails seems to be the choice for Windows and Linux users, but everyone else I know on OS X seems to be using <a href="">TextMate</a>. Whoah, what? I’ve never used TextMate — am I missing out? But wait, TextMate is just a text editor right? It’s <span class="caps">NOT</span> an <span class="caps">IDE</span> and doesn’t aspire to be. Regardless, the popular opinion seems to be that it’s “good enough”.</p> <p>So what do you use? Are you, like everyone else out there, a TextMate-phile? If so, why? Don’t get me wrong, I <em>understand</em> the allure of a minimalistic text editor for hacking script, but have you been spoiled by something as nice as <span class="caps">IDJ</span> in the past? Oh man would I kill for ctrl-space to autocomplete/interrogate an object to discover it’s methods..</p> <p>I wonder if there are a lot of people who have come over from the Java side of things who have switched to TextMate, particularly people who have used IntelliJ in the past. Am I making a blanket assumption that most of the people using text editors to hack Rails are <em>not</em> Java converts? Am I just overcomplicating the whole thing? Is TextMate really “good enough”?</p> <p>The entire Rails core team purportedly uses TextMate… Maybe I’m just missing something? I’d love to hear your opinions.</p> <p><em><span class="caps">UPDATE</span>: I’m using <a href="">NetBeans</a> now. And it’s great.</em></p> Nick Plante IntelliJ On Rails 2006-12-22T00:00:00-05:00 2006-12-22T00:00:00-05:00 <p>If you’re an <a href="">IntelliJ</a> user like me, and have recently been bitten by the RoR bug, you’ll be glad to know that there’s a plugin on the way. It’s still in it’s infancy, lacking a lot of features, and is therefore not in the repository, but that doesn’t mean we can’t play around with it. What follows is a brief tutorial on how to locate, install, and use the ruby plugin…</p> <p>First you need to check out the sources from the Subversion repo:</p> <pre><code>svn co</code></pre> <p>Use <a href="">Ant</a> to build it (run <em>ant</em> from the directory you co’d to, where the build.xml file lives). The build process should generate a jar file in dist/ called <em>ruby-<span class="caps">SNAPSHOT</span>.jar</em>.</p> <p>Next, make a new directory in your <span class="caps">IDJ</span> plugins directory called ‘ruby’ and make a lib directory in there. Copy the jar to $IDJ_ROOT/plugins/ruby/lib. On OS X, this path is something like <em>/Applications/IntelliJ <span class="caps">IDEA</span> 6.0.2.app/plugins/ruby/lib/</em>.</p> <p>Start IntelliJ. Go to Settings → Project Settiings → Project Structure. In Global Resources, under JDKs, right click and add a Ruby <span class="caps">SDK</span>. On OS X, you’ll want to point it at /usr/local, or whereever your copy of Ruby has been installed.</p> <p>Now you should be able to create a new project and select Ruby <span class="caps">SDK</span> from the <span class="caps">JDK</span> list (heh). Create a single module project, select Rails as your module type, and set the Ruby <span class="caps">SDK</span> for the module. Finally, you’ll be given the chance to generate a new Rails application skeleton, generate missing files, or use an existing Rails app. Go ahead and create a test project and generate a new Rails framework. I’ll do all the work for you and populate the project explorer with that oh-so-familiar directory structure. Check out that ugly Ruby icon they’re using. Jeeze, what is that?</p> <p>Right click in the project explorer and select New → Controller. Name your controller test and add an action name hello. Click OK. <span class="caps">IDJ</span> will run the Rails generator and update the project explorer. You now have a TestController with a hello action, the corresponding view template, and the expected test stubs.</p> <p>You can select Run → Run… to start a WEBrick server and test your app. There are some bugs here. First of all, there is no run output in the console view where you’d expect it to be. No web browser is launched, no indication is given of what port number the server gets bound to. Worse, you can’t seem to kill a running WEBrick server without killing the process from a terminal. So yeah, there’s obviously still some work to do here. For now, I’d suggest running WEBrick from the command line (<a href="">RadRails</a> still wins here, at least). No command completion or real debugging support is available yet either, but hey.. it’s a start. It’s functional, you can run tests from within the <span class="caps">IDE</span>, you get basic code formatting, syntax highlighting, etc.</p> <p>For more information, check out the <a href="">JetBrains Project Homepage</a> for the ruby plugin, where you’ll find a link to the roadmap and discussion groups. You’ll note that there are plans for autocompletion, ability to browse to symbol, proper <span class="caps">YAML</span>, <span class="caps">RXML</span> support, etc. I really hope that development continues on this. <span class="caps">IDJ</span> is much-loved amongst the Java community, and could be a huge hit in the Rails community if they get a slick, fully functional plugin out there.</p> <p><em>Develop with pleasure</em> ;-).</p> Nick Plante Relief 2006-12-20T00:00:00-05:00 2006-12-20T00:00:00-05:00 <p>So we just finished wrapping up work on the app we’ve been building for the past 8 months. Yay! It’s part of a suite of web-powered tools for a certain niche video editing system. Implemented in Java, leveraging Swing, Axis, WebObjects… Great project and totally learned a lot, but sure am relieved to have delivered it. I’m sure there’ll be a tweak to make here or there, but you know… It’s delivered (rc).</p> <p>What’s next? Well, I’m not entirely sure to be honest. For the first time in my life I’m thinking about abandoning paid work in order to invest a couple solid months of full-time effort working on the Ruby/Rails app that’s in my head. Perhaps it’s finally time to put my neck out there a little and make it happen. After all, I isn’t getting any younger, now is I?</p> Nick Plante Searchable RoR Docs 2006-12-11T00:00:00-05:00 2006-12-11T00:00:00-05:00 <p>One of the great things about <span class="caps">PHP</span> isn’t the documentation, per se, but rather the centralized, searchable docs interface at <a href=""><span class="caps">PHP</span>.net</a>. Big thanks to Jeremy Durham for putting together an equivalent <a href="">Rails resource site</a>. There’s obviously still a good bit of work to do before docs are as complete and usable as they could be, but an online searchable repository like this is definitely a step in the right direction. Bookmark it, and add some example code and comments mang.</p> <p>Oh and while we’re talking about documentation (or lack thereof), don’t forget to <a href="">donate</a> to the Rails <span class="caps">API</span> docs project at Caboo.se if you haven’t already.</p> Nick Plante JavaScript Tricks (RJS-R): Cleaning Up My Mess... 2006-12-07T00:00:00-05:00 2006-12-07T00:00:00-05:00 <p>So a couple folks have pointed out that the last Rails+YUI example I posted doesn’t work in IE. Or Safari. Eek, that’s not so good.</p> <p>Anyway, this post is kind of a hodgepodge documenting the process I went through to fix those issues and clean it up a bit. Maybe more of a ‘note to self’ than an actual blog entry, so not required reading by any means. Unless you’re having issues with IE and <a href="">Minus <span class="caps">MOR</span></a> that is, in which case the magic word is <i>content-type</i>. I’m embarassed to say how much sleep I lost tracking that one down. Sigh.</p> <pre><code>class ExampleController < ApplicationController layout "standard", :except => :add</code> <code> def show end</code> <code> def add @response.headers['content-type'] = 'text/javascript'; @thing = params[:thing] end end</code></pre> <p>That’s our updated <i>ExampleController</i>. Notice that we’re setting the content type of the response in the headers now. The default content type appears to be html, instead of text/javascript. Not entirely sure why this is happening at the moment as Minus-R appears to set the content-type in it’s render method. But anyway, for whatever reason, Safari and Firefox both work fine, but IE doesn’t like it one bit. Of course, instead of warning us (or giving us an option to warn us, for that matter) it simply discards the asynchronous response. Hence, we never see an update. Nice, eh?</p> <p>I also took the opportunity clean up the rest of our example a little bit. Here’s our new layout template:</p> <pre><code><html> <head> <title>YUI Tester: <%= controller.action_name %></title> <%= javascript_include_tag "yui/yahoo", "yui/event", "yui/dom", "yui/dragdrop", "yui/connection", "yui/container"%> <%= stylesheet_link_tag 'yui/container'%></code> <code> <script language="javascript"> YAHOO.namespace("yuitest.container");</code> <code> function init() { var handleCancel = function() { this.cancel(); }; var handleSubmit = function() { this.submit(); }; var handleFailure = function(o) { alert("failure: " + o.responseText); }; var handleSuccess = function(o) { eval(o.responseText); };</code> <code> YAHOO.yuitest.container.myDialog = new YAHOO.widget.Dialog("myDialog", { width: "500px", modal: true, visible: false, fixedcenter: true, constraintoviewport: true, draggable: true });</code> <code> var escKeyListener = new YAHOO.util.KeyListener(document, { keys : 27 }, {fn:handleCancel,scope:YAHOO.yuitest.container.myDialog,correctScope:true} );</code> <code> YAHOO.util.Event.addListener( 'myDialogForm', 'submit', function(e) { YAHOO.util.Event.preventDefault(e); YAHOO.yuitest.container.myDialog.submit(); });</code> <code> YAHOO.yuitest.container.myDialog.cfg.queueProperty("keylisteners", escKeyListener); YAHOO.yuitest.container.myDialog.cfg.queueProperty("buttons", [{ text:"Save", handler:handleSubmit, isDefault:true },{ text:"Cancel", handler:handleCancel } ]);</code> <code> YAHOO.yuitest.container.myDialog.callback = { success: handleSuccess, failure: handleFailure };</code> <code> YAHOO.yuitest.container.myDialog.render(); }</code> <code> function addThing() { YAHOO.yuitest.container.myDialog.show(); }</code> <code> YAHOO.util.Event.addListener(window, "load", init); </script> </head> <body> <div id="main"> <% if flash[:notice] -%> <div id="notice"><%= flash[:notice] %></div> <% end -%> <%= @content_for_layout %> </div> </body> </html></code></pre> <p>OK, a bunch of changes there. First, we’ve removed all the Prototype JS libs because we no longer need it — YUI’s connection manager can take care of this stuff for us, and since we’re not using the default behavior of <span class="caps">RJS</span>, there are no worries about dependence on Prototype. Next, we’ve added a couple <a href="">key listeners</a> on the popup dialog to handle enter (submit) and escape (cancel). Note that we have to use <em>Event.preventDefault()</em> in our enter key listener to suppress the default form submission action. Otherwise, we end up redirected to a new page that just contains our result string, and we don’t want that…</p> <p>Finally, we’ve also eliminated the clumsy body of the success handler and replaced it with a single statement: <em>eval(o.responseText)</em>. Yup, we can just evaluate the JavaScript returned from our Rails app. No need to append a new script tag to the body, yehck. Here’s the code that’s returned from our add.ejs template, as a reminder (it’s unchanged):</p> <pre><code>document.getElementById('hello_msg').innerHTML = '<%=@thing[:name]%>';</code></pre> <p>So yeah, it just replaces the inner <span class="caps">HTML</span> in the element named <em>hello_msg</em>. Easy enough. The next step here would be to figure out how to encapsulate the stuff in the layout using some sort of helper module or plugin. But that’s it for now.</p> <p><em>(Progress on my current Rails project has been pretty slow lately, as we’re nearing completion on a big client project (a slick Java-based webstart app that’s been occupying the majority of my time for the past 6 or so months). It’s nice to finally see the light at the end of the tunnel! Hopefully once that wraps, we’ll have some significant time to pour into the RoR ideas and prototypes we’ve been playing around with…)</em></p> Nick Plante RJS & MinusMOR 2006-12-02T00:00:00-05:00 2006-12-02T00:00:00-05:00 <p><span class="caps">RJS</span> rocks. It lets me write JavaScript without writing any JavaScript. That’s very Zen, and I like it. But sometimes I find myself writing really ugly, narsty things in my <span class="caps">RJS</span> templates. Instead of using Ruby to write JavaScript I end up writing JavaScript and appending it to the page with Ruby, especially when client side conditionals are involved. Needless to say, the template code quickly devolves into what can only be described as frankenrubyscript.</p> <p>To rid ourselves of the monster, take a look at Dan Webb’s <a href="">MinusMOR</a> plugin, which lets you return plain ol JavaScript to the browser using templates with an <em>.ejs</em> file extension. This may not seem like a big deal but it’s pretty damn helpful if you return any significant amount of client-side logic within <span class="caps">RJS</span>.</p> <p><em>[Note that you’ll need to be on the Rails 1.2 codebase to use the plugin]</em></p> <p>As a simple example, let’s overhaul our sample <span class="caps">YUI</span> test app to use MinusMOR. Now this really isn’t a great example, as the JavaScript code is super simple and therefore lends itself well to being written in Ruby. But oh well. At least it gives you an idea of how it works.</p> <p>Our <em>add.rjs</em> file used to contain the following one-liner:</p> <pre><code>page.replace_html 'hello_msg', @thing[:name]</code></pre> <p>Now, our <em>add.ejs</em> file will contain the following code instead. Note the use of ERb in the template:</p> <pre><code>document.getElementById('hello_msg').innerHTML = '<%=@thing[:name]%>';</code></pre> <p>In this case the normal <span class="caps">RJS</span> approach is quicker, sexier, and, above all else, easier to read. And, admittedly, 90% of your client-side code will more than likely be the simple kind of stuff that <span class="caps">RJS</span> rocks at (<em>update this text within that <span class="caps">DIV</span></em>, <em>switch the visible state of that <span class="caps">DOM</span> element to hidden</em>, etc). But you can certainly imagine scenarios where it’d make sense to write pure JavaScript in the template instead.</p> <p>Use <span class="caps">RJS</span> wherever you can, but once bits and pieces of frankenrubyscript start sneaking into your code, be sure to check out Dan’s plugin. Cuz there’s no denying that there are cases where using plain ol JavaScript is cleaner, as un-Zen-like as that may seem….!</p> Nick Plante Moving To The Edge, Or Thereabouts 2006-11-27T00:00:00-05:00 2006-11-27T00:00:00-05:00 <p>So I tried to update my OS X dev box to GemRails 1.2 RC 1 and ran into some issues the other day. For some reason, I just couldn’t seem to get system Rails pointing to the new (.5618) copy. I’m usually a pretty stubborn bastard, but one of the plugins I wanted to use requires <em>exempt_from_layout</em> to be available on ActionController::Base, so I figured I’d use <a href="">EdgeRails</a> and freeze a copy of 1.2 RC 1 in the project’s vendors directory.</p> <p>One of the nice things about the way this is all wired together is that you don’t have to be on the very edge of EdgeRails to take advantage of it. In this case, I just need some functionality in 1.2 RC 1 so I can update our existing project and check out using the tag:</p> <pre><code>rake rails:freeze:edge TAG=rel_1-2-0_RC1</code></pre> <p>To verify that we’re on EdgeRails now using the 1.2 codebase (so we can hang out with the cool kids), we can run <em>script/about</em>:</p> <blockquote> <p>Edge Rails revision rel_1-2-0_RC1</p> </blockquote> <p>Keep in mind that this is different than just doing a regular edge freeze since we know we’re getting exactly what we’re asking for. If we just issued an edge freeze without the <span class="caps">TAG</span> parameter we’re going to get the latest and greatest development version which of course means two things: 1) we get the bestest newest coolest stuff, and 2) there’s a good chance that some of that stuff is a bit buggy.</p> <p>For the moment, we don’t have an immediate need to be running the very latest and will therefore generally tend toward valuing stability over freshness. But as our projects grow and we shed more and more of our noobskin, I’m sure we’ll begin making even more exceptions to that rule, forcing us ever closer to the bleeding edge.</p> <p>Pun intended, of course.</p> Nick Plante Happy Thanksgiving: Rails 1.2 RC 1 Arrives! 2006-11-23T00:00:00-05:00 2006-11-23T00:00:00-05:00 <p>In case you haven’t already heard, Rails 1.2 RC 1 is out. Click <a href="">here</a> for details. Taking center stage this time seems to be the push towards creating <a href="">RESTful</a> services. Very nice. Also updates to Prototype and Script.aculo.us and, whoah, some <a href="">deprecations</a>.</p> <p>So after you finish wolfing down that enormous, weight-altering dinner, sit back in your tryptophan-induced haze and take a gander over the new stuff. Me? Nah. I’m headed up to the Great White North for a couple of Internet-free days. But I know what I’ll be doing when I get back… Enjoy!</p> Nick Plante Prototype vs YUI Connection Manager: Dialog Continued... 2006-11-20T00:00:00-05:00 2006-11-20T00:00:00-05:00 <p>In the last <a href="">blog entry</a>, I wrote about doing a first pass integration between Rails and the Yahoo UI Library’s Dialog widget. In the event handler for the save action, we created an Ajax.Request object using the <a href="">Prototype</a> library to make the Ajax call but I didn’t elaborate on why just calling this.submit() in the handler wouldn’t work. Well, the answer is pretty obvious: I wanted to tease out a second article :-).</p> <p><span class="caps">YUI</span> expects us to set up a callback handler for the success/failure of the XMLHttpRequest request that it generates when this.submit() is called. If you don’t have a callback set up, the client receives the response but just ends up throwing it away. So let’s look into how we need to change our handler to do things the “right” way (according to Yahoo, anyway). We’ll also see how this is somewhat at odds with Prototype and <span class="caps">RJS</span>.</p> <p>YUI’s <a href="">Connection Manager</a> utility exists to simplify your interface to the XMLHttpRequest object and provides a handler pattern for callbacks. It’s used throughout their library, so let’s use it here. This updated code should obviate the need for using Prototype in the body of the save action handler:</p> <pre><code>var handleSubmit = function() { this.callback = { success: function(o) { var scriptObj = document.createElement("script"); scriptObj.setAttribute("type", "text/javascript"); scriptObj.text = o.responseText; document.body.appendChild(scriptObj); }, failure: function(o) { // do something here alert(o.responseText); } }; this.submit(); }</code></pre> <p>In the code listing above, we define the callback object to handle the success / failure cases reported by XMLHttpRequest. On success, we’re going to create a new script element in the <span class="caps">DOM</span> and load it up with the response that our <span class="caps">RJS</span> template renders. Then we have to append the new element to the <span class="caps">DOM</span>. Remember, what we’re appending here is really just some more JavaScript that we’ll use to alter the page contents. Here’s the code in that <span class="caps">RJS</span> template again (add.rjs), as a reminder:</p> <pre><code>page.replace_html 'hello_msg', @thing[:name]</code></pre> <p>Alright, that’s great. But what does the JavaScript code look like that actually gets generated?</p> <pre><code>try { Element.update("hello_msg", "Welcome Interstate Managers"); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.update(\"hello_msg\", \"sdafdsfsdff\");'); throw e }</code></pre> <p>That Element.update instruction is Prototype’s way of saying “take the <span class="caps">DIV</span> identified as <i>hello_msg</i> and replace it’s guts with the string <i>Welcome Interstate Managers</i>”. Of course, that’s just the string we gave it when we serialized our form data and sent it off (see previous article for details). Simple but powerful.</p> <p>OK so that rocks, but there’s a bit of redundancy here. Yahoo’s Connection Manager utility and Prototype do a lot of the same stuff. That duplication is totally against the <span class="caps">DRY</span> spirit we’re going for. Sigh. Now I’m not well versed enough in the finer details to advocate The One True Way here, but I should note that I’m much more experienced with Prototype than I am with the <span class="caps">YUI</span> connection manager. Prototype is also much more entrenched in Rails, serving as the basis for both Scriptaculous and <span class="caps">RJS</span>, and it looks to remain that way as Sam Stephenson (Prototype’s creator) is part of the Rails core team.</p> <p>Anyway, the point I’m trying to make is that the Yahoo UI connection manager library adds further unnecessary bloat to our applications, since it’s essentially just replicating what Prototype already does. I’m sure the <span class="caps">YUI</span> guys have their reasons for re-implementing this stuff (Prototype isn’t universally well-loved), but it’s kind of unfortunate for Rails developers, who are pretty well married to Prototype at this point. That isn’t to say that the Yahoo stuff is better or worse.</p> <p>In the meantime, if we want to use YUI’s widgets, we just have to suck it up and eat a little extra pie this holiday season. Maybe it’s worth writing an alternative connection.js to act as a Prototype wrapper. Maybe we could whip up some helper modules to get these excellent UI widgets as well integrated into the Rails framework as the Scriptaculous stuff is. I’m sure this is all very possible, but just need to spend some time digging through the stuff in more detail. In any case, it seems clear that proper RoR integration needs a bit more thought. Add it to the <span class="caps">TODO</span> list!</p> <p>PS the folks at <a href="">OpenRico</a> have done a nice job providing a set of controls that are very RoR-friendly. Their focus is somewhat different than that of the Yahoo library, more emphasis on behaviors and cinematic effects rather than on widgets, per se. They have a great accordion widget though, and a live grid too (although it currently lacks cell editing support, which is one of the key things we’re looking for).</p> Nick Plante YUI Dialog On Rails: First Pass 2006-11-18T00:00:00-05:00 2006-11-18T00:00:00-05:00 <p>RoR seamlessly integrates with Prototype and the <a href="">Scriptaculous</a>…]</p> <p>The <a href="">Yahoo UI Library</a>…</p> <p>Let’s start with something simple. Oh yeah, I should mention that <a href="">Sonjaya Tandon</a> covered this same sorta stuff and what I’m doing is based on what I found there, but I’m going to do it a little bit differently, and demonstrate how you can leverage <span class="caps">RJS</span>. Here we go:</p> <p>First, let’s set up a Rails project and create a controller. Call it ExampleController:</p> <pre><code>class ExampleController < ApplicationController layout "standard", :except => :add</code> <code> def show end</code> <code> def add @thing = params[:thing] end end</code></pre> <p>Pretty simple stuff. We’ll need an <span class="caps">RHTML</span> view template for the <i>show</i> action, and an <span class="caps">RJS</span> template for our <i>add</i> action. We’ll also need a layout that’ll be added to everything but our add action. Let’s take a look at that layout (standard.rhtml):</p> <pre><code>');</code> <code> function initDialog() { var handleCancel = function() { this.cancel(); }</code> <code> var handleSubmit = function() { //this.submit(); new Ajax.Request('/example/add', {asynchronous:true, evalScripts:true, parameters:Form.serialize(myDialogForm)}); this.hide(); }</code> <code> YAHOO.yuitest.myDialog = new YAHOO.widget.Dialog("dlg", { width: "500px", modal: true, visible: false, fixedcenter: true, constraintoviewport: true, draggable: true });</code> <code> var myButtons = [ { text: "Save", handler: handleSubmit, isDefault: true }, { text: "Cancel", handler: handleCancel } ]; YAHOO.yuitest.myDialog.cfg.queueProperty("buttons", myButtons); YAHOO.yuitest.myDialog.render(); }</code> <code> function addThing() { document.myDialogForm.thing_name. <%= @content_for_layout %> </div> </body> </html></code></pre> <p>So there’s a bunch of JavaScript in there. I’m going to work on cleaning all that up and building a helper module later but for now let’s just get something functional.</p> <p>We’ve copied the relevant <span class="caps">YUI</span> library javascripts to our public/javascripts directory, and now we include them in the layout along with our defaults (prototype, etc). We’d want to trim this down to just what we need before deploying an app for real world use of course.</p> <p>We’re going to create a dialog from the <span class="caps">YUI</span> <span class="caps">YUI</span> docs and tutorials. Lots of good stuff over there, extremely well documented.</p> <p>Now here’s our show template (show.rhtml):</p> <pre><code> --></code></pre> <p>Note that the form name (myDialogForm) must match up. Also note that the dlg <span class="caps">DIV</span> uses the same name we initialize the dialog to in the layout. This is important, it means the contents of this div are rendered within the modal dialog and are therefore hidden from the view by default. When you click on the ‘Add Something’ link, the dialog will pop up. You’ll be able to drag it around the screen and enter some text in it. Yay. Then you can click save, and it should update the hello_msg <span class="caps">DIV</span>. There’s an easier way to do this of course, but we’re going to use <span class="caps">RJS</span> because the approach is demonstrative of a lot more powerful stuff you can do, leveraging Rails model data you may have on the backend and perhaps doing some processing or database access before rendering the results. You get the idea.</p> <p>So when you hit that save button, the code in the submit handler is run. Let’s look at that JavaScript again:</p> <pre><code>new Ajax.Request('/example/add', {asynchronous:true, evalScripts:true, parameters:Form.serialize(myDialogForm)}); this.hide();</code></pre> <p>We serialize the data in the form (that one text field) and submit the data asynchronously by making a direct call to Ajax.Request (thanks Prototype!). Then we hide the model dialog again, returning control to the main page. Notice that <span class="caps">URL</span>: <i>/example/add</i>. This calls the <i>add</i> action on our ExampleController, which does something important — in theory — and then renders out an <span class="caps">RJS</span> template. This <span class="caps">RJS</span> template, for our simple example, just replaces the hello_msg div’s inner <span class="caps">HTML</span> with whatever it was we typed into that text field. Here’s the <span class="caps">RJS</span> template, add.rjs:</p> <pre><code>page.replace_html 'hello_msg', @thing[:name]</code></pre> <p>That’s it for now! We’ll revisit this later if I have time, and try to figure out how to wrap it up in a module to make it easier to use and more general purpose.</p> Nick Plante Down w/ with_scope 2006-11-08T00:00:00-05:00 2006-11-08T00:00:00-05:00 <p>We need to delete some stuff. But when we delete items, we don’t <b>really</b> delete them because hey, we don’t have to (we might want them later, no?) So we have an attribute on the model, <i>deleted</i>, which is null if the item is current. When we delete an item, we update_attributes to set deleted to the current datetime.</p> <p>Yes, yes, I know, this is really common stuff. But hold on, this is where it gets kind of interesting. We want to call find on the model, like always, and only get back current items that have not been deleted. Oh, and we don’t want to have to pass in the condition every time, because that’s just gross. We’d just like to, well, add the condition to the scope. This is where the magic of <a href="">with_scope</a> can help us out.</p> <p>Let’s declare a method find_current on the model:</p> <pre><code>def self.find_current find(:all, :conditions => "deleted IS NULL") end</code></pre> <p>Well that works for our base case (finding all current items) but it’s pretty inflexible. What if I want to pass in an ID, specify a limit, additional conditions, etc?</p> <pre><code>def self.find_current(*args) with_scope(:find => { :conditions => "deleted IS NULL" }) do find(*args) end end</code></pre> <p>The answer is to use with_scope, which allows us to specify conditions here that will apply throughout the course of the block. Now we can do things like:</p> <pre><code>Item.find_current(:all, :limit => 10) Item.find_current(:first, :conditions => "name LIKE '%perishable%'") Item.find_current(13)</code></pre> <p>Which invoke the find_current method on the model with our additional parameters and includes our deleted condition in the scope automatically.</p> <p>K, so still not exactly rocket science, but it is a nice, clean solution to a common issue for sure. Unfortunately, with_scope isn’t found in my copy of Agile Web Development with Rails, which is my main reason for noting it here. Hopefully it’ll be in v2! Some other helpful bloggers are out there though, check out <a href="">Ryan Daigle’s blog</a>, which is where Ian found the article that got us started on this path.</p> Nick Plante In My Younger And More Vulnerable Years... 2006-11-04T00:00:00-05:00 2006-11-04T00:00:00-05:00 <p>Thus began the Zerosum dev blog, a place for folks who work on our code to muse about daily development happenings and such.</p> <p>I’ve never been one to keep a blog, personally, but I think of this area as a useful place for us to post about things that don’t belong in our project trac wiki or elsewhere. Things you want to share with others. Things like: “Wow cool, Ian found a new way to do X that totally rocks. Spread the word” and “Rails migrations rule, check out this snippet!”, and “Saw this thing on Foo’s blog about how to do Y without needing Z. Maybe we should think about refactoring the BlahController to do that too?”</p> <p>You get the idea.</p>
http://feeds.feedburner.com/ZerosumDirtnap
CC-MAIN-2017-13
refinedweb
61,944
63.39
AJAX: What's the best tool for the job? By greimer on Feb 06, 2006 Choices, choices, choices. Is it better to pull XML from the server and manipulate it via DOM/XSL? Is it better to use JSON to convert data directly to JavaScript variables? Is it better to pull text in as tag soup, spackling it into place via innerHTML? Or is it better to use CSV and string.split()? There are no hard and fast rules, so I'll just convey some of my thoughts and experiences. XML: An issue here is choosing what XML language to use. The XML language that sprang readily to my mind was, of course, XHTML. There are some pretty good reasons to use XHTML for something like this, plus rolling your own XML language might not be such a good idea. But mainly it provides options. With minimal fuss I can use DOM to drop elements from the X(HT)ML right onto the page, or I can be agnostic about things and treat it like XML; reading out data from it and transforming it as necessary. I just make sure my XHTML sticks to reasonable structure conventions. XHTML also has built-in metadata capability, a well-understood syntax, and, as of recently, microformats. All of this is gravy for me, the programmer. With this technique, there are some things to remember: first, an XHTML "mini-document" needs to be well-formed or the parser will reject it; second, the mini-document needs to use the XHTML namespace as the default namespace or the client may not treat it as XHTML. JSON: Render unto Caesar that which is Caesar's. Thus, in my mind, XHTML is the best data format, and JSON is the best way to import dynamic behavior. Traditional JavaScript files can get huge, and given the direction things are headed, this problem will only get worse. Why not have a minimal JavaScript file, and from there load only the functionality you need, as needed? What this entails is, instead of using JSON notation like this: var foo = {"bar":"baz"}, use notation like this: var foo = {"bar":function(){/\* do stuff \*/}}. It also might make sense to implement some design patterns on top of this, for example the command pattern or some kind of inversion of control pattern. The possibilities are endless. TAG SOUP: I'm going to resist busting on this method too much because there's always a situation where a given method is the best tool for the job. I'll just say this: importing text as tag soup and then shoveling strings into innerHTML with JavaScript is not my preferred way to do AJAX. I guess I just tend to like either pure XML or no XML at all, (but don't hold me to that!). CSV: Sometimes the sledgehammer approach is the best approach. CSV has advantages: the syntax is compact, simple, easy to understand, easy to consume, easy to generate. For transmitting mass quantities of simple, tabular data, CSV is hard to beat.
https://blogs.oracle.com/greimer/tags/tag_soup
CC-MAIN-2015-48
refinedweb
509
71.24
Hi, On 08/14/2011 07:07 PM, Brandon Allbery wrote: > On Sun, Aug 14, 2011 at 06:05, Jochen Keil <jochen.keil at gmail.com> > wrote: > >> However, if I call foo from a keybinding >> >> ((modMask, xK_x), foo) >> >> the spawned program will run but not mapped. This means that I can >> see the console output in xmonad stdout/stderr but the window will >> not pop up. I think this is because of the internal handling of >> keyevents in >> > > It's because your function is doing stuff instead of listening for X > events. If you want to go off and do something else, forkIO a thread I've already tried forkIO, xfork, seq, par, etc. all with more or less the same result: the program's window will be mapped only after the function returns. >. >> code I have written. It's some kind of of vi-mode behaviour for >> xmonad. >> > > XMonad.Actions.Submap would be a good starting point for this. Not an > ideal one, as it doesn't support timeouts or grabbing an entire > submap. Well, at least the timeout issue is solved. :) Concerning the submap. I currently take my regular keymap and AND the complemented modMask from the modifier. Then I feed this into my vi-mode function as keymap. But maybe you want to take a look for yourself. I've attached the code inline below. Regards, Jochen defaultConfig { keys = myKeyMap conf etc `Data.Map.union` viKeys conf } viKeys (XConfig { XMonad.modMask = modMask }) keyMap = M.fromList $ [ ((modMask, xK_z), viMode modMask xK_z (myKeyHandler keyMap)) ] where cleanMask mod = complement modMask .&. mod myKeyHandler km m k = M.lookup (cleanMask m, k) $ M.mapKeys (\(mod, key) -> (cleanMask mod, key)) $ M.delete (modMask, xK_z) km module XMonad.Actions.ViMode ( viMode ) where import Data.Map as M import Data.Maybe (fromMaybe) import XMonad hiding (workspaces) import qualified XMonad.StackSet as W keyEvent :: Display -> IO (EventType, ButtonMask, Time, KeySym) keyEvent d = do allocaXEvent $ \p -> do maskEvent d (keyPressMask .|. keyReleaseMask) p KeyEvent { ev_event_type = e , ev_state = s , ev_time = t , ev_keycode = kc} <- getEvent p fmap (\ks -> (e, s, t, ks)) $ keycodeToKeysym d kc 0 grabKeys :: X () grabKeys = do XConf {theRoot = root, display = d} <- ask io $ grabKeyboard d root False grabModeAsync grabModeAsync currentTime return () releaseKeys :: X () releaseKeys = do d <- asks display io $ ungrabKeyboard d currentTime viMode :: ButtonMask -> KeySym -> (ButtonMask -> KeySym -> Maybe (X ())) -> X () viMode mod key f = asks display >>= cycleKeys (mod, key, 0, True) f cycleKeys :: (ButtonMask, KeySym, Time, Bool) -> (ButtonMask -> KeySym -> Maybe (X ())) -> Display -> X () cycleKeys (mod, key, last, grab) keyHandler d = do if grab then grabKeys >> cycleKeys (mod, key, last, False) keyHandler d else do io $ flush d timeout <- io $ waitForEvent d 1000000 if timeout then releaseKeys else io (keyEvent d) >>= keyDecision where keyDecision (e, s, t, ks) | e == keyPress && s == mod && ks == key = releaseKeys | e == keyPress = do case keyHandler s ks of Just action -> do action cycleKeys (mod, key, t, False) keyHandler d Nothing -> releaseKeys | otherwise = cycleKeys (mod, key, t, False) keyHandler d -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: <>
http://www.haskell.org/pipermail/xmonad/2011-August/011642.html
CC-MAIN-2014-15
refinedweb
510
72.76
DreamSpeed CDN is unavailable for new users and will be discontinued on November 30, 2017. Your content is stored in the DreamSpeed CDN cache for 30 days by default, and you have full control over the cache settings using standard HTTP caching headers. This allows you to control how long your content is stored in the cache as well as in the web browser. HTTP headers You can set four different types of HTTP headers which have different effects on the CDN and on web browsers. If you use more than one type, they are prioritized in the order listed below: Do not cache You can specify the following: - a file to not be cached by setting Cache-Control: private - the Expires header to a date in the past Setting up HTTP headers with Cyberduck Cyberduck is a free file transfer app that works with DreamObjects and also allows for setting Cache-Control headers. Visit the How to Use Cyberduck with DreamObjects article for further instructions on how to connect with Cyberduck: Open Cyberduck and select a file. Click the Get Info button. Select the ‘Metadata’ option. Select the dropdown option to the bottom left and choose ‘Cache-Control’. Modify Cache-Control or add a new custom header. Setting up HTTP headers with the Python boto library The Python library called boto allows you to interact with DreamObjects over its S3-compatible API. Follow the instructions in the Boto article to connect with DreamObjects. The script below sets the Cache-Control header to a max-age of 2592000 seconds (30 days) for all JPG and PNG files in the bucket you specify: from boto.s3.connection import S3Connection # Replace with your DreamObjects access key and secret key connection = S3Connection('Your_Access_Key', 'Your_Secret_Key', host='objects-us-west-1.dream.io') # Change Your_Bucket_Name to the name of the bucket with CDN enabled bucket = connection.get_bucket('Your_Bucket_Name') for key in bucket.list(): print('%s' % key) if key.name.endswith('.jpg'): contentType = 'image/jpeg' elif key.name.endswith('.png'): contentType = 'image/png' else: continue key.metadata.update({ 'Content-Type': contentType, 'Cache-Control': 'max-age= 2592000' }) key.copy( key.bucket.name, key.name, key.metadata, preserve_acl=True ) Purge cache If you make an update to your files stored on DreamSpeed CDN, you’ll want to purge the cache so that it does not serve the stale content. This is easily done through the panel: Navigate to the (Panel > ‘Cloud Services’ > ‘DreamObjects’) page. Click the ‘Change Settings’ link for the bucket you want to purge from DreamSpeed CDN. The Bucket Settings window opens: Click the Purge Now button and confirm the action in the dialog that appears. The cache clears within 2 seconds and is refreshed the next time someone requests it.
https://help.dreamhost.com/hc/en-us/articles/218004377-DreamSpeed-CDN-Advanced-Cache-Settings
CC-MAIN-2017-43
refinedweb
455
63.09
Hi aaall, I have a code like this (from Why’s (poignant) guide to Ruby, in): class LotteryTicket NUMERIC_RANGE = 1…25 attr_reader :picks end def LotteryTicket.new_random new( rand( 25 ) + 1, rand( 25 ) + 1, rand( 25 ) + 1 ) rescue ArgumentError redo end end ticket = LotteryTicket.new_random() When the 3 random numbers created in this last line are not equal, everything goes right. However, when two or three are identical, the second argument error is raised and, theoretically, the method “new_random” should be run automatically again. However, an exception cames out: in `new_random’: unexpected redo (LocalJumpError) This exception should not be launched… (I thought). Suggestions?
https://www.ruby-forum.com/t/rescuing-exceptions-with-redo/102964
CC-MAIN-2022-05
refinedweb
103
51.38
curl-library Re: More CVS Makefile.vc6 Issues... Date: Fri, 3 Sep 2004 19:32:33 +0200 Hi Casey, have you also tried what Gisle suggested below? I've somehow missed to read Gisle's post until now, but I think that's a better approach than my suggestion since you dont have to define an additional var - if that works for you... Guenter. --- multi.h.orig Wed Mar 24 23:53:42 2004 +++ multi.h Fri Sep 03 19:26:22 2004 @@ -52,7 +52,9 @@ #endif #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__) +#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H)) #include <winsock2.h> +#endif #else /* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish > "Casey ODonnell" <caseyodonnell_at_gmail.com> said: >> Let me know what your thoughts are, and if there are good ways to >> reconcile Winsock and Winsock2... > Carefully reorder your headers and/or define _WINSOCKAPI_ in > your CFLAGS. > MingW's <winsock2.h> has this at top: > #define _WINSOCK_H /* to prevent later inclusion of winsock.h */ > Microsoft in their SDK where not so smart to foresee this problem. > <multi.h> could probably do something like: > #if !defined(_WINSOCKAPI_) && !defined(_WINSOCK_H) > #include <winsock2.h> > #endif > Do you provide a patch? > But, winsock2.h is only needed for the definition of fd_set. > So those args could just as well be 'void *' to avoid this problem. > Anything can be converted to 'void *' without a cast in C, right? > --gv Received on 2004-09-03
http://curl.haxx.se/mail/lib-2004-09/0008.html
CC-MAIN-2015-27
refinedweb
247
77.74
Timers with us Hello, It seems there is a problem using timers with intervals under 1ms. Taking an example of a pin toggle using interrupts every 0.5ms here is the output based on a logic analyzer: code used: from machine import Pin from machine import Timer test_pin = Pin('P11', mode=Pin.OUT) test_pin(True) class Clock: def __init__(self): self.loops = 0 self.__alarm = Timer.Alarm(self._seconds_handler, us=500, periodic=True) def _seconds_handler(self, alarm): self.loops += 1 test_pin.toggle() if self.loops == 20: alarm.cancel() clock = Clock() this happened also with self.__alarm = Timer.Alarm(self._seconds_handler, s=0.0005, periodic=True) PWM seems to working fine for the same Pin / Frequency. If a change the period to 1ms and above everything is working fine. @robert-hh Thanks for that. I really like the look of that new board! Hope it is released to market very soon. @stevo52 Some properties of the new board are here: Besides the "linear" improvement over Pyboard v1.x there is WiFi and BT included, using a separate coprocessor. - rcolistete last edited by @stevo52 Try "contact@micropython.org" to ask about 'Pyboard D' availability. I'm sure it will be released on February, but no specific day. By the way, Pyboard Lite 1.0 is better for low power usage, see the MicroPython pyboard feature table. @rcolistete Thanks for that. Some Pyboards V1,1 are available from stockists here in Australia, so I can get my hands on one. However, I would like to know what the spec's/improvement are with the new version before committing to a purchase. Most of the time new versions bring better, bigger features :-). Where can I find information on the new version? - rcolistete last edited by Pyboard Lite 1.0 (with or without accelerometer) is on stock : @stevo52 Lack of documentation is surely something that is hindering. Pycom's documentation improved over time, but it still could be better. The documentation form micropython.org used to be better, but fell a little bit behind. The PyBoard itsef, ot let#s say, the Port for the STM32F4xx family is pretty mature. That's the one MicroPython was ported to in the first place. The the forum at microypthon.org is also pretty active. But unlike Pycom, micropython.org is not driven by a commercial company. It is a few people around Damien George and a lot of first grade contributers, especially Paul, then Dave, McSurly, .. But the are pretty realistic in what they promise. @robert-hh Not sure I can wait for that new Pyboard.. is there any info available on it and what guarantee is there that it will deliver on time and won't also be plagued with perhaps overly optimistic capability or performance claims, poor documentation, errors in command descriptions, lack of corrections/updates, no action on some issues etc. From the forum there seem to be a whole lot of issues with the Pycom products that are hindering a number of people doing development work. I'm a little disappointed really as when selecting a product, for any purpose, we rely very much on product documentation to make informed choices, so that aspect of the Pycom product range lets it down. @stevo52 If you want to stay with MicroPython, try the PyBoard. Itis currently out of stock, but there is a new version expected for February. It is based on a STM controller with a classical memory architecture. ISR times are in the range of <5µs. The new board will have WiFi, if you need that. The Pycom device are good, but the ESP32 is not suited for reliable timing in the µs range. @robert-hh I'll try going back to using sleep_ms, sleep_us I guess, even though I thought it would be less precise! Otherwise, I'll have to change to a different microcontroller that can do what I need - some of the limitations of the GPY's FiPY's Micropython implementation and physical constraints (GPIO Pins) have made my development tasks harder and more time consuming than I wanted them to be! Might be time to cut my losses :-) @stevo52 Part of that is the architecture with SPI Flash and SPI RAM. If code or data is required which is not cached, it has to be imported for the SPI device, which takes time, 100-300µs. Short ISR routines can be held in internal RAM, but larger sections code typicality not. This property is common to all devices with similar architecture. @robert-hh Yeah.. I have noticed that. Bit poor really, makes it hard to apply fast accurate, sampling cycles.. @aris No. The interrupt response of the ESP32 and the Micropython architecture is poor. Response times vary from 10 µs to over 1 ms. Was there a resolution to this issue?
https://forum.pycom.io/topic/3468/timers-with-us
CC-MAIN-2020-24
refinedweb
802
67.45
I use the printf() function often so as to put multiple values on one line. I’ve discovered that the SPI.h header needs to be included. Some sketches use SPI.h and others do not need it. This is probably not SPI itself but something in it that printf() needs. Can someone tell me what needs to be included so that I don’t need SPI.h when I only want the printf() function to run? Here is my test sketch. It runs OK if SPI.h is included. #include <SPI.h> #include "printf.h" void setup() { Serial.begin( 250000 ); // Start the monitor printf_begin(); // Start printf function } void loop() { uint8_t a = 7; printf( "The value of 'a' = %d\n\r", a ); delay( 1000 ); } Here is the error statements when SPI.h is not included. In file included from PrintfTest.ino:2:0: C:\Users\Root2\Documents\Arduino\libraries\printf/printf.h:22:26: error: 'FILE' has not been declared int serial_putc( char c, FILE * ) ^ C:\Users\Root2\Documents\Arduino\libraries\printf/printf.h: In function 'int serial_putc(char, int*)': C:\Users\Root2\Documents\Arduino\libraries\printf/printf.h:24:3: error: 'Serial' was not declared in this scope Serial.write( c ); ^ C:\Users\Root2\Documents\Arduino\libraries\printf/printf.h: In function 'void printf_begin()': C:\Users\Root2\Documents\Arduino\libraries\printf/printf.h:31:29: error: 'fdevopen' was not declared in this scope fdevopen( &serial_putc, 0 ); ^
https://forum.arduino.cc/t/solved-printf-needs-spi-h-to-run/357642
CC-MAIN-2022-40
refinedweb
237
55
Yes sir, exactly. I believe that in calling computers "stupid", other epithets, we're asserting our aggressive primate dominance over these gray boxy things that in some science fiction have beamed aboard spaceship earth in order to steal our jobs or something, because they're smarter than we are. This was the "HAL story" of 2001, which you'll notice was way off target because actually we have no clue how to code a thinking human-like intelligence that passes the Turing Test (which some humans fail also). Lots of doe-eyed venture capitalists got led down that "AI lane" only to watch their money get slaughtered out behind the barn, by wild-eyed computer scientists with BS for brains (yeah, pretty crazy). Sir Roger Penrose likes to show slides of really simple chess puzzles that'd stump Big Blue. I think chess playing is a good place to get into the lore, as one of the earliest ideas of "the AI takeover" (displacement of human intelligence) came in with The Turk, a chess-playing gear-works, a box, like a computer, with a puppet player over the board that would move the pieces. This thing beat Napoleon, likely provoking a crisis in consciousness in the latter tyrant slash dictator, whereas that'd have to be one of the bravest dwarfs on record, to risk humiliating a DFL in that way (he was stuffed in amidst the gears, a kind of magician's trick). Back when I was an ardent disciple of Ted Nelson, reading Computer Lib / Dream Machines and believing in hypertext, I would yak about how key words might make a few links, but really only human intelligence is able to perceive what we call connections, which might be based on far fetched analogies, buried allusions, the kind of stuff we use in the humanities for glue language (psychoanalysis... greek mythology). You get these kinds of networking effects in Google though, because that's not just a keyword index. It has measures of "where the humans find relevance" i.e. what searches mapped to what pages -- becomes self-fulfilling in awhile, as we tend to get lazy and pick one of the "top 10" (what others have picked) but in any case, it's not like "AI" is in control of the hyperlinks. Real thinking humans have to make those URLs across disciplines. The Web is not the product of AI, but of humans collaborating (dream weaving). Probably CS types who love computers, consider this whole area fascinating and wonderful, have a hard time getting into a mindset where computers are looked upon with fear, even dread, because of all those science fiction projections. Remember 'The Matrix': the terrible future is one "run by machines" as these misanthropic men in black guys who torment our heroes are only represented as such in the simulation, have no actual form outside the bleak landscape of AI-dom, whereas the humans are encapsulated within pods, their energies harvested, their lives a mere dream. Likewise 'Terminator' is about machines taking over, starting huge wars without our permission. So calling computers 'stupid' and thinking of programming them as a rather condescending activity, where we can't use our pedagogical bag of tricks, have to be formal and direct, use a "stupid computer language" is in some sense an intellectual counter. Gauss is the right hero to bring in, as he makes those "noncomputable leaps" Sir Roger likes to talk about, whips Big Blue's ass. This whole picture gets flipped on its head in Kubrick's 'Artificial Intelligence' though, as here the predatory humans start to seem evil and fascist, given how they exult over their own supposed superiority -- a projection from many a human past (and present), wherein one caste (class) of human is made to play "subhuman" to prove the other's sorry tale of inherent superiority. Our hearts go out to the oppressed computers in this case (like I said, a reversal). Once past this stage of asserting king-of-the-hill dominance (i.e. we're done feeling threatened), I think it's OK to go back to the music idea (e.g. laptop as guitar, Portland as FOSS Nashville). What's so liberating about today's music software, a lot of it on the Mac, is even if you don't have the reflexes and training to play "in real time", you can drag and drop notes, based on whatever intuitions and theories, and run the thing back at speeds even a professional couldn't match (should you wish to do so). In that sense, we're right to see computers as "better", in the sense of "faster". We take all our file cabinet skills, what it'd take in terms of paperwork to look up a balance, deduct an amount, write out a plane ticket, mail it, and code those into our little "musical numbers", then set those running, making computers our "energy slaves". We each have the equivalent of many secretaries working for us, researchers in libraries, mail delivery people, thanks to the Internet and intranets. With a few clicks of the mouse, we mobilize virtual armies, enjoy a sense of power thereby. Our powers have become amplified. We are better served, by clerical and information resources. This "energy slave" concept didn't start with computers, arose in the 1940s w/r to earlier "ephemeralizings" (using tech to do more with less, improving living standards by optimizing, applying comprehension of principles), but it's still as relevant as ever, why Dr. Bob Fuller grabbed on to it for his 'First Person Physics' initiative. I bring this up because of the "slave" meme, which engineers keep in play within a benign context/namespace e.g. this hard drive is slaved to that master one etc. (people worry when they hear talk like this though -- we need to remember what's scary about engineers, as we move forward with STEM recruiting). Speaking of energy slaves doing clerical work, I have some business to attend to... Kirby Related: (includes the Gauss story) (lesson planning @ Math Forum) (about the AI bust) (First Person Physics) On Tue, Apr 7, 2009 at 6:32 AM, Lloyd Hugh Allen <chandrakirti at gmail.com> wrote: > I haven't posted in a while -- forgot to reply-to-edu-sig :) > > > ---------- Forwarded message ---------- > From: Lloyd Hugh Allen <chandrakirti at gmail.com> > Date: Tue, Apr 7, 2009 at 09:26 > Subject: Re: [Edu-sig] Do we "teach computers" when we write code? > To: kirby urner <kirby.urner at gmail.com> > > > As a math teacher, using the particular example of summing a finite > set of consecutive integers: > > To give students a formula, in particular n(1+n)/2, and then have them > do a set of practice problems where they apply that formula, is not > teaching. It might be training. > > Instead, consider the case of telling students that: when Gauss was in > elementary school, his teacher needed time to work on some other > matter and so told the students to add all of the numbers from 1 to > 100; and that Gauss instantly looked up and said 5050; and the teacher > hadn't actually yet done the problem himself and so denied Gauss' > answer. Gauss, as an ~8 year old, said, no, look, and wrote > > 1 + 2 + 3 + ... + 100 > > and then below that wrote > > 100 + 99 + 98 + ... + 1 > > and showed that there were 100 columns, and that each column summed to > 101. However, he then noted that he had written the series out twice, > and so had to divide that product by two. The 100 columns is the n; > the sum of the first and last number is 1+n; and then divide by two. > > And then to have the students try to represent a similar problem, and > to check their answer against the formula, and THEN to have them do a > set of practice problems, that might be teaching. > > If the computer were able to understand the story about young Gauss, > then we could teach it. Instead, we can use it to confirm that the > formula seems to work (because computers can add numbers in the > fashion that Gauss' elementary school teacher expected just as fast as > we can apply the formula), and we can show that using the formula is > still faster for the computer than actually summing the list, but no, > we are not teaching the computer. > > Perhaps if the computer were then able to, of its own volition, wonder > what we would get if we were to sum consecutive squares, then we could > teach it. As hard as it is to get students to wonder about things, > it's even harder to create that state in computers. > > -Lloyd > > On Mon, Apr 6, 2009 at 18:05, kirby urner <kirby.urner at gmail.com> wrote: >> I'm wondering what others on this list think of this non-standard use >> of "teaching" when talking about programming a computer. >> >> The authors say we're "teaching" the computer.... > _______________________________________________ > Edu-sig mailing list > Edu-sig at python.org >
https://mail.python.org/pipermail/edu-sig/2009-April/009236.html
CC-MAIN-2021-21
refinedweb
1,509
63.53
Docker is a lightweight virtualization technology for Linux that promises to revolutionize the deployment and management of distributed applications. Rather than requiring a complete operating system, like a traditional virtual machine, Docker is built on top of Linux containers, a feature of the Linux kernel, that allows light-weight Docker containers to share a common kernel while isolating applications and their dependencies. There’s a very good Docker SlideShare presentation here that explains the philosophy behind Docker using the analogy of standardized shipping containers. Interesting that the standard shipping container has done more to create our global economy than all the free-trade treaties and international agreements put together. A Docker image is built from a script, called a ‘Dockerfile’. Each Dockerfile starts by declaring a parent image. This is very cool, because it means that you can build up your infrastructure from a layer of images, starting with general, platform images and then layering successively more application specific images on top. I’m going to demonstrate this by first building an image that provides a Mono development environment, and then creating a simple ‘Hello World’ console application image that runs on top of it. Because the Dockerfiles are simple text files, you can keep them under source control and version your environment and dependencies alongside the actual source code of your software. This is a game changer for the deployment and management of distributed systems. Imagine developing an upgrade to your software that includes new versions of its dependencies, including pieces that we’ve traditionally considered the realm of the environment, and not something that you would normally put in your source repository, like the Mono version that the software runs on for example. You can script all these changes in your Dockerfile, test the new container on your local machine, then simply move the image to test and then production. The possibilities for vastly simplified deployment workflows are obvious. Docker brings concerns that were previously the responsibility of an organization’s operations department and makes them a first class part of the software development lifecycle. Now your infrastructure can be maintained as source code, built as part of your CI cycle and continuously deployed, just like the software that runs inside it. Docker also provides docker index, an online repository of docker images. Anyone can create an image and add it to the index and there are already images for almost any piece of infrastructure you can imagine. Say you want to use RabbitMQ, all you have to do is grab a handy RabbitMQ images such as and run it like this: docker run -d -p 5672:5672 -p 55672:55672 tutum/rabbitmq The –p flag maps ports between the image and the host. Let’s look at an example. I’m going to show you how to create a docker image for the Mono development environment and have it built and hosted on the docker index. Then I’m going to build a local docker image for a simple ‘hello world’ console application that I can run on my Ubuntu box. First we need to create a Docker file for our Mono environment. I’m going to use the Mono debian packages from directhex. These are maintained by the official Debian/Ubuntu Mono team and are the recommended way of installing the latest Mono versions on Ubuntu. Here’s the Dockerfile: #DOCKER-VERSION 0.9.1 # #VERSION 0.1 # # monoxide mono-devel package on Ubuntu 13.10 FROM ubuntu:13.10 MAINTAINER Mike Hadlow <mike@suteki.co.uk> RUN sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q software-properties-common RUN sudo add-apt-repository ppa:directhex/monoxide -y RUN sudo apt-get update RUN sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q mono-devel Notice the first line (after the comments) that reads, ‘FROM ubuntu:13.10’. This specifies the parent image for this Dockerfile. This is the official docker Ubuntu image from the index. When I build this Dockerfile, that image will be automatically downloaded and used as the starting point for my image. But I don’t want to build this image locally. Docker provide a build server linked to the docker index. All you have to do is create a public GitHub repository containing your dockerfile, then link the repository to your profile on docker index. You can read the documentation for the details. The GitHub repository for my Mono image is at. Notice how the Docker file is in the root of the repository. That’s the default location, but you can have multiple files in sub-directories if you want to support many images from a single repository. Now any time I push a change of my Dockerfile to GitHub, the docker build system will automatically build the image and update the docker index. You can see image listed here: I can now grab my image and run it interactively like this: $ sudo docker pull mikehadlow/ubuntu-monoxide-mono-devel Pulling repository mikehadlow/ubuntu-monoxide-mono-devel f259e029fcdd: Download complete 511136ea3c5a: Download complete 1c7f181e78b9: Download complete 9f676bd305a4: Download complete ce647670fde1: Download complete d6c54574173f: Download complete 6bcad8583de3: Download complete e82d34a742ff: Download complete $ sudo docker run -i mikehadlow/ubuntu-monoxide-mono-devel /bin/bash mono --version Mono JIT compiler version 3.2.8 (Debian 3.2.8+dfsg-1~pre1) TLS: __thread SIGSEGV: altstack Notifications: epoll Architecture: amd64 Disabled: none Misc: softdebug LLVM: supported, not enabled. GC: sgen exit Next let’s create a new local Dockerfile that compiles a simple ‘hello world’ program, and then runs it when we run the image. You can follow along with these steps. All you need is a Ubuntu machine with Docker installed. First here’s our ‘hello world’, save this code in a file named hello.cs: using System; namespace Mike.MonoTest { public class Program { public static void Main() { Console.WriteLine("Hello World"); } } } Next we’ll create our Dockerfile. Copy this code into a file called ‘Dockerfile’: #DOCKER-VERSION 0.9.1 FROM mikehadlow/ubuntu-monoxide-mono-devel ADD . /src RUN mcs /src/hello.cs CMD ["mono", "/src/hello.exe"] Once again, notice the ‘FROM’ line. This time we’re telling Docker to start with our mono image. The next line ‘ADD . /src’, tells Docker to copy the contents of the current directory (the one containing our Dockerfile) into a root directory named ‘src’ in the container. Now our hello.cs file is at /src/hello.cs in the container, so we can compile it with the mono C# compiler, mcs, which is the line ‘RUN mcs /src/hello.cs’. Now we will have the executable, hello.exe, in the src directory. The line ‘CMD [“mono”, “/src/hello.exe”]’ tells Docker what we want to happen when the container is run: just execute our hello.exe program. As an aside, this exercise highlights some questions around what best practice should be with Docker. We could have done this in several different ways. Should we build our software independently of the Docker build in some CI environment, or does it make sense to do it this way, with the Docker build as a step in our CI process? Do we want to rebuild our container for every commit to our software, or do we want the running container to pull the latest from our build output? Initially I’m quite attracted to the idea of building the image as part of the CI but I expect that we’ll have to wait a while for best practice to evolve. Anyway, for now let’s manually build our image: $ sudo docker build -t hello . Uploading context 1.684 MB Uploading context Step 0 : FROM mikehadlow/ubuntu-monoxide-mono-devel ---> f259e029fcdd Step 1 : ADD . /src ---> 6075dee41003 Step 2 : RUN mcs /src/hello.cs ---> Running in 60a3582ab6a3 ---> 0e102c1e4f26 Step 3 : CMD ["mono", "/src/hello.exe"] ---> Running in 3f75e540219a ---> 1150949428b2 Successfully built 1150949428b2 Removing intermediate container 88d2d28f12ab Removing intermediate container 60a3582ab6a3 Removing intermediate container 3f75e540219a You can see Docker executing each build step in turn and storing the intermediate result until the final image is created. Because we used the tag (-t) option and named our image ‘hello’, we can see it when we list all the docker images: $ sudo docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE hello latest 1150949428b2 10 seconds ago 396.4 MB mikehadlow/ubuntu-monoxide-mono-devel latest f259e029fcdd 24 hours ago 394.7 MB ubuntu 13.10 9f676bd305a4 8 weeks ago 178 MB ubuntu saucy 9f676bd305a4 8 weeks ago 178 MB ... Now let’s run our image. The first time we do this Docker will create a container and run it. Each subsequent run will reuse that container: $ sudo docker run hello Hello World And that’s it. Imagine that instead of our little hello.exe, this image contained our web application, or maybe a service in some distributed software. In order to deploy it, we’d simply ask Docker to run it on any server we like; development, test, production, or on many servers in a web farm. This is an incredibly powerful way of doing consistent repeatable deployments. To reiterate, I think Docker is a game changer for large server side software. It’s one of the most exciting developments to have emerged this year and definitely worth your time to check out. 2 comments: Two ways you can approach new builds and VM instances. 1. Build an image for mono (sans C# build and docker RUN statement), then build an image for running the build / running (with the option of building separate images for building and running applications) 2. Use the -v and -volumes-from options executing a "docker run" command These two options seem to becoming common in certain NodeJS applications I've been going through. that seems amazing, kind of like a layer below chef, puppet and vagrant? So could you run an mvc4 app if you could get it to run under mono?
http://mikehadlow.blogspot.com/2014/04/a-docker-hello-world-with-mono.html
CC-MAIN-2016-36
refinedweb
1,656
55.03
OpenOffice provides a suite of applications whose native file format consists of a set of XML files, compressed into a ZIP archive. This hack explores the basics of the OpenOffice file format. OpenOffice () is a suite of free, multiplatform, open source applications for the desktop, sponsored by Sun Microsystems (). The suite includes text-editor, spreadsheet, drawing, and presentation applications, each of which uses an XML-based file format. Table 4-2 lists the OpenOffice applications and their file extensions. Each file is saved as a collection of XML documents and stored in a ZIP archive. (You can also save documents in other formats, such as text, Rich Text Format, or HTML. You can also export a document as PDF.) The specification of the OpenOffice XML file format is being maintained by an OASIS technical committee (). In the OpenOffice subdirectory of the book's file archive is a small file, foaf.sxw, a snippet taken from the FOAF hack [Hack #64] . It is shown in OpenOffice's Writer application in Figure 4-5. You can use any ZIP tool to examine or extract the XML files from this ZIP file. I'll use the unzip command-line tool that comes with Unix distributions such as Cygwin (). While in the OpenOffice subdirectory, enter this command at a shell prompt: unzip -l foaf.sxw The -l option allows you to inspect the contents of the compressed file without extracting the files from it. This command produces: Archive: foaf.sxw Length Date Time Name -------- ---- ---- ---- 30 04-04-04 04:51 mimetype 4178 04-04-04 04:51 content.xml 8062 04-04-04 04:51 styles.xml 1174 04-04-04 04:51 meta.xml 9180 04-04-04 04:51 settings.xml 752 04-04-04 04:51 META-INF/manifest.xml -------- ------- 23376 6 files Extract these files into the OpenOffice subdirectory with: unzip foaf.sxw You'll see this: Archive: foaf.sxw extracting: mimetype inflating: content.xml inflating: styles.xml extracting: meta.xml inflating: settings.xml inflating: META-INF/manifest.xml Briefly, here's what each of these files contains: Contains the file's media type; e.g., application/vnd.sun.xml.writer. Holds the text content of the file. Holds any meta information for the document. You can edit the meta information associated with this document by selecting File Properties. Contains information about the settings of the document. Stores the styles applied to the document. You can apply styles to the document by selecting Format Stylist (or by pressing F11). Contains a list of XML and other files that make up the default OpenOffice representation of the document. For illustration, we'll look at one of the files stored in the OpenOffice saved-file archive. Example 4-12 shows the XML markup that's inside content.xml. This document is nicely indented because in the Tools Options Load/Save dialog box under General settings, I've unchecked the Size optimization for XML format (no pretty printing) checkbox. It's checked by default, meaning that normally the XML files are saved without indentation. <="Tahoma1" fo: <style:font-decl style: <style:font-decl style: <style:font-decl style: <style:font-decl style: <style:font-decl style: </office:font-decls> <office:automatic-styles> <style:style style: <style:properties fo: </style:style> <style:style style: <style:properties style: </style:style> <:h text:Identify Yourself with FOAF, an Application of RDF</text:h><text:p text: FOAF provides a framework for creating and publishing personal information in a machine-readable fashion. As you learn FOAF, you will also get acquainted with RDF in a practical way as well.</text:p> <text:p text:The Friend of a Friend or FOAF project () is a community-driven effort to define an RDF vocabulary for expressing metadata about people, and their interests, relationships and activities. Founded by Dan Brickley and Libby Miller, the FOAF project.</text:p><text:p text:.</text:p><text:p text: Being a W3C Resource Description Framework hack introduces the basic terms of the FOAF vocabulary, illustrating them with a number of examples. The hack concludes with a brief review of the more interesting FOAF applications and considers some other uses for the data. The FOAF graphic is shown in Figure A-1.</text:p> <text:p text:Figure A-1: FOAFlets</text:p> <text:p text: <text:p text: <draw:image draw:</text:p> </office:body> </office:document-content> The XML documents in OpenOffice use DTDs [Hack #68] that come with the installed package, though XML Schema and RELAX NG schemas will be available in future versions. For example, on Windows, these files are installed by default in C:\Program Files\OpenOffice.org1.1.1\share\dtd\officedocument\1_0. This document uses office.dtd (line 3). (These DTDs are not in the book's file archive.) On line 4, the office:document-content element is the document element with the namespace. Many other namespaces are declared, along with some familiar ones, such as for SVG [Hack #9] and XSL-FO [Hack #48] . Various font declarations are stored in style:font-decl elements on lines 21 through 37. Attributes with the fo: prefix properties from XSL-FO. Lines 38 through 56 list styles that are used in the document. Lines 58 to 67 contain markup used for numeric sequencing in the document. A heading appears on line 68, followed by body text in lines 69 through 97. Lines 98 through 106 show how OpenOffice defines a reference to a graphic, including attributes from the SVG and XLink namespaces such as svg:width and xlink:href. The embedded graphic is stored in the Pictures subdirectory of foaf.sxw as the file 10000000000001A6000000F34FFA992C.jpg (line 104). For details on the OpenOffice file format, see the OASIS OpenOffice specification: For documentation and examples of working with OpenOffice XML, see J. David Eisenberg's OpenOffice.org XML Essentials ()
https://etutorials.org/XML/xml+hacks/Chapter+4.+XML+Vocabularies/Hack+65+Unravel+the+OpenOffice+File+Format/
CC-MAIN-2021-31
refinedweb
979
58.79
How to Create Bitmap Objects of an Image File on Android Developing apps for the Android platform allows you to handle various media types users have on mobile devices, including image files. With a few additions to the Java code for an Android app, you can retrieve the content of an image file on the user's file system. This content can then be stored within the application programming code as a Bitmap object for further processing or display. Many Android apps for businesses or recreation involve handling media data such as images, so the platform provides ready access to this content. 1 Open the Java file in which you want to carry out your image processing. This may be an Android Activity class file or any other Java class you have in your application. If you plan on importing the image content following user interaction with your app, move to the place in which this interaction is detected, such as the "onClick" method following button clicks. 2 Add the necessary import statements to your class file. You will need a variety of Android Java classes added to your class file in order to carry out the image importing and Bitmap saving process. At the top of your Java file, add them as follows: import android.graphics.Bitmap; import android.graphics.BitmapFactory; The Bitmap class is necessary to store the image content as a Bitmap object and the Bitmap Factory allows you to decode the image resource within your app. 3 Store the path to the image file as a string variable. To decode the content of an image file, you need the file path stored within your code as a string. Use the following syntax as a guide: String picPath = "/mnt/sdcard/Pictures/mypic.jpg"; Replace the string content with the path to the image you want to load, including its location and name (making sure you add the file extension). This example represents a JPEG file saved with "mypic" as its name, stored in the Pictures directory on the user's SD card. 4 Create a Bitmap object. Declare a Bitmap object for your loaded image. Give the variable Bitmap as its type and a name of your choice so that you can carry out further processing on it once the image data is loaded in. Use the following syntax as a guide: Bitmap picBitmap You can load the image content directly into this variable. 5 Decode your image file. Extend the line in which you declare your Bitmap variable to decode the image file, loading the image data into your app: Bitmap picBitmap = BitmapFactory.decodeFile(picPath); Alter the parameter to the "decodeFile" method if you gave your file path string variable a different name. If the decoding operation is successful, the Bitmap variable will contain the image data read in from the specified file. References Resources Tips - You can set Bitmap Options when decoding image files, allowing you to control the details of the image data that is imported. Warnings - If you do not use a valid file path to your image it will not be loaded into the app successfully..
https://smallbusiness.chron.com/create-bitmap-objects-image-file-android-56135.html
CC-MAIN-2021-10
refinedweb
524
60.65
Rich HTML in GitHub README Embed rich HTML in any Markdown document, even a GitHub readme, using SVG and foreignObject. TL;DR Jump to the example below to create a rich HTML document enveloped in an SVG file. Readme frenzy. Enter foreignObject <foreignObject> is an SVG element which can include elements from different XML namespaces. So, if our main XML namespace is SVG (), it can contain XHTML (), and all the features it supports, including a style tag. Following is an example of an SVG file with embedded HTML document featuring CSS styles Put it together Then, all that’s left is to include this an as image in your readme repo. Folder structure username/ (repo) ├── README.md └── image.svg README content: # Welcome, I've been expecting you. Go nuts, create amazing things with HTML and CSS to enrich your readme and show off your wicked skills. This technique works for both normal repositories and profile README repos.
https://omrilotan.medium.com/rich-html-in-github-readme-bfb3de791441?readmore=1&source=---------1----------------------------
CC-MAIN-2021-10
refinedweb
157
62.78
Sometime in your application, you want to have the ability to execute some action after certain time. E.g. you may be saying that I want to start calculations after 30 minutes of completion of next step. Or you may have requirement of executing certain action continuously at fixed interval. In programming languages line C#, Java, C, C++ etc. you have class like Timer that provides this type of functionality. Python is not different in that regard. It also has a Timer class. Following code snippet shows to build a Clock class that ticks at fixed interval. This sample prints current time after every one second. You can replace the code in tick function to do whatever action you want to take. from datetime import datetime from threading import Timer class Clock(): """ Clock class """ def __init__(self, frequency=1.0): self.frequency = frequency self.counter = 0 def tick(self, frequency=1): self.counter = self.counter+1 now = datetime.today() print(f"{self.counter}: {now}") self.timer = Timer(frequency, self.tick) self.timer.start() def stop(self): try: self.timer.stop() finally: pass myClock = Clock() myClock.tick() This sample code also implements stop function that allows you to stop the execution. Keep in mind that Python Timer object ticks only one time after you call start function on it. To keep it ticking all the time, I have called start function from with in tick function. Learn Python: How to use Timer to develop a clock using Python Create countdown clock using angularJS services Create a ticking clock using angularJS using timeout
https://byteblocks.com/Post/Learning-Python-How-to-use-Timer-to-develop-a-clock-using-Python
CC-MAIN-2021-39
refinedweb
261
60.51
GIVEN that the recent financial crisis had its roots in the credit markets, it is natural that policymakers should regard signs of excess in the markets with extreme caution. Back in February, the Fed's Jeremy Stein warned that worrying signs were starting to emerge. Those signs are still there; in his excellent report on the markets "The Bubble-Taper Tightrope", Jim Reid of Deutsche Bank writes that 2013 has been a record for PIK (payment-in-kind) and covenant lite issuance on both sides of the Atlantic. In addition, the number of covenants per transactions in the loan market is at record low levels. CCC issuance has also picked up markedly in 2013. Cutting through the jargon, investors are buying bonds with less investor protection, from companies with poor credit ratings and are willing to accept more bonds, instead of cash, as interest. But while those may be bubble signals, the fundamentals do not present quite the same picture. The key measure for credit investors is the spread (excess interest rate) over government bonds; the narrower the spread, the less protection the investor is getting against default. Spreads were incredibly tight in 2007, when there was a bubble. However, compared with history, spreads are not in the lowest quartile for either investment grade or high-yield, according to Mr Reid (although for US high-yield they are close). Furthermore, the fundamentals suggest lowish spreads are justified; the average annual default rate on single B-rated bonds over the last 10 years has been just 1.4% (even allowing for the credit crisis), compared with the average in the previous 20 years of 6.6%. This may be down to the willingness of fixed-income investors to roll over debt, which solves the refinancing problems of the corporate sector. In turn, this may be caused by QE, which has seen central banks buy government bonds and pushed traditional investors into buying corporate debt. So it would be possible to make a bearish case for corporate debt in 2014, if Fed tapering caused a sharp rise in government bond yields or if a slip into recession caused an unexpected surge in defaults. Any sell-off might be exacerbated because liquidity in the market has declined; market-makers have lower inventory than they used to. However, it seems likely that if tapering did push up yields sharply or if the developed world's economies faltered, the Fed would step up the pace of QE faster than you can say "Janet Yellen". In addition, inflation has generally been falling, not rising, and with real yields up a lot from their lows, some of the bearishness about government bonds is overdone. Another reason why it is hard to put the "bubble" tag on credit is that returns this year have been mixed. As of last week, according to Mr Reid, US investment grade investors had received a negative 1.7% return (minus 3.4% on non-financials) while European IG investors had earned just 2.3%. High-yield investors had earned more (8.7% in Europe, 6.2% in the US). soi perhaps, to use a dotcom bubble analogy, we have just been through 1998 rather than 1999. It is hard not to agree with Mr Reid's conclusion that while we're not in a bubble now, we could be if 2014 is like 2013 on the macro front.
http://www.economist.com/node/21591827/print
CC-MAIN-2014-35
refinedweb
566
67.99
Eric CherngVertigo Software, Inc. James DuffVertigo Software, Inc. Dino ChiesaMicrosoft Corporation October 28, 2004 Intended audience: Architects and Developers Download the Interoperability Sample for this article IntroductionInteroperability Sample ContentsPrerequisites and Required SoftwareWhy Web Services?Web Service 1: AdditionWeb Service 2: Ratings and ReportsWeb Service 3: Product SearchConclusionRecommendations/TipsAcknowledgementsUseful Links As Web service adoption increases, vendors are striving to add more features and standards into their frameworks to enable richer and more robust communication between systems. As organizations spend more time and money investigating how best to leverage Web services and its enabling technologies, they should be aware of the strengths and limitations of the technologyspecifically, those related to developer agility, maintainability and interoperability. This paper specifically focuses on interoperability and takes as a starting point, interoperability between the Microsoft .NET Framework and IBM WebSphere via Web services. The goal of this whitepaper and the accompanying sample is to show developers of each platform how to integrate with the other platform. More specifically we will look into Microsoft's .NET Platform and IBM's WebSphere Platform. The samples demonstrate basic techniques and principles that are reusable across all projects where cross-platform interoperability via Web services is required. The sample contains: The techniques and concepts discussed in this article are general, and apply to connecting platforms from any two vendors. However the samples were developed and tested only with the pairing of the Microsoft .NET Framework and the IBM WebSphere SDK for Web Services. This interoperability article (and the related sample) assumes that the reader is familiar with the basics of both the .NET Framework and ASP.NET and the IBM WebSphere Application Server. Web Service 1 is for developers who have never created Web services before or who have not experienced both platforms. Even if you are familiar with Web services and both platforms involved we recommend that you at least review the Web Service 1 documentation as it contains useful hints and tips that are not covered in Web Services 2 and 3. The following software was used to create and test the samples. If you do not have any of the Java software, it is crucial that you install the required software in this order: Web services as an application technology have been with us for many years. Long before organizations and companies created the standards for Web services, Business Analysts, Architects and Software Engineers realized that their company's data was spread across many systems that needed to talk to each other. Previous attempts to link applications together using RPC based technologies such as RMI, DCOM, and other platform-specific inter-connection mechanisms had typically failed due to the wide variety of vendors and platforms that were in use across organizations. These approaches also failed as they were not suited to Internet use where responses could be slow or non-existent. The alternative approaches using message queues, PUT/GET verbs, and manual message marshalling had problems with maintainability and programmer productivity. Hence, developers turned to using some common standards and protocols, namely XML and HTTP. When engineers started building applications that talked to each other, XML was chosen because of its ubiquitous use and support across all platforms. HTTP was chosen due its wide adoption and its ability to traverse firewalls. Vendors such as Microsoft and IBM started building frameworks to support these development efforts and to make the job of the developer easier. The frameworks achieve this by removing the burden of XML serialization and de-serialization and by providing the common infrastructure pieces such as the code required to make connections between systems. With the birth of Web services came the promise of simpler, easier integration between heterogeneous systems and applications. Vendors, using Web services as a catalyst, are now rallying around the concept of Service Oriented Architecture where individual solutions, which may still be built (justifiably) using proprietary RPC protocols such as RMI and DCOM, can be connected together to enable real time data to flow across the enterprise. So the benefits and potential for integration exists, but, in practice, most developers find that creating interoperable Web services is quite a challenge. There are many hidden dangers in creating even the simplest of Web services, such as conflicting types or unsupported features. Our first sample will show you one example of an interoperable Web service and walk you through the process of designing and creating such a Web service. The first sample demonstrates the basics of interoperable Web service. It is a simple addition Web service that accepts two integers from the client and returns the sum of the two numbers. The following high-level diagram depicts what the architecture of this Web service looks like: Figure 1. High-level architecture of Web Service 1 The most common approach when building Web services, and the one demonstrated most often and supported best by tools, is to "infer" a Web service interface from an existing implementation. A developer might write: public int Add(int x, int y) { return x+y; } In ASP.NET, exposing this as a Web service is as simple as adding a WebMethod attribute to the code. This approach is often called "Implementation First" or "Code First", because the Web service interface, formally described in a Web Service Description Language (WSDL) document, is derived from the implementation. Figure 2. Implementation First Web service development With the Implementation First Web service development approach, you start off by writing code for your Web service (see #1 in Figure 2). After you compile, the Web services framework uses your code to dynamically generate a WSDL file (see #2). When clients request your Web service definition, they retrieve the generated WSDL and then create the client proxy based on that definition (see #3). For example, in ASP.NET, the WSDL can be dynamically generated from an implementation with the URL like so: When the .NET runtime detects the WSDL parameter in the request, it uses reflection on the code decorated with the WebMethod attribute to dynamically generate an operation in the WSDL file to describe the underlying service. WebMethod This implementation approach works very well and is quite simple, but can introduce a few problems, especially in scenarios where the Web service is used to connect heterogeneous systems. For example, in the Implementation First approach it is possible to include platform-specific types in the Web service. .NET DataSets and Java Vectors are platform specific types that can't be represented easily in other platforms. This is because there is currently no single well-defined mapping between such platform-specific types and XML. Just because a .NET client can recognize a blob of XML as a Dataset, it doesn't mean a Web service client written in Java can do the same. Interoperability problems arise as a result. The W3C XML Schema standard defines a number of built-in data types, among them string, integers of various sizes, Boolean, single- and double-precision floating point, dateTime, and others. Each application platform also supports a set of its own data types. The intersection of these data type sets defines the types that will be most interoperable across different platforms. If you start with XML Schema types, it is easy to map to platform types, but if you start with platform types there may not always be a mapping to an XML Schema type. For example, XML Schema integers, strings, Booleans, and float all map nicely to the corresponding data types in .NET or Java. However, Vectors and Hashtables are native types to individual platforms and are not part of the XML schema official types. See the XML Schema data types specifications for more information on the supported data types. Most Web services runtimes (including the one built-in to the .NET Framework and the WSDK) can map between these XML Schema primitives and platform-specific primitives, i.e. a string in XML Schema maps to a System.String in .NET, and to a java.lang.String in Java. Using the XML Schema primitives, as well as structures and arrays built from those primitives, it is possible to construct more complex data types, described in XML Schema, that can be mapped with high-fidelity from one platform to another. These data types can then be employed in WSDL documents for use in the Web service. System.String java.lang.String This is the core of what is known as the "WSDL first" design: by using XML Schema types to define the data types used in the Web service you increase the probability that you will use data types that can be mapped from one platform to another. The WSDL First approach is also sometimes called the "Schema First" approach. Even though the two terms are typically used interchangeably, there is actually a small distinction between the two terms. What we are advocating in this paper is that architects and developers consider building up the contract using WSDL definitions before they build the underlying code to support the service. To build the WSDL file developers can either create XML Schema definitions that are specific to the interface they are used with, "WSDL First" design, or they can use XML Schemas that are already defined within their application domain, "Schema First" design. This paper will use the "WSDL First" terminology. Figure 3. WSDL First Web service development The challenge with the WSDL First approach is that current tools in production today do not promote this practice. It's definitely possible, but not easy. Visual Studio provides a Schema editor and an XML editor, but no WSDL editor. Eclipse also does not include a WSDL editor. Fortunately both environments do provide a capability to generate Web service skeleton code, in addition to client-proxy code from a WSDL file. You can use any tool to create your own WSDL file including VI and Notepad. Instead of directly editing the text, you can also use specialized tools, such as Altova's XmlSpy, that have WSDL designers to help with the task. However, even this may not be a solution as many developers are not able to "think in WSDL." One solution to this problem is to quickly prototype a Web service interface using the Implementation First approach. We use the dynamic WSDL generation features of ASP.NET, or IBM WSDK, to create a template WSDL file. Then we can begin development using the WSDL First approach, tweaking the interface as required. This process iterates until the WSDL is final. As you can see from Figure 3 above, there are three high-level steps for creating Web services using the WSDL First approach: Sub-steps A and B of step 2 can be done in any order you wish. Because both depend on the WSDL document, it is only important that the WSDL document be created first before A or B is done. The rest of this section will walk through the steps to developing the first Web service sample following the WSDL First process. The complete source code for this sample can also be found in the download accompanying this paper. Before we go into the WSDL First approach of creating Web services we will look at the Implementation First development model in Visual Studio .NET. The reason that we are demonstrating this method first is that creating a WSDL file from scratch is hard. Using the WSDL file generated from the Implementation First approach to "jump-start" the development process is a much simpler alternative given the tools at our disposal. Imagine having to type this all out by hand: <?xml version="1.0" encoding="utf-8"?><definitions xmlns: > </s:schema> </types> <message name="AddSoapIn"> <part name="parameters" element="s0:Add" /> </message> <message name="AddSoapOut"> <part name="parameters" element="s0:AddResponse" /> </message> <portType name="Service1Port"> <operation name="Add"> <input message="s0:AddSoapIn" /> <output message="s0:AddSoapOut" /> </operation> </portType> <binding name="Service1Soap" type="s0:Service1Port"> <soap:binding <operation name="Add"> <soap:operation <input> <soap:body </input> <output> <soap:body </output> </operation> </binding> <service name="Service1"> <port name="Service1Soap" binding="s0:Service1Soap"> <soap:address </port> </service></definitions> Of course for the WSDL-wiz, this exercise is trivial, but for the rest of us, it would take forever to learn the 51-page WSDL specifications. This is why we use the Implementation First to start off because writing code to create a Web service is the simplest method for developers. First create a C# ASP.NET Web Service project in Visual Studio .NET. Name the project WebService1WSDL. Figure 4. Visual Studio .NET New Project dialog box Next, open the code for Service1.asmx. Uncomment the HelloWorld method and replace the method with this one: [WebMethod]public int Add(int x, int y) { return -1;} Figure 5. Implementation First Web service code Build the project and make sure there aren't any errors. Next, right click on Service1.asmx and set the page as the start page. You can now press F5 and view the Web service test page as shown in Figure 6. Figure 6. Web service test page It's important to realize that the ASMX file is the actual Web service. The page you are looking at is generated by the framework to document the Web service, and to allow the developer to test the Web service without having to manually create a client application. The test functionality is only available when you view the page locally, and does not work for Web services that take complex data types as input parameters. For security reasons, you should remember to disable this test page once you deploy your Web service to a production machine. Next, click on the Service Description link on the top right side of the page. This will open another web page showing you the generated WSDL for your service. The WSDL generation function is always available unless you specifically disable it. Save the generated WSDL to a file on your local drive and name it WebService1.wsdl. Figure 7. Framework generated WSDL file You have just created a WSDL file, without having to learn any WSDL specifications! Another important tip here is that since we generated the WSDL file from this temporary project, the location of the Web service in the WSDL document is hard coded to point to this temporary project. While this does not affect the Web service, the clients that use this WSDL file will use this reference as the location of the Web service. Thus, it is important that you change this value before deploying this WSDL file to our web site. We will change this reference later once we know the actual location of our Web service. If you forget to change this location and client applications have already been built, you can still fix the reference by modifying the location that client references point to. Both .NET and WebSphere Web service client proxies allow setting a URL property. This is also useful when moving from development to production where the final end point of the service is the only thing you want to change. Since the Web service we're building is simple, our generated WSDL file does not require any more tweaking. The next step is to create the actual .NET Web service. Using the WSDL generated in the previous step, we will now create a new .NET Web service. In order to go from the WSDL file to a source code file, we will use a console application called wsdl.exe to generate the code. This tool will parse a WSDL file and any other external files to create a single source code file containing all classes, methods, and types required to implement our Web service. Wsdl.exe is installed along with Visual Studio .NET 2003 (and the .NET SDK). To use the tool, you will need to open the Visual Studio .NET 2003 Command Prompt, which is by default located in the Start menu, All Programs, Microsoft Visual Studio .NET 2003, Visual Studio .NET Tools. Once open, navigate the command prompt to where you previously saved WSDL file. Execute the following command to have wsdl.exe generate our Web service source file. wsdl.exe /server WebService1.wsdl Figure 8. Visual Studio .NET 2003 Command Prompt executing wsdl.exe Notice that the utility outputs a message indicating that Service1.cs has been successfully created. This file will be the starting point for our Web service. The file generated by wsdl.exe is only a template of the method that we want to implement; hence, it needs to be modified in order to work properly. The current wsdl.exe command always generates an abstract class for the Web service when it is executed with the /server option. We'll convert this to a concrete class by removing the abstract keyword and providing an implementation for the Add method. We will also put the class in the WebService1 namespace. The resulting code looks like the following: /server abstract Add WebService1 namespace WebService1 { /// <remarks/> [System.Web.Services.WebServiceBindingAttribute(Name="Service1Soap", Namespace="")] public class Service1 : System.Web.Services.WebService { /// <remarks/> [System.Web.Services.WebMethodAttribute()] [System.Web.Services.Protocols.SoapDocumentMethodAttribute( "", RequestNamespace="", ResponseNamespace="", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle= System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int Add(int x, int y) { int result; result = x + y; return result; } }} You might wonder, why not just subclass the generated abstract class, instead of converting it to a concrete class? There's a good reason. The wsdl.exe tool generates code that is decorated with attributes that are used by .NET's XML serializer and Web services runtime to map from objects to XML and back. For example, an attribute in our example uses the namespace for the generated XML document. These attributes are not inherited by subclasses. Therefore, sub-classing the abstract class, we would need to cut-and-paste all of these attributes on our concrete class. So instead of duplicating all the attributes by hand, it is simpler to just edit the file directly. Of course, this means that if the WSDL changes, you will need to regenerate the source code for the WSDL file, and if not done carefully, this process may erase all our existing code. You will have to manually copy the Web service implementation code from your old file to the new file. Now that we have the Web service source code ready, it is time to create our Visual Studio solution. Create a new Visual Studio .NET C# ASP.NET Web Service project and give it the name WebService1. Once you have your project created, copy the Web service implementation code Service1.cs created earlier to the directory where Visual Studio generated the Web service files. This is usually in c:\inetpub\wwwroot\WebService1. Figure 9. Windows Explorer showing the Web service project files The sample Web service, Service1.asmx, was generated as a part of the Visual Studio project wizard. Since the wsdl.exe command only generates the template implementation code and not the entry point (the ASMX) file, we want to reuse the VS generated Service1.asmx instead of creating our own. However Service1.asmx already has a corresponding source file. An easy way to combine the ASMX file with our implementation code is by simply deleting the implementation code generated by VS (Service1.asmx.cs) and renaming our implementation code to that. Make sure that Service1.asmx and Service1.asmx.cs are not open in Visual Studio before you do this. So, delete the current Service1.asmx.cs and then rename our Service1.cs to Service1.asmx.cs. To verify that the code transplant worked, select Service1.asmx in Solution Explorer in Visual Studio and click the View menu, and then click Code. You should now see the template code with the Add method implementation we modified earlier displayed in Visual Studio .NET. Finally, to test that the Web service is working properly, right click on Service1.asmx and click Set As Start Page. Then go to the Debug menu, and click on Start to build the project and to open Service1.asmx in your browser. Verify that your Web service works correctly using the test page. Figure 10. Web Service Add test page Figure 11. Response from the Web service of adding 12 and 45 To wrap up the .NET Web service, we now need to go back to the original WSDL document to make some minor changes. As mentioned before, the WSDL document is currently pointing at our temporary project Web service. Now that we have finished creating our real Web service, we can modify the location reference to point to this Web service. You can do this by opening up the original WSDL document and then replacing the soap:address element's location attribute to point to the location of this new Web service. The new soap:address element should look similar to the following: <port name="Service1Soap" binding="s0:Service1Soap"> <soap:address</port> Figure 12. Location of Web service being modified in the WSDL file This concludes building a .NET Web service using the WSDL First approach. Next, we will build the WSDK Web service client to consume this .NET Web service. Now that we have a Web service implemented, it's time to create a client to consume the Web service. Since this paper is about interoperability, we will consume the .NET Web service using a JSP page running within IBM's WebSphere Application Server. Start Eclipse and create a new Dynamic Web Project. Give it the project name WebServiceClient1 and name the EAR project file WebServiceClient1Ear. Figure 13. Eclipse showing the WebServiceClient1 project Next, add the WSDL file to the WebServiceClient1 project. You can do this by dragging and dropping the file directly into the project in the Eclipse Navigator pane. Now we want to generate a Java proxy for the Web service. Similar to how Visual Studio .NET creates a proxy class when adding a web reference to a project, the WSDK Tools will create a set of Java files that make calling the Web service easier than manipulating the network stream directly. Because we had already added the WSDL document in the project, you can create the proxy by right clicking the WSDL document, point to the Web Services menu, and then click on Generate Client. This will bring up the WSDL to Java Bean Proxy wizard as shown below in Figure 14. Figure 14. WSDL to Java Bean Proxy wizard In the first dialog, make sure to check the Test the generated proxy check box. This will generate the test JSP page (similar to the test page generated from Service1.asmx when creating the Web service in Visual Studio) that we will use to verify the proxy classes generated. The default options for the rest of the wizard will work so click Finish. After Eclipse completes generating all the necessary files, the following test page is displayed in the Eclipse main window. Figure 15. Eclipse IDE showing the test JSP page Click on add(int,int) in the Methods pane and provide 2 numbers to be added in the Inputs pane. You should see the sum of your 2 numbers in the bottom Result pane. Behind the scenes, this JSP page is calling the Web service proxy class, generated earlier by the WSDK Web service wizard, to call our .NET Web service. Because we had changed the Web service location reference in the WSDL document, our Java client knows exactly where to find the Web service we created in step 2 earlier. If the displayed sum of your 2 numbers is correct, then this successfully verifies that the Java proxy was generated properly and is actually talking to the .NET Web service. add(int,int) Another method to verify the connection between service and client is to set a break point in the Web service code in Visual Studio .NET and then run the service in debug mode. In the Java side, once you execute the add function in the JSP page, you should see Visual Studio .NET stop the execution of the Web service and break at the point you specified. At this point, we have verified that the Java proxy class generated from the WSDL is functioning properly. We also used the test page generated by the WSDK wizard to test calling the .NET Web service from Java. Since both are working properly, this completes both the .NET Web service and the Java Web service client demo of Web Service 1. Though we do not describe in detail the steps for creating the .NET Web service client and the Java Web service server, the sample code accompanying this article does include implementations of both server and client, in both .NET and Java. If you want to generate these yourself, you can find other tutorials for those steps. The second sample builds on the first by creating a Web service that uses a much more complex data schema. Our goal for this sample is to show interoperability between .NET and WebSphere when using complex data types. In the schema for this sample, there is a combination of complex types, simple types, enumerations, restrictions, arrays, and types that inherit from other types in addition to the standard XML Schema types. The differences between the two platforms and the issues in developing interoperable Web services are more apparent in this sample because of this increased complexity. The company, Stuff Sellers, sells various products to various business types. Each business is allowed to submit reviews of the products they buy. Web Service 2 takes the scenario of a ratings service that allows users to submit a report for a given rating or to obtain a list of all reports for a given rating identified by a number. In this case a report can be seen as analogous to a review and the sum of the reviews is used to generate the final rating. The following diagram depicts the high level elements of the data schema. Figure 16. Main elements of Web Service 2 data schema The top level element is Ratings. Each Ratings element contains an array of ReportSet elements (encapsulated in the ReportSetArray type). Then each ReportSet element contains an array of Report elements (encapsulated in the ReportArray type). All three of these top level elements are data types that inherit from the MyBase type. To see the actual XML Schema definition for this data schema, refer to the WebService2SharedTypes.xsd file in the samples download. As is the case with WSDL, there are two ways to generate an XML Schema. The first is to manually design the schema using a schema designer (in the case of XML Schema, Visual Studio does include a designer). The second is to infer the schema from an existing .NET type, using the xsd.exe utility. And as with WSDL, these two techniques can be combined in an iterative approach to tweak a schema so that it looks just right. In some cases, the data schema has been previously defined, and exists independently of the Web service implementation or interface. This may be the case when you are assigned to create a Web service based on the design of a current system. Whether you create the schema or are provided with an existing one, the data schema should be described in a selfstanding XML Schema XSD file, to allow for modularity and re-use. The following is a class diagram depicting the XML Schema defined in the data schema for this Web service. In the same code, the schema is defined in the file WebService2SharedTypes.xsd. The code generated from the data schema (the XML Schema file) on each platform should follow a class structure similar to this diagram. Figure 17. Class diagram of the data schema in Web Service 2 In the first Web service, we used the .NET Framework to generate the initial template WSDL file. Because our Web service was simple, that was the only step we needed to do to create the WSDL. Unfortunately, this Web service is not as simple and thus requires some manual tweaking. Including references to our data schema, changing the namespace, and creating the proper messages for the portTypes are just some of the changes we had to make to the template WSDL file in order to maintain interoperability. portTypes The WSDL document for this Web service defines two operations: GetRatings and SubmitReport. GetRatings returns a Ratings type if the ID provided matches a given rating. The SubmitReport operation is used by clients to submit a new Report associated with a specific Ratings and ReportSet. You can see the WSDL definition of these operations in WebService2.wsdl in the samples download. Ratings There are two ways to include XML Schema definitions in WSDL files: you can define the schema inline in the WSDL file or by referencing your XML Schema files in your WSDL file using the xsd:import element. Because inline definitions are part of the WSDL file, they are simple to maintain. However, since a data schema describes data and not the Web service interface, and is sometimes used independently of the web service interface, it is more logical to separate the two definitions into two separate files. If your Web service is simple and doesn't require many complex data types, then inline schema will work fine (as in Web Service1), but in general most Web services should separate the data schema from the Web service definition. In this Web service, we decided to use the xsd:import method to reference the external XML Schema file, WebService2SharedTypes.xsd from the WSDL file, WebService2.wsdl. In the WSDL file, it looks like this: <types> <xs:schema <!-- Import the Shared Types --> <xs:import <!-- Import the Message Parameters --> <xs:import </xs:schema> </types> . . . To create the Web service template code in .NET, run wsdl.exe with the following parameters: wsdl.exe WebService2.wsdl WebService2Interface.xsd WebService2SharedTypes.xsd Notice that wsdl.exe requires the input WSDL file and all of the included XSD files to be specified on the command line together. When importing an XSD into a WSDL, it is possible to provide a schemaLocation attribute. According to the WSDL specification, this attribute serves as a "hint" for the location of the schema, and the hint may or may not be followed by tools that interpret the WSDL file. In this case, wsdl.exe does not use the schemaLocation hint, so the external schema files must be specified on the command line. On the other hand, the IBM WSDK tools do utilize the schemaLocation hint and will load the files directly when specified. An important detail to pay attention to is that the ID element of MyBase is defined with type xsd:int and includes the minOccurs=0 attribute. The XML Schema definition of MyBase looks like this: <xs:complexType <xs:sequence> <xs:element </xs:sequence></xs:complexType> When minOccurs=0, this indicates that the ID property can be left out of the resulting XML document. This causes a problem for the .NET platform. In .NET, the xsd:int maps to Int32, which is a value type, and value types cannot be NULL. Basically this means there is no way to determine whether the ID property has been set or not since all values of Int32 are valid values. The .NET Framework resolves this problem by creating another variable named IDSpecified of type Boolean. This variable is checked by the .NET XML Serialization logic to determine whether the ID variable has been set or not, essentially giving ID the NULL/not NULL value. Therefore whenever you attempt to access the ID variable, you should always check or set the IDSpecified variable first. For more information on this usage pattern, see the MSDN documentation for the XmlIgnoreAttribute class. ID The following is what the MyBase type gets translated to in C# code: [System.Xml.Serialization.XmlTypeAttribute(Namespace= "")][System.Xml.Serialization.XmlIncludeAttribute(typeof(Report))][System.Xml.Serialization.XmlIncludeAttribute(typeof(ReportSet))][System.Xml.Serialization.XmlIncludeAttribute(typeof(Ratings))]public class MyBase { public int ID; [System.Xml.Serialization.XmlIgnoreAttribute()] public bool IDSpecified;} This issue does not occur when using the WebSphere sample, because when an xsd:int is used with minOccurs=0, the WSDK tools generate a variable of type java.lang.Integer instead of the native int Java type. The java.lang.Integer type is a reference type, and it is possible for a variable of this type to take the NULL value to indicate that it has not been set. Using the tools provided in the WSDK, the following is what the MyBase type gets translated to in Java code: public class MyBase implements java.io.Serializable { private java.lang.Integer ID; public MyBase() { } public java.lang.Integer getID() { return ID; } public void setID(java.lang.Integer ID) { this.ID = ID; }} Another difference that is evident when comparing the C# code generated from the XML Schema, to the Java code generated for the same schema, is the inclusion of code attributes in the C# code. As we said earlier, these are used by the XML Serializer in .NET to help in mapping from class instance to XML. Java also requires similar "metadata". In the case of the Web services runtime in WSDK, this metadata it is stored independently, in an XML file that defines the type mappings. See the WSDK documentation for more information. Another point of interest: if you examine the classes generated by either the .NET tools or the WSDK tools, you will find that the generated data types may not be what you, as a developer, would write without considering interoperability. Examine the Ratings.java class generated by WSDK. Excluding some housekeeping code, it looks like this: public class Ratings extends org.example.MyBase implements java.io.Serializable { private java.lang.String description; private int confidenceLevel; private java.util.Calendar expiration; private org.example.ReportSetArray allReports; public Ratings() { } public java.lang.String getDescription() { return description; } public void setDescription(java.lang.String description) { this.description = description; } public int getConfidenceLevel() { return confidenceLevel; } public void setConfidenceLevel(int confidenceLevel) { this.confidenceLevel = confidenceLevel; } public java.util.Calendar getExpiration() { return expiration; } public void setExpiration(java.util.Calendar expiration) { this.expiration = expiration; } public org.example.ReportSetArray getAllReports() { return allReports; } public void setAllReports(org.example.ReportSetArray allReports) { this.allReports = allReports; }} For the primitive data members, of type int and string, perhaps they reflect what any designer might hand-author: following JavaBean conventions with getters and setters wrapped around a private member. But then some of the differences appear. The date value is handled by a Calendar, not a java.util.Date. And, an Array is wrapped by a custom class, also accessible via a getter/setter pair. This generated class may not be what you would write yourself, but it does the job, and it has the added advantage of being interoperable. You could make the same statements about the code generated by the .NET tools. We followed the general steps outlined in the section for Web Service 1, above, to build two Visual Studio projects: one for the client, and one for the server. We did likewise with the WSDK to build two WebSphere projects. All of these clients and servers are mutually interoperable. Compile and run the Visual Studio projects and the Eclipse projects in the samples download to see all of this in action. Be sure to check the Readme for the samples download before proceeding. This sample explored the use of complex data types in an interoperable Web service. The W3C XML Schema plays a key role in defining the message types and data elements to be exchanged. This section discussed how to develop an XSD for a complex data type, and how to employ that XML Schema in a WSDL document. This section also pointed out some of the edge cases to be aware of, for example, the difference between value and reference types in .NET, and the implications that this difference has on XML Serialization. In the next sample, we will expand on the ideas from this sample and explore interoperability using extensible data elements. Most Web services employ a fixed data schemathat is, the types of data sent over the wire are known at design time. But sometimes a static data schema does not fulfill the requirements for the application. Consider the following business scenario. As mentioned in Web Service 2, Stuff Sellers sells various products to both consumers and other businesses. Because the company sells so many different products, the manager has asked us to create a Web service that will make it easier to search the database of products. Our search will be used indirectly by consumers through the Internet store front, and directly by other businesses. The manager would like the Web service to support the following three requirements: In addition to these requirements, the manager would like the Web service interface to be as simple as possible. Specifically, the Web service should have only a single entry point. Looking over the products that Stuff Sellers currently sells, we find that all products at a minimum have a Name, Description, Price, and a SKU. These attributes will make up the base properties for all our products. In addition, each product also has its own unique set of attributes. For example a DVD movie has a RegionEncoding, a VideoFormat, a Language, and a DateofRelease. A Book product has a list of Authors, a Publisher, an ISBN, and a PublishedDate. Therefore, the base product type will expose all of the properties that are common across product types, and will allow extensions for properties that are specific to particular product types. The following is a class diagram of the data schema defined for Web Service 3. Figure 18. Class diagram of the data schema in Web Service 2 The XML Schema type definition for SearchResult (in WebService3SharedTypes.xsd) is defined as the following: <xs:complexType <xs:sequence> <xs:element <xs:element <xs:element <xs:element <xs:element <xs:any </xs:sequence> </xs:complexType> As you can see, SearchResult is the parent type that represents all products found by the Web service. SearchResult contains properties that are common to all product types. In addition, SearchResult also contains an xsd:any element, which acts as a wildcard. An XML file that validates to this schema can include any XML element at that location. For our purpose, the xsd:any element will contain one of the product property types that can be returned by the Web service. We have defined three such product property types in WebService3ExtendedProperties.xsd: DvdProperties, BookProperties, and CDProperties. In practice, a client application will access the common properties by checking SearchResult, and will access the extended properties for that product by checking the member variable that contains the product specific properties types. An alternative to using xsd:any in the schema to match any XML element is to employ a string element in the schema, which will contain dynamically generated XML. Using a string is a similar "wildcard" approach. The difference is that the XML contained within the string will be "escaped" for transmission, and so will be opaque to XML parsers, which is not what we want. It is cleaner to integrate the dynamic XML as part of the XML document instead of escaping it into a string element. In either case, there is a bit of extra work required, to generate the XML on the sending side, or to parse it on the receiving side. Just as in the second sample, the WSDL document for this Web service is separated into two files: WebService3.wsdl and WebService3SharedTypes.xsd. WebService3.wsdl contains declarations that define the Web service and WebService3SharedTypes.xsd is an XML Schema file that contains the data types used by the Web service. The following is a sample capture of the SOAP message returned by the Web service to the client. <?xml version="1.0" encoding="utf-8" ?> <soap:Envelope xmlns: <soap:Body> <SearchResponse xmlns=""> <SearchResult> <SearchResult> <SKU>B05502HB9I</SKU> <Price>14.99</Price> <Name>Spain's History</Name> <Description>Short documentary on the history of the Spain.</Description> <ProductType>DVD</ProductType> <DvdProperties xmlns=""> <Region>EUROPE</Region> <Format>PAL</Format> <Language>Spanish</Language> <ReleaseDate>2000-05-14</ReleaseDate> </DvdProperties> </SearchResult> <SearchResult> <SKU>A04D5E87RJ</SKU> <Price>20.00</Price> <Name>Spain's History</Name> <Description>Companion coffee table book to the documentary "Spain's History".</Description> <ProductType>Book</ProductType> <BookProperties xmlns=""> <Authors> <Author>Mark Person</Author> </Authors> <Publisher>BookPub Central</Publisher> <ISBN>0459756212</ISBN> <PublishedDate>2003-08-08</PublishedDate> </BookProperties> </SearchResult> </SearchResult> </SearchResponse> </soap:Body> </soap:Envelope> There is also a third file, WebService3ExtendedProperties.xsd, which isn't imported into the WSDL, but is essential for the Web service to generate a response, and for clients to be able to interpret the response from the Web service. This file contains the definitions of the dynamic part of the data: the extended properties for the product types. The advantage of keeping the product types separate from the types used by the Web service is the ability to extend the product types, without modifying the interface. Eventually Stuff Sellers will expand its business and start selling other types of products. Since search results will contain these new products, adding the new products in a simple way is a crucial requirement. With our design, supporting new types is a simple matter of extending the Web service implementation to return the new types and extending the data schema defined in WebService3ExtendedProperties.xsd. Publishing the new XSD file to the web and letting customers know of the change are the last steps needed. There is no change needed to the WSDL file. Web service clients that do not wish to use the extended properties or simply pass on the extended properties to other services can chose to ignore the extended properties. At runtime, these clients need not de-serialize the XML blob into objects. For example, if an application is written to filter products based only on price, then it doesn't matter what type of product is returned. In this case, the client only needs to check the base property Price of the SearchResult type and can safely ignore the extended properties. With the use of xsd:any, the Web service has the flexibility to add new features without having to break existing clients. New Web service clients can use the new product types while existing applications will simply ignore the new product types. Even if existing product types are removed, the existing Web service clients will still function properly because they will simply not execute the code pertaining to the old products. This design provides the best of both worlds, where response messages can be extended for new applications, while still allowing existing applications to function properly. Converting between XML and corresponding instances of objects is called "XML serialization", or "XML binding". The process of converting between parameters to a Web service call, and the XML sent over the wire in a Web service request or response, is usually done automatically by the Web services runtime. However, when using schema extensions that are not defined in the WSDL (or its imported XSDs), this XML serialization and de-serialization must be done manually. .NET exposes tools and programming interfaces that enable this. IBM WebSphere does not expose public interfaces to manually perform XML serialization. The Java client and server require an add-on capability to perform the Java-to-XML binding. One such add-on is the JAXB API that is part of Sun's JWSDP. Installing the JWSDP will give you the JAXB compiler, which can generate Java class from an XML Schema, similar to the xsd.exe utility for .NET. Using the classes to reference the data types is much simpler than directly manipulating XML elements. In JAXB, the generated data type classes are also responsible for "marshalling" or "serializing" to, and "unmarshalling" or "deserializing" from, XML files that conform to that XSD. The .NET Framework SDK also includes a tools and a framework for binding XML data to .NET classes. The Xsd.exe tool parses an XSD file to create a corresponding source code file that contains the data type definition classes. At runtime, applications can use the System.Xml.Serialization namespace of classes to create an object graph from an XML stream, or vice-versa. System.Xml.Serialization For example, at compile time, to generate C# classes from the WebService3ExtendedProperties.xsd schema, use the following command: xsd.exe /classes WebService3ExtendedProperties.xsd And then at runtime, to create the object graph from a file, use these few lines of code: FileStream fs = new FileStream(path, FileMode.Open); XmlSerializer s= new XmlSerializer(typeof(BookPropertiesType)); BookPropertiesType props; try { props= (BookPropertiesType) s.Deserialize(fs); } finally { fs.Close(); } Normally, for data types used in Web services interfaces, the steps of creating the data type classes and performing the serialization are performed automatically for you: the former by the wsdl.exe tool or the "Add Web Reference" in Visual Studio, and the latter by the web services runtime in .NET. When you pass a parameter to a web service, the parameter is automatically serialized to XML for transmission across the network. The use of xsd.exe is necessary here to create the classes because the WebService3ExtendedProperties.xsd schema is not explicitly included in the web service interface definition. What about the serialization at runtime? When parsing a Schema, xsd.exe will map xsd:any elements to fields of type XmlElement. By modifying the generated classes, changing the type of the field to System.Object rather than System.Xml.XmlElement, and decorating the field with XmlElementAttribute attributes, we can tell the framework to map the XML data to specific .NET datatypes, rather than a generic XmlElement. For example, in this snippet, the Any field will map to one of the three flavors of extended properties. [System.Xml.Serialization.XmlElementAttribute(ElementName="DvdProperties", Type=typeof(NetWSServer3.DvdPropertiesType), Namespace="")] [System.Xml.Serialization.XmlElementAttribute(ElementName="BookProperties", Type=typeof(NetWSServer3.BookPropertiesType), Namespace="")] [System.Xml.Serialization.XmlElementAttribute(ElementName="CDProperties", Type=typeof(NetWSServer3.CDPropertiesType), Namespace="")] public object Any; With these modifications to the generated classes, the .NET runtime will automatically and implicitly serialize the Product property object types to and from XML. Without this capability, the developer would have to explicitly serialize these classes to XML. And in fact, this is the approach taken with WebSphere for the extended properties types. (See the sample code for details). While developing this sample, one consideration was to determine whether to make the ProductType an enum or just a string. The benefit of an Enumeration is that the different types are explicitly stated and thus cannot be confused. However in the end, the decision not to use enum was taken because of the requirement for extensibility: we want the flexibility to create additional and possibly remove existing product types without breaking existing clients. If ProductType was defined as an enum, then future product types that get passed to old clients would break. Therefore a string was used instead because this allowed the flexibility to expand the product lines while keeping existing Web service clients still working. As with Web Service 2, the data types generated here by the tools probably will not match what a developer might write when modeling the problem in code. However, here again, the key advantage of starting with WSDL and generating code is interoperability. As with Web Service 2, we followed the general steps outlined in the introduction of this article to produce client and server projects for both Visual Studio and the WebSphere web services SDK. And here again, the resulting clients and servers are fully interoperable. Ok, enough description. Compile and run the Visual Studio projects and the Eclipse projects in the samples download to see the extensibility of Web Service 3 of this in action. Web Service 3 showed the use of complex data types, statically included as well as dynamically included in a WSDL. The support for extensible types allows for the flexibility to expand and to modify the interface with minimal changes required to the Web service and to the Web service clients. With the three Web services shown in the paper, we can see that it is definitely possible to create interoperable Web services using complex data types. The easy path through the developer toolsthe "Implementation First" approachoften leads to interoperability challenges. However, by defining the Web service interface first, in WSDL, and generating clients and servers from that interface definition, many interoperability pitfalls can be avoided. Even though we have shown the "WSDL First" approach specifically for .NET and WebSphere, the concepts illustrated apply to interoperability across all platforms. Hand-authoring WSDL is not easy. This paper also explored the approach of iteratively developing and refining WSDL files and W3C XML Schema definitions, using the prototyping tools included in Visual Studio .NET and the WSDK. Finally, the paper provided tips and pointers about likely pitfalls on the path to creating interoperable and extensible Web services. Armed with these ideas of creating interoperable Web services, we may eventually achieve the dream of ubiquitous access to any system, regardless of platform and architecture. The following is a listing of recommendations and tips reviewed in this paper. System.Web.Services.Protocols.SoapException com.ibm.ws.webservices.engine.WebServicesFault java.lang.NullPointerException When a WSDL file references other files (i.e. XSD files), you must explicitly provide the location of these files as arguments to wsdl.exe. For security reasons, wsdl.exe will not automatically load files from the schemaLocation references in the WSDL file. For example, if you're generating the code for Web Service 2, you will need to execute the following command: schemaLocation wsdl.exe WebService2.wsdl WebService2Interface.xsd WebService2SharedTypes.xsd Refer to Web Service 2 for more information on this topic. Wsdl.exe by default generates template code in C#. If you prefer another language (i.e. VB.NET), include the /l option with the command: /l wsdl.exe /l:vb WebService1.wsdl When generating a source file for a Web service (using the /server option), the tool creates an abstract template class that is associated with the WSDL document. It is recommended that you modify this file directly rather than sub-classing the generated file. For more information on this topic, refer to Web Service 2. Visual Studio .NET 2005, will support generating template source files from the WSDL directly in the IDE. In addition to this, if the WSDL document changes and the template file needs to be regenerated, the IDE will do so in such a way that any existing code already in the old template will carry over to the new one. When creating a Web service application in Visual Studio .NET, the generated project automatically provides the test page that appears when the Web service is accessed through the browser. Since we are developing Web services using the WSDL first approach, it is recommended that you disable this automatically generated WSDL and publish our own WSDL in a public location. To disable the automatically generated test page and WSDL, add the following into the <system.web> element of your web.config file of your project: <system.web> <webServices> <protocols> <remove name="Documentation" /> </protocols> </webServices> In addition to the wsdl.exe approach to creating a Web service proxy class, you can also use the built in tools in Visual Studio .NET for a more user friendly approach. The Add Web Reference dialog box will ask you to point it to a WSDL file, which it will take in then generate a proxy class. Behind the scenes, the dialog essentially calls wsdl.exe in the background to process the WSDL file. Unfortunately there is a bug in creating a client proxy if you use the Add Web Reference command in Visual Studio .NET 2002 to point to a WSDL document that uses xsd:import. If this is your case, always use the wsdl.exe command to generate the client proxy. This bug has been fixed in Visual Studio .NET 2003, which will properly retrieve all the imported files and then generate the client proxy class. With the tools provided by the WSDK, the Web services functionality in Eclipse is similar to Visual Studio. In Eclipse, you will need to create a Java Bean or EJB and use that as the template for a Web service. There are also some command line utilities you can use to generate Web service template files. You can find documentation in Eclipse to get more detailed instructions on how to do this. Thanks to Simon Guest of Microsoft for his excellent technical reviews and feedback. Also thanks to Neil Chopra and Mike Hanley of Vertigo Software for testing and helping with some of the ideas in this paper.
http://msdn.microsoft.com/en-us/vstudio/aa700847.aspx
crawl-002
refinedweb
8,801
55.24
« Previous 1 2 3 Graph database Neo4j discovers fake reviews on Amazon Digital Detective YAML in the Go Universe Listing 3 uses Unmarshal() (line 24) from the official YAML module in the Go universe to transpose the YAML data as a byte array after reading with io/ioutil (line 8) into a Go data structure. The strict Go typing plays along with the fairly casual YAML here in a fairly offhand way by defining a string-indexed hash table with entries consisting of arrays of strings. The Config type structure starting in line 12 defines the hash map with the nested string arrays in the Reviews entry. Capitalization is important here so that the YAML module can access it. Starting in line 35, two for loops iterate over all products in the hash map and then over the array of reviewers for each entry. Before line 50 compiles the command for adding the relation, the if conditions in lines 38 and 44 check whether the two endpoints of the relation already exist as nodes in the database. If the created map variable indicates that a node is still missing, the code adds to the cmd string a command that creates the node with a MERGE instruction. It terminates all commands with line breaks. In this case, it is important not to send semicolon-separated Neo4j commands, because it will cause problems if some of them define variables (e.g., reviewer1) that are reused later (when the relation is created). A semicolon terminates a command (line 56), and Neo4j then forgets all variables defined previously. Contacting the Server The toNeo4j() function contacts the browser port of the server in the container starting in line 60 assembles. It transmits the command string cmd, which it has assembled from the map data, and preceeds the instructions with a command to first delete all previously existing data. The open source package used here, cq from GitHub, is a bit outdated. Although it does not use the API module's Bolt connection supported by Neo4j on port 7687, it works fine. It's also easier to install than the default, which forces you to download some obscure Bolt binaries. In typical SQL style, line 61 contacts the server in the Docker container. Line 68 uses Exec() to send the command present in cmd over the port, which the server acknowledges with an error message if something went wrong. With the command sequence $ go mod init rimport $ go build Go fetches the libraries needed to create the binary from GitHub and creates an executable program named rimport. When called, the executable first reads the reviews.yaml file from disk and then pumps the necessary commands into the container port to the Neo4j server. The user can then send queries to the data model for fraud detection, as shown in Figure 2. Installation Troubles The current Docker image neo4j:latest drags in the latest Neo4j version 4.0.3, which does not yet support any graph algorithms. To install it, you have to download a .jar file from the Neo4j site [4] and dump it into the ~/neo4j/plugins/ directory. There, the Docker container will grab it when the Neo4j server is started, because the docker run command in Figure 3 imports the plugin directory with the -v option. Hold on, not so fast: The Graph algorithm's plugin is only available as version 3.5.9. If you think you can simply use it with a Neo4j database of version 4.0.3, think again. Right after restart, you'll see the container quickly giving up the ghost with a long, but completely meaningless, stack trace. If you install neo4j:3.5.9 instead of neo4j:latest , you will have more luck. The server starts up properly, and the database query for algorithms in the algo.* namespace reveals a long list (Figure 4). Unfortunately, you will encounter more obstacles. When you try to use one of the algorithms, an error message on the screen explains that this is not possible in a "sandbox" for safety reasons. Instead, you will need to exempt the imported algorithms from the routinely imposed restrictions. To do this, the environment variable NEO4J_dbms_security_procedures_unrestricted is set to a regular expression to specify that everything below the namespace algo enjoys free rein. The Docker command in Figure 3 already defines the variable correctly. It also sets the NEO4J_AUTH variable to neo4j/test, which tells the server to omit the otherwise mandatory password reset. Let the fun begin! Infos - "Saving and Evaluating Network Paths in Neo4j" by Mike Schilli, Linux Magazine , issue 164, June 2014, pg. 66, - Node similarity algorithm: - Jaccard index: - Retroactively installing the Algo plugin for Neo4j: - Listings for this article: « Previous 1 2 3 Buy this article as PDF (incl. VAT)
https://www.admin-magazine.com/Archive/2020/58/Graph-database-Neo4j-discovers-fake-reviews-on-Amazon/(offset)/6
CC-MAIN-2022-27
refinedweb
799
61.97
This tutorial follows Tutorial 1 Provided you are using react-router-dom the code should still work for you. I will be linking the github repo ASAP Step1 Setup files needed for tutorial. - Open your Project in VsCode a. cd projects/yourprojectnamehereb. code .c. or Just use the file menu - Open the VS Code Terminal and Get the status of git. a. git status1. You should be on the master branch and your working tree should be clean - Checkout to a new branch and set the upstream a. git checkout -b <Tutorial-2-PrivateRoute>b. git push -u origin <Tutorial-2-PrivateRoute> - Create a PrivateRoute file a. touch src/cofigs/PrivateRoute.jsx - Create a private file a. touch pages/admin/AdminHome.jsx - Add some content to the AdminHome file import React from 'react' const AdminHome = () => { return ( <div> <h1>Welcome home Admin</h1> </div> ) } export default AdminHome Step 2 Creating the Private Route File. - Import React, Route and Redirect a. imrb. imdc. import { Route as R, Redirect as RD } from 'react-router-dom'; - Setup the arrow fucntion Note: We are not using |rafce| here because we are bringing in props. (More to be explained later) a. const PrivateRoute = ({ component: Component, ...rest }) = { <R {...rest} render={props => localStorage.getItem('token') ? ( <Component {...props} /> ): ( <RD to='/' /> ) } [/]()> ); export default PrivateRoute; Lets Break this down: Components - let you split and isolate the UI into independent, reuseable pieces they are like JS functions Props - the inputs that components accept Render - Display Ternary - If Else Statement localStorage - a place where you can store data on a users machine to be used by the site ... - Spread operator - expands a string, object, or array into it's elements What are we doing? - We are bringing the component property defined on props from our AppRouter file (we will hook this up in a minute) and assinging it to a new location in state called Component. - We are then taking any remaining objects defined on props and collecting them in an argument called ...rest - After this we are setting up a route to render our props to our private componenet IF there is a token in localStorage otherwise, we are redirecting to home. Step 3 Setting up the AppRouter file to render the PrivateRoute - Open the AppRouter.jsx file and import PrivateRoute a. import PrivateRoute from './PrivateRoute.jsx'; - Import the AdminHome Page a. import AdminHome from '../pages/admin/AdminHome.jsx'; - Add a Private Route to the AdminHome Page a. <PrivateRoute path='/admin/AdminHome' componenet={AdminHome} /> - Add a NavLink to the AdminHome page a. open the NavBar.jsx file b. <NL to='/admin/adminhome/'>Admin Home<NL/> Step 4 Tying it all together - Run your app a. npm start - Open your developer tools (Chrome) Firefox works too a. right click on the page b. click inspect - Clear Tokens from localStorage if any a. In the top of the developer tool click Application b. To the right click Local Storage c. Open the local storage for the page you are on d. if there is a token delete it (click and press the x) - Try to navigate to AdminHome a. It should not work and redirect you to Home - Add a token a. In the place where we checked for tokens double click the key field and type token (be sure this matches what you are calling from local storage) b. Give your token any value - Navigate to your Admin Home - Add, Commit, Push, and Pull Request your new private route Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/skylerwebdev/setting-up-a-private-route-in-react-3ph0
CC-MAIN-2021-43
refinedweb
578
65.83