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 |
|---|---|---|---|---|---|
Virtual Worlds and ESP 310
"Instead of thinking about telepathy from a present perspective, as in 'we have/use it now,' consider it from an evolutionary standpoint.."
Sesticulus raises a similar idea in a more compact form (it could be called the haven't been slapped" argument): ."
Reader seanellis writes with his prediction of the experiment's outcome:
statistical."
Even more dubious, dpbsmith writes not to "discount the possibility of outright fraud," asking: "Are they planning to strip-search the participants for hidden transmitters and receivers??"
Further, dpbsmith is disappointed that the article ."
Reader mdkemp took issue with the implication in some readers' comments that this research was disreputable, pointing out that such research is also undertaken "at respected institutions," writing: "Research into this stuff isn't just for [k]ooks and crazies -- even Princeton has a small lab the goal of which is to experimentally gather a 'better understanding of the role of consciousness in the establishment of physical reality.' It's called the 'Princeton Engineering Anomalies Research' (PEAR) lab, and its web page can be found at princeton.edu/~pear."
This met with an acerbic response from reader aepervius, who calls PEAR "a laughing stock" with "bad hypotheses, bias, bad statistical analysis, etc." He points out critical reports critical of PEAR at skepdic and at the Skeptic Report.
Reader RexRhino expressed a common sentiment:
"Can someone tell me why this isn't as outrageous as spending tax money to research 'intelligent design'? I mean, there is no real scientific theory that describes how telepathy would work, and virtually all scientific evidence says that telepathy doesn't exist. Telepathy is pretty much to fortune telling what Intelligent Design is to creationism — turning superstition into pseudo-science to make it palatable to the modern audience. I realize that England doesn't have the same strict legal seperation between religion and state as other countries, but even if research into the mystical and supernatural isn't strictly illegal it is certainly a questionable use of taxpayer money, no? Why are people outraged over Intelligent Design but not this kind of stuff?"
Reader Pyromage provided one answer to that question, writing: "Because it's possible to devise an experiment that could provide scientific evidence in its favor. ... Such an experiment does not — even in theory — exist for [Intelligent Design]."
Other responses to the story show that at least many Slashdot readers are none too happy with research into telepathy being done with tax monies. A long thread on that very topic raised several good points:
Reader denoir kicked off this thread with a sarcastic call to "invest some more tax money on finding UFOs, the Loch Ness Monster and inventing the perpetuum mobile!"
To this, reader misleb responded "I'm always been surprised at the kind of reaction anything labeled 'paranormal' gets from rational people. Why exactly couldn't telepathy exist? Is there some fundamental law of nature which states that two people cannot communicate over a distance without sound or visual cues? Obviously, you'd have to identify a mechanism for the communications. If telepathy exists, it isn't magic. ... If you had told someone from 200 years ago that you could communicate with people across the globe in real-time, they'd probably think you were some kind of sorcerer. But since then we've discovered radio waves..."
Reader Alsee has a satirical reponse: "Why exactly couldn't invisible pink unicorns exist? Is there some fundamental law of nature which states that invisible pink unicorns cannot exist? Obviously, you'd have to identify a mechanism for invisible pink unicorns. If invisible pink unicorns exist, it isn't magic. ... Telepathy, invisible pink unicorns, elves, Zeus, telekenesis, Narnia, rain dances, flying potions, the Tooth Fairy, I'm always surprised at the reaction of rational people when they think that these things do not exist."
Wavicle offers another reason for the widespread skepticism about such research:
."
The same corner of the discussion led to a freewheeling exchange of comments on scientific credulity and exotic explanations for telepathy involving quantum mechanics.
Reader kfg writes ...' is not a theory.) A theory is model that is concordence with data. ... Which brings us back to the need to show me it exists, particularly since everything I have ever seen so far indicates that the world works just spiffily in accordance with the rules of chance."
Reader Thing 1 asserts "if the human brain works on quantum principles, and one of those principles is communication at a distance, then that tells me that telepathy is possible," and mentions the phenomenon of entanglement as a mechanism for instantaneous communication: "Through a process, two electrons become 'entangled,' and when separated experimentally up to 10 km, when the spin on one is changed, the spin on the other is changed immediately--with no speed-of-light delay."
To this, reader aardvarkjoe responds that "The problem is that, in these 'entanglement experiments,' no information is being transmitted from the first site to the second. By measuring the state of the first electron, you can instantaneously affect the state of the second electron — but according to all of the current theories, there is no way to actually use that to communicate. (If that sounds weird ... it is. Quantum theory is rather unintuitive.)"
Several readers' comments were not about the experiment at issue in this case, but rather about the James Randi Educational Foundation prize I mentioned. Two comments in particular sum up many of the others: Reader nido calls Randi a fraud with an agenda" and says this is how Randi is viewed by "people who can," to which Mr2001 responds .' ... It's a pity that there's no evidence that these experiences actually took place in reality, not just in the participants' imaginations, don't you think? Because if there were evidence, someone would be a million dollars richer."
Many thanks to everyone who took part in the discussion, in particular those readers whose comments are quoted above.
ESP, I sensed that. (Score:2, Insightful)
I think for the large part, the world of psychics is snake oil, predators preying on the gullible.
But, if you're familiar with the double-slit "interference" experiment [physicsweb.org], you may get an uneasy sense there is much for us to learn about interaction of particles, forces, energies, etc. It's not for me to determine ESP is real but I've experienced unexplainable phenomena at least to my level to understand.
One example, a very close friend in college, she was an identical twin, and talked about the typical enta
Re:ESP, I sensed that. (Score:3, Insightful)
Re:ESP, I sensed that. (Score:4, Funny)
Re:ESP, I sensed that. (Score:3, Insightful)
Don't forget the gullible dancing for money. Not everyone who operates on a false premise are predators; some are just ignorant.
But, if you're familiar with the double-slit "interference" experiment, you may get an uneasy sense there is much for us to learn about interaction of particles, forces, energies, etc. It's not for me to determine ESP is real but I've experienced unexplainable phenomena at least to my
Re:ESP, I sensed that. (Score:4, Insightful)
I've been with my wife for nearly eight years, married for four. I finish her sentences, she seems to know when I've forgotten my keys, and keeping presents and surprises secret from one another is a huge undertaking. That doesn't make us telepathically linked, though. Intuitive about each other, maybe, but that's nothing paranormal.
Ee:ESP, I sensed that. - NOT ESP!! (Score:2)
I have proof! See the star next to his name!
Re:ESP, I sensed that. (Score:2)
Re:ESP, I sensed that. (Score:5, Insightful)
Re:ESP, I sensed that. (Score:3, Interesting)
Re:ESP, I sensed that. (Score:3, Insightful)
Re:ESP, I sensed that. (Score:2)
Re:ESP, I sensed that. (Score:2)
In other words, the mind is not only selective about paranormal-sounding things. It's selective about all things, including what we consider factual.
In other words, selectivity of human mind is evenly distribu
Gullible (Score:2)
Advice: When someone says 'I was going to call you later' do not take it literally.
Re:Gullible (Score:2)
Re:ESP, I sensed that. (Score:3, Insightful)
Why not? Things with long-shot odds happen everyday. Somebody winning the 'jackpot' in a lottery has obscene odds (far worse than those two girls picking the same card) yet I don't hear people attributing ESP to it.
It happens often enough. (Score:2)
(And at certain points in your life, news that seems life changing is silly in retrospect)
That last comment isn't supposed to be a barb, since I don't know how old you are. Just a thought...
Re:ESP, I sensed that. (Score:2, Insightful)
When you break into your "can you really feel object"
Re:ESP, I sensed that. (Score:2)
Try reading a book on QM other than The Dancing Wu Li Masters and get back to us.
It's just standard procedure for every woo-woo to pull out the word "quantum" these days. And really it's just gotten old. My computer works on actual understood quantum principles that are repeated a billionfold, but there still ain't one ghost, telekinetic, telepath, or dowser that c
Re:ESP, I sensed that. (Score:2)
Re:ESP, I sensed that. (Score:2)
There's a huge
Re:ESP, I sensed that. (Score:2)
What you're arguing is semantics - no science can possibly COMPLETELY understand something by your reasoning - science explores the "how"s, not the "why"s. Stick to religion if you want to know "why" light does what it does.
Re:ESP, I sensed that. (Score:2)
So unless our understanding has grown by a substantial amount since 1988, I'd say that we don't understand light completely. As such, we don't understand the behaviour of light in arbitrary situations, such as the double slit. Indeed, we can come up with some pretty sure probabilities by wrapping math around them, but we cert
Re:That doesn't answer his question... (Score:2)
Re:ESP, I sensed that. (Score:5, Funny)
Depends. I think I have latent psychic powers, but its not very useful.
Mostly, I notice it when people call in to my job at tech support and I already know what the problem is.
And I already know the solution to their problem.
You know... Rebooting the computer
Unfortunatley I haven't been able to figure out how to strangle people remotley with my mind... yet.
Re:ESP, I sensed that. (Score:2)
I'm getting something... here it comes... you do Windows support for a living!
Re:ESP, I sensed that. (Score:2)
Re:ESP, I sensed that. (Score:2)
Not that odd really - given the (statistically) limited number of birthday card styles out there.
I don't have twins. (Score:2)
I think it's partly due to the fact that we already know what kind of card a person wants (funny, mushy, religious, plain), and there usually isn't much selection turn-over from year to year.
Have you ever picked up the same card for someone's birthday like 3 times in a row? I have. WHY DON'T THEY FIND NEW PEOPLE TO MAKE CARDS ANYWAY? Ugh.
I was just gonna say, "8 o'clock" (Score:4, Funny)
Context (Score:2)
I'm studying the effects of negative reinforcement on E.S.P. ability.
The effect? I'll tell you what the effect is, it's pissing me off!
Of course it's possible! (Score:4, Interesting)
That doesn't mean it was likely to have evolved naturally though. There does seem to be a whiff of real "irreducible complexity" in an iPod...
Re:Of course it's possible! (Score:2)
Only 400 posts... (Score:4, Insightful)
Duh! Editors w/ ESP (Score:5, Funny)
Obviously the editor has a strong premonition the other 400 were on the way!
Paranormal Scmaranormal (Score:5, Insightful)
I'm always been surprised at the kind of reaction anything labeled 'paranormal' gets from rational people. Why exactly couldn't telepathy exist?
There's nothing logically impossible about the idea of telepathy. Or the Loch Ness Monster. Or UFOs.
The thing you need to realize, however, is that they're labeled 'paranormal' for a reason. If we had solid evidence of any of them, we'd call them scientific fact. People look down on these ideas because, while there may be some people who believe in them, rigorous studies haven't been able to substantiate any of them.
That being said, I don't see any reason there shouldn't be some continued research into these areas. The more basic research, the better, I say. What doesn't make sense, however, is sinking substantial amounts of money into research in areas that show no actual promise of ever turning up anything. Or, spending a lot of time doing non-scientific work in these areas. I'm sure paranormal enthusiasts can point to lots of "evidence" for telepathy. How much of it would actually stand up to scrutiny, though?
Re:Paranormal Scmaranormal (Score:2)
Ther
Re:Paranormal Scmaranormal (Score:5, Interesting)
It goes further than that, though. This touches the question whether there are phenomena that cannot be described by current scientific practices or not. If true, then telepathy may well be unproved for a very long time.
Also, if someone is REALLY capable of telepathy, chances are high that this person keeps it a secret. Reading thoughts allow revealing true motives. If one reads the minds of ESP-interested people, one may well find some rather sinister motives (like, abusing it for stealing, blackmail, military applications..) Also, reading other's minds could be quite scary and disturbing, so it would not surprise me to find lots of insane people among the real psychics.....
Re:Paranormal Scmaranormal (Score:2)
Intuition is not tele
Re:Paranormal Scmaranormal (Score:2)
Empathy would be a logical step above intuition. If people's emotions emit signs we do not know of, and if these signs are just crude psychic projections or whatever, then it would be hard to distinguish it from intuition in the first place. Of course, once detected, an experiment would be easy: sit the supposed psychic in a sealed chamber, stick a totally random person whose mood is known (sad, amused, enraged...) in a sec
Re:Paranormal Scmaranormal (Score:2)
This wasnt mentioned as evidence, just some random thoughts. I am allowed to have random thoughts without some rationalist inquisition knocking on my door, am I not?
Well, when you have random thoughts maybe you shouldn't present them in such a manner as it looks like you're trying to defend the idea of telepathy. Given that you mentioned these random thoughts in the context of a discucussion about what science is, I think it's quite normal for someone to call you on that and say it's not scientific, and in
Re:Paranormal Scmaranormal (Score:2)
Suppose you're watching a cardsharp. He has you extract all the queens, put them back in the deck, then he shuffles it and the queens appear on the top. How did he do that?! Buggered if I know. This doesn't mean that it's "unproved" that a cardsharp can do that, bcos we've seen it happen. All it means is that we don't know the method yet.
Now telepathy. Can someone read someone else's mind? It's really a very simple test - do they continuously get i
How James Randi helped me see the light (Score:2)
Yes, and if you ask Randi he will tell you that magic tricks are also heavily dependent on the environment and situation. (The rest of the post is not aimed at you personally)
How Randi helped me see the light (a bedtime story):
Thirty odd years ago I dropped out of high school with reasonably good marks in science, shortly after this Uri Geller appered on my TV and started bending spoons and such. He conducted an "experiment" with th
Re:How James Randi helped me see the light (Score:3, Insightful)
Re:Paranormal Scmaranormal (Score:2)
You are missing the point. It isn't about detecting ESP, UFOs, ghosts, it's investigating unexplained phenomenon. People tried to explain
Re:Paranormal Scmaranormal (Score:2)
It's because it's not normal, and it sounds better than "abnormal".
-Adam
Subjectiveness (Score:5, Insightful)
People with greater than average skill are always derided by the masses. Or, as Einstein put it: "Great thinkers will always face violent opposition from mediocre minds." Just because someone might be more perceptually evolved is no reason to cast them away.
Moreover, it is vastly ignorant of us to think we know everything there is to know about consciousness or any aspect of the physical world. As soon was we start thinking that way, the sooner the evolution of science stops.
We should honor this experiment, not immediately dismiss it. Yes, let's make sure rigorous checks are in place, and that the data is properly validated. But give it a chance, eh?
Re:Subjectiveness (Score:5, Insightful)
It is not uncommon for people with psychological disorders to think they are better than everyone around them, or "more aware" of what's truly going on in the world. Especially people that have severe insecurity issues.
Re:Subjectiveness (Score:2, Interesting)
Re:Subjectiveness (Score:2)
Your response is the typical defensive "nutjob" response - whether you actually
Re:Subjectiveness (Score:3, Insightful)
Actually it is up to whomever the claim is being made to decide the validity of
Re:Subjectiveness (Score:2)
General relativity (as opposed to special relativity) wasn't testable then. But to his credit, at least the model was consistent and backed by rigorous formalism, which is far more than can be said for the woo-woo crowd.
Nowadays, our GPS satellites depend on compensating for both special and general relativistic effects, otherwise they'd be off by miles. Science wins another one. I bet that flaming ball in the sky actually i
Re:Subjectiveness (Score:2)
"Great spirits have always found violent opposition from mediocrities. The latter cannot understand it when a man does not thoughtlessly submit to hereditary prejudices but honestly and courageously uses his intelligence."
a question of power (Score:2)
Suppose, for a moment, that Telepathy was a normal phenomena, a skill that anyone could access. However would the earth's self-appointed ruling class keep the roiling masses in line?
For example, could George W. Bush's handlers have pushed the populace into initially accepting the
Re:Subjectiveness (Score:2)
People with greater than average skill are always derided by the masses. Or, as Einstein put it: "Great thinkers will always face violent opposition from mediocre minds." Just because someone might be more perceptually evolved is no reason to cast them away.
They laughed at Einstein.. but they also laughed at bozo the clown. (And in actuality, respected scientists didn't laught at Einstein). What makes you think you're Einstein, and not Bozo?
Meta: Escaped Backslash (Score:4, Interesting)
But I wish it were less centralized. Slashdot is better than newspapers because it's mainly "letters to the editor", sparked by editors' published stories. Because those LoE's are letters to each other. Maybe the top 5% by moderated points, weighted by metamoderation and negative comments (also metamoderated), of posters to each day's top story or two (by comment count), could be autoinvited to a Backslash discussion among themselves, summarizing and highlighting comments. That competition might also encourage better comments.
Deja Vu .. The First Time Around (Score:2, Insightful)
I haven't had much of this lately, but I used to see before I'd be somewhere I'd never been, people in place and all. I wasn't sure it was the same as Deja Vu as I'd actually see these places in my dreams and be stunned when I saw them come together. I think something works, but I haven't had one of these episodes for years.
Score: -5 Daft?!? I didn't foresee that!
Re:Deja Vu .. The First Time Around (Score:2)
The problem with such anecdotes is that memory is simply not reliable. Really, you forget more than you remember, and your brain just sort of invents things to fill in the gaps. Over
Re:Deja Vu .. The First Time Around (Score:2)
My High School psychology class Experiment... (Score:5, Interesting)
Everyone scored between four to six right answers except for one kid who on all three tests scored between twelve to fifteen correct answers.
Re:My High School psychology class Experiment... (Score:3, Insightful)
Everyone scored between four to six right answers except for one kid who on all three tests scored between twelve to fifteen correct answers.
Yah, and when I was in high school I measured the acceleration do to gravity, g, and found the published value to be off by 20% by my experiment. Obviously there's nothing wrong with my experiment, and someone wrong with the published value of g.
Re:My High School psychology class Experiment... (Score:3, Informative)
Re:My High School psychology class Experiment... (Score:4, Informative)
I disagree. There is a strong connection between your mind and body, and I've sat through several experiments where a person can mimic the very subtle body language of a subject and can start to have the same thoughts as the subject. It's uncanny, and you can do this yourself. Sit down with a friend and concentrate about any one thing (easier if you are emotional about it) and have your friend mimic you exactly - including breathing, then have them describe their thoughts. Most of the time they'll tell you what you're thinking, sometimes even including images.
Do that from across the room, and you've got one explanation for ESP.
Re:My High School psychology class Experiment... (Score:2)
Re:My High School psychology class Experiment... (Score:2)
Re:Prove?? (Score:2)
If your memory of the runs is correct he also improved over the course of your experiment.
This, however, to me, even more strongly suggests that the student in question was aware of some form of 'read' or 'tell', or otherwise expert in some other, completely mundane, method of doing well at t
Proof that ESP exists! (Score:2)
I want my million dollars in small bills.
How about man - machine telepathy? (Score:2)
Ever heard a tune in your mind then switched on the radio and it was there? Maybe
Re:How about man - machine telepathy? (Score:2)
Or maybe it's just selective memory. Doesn't it freak people out when you expect a system to do something nobody expected... but it doesn't ? Well, no, that doesn't freak people out because they're used to it. They only remember that one single time when you were right, and forget the thousands
Genetics vs Telepathy (Score:2)
For example, what if telepathy worked only when you were standing at a particular location? When you moved, no more telepathy. This would clearly be an environmental factor NOT genetic.
BTM
There have been both (Score:2)
Indeed, both person-associated (genetic or chance) phenomenoa have been said to occur, as well as environmental/locational.
Re:There have been both (Score:2)
Additionally, my wife can "read" colors from my mind (i.e. I think of a color and she guesses, with very high accuracy, the correct color. And no, I don't think of simple colors like red, green, or blue, bu
Evolution is not instant (Score:4, Interesting)
If we make the relatively trivial assumption that telepathy would require a relatively high level of brain function (both as a matter of technical requirement, and also of being able to process and understand the information) then suddenly the point in our evolution it would be most possible for these traits to begin to appear we have already began stagnating our gene pool by artificially protecting those of weaker traits, thus significantly reducing any evolution.
If we look through recorded time, and due to our nature likely much before recorded time as well, people who can 'hear voices' or otherwise know things they should not be able to know are typically regarded as crazy, devilspawn, witches, or some other name in which heavy medication, stoning, or burning at the stake would be prescribed. I would pose that because of this, not only would telepathy not be a survival advantage, any marked ability would indeed be a disadvantage.
IMO it's also very realistic to assume telepathy would be like other ability, and require some practice and training before it would be any more than rare and involuntary flashes of thoughts.
Re:Evolution is not instant (Score:2)
Re:Evolution is not instant (Score:2)
'Supernatural' is the label given to things that people do not understand. Yes, I realize there are a lot of hoaxes and BS out there, which is what makes the persuit of information about anything related to ESP a futile battle against an army of minds that were closed by so many liars and so many that proclaim they understand The Truth(TM) that are just as clueless as everyone else.
Imagine if you will, a video walkie-talkie. Simply a screen, a cheap camera, a m
Re:Evolution is not instant (Score:2)
The primary difference is in the training people pursue.
Ingo Swann [biomindsuperpowers.com] says the "superpowers" are universal, and can also be trained. Some people are better than others, as with any field of
Why Always with the "Quantum"? (Score:5, Informative)
Quantum Mechanics is not magic. It's also not dimly understood. It is counterintuitive, but that doesn't mean that it somehow turns black into white.
The big problem with QM is how people write about it. With the double-slit experiment, for example, you'll read a phrase like "when you observe which slit each photon goes through, the interference patterns disappear". The problem is, most people think of observation as something completely passive. But in the realm of QM, observation is very active and very destructive. In QM-speak, it goes without saying that to observe something is to change it. If the above phrase were written "when you jigger with each photon to try to get an idea of which slit it goes through, the interference pattern vanishes", it would be equally accurate and sound a lot less magical. A pretty pattern of waves on the surface of a pond will vanish if you jump into the pond to get a look at the waves up close.
Entanglement is described with equal misguidance. Usually you get a phrase like "when you measure measure one photon of the entangled pair, the other one's spin changes instantly across any distance to match". Sounds magical, right? But it ain't. The spin "changes" from a state where it has all possible values with equal probability of each into a state where you know what the value of that spin is. QM is all about probabilities and information and not so much about the actual particles. Instead of saying "the particle's spin changes", it would be more correct to say "what we know about the particle's spin changes". But instead we get shorthand that is clear to anyone who groks QM but is counterintuitive to the layman. By observing your electron (and remember, observing means you've destroyed information in it by getting the spin information out), you've gained some information about it. Because of the entanglement, you've also gained information about the other memeber of the pair, without disturbing it, at that very moment, no matter where the other member of that pair is. That's it.
Re:Why Always with the "Quantum"? (Score:2)
Anything where you don't understand how it works is magic.
Why do we find this video amusing for example? [pistolwimp.com]
If some how the video went back in time a few hundred years (and you took the laughter away) what would the people think he was doing?
Re:Why Always with the "Quantum"? (Score:2)
Re:Why Always with the "Quantum"? (Score:2)
Boring? How about fascinating!
Maybe telepathy is not possible. Maybe it is. Maybe the human race is just on the cusp of beginning to evolve it, so experiments are unpredictable. Or maybe "work without effort" is something the human race strives for, and why I'm so into automation, and people just want to believe.
Well anyway, I'm borg now so you won't be hearing from me again.
Conjecture and questions (Score:3, Insightful)
Haven't been slapped: women I find attractive, as a rule, do not have telepathy
Depending on what you find attractive in women, chances are that such women will also be attractive to others. In that event, I believe they'd be somewhat immune due to constant hinting thoughts of passerby.
Taxpayer's money: research into the mystical and supernatural isn't strictly illegal it is certainly a questionable use of taxpayer money
How many expeditions across the world, expected to fall off the "edge" were funded by what would have then been something similar to taxpayer's money?
Why exactly couldn't invisible pink unicorns exist?
There's a likelyhood to all things, as well as a case history. Cases of various paranormal events exceed those of invisible pink unicorn reports (although how something can be pink when invisible?). It leaves the possibility of lots of crazy people, lots of easily influenced/misled people (more likely), or the possibility that various paranormal circumstances may exist. Lots of things that would have been 'witchcraft' or paranormal years back are commonplace. I suppose the trade-off is in exactly how much money is spent vs the results received.
By measuring the state of the first electron, you can instantaneously affect the state of the second electron -- but according to all of the current theories, there is no way to actually use that to communicate
Why not? If you can in any how tell that the state of the second electron has been altered, and you could consistently alter/un-alter/re-alter the second electron, you could transfer binary data... with the limits being on how quickly one could read the changes given or affect a change.
It's a pity that there's no evidence that these experiences actually took place in reality, not just in the participants' imaginations, don't you think
Which leads to a previous statement. Not everyone is a liar, some people honestly (but mistakenly) believe in a paranormal ability or event that may have an existing scientific explanation beyond their own knowledge. Of course, some other unexplainable/supernatural events over time have become normal scientific data as science progressed as well.
One thing I do wonder is about experiments done with twins (quite a few interesting cases of people having an unusual 'connection' there), and experiments vs situations of duress. Sure, a million bucks is a nice incentive, but if one did have an invisible supernatural transmitter in one's head... say a weak one... a life-threatening situation might just be the thing that squeezes out the juice in it, and that's not really something that can be (legally) simulated. Certainly there are cases where humans put in "impossible" situations have gone beyond what science dictated should be possible.
Re:Conjecture and questions (Score:2)
You are using a false assumption there, which is that it's repeatable. The thing about entanglement is, you can just do it once. And you can't figure out which way it'll go. Once you observe either electron, and force it to a particular spin, the other one is forced to the opposite spin. Then you're done, they both have fixed spins. To get them to d
PEAR results (Score:3, Insightful)
I think they ought to have a World Wide Telekinetic Westling Federation where they pit two cerebral pro's against each other in ring with a noise generator between them; each combatant would either have with a big 0 or 1 on his jersey. After the bell the cumulative results in big readable digital displays in real-time above their heads.
Summary of the Backslash Summary (Score:2)
The Experiment
Many readers pointed out flaws in the experiment, it was not controlled enought to the point that any results from it would be completely invalid and would only play into the hands of the crackpots.
Proving Telepathy doesn't exist
Althought it is not possible to "prove that something doesn't exist", it is possible to show that the consequences of something existing would disagree and conflict with present knowledge and would lead to absurd consequences - reductio ad absurdum et al...
Fo
Re:Summary of the Backslash Summary (Score:2)
Sounds like a mental dictatorship.
"We decide what your scientific interests have to be! Deviating from them is heresy and will be punished by exclusion from the scientific community! Be a good scientist
Re:Summary of the Backslash Summary (Score:2)
Ah, such delicious flamebait, I cannot resist the temptation.
Ok, aside from the fact that I was not suggesting any of those things that you claim and was only pointing out "my dismay of the lack of critical thinking and imagination people have"...
I think someone's a bit touchy-feely about supposedly being "excluded" from the "scientific community", whatever that means. Unlike your characterization of science as 'mental dictatorship', things are appreciated as science based on the merit of consistant log
Re:Summary of the Backslash Summary (Score:3, Insightful)
No one is dictating to anyone what to think. The problem is the sharing of a limited resource (language). When different groups of people use the same word (science) for to represent different concepts it creates a namespace collision. We all know how in
Re:Summary of the Backslash Summary (Score:2)
Meh, we've all had those moments. (Score:2, Interesting)
Some "coincidences" do occur for many people often everyday mainly because of our own intuitive processes and subconscious processes picking up a lot more subtleties than our conscious minds are aware of - is this "telepathy" per se? Probably not, but many people make a very good business out of reading others almost as good as the real thing. Even then, our subconscious minds pick up so much of what we don't that often we'll get excited about something bad
Glitches in perception? (Score:2)
Of
ID test (Score:2)
"Because it's possible to devise an experiment [slashdot.org] that could provide scientific evidence in its favor.
I replied that
I don't think it would be too hard to come up an experiment that could falsify a particular stain of ID.
First, we'll define an impersonal ID: the intelligent designer is simply a phenomena that is intelligent, like a human being or other
Slap Theory (Score:3, Interesting)
Consider this scenario: You're in the public place. You see the woman. You look her up-and-down and think, "Hey now." The woman turns around and sees you looking her over and thinks, "Gads. What a jerk." Well, obviously, there was no telepathy involved here. She saw you looking at her like a hungry dog at a piece of meat and immediately knew what you were thinking. But what made her turn around at that moment? Was it just a coincidence? Obviously, it had to be. There's no way she could have known what you were thinking.
Or, her "sixth sense" told her there was a potential mate/threat/whatever. Automatic reaction was to look around for it. When she saw you looking her over, she figured she'd found the target of the problem (since the feelings went away) and the rest of her senses allowed her to form a better picture of what was happening and since she never really knew why she was looking around (lower brain function caused the reaction), she wouldn't chalk it up to telepathy.
Remember, there are tons of things that we do that we don't consciously do. A simple example is we pull our hands away from hot things. There's no conscious decision there. We know why we did it, sure, but there was no higher-brain decision process involved.
+5, Preinsightful (Score:2)
comment numbers understated ... (Score:2)
The only comment I remember trying to make was that my wife tends to know what's on my mind, but that's because she's known me for over 10 years and my thoughts in that area are pretty predictable
Correction: Project is privately funded (Score:2)
I made a comment about this [slashdot.org] the last time around, pointing out that despite the prevalent Slashdotter belief, this pseudoscientific research is privately funded. Here's a paste of what I said before:
I'm pretty sure there isn't any tax payer money involved. According to this page [manchester.ac.uk], the project is sponsored by a Portuguese group called the "Bial Fo [bial.com]
How to increase traffic to your blog (Score:2)
2. Select the most controversial comments.
3. Post story about controversial comments.
4. Three question marks.
5. Traffic!!!
Good job, timothy. I expect to see a lot more or your stories about gay marriage, abortion, and flag burning being posted on the main page. Keep up the dubious work.
Telepathy = some sort of Group Consciousness? (Score:2)
Also, the question needs to be asked: what physical property of the universe would allow the miniscule electrical signals in human brains to be able to be receieved and understood by persons disconnected in space? Even if only by a few millimetres? To me (at least) it seems unlikely there is this unknown quality of the universe. It seems likel
Better spent on Telepathy (Score:2)
Then again, that's just me. And, like you, I'm screwed there.
Re:I got to meet Randi (Score:3, Informative)
After having done so, many people will naturally be interested in finding out how you do so in an effort to advance hum
Re:Holographic Physics (Score:2)
Of course, this descr
No proof there (Score:2) | https://slashdot.org/story/06/07/18/2046227/virtual-worlds-and-esp?sdsrc=next | CC-MAIN-2016-40 | refinedweb | 6,444 | 62.68 |
<ac:macro ac:<ac:plain-text-body><![CDATA[
Framework: Zend_Loader_Autoloader_Resource Component Proposal
Table of Contents
1. Overview
2. References
3. Component Requirements, Constraints, and Acceptance Criteria
_Loader_Autoloader_Resource is intended to simplify loading resources that do not have 1:1 class prefix/filesystem mappings. The primary use case is for use with modular applications, to allow autoloading of module-specific classes.
- This component will implement Zend_Loader_Autoloader_Interface.
- This component will require specification of both a prefix and base directory
- This component will provide default component/subdirectory mappings
- Users will be able to register custom component/subdirectory mappings
- This component will allow autoloading arbitrarily nested classes under existing component maps
- This component should also act as an object factory and registry for the given resource namespace
4. Dependencies on Other Framework Components
- Zend_Loader_Exception
- Zend_Loader_Autoloader
5. Theory of Operation
Typically, this component will be instantiated in a module's bootstrap. It's purpose is to provide the ability to autoload components in that subdirectory, assuming a standard directory layout.
For instance, the bootstrap might do the following:
This would then allow your module code to use autoloading to arbitrary resources. For instance, the following directory structure would establish the associated classes:
When the resource autoloader is in play, you can simply instantiate these classes, without worrying where they are:
6. Milestones / Tasks
- Milestone 1: [DONE] Proposal created
- Milestone 2: [DONE] Working prototype checked into public repository
- Milestone 3: Community review of proposal
- Milestone 4: Proposal acceptance
- Milestone 5: Passing unit tests and initial documentation committed to incubator
- Milestone 6: Review for inclusion in trunk
7. Class Index
- Zend_Loader_Autoloader_Resource
8. Use Cases
Basic usage:
Using as an object factory and registry:
Registering custom resource paths:
36 Commentscomments.show.hide
Dec 17, 2008
Till Klampaeckel
<p>Great idea – any chance to share code yet?</p>
Dec 17, 2008
Matthew Weier O'Phinney
<p>Yes – see the link to the "Pastebin resource loader implementation" in the References section.</p>
Dec 18, 2008
Lars Strojny
<p>Nice thing. Even the service location issue is solved that way. When this component is settled, we can start doing proposals for automatic dependency injection. Thanks Matthew!</p>
Jan 01, 2009
fc
<p>I noticed in your Pastebin application that you are using the conventional and modular directory structure, however, the conventional doesn't have a models directory. So, the million euros question is: What happens if you don't have a modular directory structure? How do you load resources?</p>
<p>I see this working fine in modular applications, but what if I'm building small applications like these ones:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
project_a/
app/
controllers/
forms/
models/
views/
public/
project_b/
app/
...
public/
]]></ac:plain-text-body></ac:macro>
<p>Also, the way you are instantiating your class:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$foo = new Spindle_Model_Foo();
]]></ac:plain-text-body></ac:macro>
<p>Doesn't it go against the naming convention the framework uses? Shouldn't it be Spindle_Models_Foo?</p>
Jan 08, 2009
Ralph Schindler
<p>Federico, the naming convention the framework uses applies to "library" code, not "application" code. So, that said, I think that naming suggested works well.</p>
<p>I will try and do a writeup on the distinction between library and application code, as its been something that has come up alot recently.</p>
Jan 13, 2009
Simon Corless
<p>Firstly I think this is a brilliant idea and much needed. A couple of things just to clear up what you've written and may be obvious but aren't upon first glance! (to me anyway!!).</p>
<p>In the very first example under Theory of Operation you setup a basic loader you then call a form:<br />
$form = new Spindle_Form_Bug(); <br />
But your module directory structure has forms in the forms directory, from the auto loading I would assume forms should be in a Form directory?</p>
<p>If this is the case are we saying that setting up a simple autoloader as in the first example allows for the use of any resource as long as it's named correctly? Much like the autoloader now for framework components.</p>
<p>What does it do about upper and lower case naming? Should models be located at:<br />
module/model/ or module/Model? What would the default be (I assume it's as your directory structure is above).</p>
<p>With regards to this it would also be nice if the prefix was automatically set to the module name, this would save our own logic and I'm 99% sure most people would want it to generally autoload from the module.</p>
<p>Finally is the resourceloader->addResourceType() first attribute necessary?</p>
<p>$resourceLoader->addResourceType('validator', 'validators', 'Validate');</p>
<p>I haven't looked how it works internally yet but do you need to specify the type of resource it is? Wouldn't it be simpler with notation much like the helper paths?</p>
Jan 13, 2009
Matthew Weier O'Phinney
<p>Thanks for reviewing the proposal! To answer some of your questions:</p>
<p>"But your module directory structure has forms in the forms directory, from the auto loading I would assume forms should be in a Form directory?"</p>
<p>No – look at the implementation. A resource loader requires a namespace (mapped to a base directory), and then one or more resource types. Each resource type is mapped to a particular directory. In the case of a 'form' type, it maps to the 'forms' subdirectory – so class Spindle_Form_Bug is found in 'spindle/forms/Bug.php'. So, to answer your followup question, it <em>does</em> allow loading any resource as long as it is named correctly – i.e., if the namespace, resource prefix, and class name resolve to a file, then it will load that class from that file.</p>
<p>In the default implementation I provided, the following mappings occur:</p>
<ul>
<li>module name => resource namespace (e.g., 'spindle' => 'Spindle')</li>
<li>resources:
<ul>
<li>'Model' maps to subdirectory 'models' (e.g., 'Spindle_Model_' => spindle/models/')</li>
<li>'Form' maps to subdirectory 'forms' (e.g., 'Spindle_Form_' => spindle/forms/')</li>
<li>'Plugin' maps to subdirectory 'plugins' (e.g., 'Spindle_Plugin_' => 'spindle/plugins/')</li>
<li>'Helper' maps to subdirectory 'controllers/helpers/' (e.g., 'Spindle_Helper_' => 'spindle/controllers/helpers/')</li>
</ul>
</li>
</ul>
<p>The first argument of addResourceType() is used with the load() method and with overloading: $loader->loadValidator('Foo') would load 'Spindle_Validate_Foo'. It's also used to allow fetching the resource type for modifications or removal.</p>
Jan 15, 2009
Simon Corless
<p>Ok I see, I was basing the implementation off the Theory of Operation example where there is no mapping (or as far as I can see anyway!).</p>
<p>$autoloader = new Zend_Loader_Autoloader_Resource(array( <br />
'prefix' => 'Spindle', <br />
'basePath' => realpath(dirname(<em>FILE</em>)), <br />
));</p>
<p>Thus my question was meant to be do you then have to add resourceTypes to make it work? Or does the autoloader use a bit of magic and as long as there's a base prefix and path try and resolve paths based on the name?</p>
<p>If I have classes Module_Model_Test, by just setting the basic setting above would it try and autoload Module/Model/Test.php or do I have to specify the resource as addResourceType('model', 'Model', 'Model')?</p>
<p>What about my question about automatically setting he prefix to the current module? To be clear would you set every resource up in the bootstrap for all your modules or would you set them up on a per module basis? This depends on how the above question turns out.</p>
Jan 15, 2009
Matthew Weier O'Phinney
<p>There are default mappings provided in the implementation – this is why the Theory of Operation sample does not show using any mappings. So, for the default use case, if you follow the project structure recommendations that were approved in another proposal, you don't need to create any mappings. If you have additional resource types, or your directory structure is not consistent with the ZF recommendations, then you would define your own mappings.</p>
<p>In your example of Module_Model_Test, it would attempt to load it from module/models/Test.php by default.</p>
<p>As for automatically setting the prefix to the current module, there is another proposal at play. Zend_Application provides for both application-wide and module-level bootstrapping. Currently, our plan is that each module's bootstrap would register a resource loader for that module by default. This allows for each module to have it's own structure, if desired.</p>
Feb 24, 2009
Thorsten Ruf
<p>Hi Matthew,</p>
<p>personaly i'am not a big fan of the module-level bootstraping. What solution do i have to use if i need a model from another module? If there is only a ressource loader for every module, what happens in the following case:</p>
<ul class="alternate">
<li>Assuming current module is 'Spindle'.</li>
</ul>
<p>$model = new Forum_Model_Thread()</p>
<p>Isn't it a better solution to create automatically a full Autoloader for every module in bootstrap? Doing this will give you access to all module ressources.</p>
<p>A second advantage is you can provide a simple caching functionality. Thus saves the "per Request" building of the Ressource Loader.</p>
<p>What do you mean?</p>
<p>Of course i can't wait to see the final component in the next release. <ac:emoticon ac:</p>
Feb 24, 2009
Matthew Weier O'Phinney
<p>The way we are approaching it currently is that every module's bootstrap is loaded on each request (assuming the module has a bootstrap). This way all autoloaders are setup, and any routing or other tasks that may be necessary are accomplished. This immediately solves the issue of needing to use models and other resources from another module.</p>
<p>You will also have the flexibility to define your entire autoloading solution up front in your application bootstrap.</p>
<p>I do hope to add caching ability to the resource loader prior to the final 1.8 release, and it will likely work similarly to how the PluginLoader's caching works.</p>
Jan 14, 2009
Keith Pope
<p>Good proposal, I have spent a lot of time finding ways to load resources, this would be a great addition.</p>
Jan 16, 2009
fc
<p>The prefix option is mandatory and always maps to a module, but what happens if you don't have a modular directory structure? I guess you can group the MVC into a module in order to use this component. So, is it right to say that users who want to use this component have to create a modular directory structure? And therefore Zend_Application and this proposal will make the standard directory structure obsolete?</p>
Jan 16, 2009
Matthew Weier O'Phinney
<p>In the examples shown here, it maps to a module – but it doesn't have to. It does, however, assume that all items which it can autoload share a common class prefix and are grouped in a common tree. If you pass an empty string as a prefix, than the prefix is omitted, and only the resource type prefix will be used (e.g, Form_Login might map to forms/Login.php within the base directory registered for the loader). </p>
<p>Thus, it does not make the standard directory structure obsolete by any means. However, it does encourage you to choose a class prefix for your application resources – which will simplify refactoring later should you choose to utilize a modular directory structure.</p>
Jan 20, 2009
Keith Pope
<p>Hi,</p>
<p>I have been trying out the code from the spindle app and it works very well indeed, I did have a bit of trouble getting it off the git hub though, seems if you browse backwards from the link you gave it seems to go to a different fork??</p>
<p>While testing I wanted to have my ZDB row classes autoloaded, however Zend_Db_Table uses Zend_Loader::loadClass() which does not touch the autoload mechanism. I was thinking maybe we could have a way of either injecting the resourceLoader or a switch to tell the ZDB classes not to use Zend_Loader? Unless there is a way to hook loadClass into the autoloader implementation? </p>
<p>I think the need to be able to load rows/rowsets etc would be a fairly common use-case.</p>
Jan 23, 2009
Keith Pope
<p>Hi Matthew,</p>
<p>I have noticed there are two issues tracking my problem with Zend_Loader usage in Zend_Db_Table.</p>
<p><a class="external-link" href=""></a> </p>
<p>It would be cool if you could put some weight behind these issues or link them to this proposal so that all the work can be completed at together.</p>
<p>Thx</p>
<p>Keith</p>
Jan 23, 2009
Matthew Weier O'Phinney
<p>Yes, one of the factors pushing this solution and the general Autoloader proposal is to fix some issues found elsewhere in the framework. Besides the issues you link above, there are some that are related to autoloading that we simply cannot overcome with a Zend_Loader based solution (but where moving to a separate autoloader class, we can), and there are other places where using Zend_Loader could be minimized or eliminated if we can fall back to an Autoloader (which would make class_exists() calls return true).</p>
Jan 23, 2009
Keith Pope
<p>Thats great <ac:emoticon ac:</p>
<p>I have another suggestion from using your spindle implementation, when using load it would be good if you could pass in extra args that would be passed to the construct.</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
// from action helper
$this->_helper->resourceLoader->getForm('myForm', array('config_array'));
//in resource loader
$resourceLoader->load('myForm', 'Form', array('config'), $otherArgs, $etc);
]]></ac:plain-text-body></ac:macro>
<p>Though as I write this I realize that the instances are not instantiated on every call. Anyway might be something to think about.</p>
<p>Other than some little things like that it has been working very well, if this can be made uniform across the framework like you suggest I think it will make a very good addition.</p>
Jan 27, 2009
Robin Skoglund
<p>Just stopped by to say that this is a great proposal.</p>
<p>Any thoughts on when we might see it in ZF?</p>
Jan 27, 2009
Matthew Weier O'Phinney
<p>I'll be posting it to the incubator this week, and it will likely be in trunk within the month.</p>
Feb 18, 2009
Cristian Bichis
<p>Good extension. Would be a nice feature.</p>
<p>Testing it...</p>
Feb 18, 2009
fc
<p>I can see some variations in the way I'm using the getModel() method. A model can be anything, a db model, cache model, array model, etc, and at the moment I'm treating the resource type and the classes differently. For example, in my controller I can get an instance of a model using the getModel() method like this:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$user = $this->getModel('User'); // returns an instance of <class UserModel extends My_Model>
$user = $this->getModel('UserInput'); // <class UserInputModel extends My_Model_Input>
$user = $this->getModel('UserDb'); // <class UserDbModel extends My_Model_Db>
$user = $this->getModel('UserDbTable'); // <class UserTableModel extends My_Model_Db_Table>
]]></ac:plain-text-body></ac:macro>
<p>This way I have more control over what I'm loading. If I load UserDbModel, an instance of Zend_Db gets injected into UserDbModel. If I load UserInputModel, specific filters and validators get injected, etc.</p>
<p>So, my question is, what problem is this component trying to solve? Autoloading a class? That's not really a problem. The reason I'm asking is because, although some users keep asking "how do I load a model?", I don't think they are asking "how do I include a class?". What I think they are really asking is: "Hold on, there's no model in the ZF. The M is missing! Cake has it, Symfony has it, and hell, even Rails has it. So, how do I load a model?"</p>
<p>I honestly think people are struggling to understand this. Matthew's "Model infrastructure" post targets this problem, and I think it should be added to the manual, otherwise not a lot of people are going to find it.</p>
<p>Anyway, that's just my opinion.</p>
Feb 18, 2009
Matthew Weier O'Phinney
<p>This component is primarily targetted at autoloading of classes that fall under a different filesystem layout than that outlined in the Coding Standards – its original purpose was to serve as a mechanism to autoload resources (classes) falling under modules.</p>
<p>A secondary requirement is to act as an object factory and registry for the given set of resources. This allows for a couple of things: first, the ability to re-use objects within the application lifetime, and second, the potential to provide dependency injection during object instantiation. This latter is not directly treated, in part because we're not addressing what objects may need to be injected into the various resources. However, you can easily extend the resource loader to do this, and it is an intended part of the design.</p>
Feb 18, 2009
fc
<p>Great. "Provide dependency injection during object instantiation", I like the sound of that. I'm glad we finally have a resource loader!</p>
Mar 02, 2009
Simon Corless
<p>I've just implemented the autoloader in my test application and I like it a lot! (And it works well so far).</p>
<p>One question, if I have sub directories do I need to specify each one as a prefix / directory?</p>
<p>i.e.<br />
Model - models/<br />
Model_Rowset - models/rowset/<br />
Model_Row - models/rows/</p>
<p>$autoloader->addResourceType('model', 'models', 'Model_');<br />
$autoloader->addResourceType('modelRowset', 'models/rowsets', 'Model_Rowset_');<br />
$autoloader->addResourceType('modelRow', 'models/rows', 'Model_Row_');</p>
<p>Would each of the above need a mapping or is there a way to make Model pick up it's sub directories. It doesn't appear to by default so I'm assuming the answer is to set each one (which is probably correct as they are individual resources).</p>
<p>Also in other elements of the framework that require paths if an additional (or un-required) / is added to the path passed to the element it is removed (or more correctly a new one is not added). For the sake of continuity should the autoloader not do the same?</p>
<p>i.e. at the moment the following seems to occur:<br />
$autoloader->addResourceType('model', 'models', 'Model_');<br />
path: base_path/models/</p>
<p>$autoloader->addResourceType('model', 'models/', 'Model_');<br />
path: base_path/models//</p>
<p>This is just an observation, I don't know how much of an effect the check has on speed.</p>
<p>Thanks</p>
Mar 03, 2009
Matthew Weier O'Phinney
<p>First off, as you create your resource maps, the third "namespace" or "component" argument does not need a trailing '<em>' – it in fact will get stripped off. As for the trailing slash, I _think</em> we trim it off already; if not, I'll add a check for that.</p>
<p>Second, if you do your directory structure the way you suggest, yes, you'll need to create a mapping per resource type. But there's an easier way. <ac:emoticon ac:</p>
<p>If you have:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
models/
Row/
User.php
Rowset/
Users.php
]]></ac:plain-text-body></ac:macro>
<p>then you can simply say "new Namespace_Model_Row_User()", and it will happily do its business. The key to allowing the resource loader to find items in subdirectories is to simply name the subresource segments following ZF coding standards.</p>
Mar 03, 2009
Simon Corless
<p>Stupidly that's how I had it originally before I started using the autoloader! Changing it back works perfectly thanks.</p>
<p>As mentioned in my first comment the directory path trailing / is added but is not stripped if one is used, the additional prefix underscore is added.</p>
Mar 03, 2009
Simon Corless
<p>How do I go about using multiple autoloaders, if I can?</p>
<p>I have my defaults for the module the user is currently in using Application_Module_Autoloader but I also want to invoke the account module during the controller plugin process to authenticate the user. This has the prefix Account_Model_User and is invoked from a different plugin to the one the autoloader is run in.</p>
<p>How do I allow this to work? The obvious way is to call the file directly via include, this may or may not be faster anyway?</p>
Mar 03, 2009
Matthew Weier O'Phinney
<p>Each autoloader has its own instance; you simply instantiate multiple autoloaders.</p>
<p>Zend_Application will have a 'modules' or 'module' resource which, as part of its work, instantiate a Zend_Application_Module_Autoloader for each registered module and attach it to the module bootstrap as well as the main autoloader instance.</p>
<p>In the meantime, simply loop through the results of getControllerDirectory(), and instantiate them:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$loaders = array();
foreach ($front->getControllerDirectory() as $module => $directory) {
$loaders[$module] = new Zend_Application_Module_Autoloader(array(
'namespace' => ucfirst($module),
'basePath' => dirname($directory),
));
}
]]></ac:plain-text-body></ac:macro>
Mar 06, 2009
Cristian Bichis
<p>Hi,</p>
<p>I am using by not more than one week resource autoloader. Which makes working with modules and their resources very good.</p>
<p>But, i have also one problem. I am working over an application with multiple modules. Things started to mess up when i added for two modules (or even for one module) models, plugins, forms with same name as: Users, Acl, Auth, aso.</p>
<p>Due to this similarity of names is a terrible mess into my Eclipse now... Always when i saw opened an Acl.php file i need to check before:</p>
<ul class="alternate">
<li>what module is related ?</li>
<li>what's the purpose: is model, plugin, aso ?</li>
</ul>
<p>If it's not the file needed i am start looking over project tree, and of course, i need to look very carefully to pick the right file.</p>
<p>I am wondering if is not maybe an ideea to add a facility to allow file names as:<br />
Admin_Plugin_Acl.php instead of Acl.php. This way i think would be much easier to "locate" files into opened files list.</p>
<p>That's just an ideea... Resources autoloading is great otherwise...</p>
Mar 06, 2009
Matthew Weier O'Phinney
<p>In our naming conventions, '_' indicates either a directory separator, a component separator – putting it into the filename breaks many assumptions and introduces unnecessary complexity into how classes are loaded.</p>
<p>The class name should tell you what it is, and the directory structure should as well, to a certain degree. Again, looking at the recommended directory structure for modules:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
foo/
forms/
Login.php
User.php
models/
User.php
apis/
User.php
]]></ac:plain-text-body></ac:macro>
<p>Yes, there are three "User.php" files – but the directory structure clearly indicates their purpose. Additionally, the classes they contain will be different: Foo_Form_User, Foo_Model_User, and Foo_Api_User.</p>
<p>Different IDEs and editors deal with open files differently. Vim, for instance, allows you to see the entire path to the file, and for each open file, which allows you to determine at a glance which file you need to work with. (Additionally, the status bar tells you the filename and path.) Code folding in editors makes it easy to trivially jump around and determine the class name if you forget.</p>
<p>While I understand your pain, explore your IDE carefully, as you can likely get it to help you in situations like these.</p>
Mar 24, 2009
Rick
<p>Unless I'm missing something, there is a <strong>performance problem</strong> with the current code that is trivial to fix.</p>
<p>The performance could be O(1), but currently it's O( n ). The loop in the main My_Loader_Autoloader class is unnecessary. It could be removed if the array of My_Loader_Autoloader_Resource classes were stored as an associative array keyed by prefix. So, instead of parsing the class to be autoloaded within each My_Loader_Autoloader_Resource class and checking for the prefix, simply do that in the main My_Loader_Autoloader class. Simplified example:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
// ...
if(isset($this->_autoloaders[$prefix]))
// ...
]]></ac:plain-text-body></ac:macro>
Mar 24, 2009
Matthew Weier O'Phinney
<p>I have three comments.</p>
<p>First, the code here is out of date with the current implementation. Please look at the code in the incubator, which is much different from what is presented here in order to make your commentary. I'll try and update the code samples here, but this is lower priority than documenting the code at this point.</p>
<p>Second, it does not make sense to associate a prefix or multiple prefixes with each and every autoloader; some autoloaders may not be prefix based (PEAR is a good example, as there is not a common prefix across all classes).</p>
<p>Third, it's entirely possible that more than one autoloader will target the same prefix. In such a case, doing a key-based lookup could result in a false negative as another, later registered autoloader would be capable of loading the class.</p>
Mar 24, 2009
Rick
<p>Thanks for the clarification Matthew.</p>
<p>The Zend_Loader_Autoloader is now more complex, but performance is better now since only Zend_Loader_Autoloader_Resource objects that were instantiated with the proper namespace (prefix) will be attempted.</p>
<p>Still, considering Zend_Loader_Autoloader_Resource objects are allowed only one namespace (prefix) and assuming no two Zend_Loader_Autoloader_Resource objects will share the same namespace, perhaps it's better to register a new, simpler autoloader. After all, loading resources was the intent of this proposal.</p>
<p>Something unrelated that I noticed was that namespaces are stripped of an underscore in Zend_Loader_Autoloader_Resource. So, for example, the loading of My_Class MyClass may be attempted by the same Zend_Loader_Autoloader_Resource object?<br class="atl-forced-newline" /></p>
Mar 24, 2009
Matthew Weier O'Phinney
<p>You're making some rather broad assumptions that may or may not be true. First, the primary Autoloader class is not registering <em>only</em> resource autoloaders; it is meant to manage arbitrary autoloaders, which may be resource autoloaders or userland autoloader implementations. As such, there may be overlap at times – a general purpose autoloader and a resource autoloader may both be intercepting the same namespace.</p>
<p>The reason the underscore is stripped inside of the resource autoloader is that the classes served by Zend_Loader_Autoloader_Resource are expected to follow ZF naming conventions – not arbitrary conventions. As such, we strip it off, as the comparison will always be with the segment of the class preceding the first underscore. For Zend_Loader_Autoloader, namespaces can be arbitrary, and may or may not load classes following ZF naming conventions.</p>
<p>Now, all of this said... there is one piece of development left with Zend_Loader_Autoloader, and it has to do with what you're touching on: having Zend_Loader_Autoloader::autoload() do some optimistic matching of namespaces to determine which autoloaders to try. It's still marked as a todo in development, and you'll likely see this feature before the 1.8 release.</p>
Mar 24, 2009
Matthew Weier O'Phinney
<p>Also, one more thing, can we move this discussion to the mailing lists instead of the proposal page?</p>
<p>Thanks.</p> | http://framework.zend.com/wiki/display/ZFPROP/Zend_Loader_Autoloader_Resource+-+Matthew+Weier+O'Phinney?focusedCommentId=10158199 | CC-MAIN-2014-42 | refinedweb | 4,652 | 53.61 |
Click Once and Unbind
Have something happen on a click event, but only once! Unbind the click handler after the element has been clicked once.
$('#my-selector').bind('click', function() { $(this).unbind('click'); alert('Clicked and unbound!'); });
Also see Ben's comment below for jQuery's .one() function which is essentially the same thing.
Doesn’t this have the same effect as:
$(‘#my-selector’).one(‘click’, function() {
alert(‘This can only happen once’);
});
?
Indeed it is, thanks for posting.
The bind formula does allow you to re-bind the click event later if needed.
I need to re-bind a click event after some animate effects have been applied. What I want to happen is allow the user to click the button only once until the animate sequence has completed. In other words click (only allow once until event finishes), unbind, animate, re-bind click. I have had some trouble with this, any suggestions?
Instead of binding and unbinding the event, maybe instead just check if the element is animated before doing what you were going to do.
You can test if something is currently being animated with :animated as part of the selector.
Sweet! thanks guys.
did not know the one() trick : -)
art
Hey,
one() is a nice feature, but not always is a working solution. When we have a function, and inside we bind click event, to call that function recursively, we need to unbind the callback before we can call the function – if not, we get infinite loop.
function f()
{
$('foo').click(function(){
$(this).unbind('click');
f();
});
// something else
}
We cannot do that with one() function. But thanks for the tips!
Good trick, but be carreful with the unbind(‘click’) wich will unbind all click events. Use namespace for this is safer. To be sure that only the good click event is unbinded :
$('#my-selector').bind('click.myEvent', function() {
$(this).unbind('click.myEvent');
alert('Clicked and unbound my event!');
});
is possible to remove unbind on blur ?
As others have said .one() is the best solution, but if you need to bind / unbind, you should be very careful when using $(‘#selector’).unbind(‘event’), as all listeners for the ‘event’ will be unbound.
This will ensure that you are only unbinding the one listener. | http://css-tricks.com/snippets/jquery/click-once-and-unbind/ | CC-MAIN-2014-42 | refinedweb | 375 | 68.67 |
Build an Alexa With Raspio Pro Hat and Raspberry Pi
Introduction: Build an Alexa With Raspio Pro Hat and Raspberry Pi
Hello there,
The Amazon Echo let's you talk and ask questions to your computer. It adds 'Artificial Intelligence' to your machine. It' s a lot of fun!
But for the moment, the 'Echo' is only available in the USA and it has a certain pricetag....
Luckely! You can make one yourself, using a Raspberry Pi. It works outside the USA and it is much cheaper.
What's the difference between the Amazon Echo and your homemade Alexa?
- On the homemade version, you have to push a button before asking a question. It is not allowed to put your own Alexa in 'listining' mode.
- The design of your Alexa of course. You can dress it up the way you want :-)
I've built my Alexa for Raspberry Pi, using the Raspio Pro Hat add-on board. It makes wiring your project much more simple and save!
Materials:
- Raspberry Pi 3
- Raspio Pro Hat
- USB microphone
- Speaker with 3.5mm audio jack
- RGB-led
- Button (momentary switch)
- some male-to-male wires
Let' get started!
Step 1: Installing Alexa on Your Pi
I'm starting with the assumption you have a Raspberry Pi up and running. I won't give you a detailed description on how to install an Alexa on your Pi! There are already some good tutorials on the web. I'll give the links of the 2 I used for this project.
I used the code of Novasprit Tech, wich you can download from Github:
I've used the tutorial of TheRaspberryPiGuy, which helps you through wonderfully through the steps of making an Amazon account and getting all the settings right:
The other tutorial i've used is the one of Novaspirit Tech. This one helps you with configuring a button (momentary switch) and leds:
Step 2: Raspio Pro Hat and Wiring Your Alexa
Why do I use a Raspio Pro Hat ()?
Well, it's makes your life, the wiring and your project design a lot easier!!!
- The Raspio Pro Hat puts the Raspberry Pi's GPIO ports in numerical order and clearly labelled. You don't have to count pins or wonder which port you're connecting to.
- LEDs need no current-limiting resistors because they are already built-in.
- The Raspio Pro Hat also has a protection circuit on each GPIO port, which means you won't damage your Pi's ports by wiring something up incorrectly.
Another advantage of the Raspio Pro Hat: it keeps your project very compact! The hat fits nicely on a raspberry and they are well connected together. That makes it easier to place it in a box or the make a custom fit enclosure!
Now to the wiring!
- The button (momentary switch) is connected to GPIO pin 18
- The RGB-led is connected to pins 24, 25 and 27. Make sure you orientate the RGB pin correctly!
- the first pin of the led goes to GPIO pin 24. This is the pin for the colour Red
- the second pin (the longest one) goes to GND
- The third pin goes to GPIO pin 25. This is the pin for the colour Green
- The fourth pin goes to GPIO pin 27. This one is for Blue
This hasn't got much to do with wiring, but don't forget to put your microphone in an usb port!
Step 3: Make Some Changes to the Alexa Code
In order to have the RGB-led working and to have a blue status light, you have to make some changes to the code.
While your doing that, I also recommend the following change to cleanup the GPIO-ports after interrupting the program with CTRL-C.
Look for the file 'main.py' in the 'AlexaPi' folder
1. Around line 56, you should find the Alexa function:
def alexa():
GPIO.output(lights[0], GPIO.HIGH)
Change this into
def alexa():
GPIO.output(27, GPIO.LOW) #blue light out
GPIO.output(24, GPIO.HIGH)
2. Around line 106, i'v added a line of code:
GPIO.output(lights, GPIO.LOW)
GPIO.output(27, GPIO.HIGH) #blue light on
3. Around line 111, after
def start():
add
GPIO.output(27, GPIO.HIGH) #blue light
4. Around line 116, after ifval != last:
add
GPIO.output(27, GPIO.LOW) #blue light out
5. For adding the GPIO cleanup, go to the end of the file.
after line 143: if __name__ == "__main__":
ad this try:
and finally, after the last line: start()
add this
except KeyboardInterrupt:
GPIO.cleanup()
print " clean program exit."
pass
But I recommend to use the file you can download here. It is very important that all the indentations in the code are correct. Otherwise you will get problems with your LED!
Step 4: Status LED
The status led is an RGB-led which has 4 colours defined:
- Blue: Alexa is ready to take your question
- Green: Alexa is listing to your question
- Orange: Alexa is thinking
- Red: Alexa is answering your question
Remember: You have to push and keep pushing the button throughout asking your question!!
Step 5: Auto-start and Designing Your Alexa
You can program your raspberry to start the Alexa program on boot.
There is an exellent tutorial of my fellow countryman Frederick Vandenbosch, who has written a script not only to make Alexa start at boot, but to also check if the service is running and if not, to start it up again!
You can give your Alexa whatever desing you want! Built it in a box, in a desk, in a closet,..... or make your own enclosure! Frederick used a nice arcade button and a cardboard box with a magnetic lid.
Check it out here!
Step 6: Speak Up, Alexa!
As you noticed in the video, my Alexa isn't speaking very loud.....
The reason for that could be the use of an old speaker with a 3.5mm audio jack. In order to get my speaker working, I had to force the sound to go to the audio jack. You can do this by running the command:
sudo raspi-config
Then, go to the advances options and choose audio. There you can select the audio jack.
It is possible to use an usb speaker. Frederick Vandenbosch has made his Alexa with a usb speaker. Check it out!
So, I hope you like this 'tutorial' and have a go at it yourself!
Good luck!!!! | http://www.instructables.com/id/Build-an-Alexa-With-Raspio-Pro-Hat-and-Raspberry-P/ | CC-MAIN-2017-39 | refinedweb | 1,082 | 82.75 |
I need help with a program i am writing. It takes in a line from the user and then decides wat to do. there are to many options to spesify. some of the options are:
set TARGET 453.212.556.22
This command will differ becuase the host will never be the same.
set FUNCTION create:tcp
This function will also differ becuase there are allot of things that can be created like: reverse tcp connection, vnc session, webcam session.
use NETWORK 10.0.0.2
That will be the defualt gateway, there is also going to be allot of them.
>: download "filename" "destination"
This is going to download a file from the computer to the other computer.
See my problem isnt to write these functions. The problem is i cant seem to make my "input string" into keywords so that it can choose the write action. I cant really go and type:
set TARGET 0.0.0.1
All the way up to newest ip address, that would take ages and the program would be to big.
So i need to make my program read the firs few words:
set TARGET
and then get the next word:
10.0.0.0
One might say that i am trying to make a terminal (for linux users) or a cmd (for microsoft user).
it should act just like a cmd / terminal: getting the user input. deviding it into keywords so that it can choose wat to do.
You cant tell me that microsoft's or linux's terminal has each and every ipadress + any other possible name of a program or directory in its database. They must have used keywords.
Here is my code:
NOTE: this code istn my actual code, this is just to demonstrate what i am saying:
#include <iostream> #include <someotherheaders> using namespace std; int vncsession(); { //connects to other computer using vnc } int downloadfile(string filnamelocation, string filenamedest) { // downloads a file from target to destination } int main() { string input; cout<<">: "; getline(cin, input); if(line == "use FUNCTION ") vncsession(); else if (line == "download ") downloadfile(keyword1, keyword2); }
So my question actually is: How am i going to make my program brake that line into keywords and then do what it must. I have tried using an enum before but it didnt work. | https://www.daniweb.com/programming/software-development/threads/421117/help-with-strings | CC-MAIN-2017-09 | refinedweb | 382 | 70.84 |
How can I write to SiPy flash memory?
I need persistent storage for my application and intend to use the internal flash memory. The spec sheet says that there is 4MB flash but I can't find any documentation for using the flash. We are not designing another pcb and intend to just use the sipy board with a power supply for a demo. Without having the ability to use onboard flash memory, the application isnt much use when the power resets which would happen periodically.
@jmarcelino Thank you for sharing this. To add to this question, are there code example of we can persist an array of structs to the file system? I have a clear idea of how I want to implement a simple persistent database but I cant find micropython examples of doing so. The btree library would have been great but I realised I couldnt use it in this version of the port.
- jmarcelino last edited by jmarcelino
You can write files to the onboard /flash filesystem, there's about 512Kb available
(the stated 4MB includes the space taken up by two copies of MicroPython and some system storage area)
See this existing topic on how to read/write to files:
more info about my Sipy
MicroPython v1.8.6-724-g2b9ed601 on 2017-07-28; SiPy with ESP32
Type "help()" for more information.
import os
os.uname()
(sysname='SiPy', nodename='SiPy', release='1.7.8.b1', version='v1.8.6-724-g2b9ed601 on 2017-07-28', machine='SiPy with ESP32', sigfox='1.0.
1') | https://forum.pycom.io/topic/1661/how-can-i-write-to-sipy-flash-memory | CC-MAIN-2022-21 | refinedweb | 259 | 63.09 |
This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers
Obtaining parallelism in Python* has been a challenge for many developers. In issue 35 of The Parallel Universe, we explored the basics of the Python language and the key ways to obtain parallelism. In this article, we’ll explore how to achieve parallelism through Numba*.
There are three key ways to efficiently achieve parallelism in Python:
ctypes
cffi
All three methods escape the global interpreter lock (GIL), and do so in a way that’s accepted within the Python community. The Numba framework falls under the third method, because it uses just-in-time (JIT) and low-level virtual machine (LLVM). The Numba IR is changed from a stack machine representation to a register machine representation for better optimization at runtime. From there, the range of options and parallelism directives opens up.
In the following example, we’re using pure Python to give Numba the best chance to optimize without having to specify directives:
import array
import random
from numba import jit
a = array.array('1', [random.randint(0,10) for x in range (0,10000000)])
@jit(nopython=True, parallel=True)
def ssum(x):
total = 0
for items in x:
total+=items
return total
%timeit sum(a)
111 ms ± 861 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit ssum(a)
4.2 ms ± 108 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# Nearly 26X faster!
Pure CPython bytecode is easier for the Numba interpreter to deal with compared to mixed CPython and NumPy code. The @jit decorator tells Numba to create the IR, and then a compiled variant, before running the function. Note the nopython attribute on the decorator. This means that we don’t want to fall back to stock interpreter behavior if Numba fails to convert the code (more on this later). We used Python arrays instead of lists because they compile better to Numba. We also created a custom summation function because Python’s standard sum has special iterator properties that won’t compile in Numba.
@jit
nopython
The previous example works well for general Python. But what if your code requires the use of scientific or numerical packages like NumPy or SciPy? Take, for example, the following code that calculates a resistorcapacitor (RC) time constant for a circuit:
import numpy as np
test_voltages = np.random.rand(1,1000)*12
test_constants = np.random.rand(1,1000)
def filter_time_constant(voltage, time_constant):
return voltage * (1-np.exp(1/time_constant))
%timeit filter_time_constant(test_voltages, test_constants)
11.2 µs ± 145 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In this case, we’ll use the @vectorize decorator instead of @jit because of NumPy’s implementation of ufuncs:
@vectorize
ufuncs
from numba import vectorize
@vecotrize
def v_filter_time_constant(voltage, time_constant):
return voltage * (1-np.exp(1/time_constant))
%timeit filter_time_constant(test_voltages, test_constants)
4.74 µs ± 46.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Over 2x faster!
When dealing with specialized frameworks such as NumPy and SciPy, Numba is not only dealing with Python, but also with a special type of primitive in the NumPy/SciPy stack called a ufunc, which normally means one would need to create a NumPy ufunc with C code—a difficult proposition. In this case, the np.exp() is a good candidate, since it’s a transcendental function and can be targeted by the Intel® Compiler’s Short Vector Math Library (SVML) in conjunction with Numba. Both @vectorize and @guvectorize can use Intel’s SVML library and help with NumPy ufuncs.
ufunc
np.exp()
@guvectorize
While Numba does have good ufunc coverage, it’s also important to understand that not every NumPy or SciPy codebase will optimize well in Numba. This is because some NumPy primitives are already highly optimized. For example, numpy.dot() uses the Basic Linear Algebra Subroutines (BLAS), an optimized C API for linear algebra. If the Numba interpreter is used, it will actually produce a slower function because it can’t optimize the BLAS function any further. To use the ufunc optimally in Numba, we’d need to look for a stacked NumPy call, in which many operations to an array or vector are compounded. For example:
numpy.dot()
%timeit np.exp(np.arcsin(np.random.rand(1000)))
19.6 µs ± 85.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
@jit(nopython=True)
def test_func(size)
np.exp(np.arcsin(np.random.rand(1000)))
%timeit test_func(1000)
16 µs ± 80.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
The Numba @jit performance is slightly better than the straight NumPy code because this computation has not one, but three, NumPy computations. Numba can analyze the ufuncs and detect the best vectorization and alignment better than NumPy itself can.
Another area to tweak Numba’s compilation directives and performance is using the advanced compilation options. The main options used are nopython, nogil, cache, and parallel. With the @jit decorator, Numba attempts to choose the best method to optimize the code given to it. However, if the nature of the code is better known, you can directly specify a compilation directive.
nogil
cache
parallel
The first option is nopython, which prevents the compilation from falling back to Python object mode. If the code is unable to convert, it will instead throw an error to the user. The second option is nogil, which releases the GIL when not processing non-object code. This option assumes you’ve thought through multithreaded considerations such as consistency and race conditions. The cache option stores the compiled function in a file-based cache to avoid unnecessary compilation the next time Numba is invoked on the same function. The parallel directive is a CPU-tailored transformation to known reliable primitives such as arrays and NumPy computations. This option is a good first choice for kernels that do symbolic math.
Stricter function signatures improve the opportunities for Numba to optimize the code. Defining the expected datatype for each parameter in the signature gives the Numba interpreter the necessary information to find the best machine representation and memory alignment of the kernel. This is similar to providing static types for a C compiler. The following examples show how to provide type information to Numba:
@jit(int32(int32, int32))
# Expecting int32 values when being processed
@jit([(int64[:], int64 int64[:])]
# Expecting int64 arrays values when being processed
@vectorize([float64([float64(flat64, float64)])
# Expecting float64 arrays values when being processed
In general, accessing parallelism in Python with Numba is about knowing a few fundamentals and modifying your workflow to take these methods into account while you’re actively coding in Python. Here are the steps in the process:
Achieving parallelism with Numba just takes a bit of practice and the right fundamentals. Getting both the performance advantages of stepping out of the GIL while having maintainable code is a testament to the Python community’s hard work in the scientific computing space. Numba is one of the best tools to achieve performance and exploit parallelism so it should be in every Python developer’s toolkit.
Get the software
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | https://www.codeproject.com/Articles/5247893/Parallelism-in-Python-Using-Numba-2?PageFlow=Fluid | CC-MAIN-2019-51 | refinedweb | 1,235 | 54.73 |
My tests on Firefox:
should we also rename here?
sib-route→
solid-route
sib-router→
solid-router
As we were not using the package manager for js dependencies but the es6 import on cdn, we don't have an overview of:
here is the list of the differents external libraries I found in the code of sib-core:
import JSONLDContextParser from '';
import Calendar from '';
import Leaflet from '';
import JSONLDContextParser from '';
import SlimSelect from '';
import asyncSome from '';
import asyncEvery from '';
import asyncToArray from '';
import asyncChain from '';
import asyncFilter from '';
import asyncReduce from '';
import asyncSlice from '';
import asyncMap from '';
and soon
fuse.js,
portal.js,
rxjs and/or others
In a first time I suggest to not allow to change fuse settings and use default settings (suitable in most case).
I someone ask it, we'll think about it.
Another improvement: it will not only filter, it will also reorder by relevance.
Indeed @Alice-P, by default the fields starting with
@ are ignored. (see)
permission doesn't start by
@ so it should be visible.
However on version 0.8 it was indeed hidden.
I suspect that this change in behaviour was introduced by a
base_context modification. What do you think @matthieu?
this should also solve some other problems like typing mistake, accented letters, upper/lower case
We probably need to use "fuzzy-search" library like fuse.js or fuzzyset.js
Clément (920ec5ad) at 26 Feb 07:52
Clément (920ec5ad) at 25 Feb 03:27
update: retro compat "solid" → "sib" prefix | https://git.happy-dev.fr/clement.atom | CC-MAIN-2021-39 | refinedweb | 248 | 63.29 |
StomperStomper.
I've looked at the stomp client by Jason R. Briggs. I've based some of the 'function.
Release Process
Submit a pull request with tests if possible. I'll review and submit. All tests must pass. I tend to run against python3.7 nowadays. I will then increment the version, add attribute and then release to pypi if all is good.
Help Oisin remember the relase process:
# clean env for release: mkvirtualenv --clear -p python3.7 stomper # setup and run all tests: python setup.py develop python setup.py test # Build and release to test.pypi.org first: pip install twine python setup.py sdist bdist_wheel twine upload --repository-url dist/* # On success twine upload dist/* # Commit any changes and tag the release git tag X.Y.Z
Supported STOMP Versions
1.1
This is the default version of the of STOMP used in stomper versions 0.3.x.
1.0
This is no longer the default protocol version. To use it you can import it as follows:
import stomper.stomp_10 as stomper
This is the default version used in stomper version 0.2.x.
Version History
0.4.2
Thanks to for contributing a fix to include the license in the distribution. OM: Added minor fix to support test.pypi.org uploading before releasing. Document my release process to help me next time around.
0.4.1
Thanks to Ralph Bean () contributing a fix to setup.py and utf-8 encoding under python3.
0.4.0
Thanks to Lumír 'Frenzy' Balhar () contributing python3 support.
0.3.0
This release makes STOMP v1.1 the default protocol. To stick with STOMP v1.0 you can continue to use stomper v0.2.9 or change the import in your code to:
import stomper.stomp_10 as stomper
Note Any fixes to STOMP v1.0 will only be applied to version >= 0.3.
0.2.9
Thanks to Ralph Bean for contributing the new protocol 1.1 support:.3
OM: I've fixed issue #9 with the example code. All messages are sent and received correctly. 'nn' 'nn' 'x 'nn' between the header and the body, which I think is missing (it currently has only one 'n').
- Added CONNECTED to VALID_COMMANDS so syncBuffer() does not decide these messages are bogus.
- Added new unit test file teststompbuffer which covers the new functionality. | https://libraries.io/pypi/stomper | CC-MAIN-2020-16 | refinedweb | 390 | 70.9 |
Progress.swift :hourglass:
Just wrap the
SequenceType in your loop with the
Progress SequenceType and you'll automatically get beautiful progress bars.
Updating the progress bar does not work in the Xcode console because it does not support the cursor movements. If you want it to look nice run it in a real terminal.
Example
Just take a regular loop like this
for i in 1...9 { ... and wrap the
1...9 range in the
Progress type and you'll automatically get a nice progress bar.
import Progress for i in Progress(1...9) { ... }
Creates this output:
$ 4 of 9 [------------- ] ETA: 0:00:05 (at 1.01 it/s)
It also works with all the other types adopting the
CollectionType protocol like dictionarys:
Progress(["key": "value", "key2": "also value"]) and arrays:
Progress([1, 52, 6, 26, 1]).
You can also create the progress bar manually without a sequence type:
var bar = ProgressBar(count: 4) for i in 0...3 { bar.next() sleep(1) }
Configuration
You can configure the progress bar by combining single building blocks of type
ProgressElementType.
Either by setting a default configuration:
ProgressBar.defaultConfiguration = [ProgressString(string: "Percent done:"), ProgressPercent()]
which creates the following result:
$ Percent done: 80%
or by providing a specific configuration in the Process initializer:
Progress(0...10, configuration: [ProgressPercent(), ProgressBarLine(barLength: 60)])
resulting in something like this:
$ 100% [------------------------------------------------------------]
Available
ProgressElementType elements:
ProgressBarLine(The actual bar. E.g. "[---------------------- ]").
ProgressIndex(The current index & overall count. E.g. "2 of 3").
ProgressPercent(The progress in percent. E.g. "60%").
ProgressTimeEstimates(Estimated time remaining & items per second. E.g. "ETA: 00:00:02 (at 1.00 it/s)").
ProgressString(Adds an arbitrary string to the progress bar).
Installation
Cocoapods
Progress.swift is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "Progress.swift"
Carthage
To integrate Progress.swift into your Xcode project using Carthage, specify it in your Cartfile:
github "jkandzi/Progress.swift"
Run
carthage update to build the framework and drag the built
Progress.framework into your Xcode project.
Swift Package Manager
To install with the Swift Package Manager, add the following in your
Package.swift:
import PackageDescription let package = Package( name: "MyProject", dependencies: [ .Package(url: "", majorVersion: 0) ] )
Manual
You can also copy the
Progress.swift file into your Xcode project.
Contribution
You are welcome to fork and submit pull requests.
Author
Justus Kandzi, justus.kandzi@gmail.com
License
Progress.swift is available under the MIT license. See the LICENSE file for more info.
Github
Help us keep the lights on
Dependencies
Used By
Total: | https://swiftpack.co/package/jkandzi/Progress.swift | CC-MAIN-2019-18 | refinedweb | 423 | 52.76 |
At present I am working on 2d side scrolling game.
I want camera follow for player movement only in horizontal movement. Right now I have written this type of target following script
public class SmoothFollow : MonoBehaviour
{
public Transform target;
public float smoothness = 10f;
private Vector3 targetInitialPos;
void OnEnable ()
{
target = null;
}
void Update ()
{
if (!target) {
target = GameObject.Find ("MrJump").transform;
targetInitialPos = target.position;
} else {
Vector3 cameraPosition = target.position - targetInitialPos;
cameraPosition.y = 0f;
cameraPosition.z = -10f;
// transform.position = cameraPosition;
transform.position = Vector3.Lerp (transform.position, cameraPosition, Time.deltaTime * smoothness);
}
}
}
If I directly apply cameraPosition to camera transform then it stuttering in mobile devices. So that I used lerp for this purpose but didn't got success in that also.
I have attached small video also to represent my problem correctly.
Camera Stuttering Video
Using above code it shows jerky movement of camera. Not smoother one that I want. Please give some suggestion in this.
mm... and why did you comment out the 20th line instead of 18th?
Because doesn't notice any changes in output. Still noticing jerky camera movement.
Please give some help.
Answer by Surprisejedi
·
Mar 31, 2015 at 10:28 PM
Ahhh, I had this problem too! But I found the solution but very sadly it was in 3d. But I may be able to help you. First make sure that the smooth follow target is the player. Second make sure the distance is 0 and that's what helped me! Hope it helped you!
And if that doesn't help than add mouse orbit. If your game is based on going upwards make sure that Max and Min x is 0 or if it is horizontal than make Max and Min y 0. Hope all my advice.
Smooth Camera follow for 2D platformer game
1
Answer
how can i avoid the rotation effect of the camera being the child of the player? #c
2
Answers
Camera not following player.,Camera not following player...
1
Answer
How to make an camera offsets in Unity Smooth Follow Standard Assets?
0
Answers
Make the camera follow the players
1
Answer | https://answers.unity.com/questions/936852/follow-player-in-2d-game.html | CC-MAIN-2019-35 | refinedweb | 349 | 61.83 |
When will you be posting part 4?
Part 3 | Building a quiz app with BaasBox
In the first part of this series you have learned how to use the BaasBox SDK in Swift. In the second part you have learned how to fetch questions from the backend and run the game.
In this third part we are going to learn how to save the score of each game on the backend and how to load the ranking.
In the current version of the application we already have all the game logic in place. The "play" function detects when a round is over and dismisses the view controller. Before doing that, we need to update the score of the user on the backend. This is pretty easy to do. Here is the outline of what we need to do:
We can fetch data about the currently logged in user as follows:
var currentUser = BAAUser(); BAAUser.loadCurrentUserWithCompletion({(object:AnyObject!, error: NSError!) -> () in currentUser = object as BAAUser; })
This returns a fully parsed instance of BAAUser representing the logged in user. Each user in BaasBox has four dictionaries with different visibilities. The one we are interested in is "visibleByRegisteredUsers", which means visible by all the users that have an account on the platform. We are going to create/update the property named "score" within that dictionary as follows:
if let score = currentUser.visibleByRegisteredUsers["score"] as? Int { currentUser.visibleByRegisteredUsers["score"] = score + self.points } else { currentUser.visibleByRegisteredUsers["score"] = self.points }
This code creates the property if it does not exist (some user might have an account but have never played) or updates its current value. Once we are done we can call
updateWithCompletion which will save the updates user on the backend. Summing up here is the full new function
play()<br>
func play() { if (questions.count == 0) { if (points > 0) { var currentUser = BAAUser(); BAAUser.loadCurrentUserWithCompletion({(object:AnyObject!, error: NSError!) -> () in currentUser = object as BAAUser; if let score = currentUser.visibleByRegisteredUsers["score"] as? Int { currentUser.visibleByRegisteredUsers["score"] = score + self.points } else { currentUser.visibleByRegisteredUsers["score"] = self.points } currentUser.updateWithCompletion({(object:AnyObject!, error: NSError!) -> () in if (error == nil) { println("score updated") self.dismissViewControllerAnimated(true, completion: nil) } else { println("error in updating score \(error)") } }) }) } else {) } Now build and run the application and make sure that you see the "score updated" log statement when you finish a game with more than zero points. The next step is to show the rankings for the game.
The Score View Controller will load user profiles sorted by score, from the highest to the lowest, and display them in a table view. Let's see how easy it is. Create a new class named
ScoreTableViewController as a subclass of
UITableViewController. Now drop a Table View Controller in the Storyboard and set its class to
ScoreTableViewController. Next select the table view cell, set "scoreCellID" as cell reuse identifier and set its style to subtitle. Now open
ScoreTableViewController.swift and make the following changes:
At this point the code should look like this:
import UIKit class ScoreTableViewController: UITableViewController { var users:BAAUser[] = [] init(style: UITableViewStyle) { super.init(style: style) } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.users.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("scoreCellID", forIndexPath: indexPath) as UITableViewCell let user = self.users[indexPath.row] cell.textLabel.text = user.username(); if let score = user.visibleByRegisteredUsers["score"] as? Int { cell.detailTextLabel.text = String(score) } else { cell.detailTextLabel.text = "0" } return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
The last step is to perform the fetch request to the server. The query will retrieve the list of registered users sorted by the value of the score property. This is as easy as injecting the following dictionary in the parameters of the request.
let parameters = ["orderBy" : "visibleByRegisteredUsers.score DESC"]
The key "orderBy" is required by the server and the value specifies the property of the
BAAUser class that we want to use as a criterion for sorting. We will perform the call in viewDidLoad() so change it as follows:
override func viewDidLoad() { super.viewDidLoad() let parameters = ["orderBy" : "visibleByRegisteredUsers.score DESC"] BAAUser.loadUsersWithParameters(parameters, {(users: AnyObject[]!, error: NSError!) -> () in if (error == nil) { self.users = users as BAAUser[] self.tableView.reloadData() } else { println("error loading users %@", error) } }) }
In case the call is successful we cast and cache the result in the array, otherwise we print the error. Finally, we need a way to show the newly implemented view controller. Open the Storyboard and add a new button named "Scores" to the HomeViewController. Control-drag from the navigation controller to
ScoreTableViewController and select "show" as a segue type. Then select the segue and name it "showScores". Finally hook up the "Scores" button to an IBAction defined as follows:
@IBAction func scoreButtonTapped(sender: UIButton) { navigationController.performSegueWithIdentifier("showScores", sender: nil) }
We are done! Run the application and tap the scores button. It will trigger a request to fetch registered users sorted by score and show it in the table view.
In this third part of the series you have learned how to create the view to display the ranking of users in the game. You have seen how it is easy to create a table view controller in Swift and to perform a request with parameters to the BaasBox backend. In the fourth part we will wrap up the key points of the tutorial and provide you a link with the complete application, graphics included!
Great tutorial
We will keep you updated. Thanks.
Update on the tutorial?
Please login in order to leave a comment.
When will you be posting part 4?
Great tutorial
We will keep you updated. Thanks.
Update on the tutorial? | https://www.chupamobile.com/tutorial-ios/swifting-with-baasbox-599/comments/429 | CC-MAIN-2018-30 | refinedweb | 973 | 50.73 |
#include "univ.i"
#include "ha0storage.h"
#include "hash0hash.h"
#include "mem0mem.h"
Hash storage. Provides a data structure that stores chunks of data in its own storage, avoiding duplicates.
Created September 24, 2007 Vasil Dimov
Creates a hash storage. If any of the parameters is 0, then a default value is used.
Empties a hash storage, freeing memory occupied by data chunks. This invalidates any pointers previously returned by ha_storage_put(). The hash storage is not invalidated itself and can be used again.
Frees a hash storage and everything it contains, it cannot be used after this call. This invalidates any pointers previously returned by ha_storage_put().
Gets the size of the memory used by a storage. | http://mingxinglai.com/innodb-annotation/ha0storage_8ic.html | CC-MAIN-2018-51 | refinedweb | 115 | 62.85 |
eaccess()
Check to see if a file or directory can be accessed (extended version)
Synopsis:
#include <libgen.h> #include <unistd.h> int eaccess( const char * path, int amode );
Since:
BlackBerry 10.0.0 eaccess() function is an extended version of access(). It checks if the file or directory specified by path exists and if it can be accessed with the file access permissions given by amode. However, unlike access(), it uses the effective user ID and effective group ID. eaccess() function isn't implemented for the filesystem specified in path.
- ENOTDIR
- A component of the path prefix isn't a directory.
- EROFS
- Write access was requested for a file residing on a read-only file system.
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/e/eaccess.html | CC-MAIN-2018-09 | refinedweb | 137 | 60.72 |
Header image by Chris Leggat on Unsplash.
Another day, another heated "discussion" about how static typing in JavaScript is both the single greatest thing since sliced bread and the worst thing to have happened to humanity as a whole.
Let's look into a recent dev.to post that has been stirring this debate back up again. I'll try to clear out some misconceptions, and hopefully, take things in a level-headed manner.
Before I start, I want to change up some terms I used, especially the one in the title. Instead of referring to TypeScript specifically, I'd like to use the term "typed JavaScript". Because there's also another tool in the typed JS land, Flow, and I don't want to leave Flow users out. After all, we have the same goal of enforcing type soundness/safety in our apps.
Another term that I would like to throw into the glossary is "dynamically-typed" JS, or "dynamic" for short. Despite what the original post wanted to make you believe, writing JS code without type annotations doesn't mean that your code doesn't have types. A string written in dynamic JS still has a type of
string. So is a
number,
boolean, you get the point. You just don't have to explicitly express said types.
Yes, it's longer to start writing statically-typed JS short-term...
I'm going to level with you: writing dynamically-typed JS is faster in the short-term. You might be surprised hearing that from a TypeScript advocate, but I'm being serious here. Really!
Let's say you're writing a Node.js library. If you're writing it in dynamically-typed JS, you can write your library and publish it, all without going through any build tools. It's that fast! For tiny libraries that do one thing, writing it like this is the most effective way because of the speed.
But now, let's say you're writing an entire backend in Node.js. It's just a tiny API service with a couple endpoints. You have written your authentication system, middleware, and controllers in JavaScript. And since it's a small endpoint with minor functionalities, you went with plain ol' JavaScript.
Now, imagine that tiny API service balooned into a full-fledged platform API with thousands of code. Probably tens of thousands of lines of code. Then you realised that you found a bug in one of your endpoints. Oh dear! Unit testing didn't catch it, so you had to spend hours to trace around your app, looking for the issue. Maybe even setting up breakpoints, or even doing the old-fashioned
console.log-driven debugging.
Then, you found the issue. Remember that one time you refactored that one middleware? You also changed the name of the exported function along with it. Sure, you had that middleware unit-tested, but your unit tests were only isolated to that middleware.
Then your eyes came across a file where you had that middleware imported. Of course. You changed the exported function name, but you forgot to rename the imports.
Hours of productivity lost just because of a typo or missing file!
...but the long-term effects are real!
Sure, you can also check mismatched imports with linting tools. But you might also want to rename a function — as well as updating the function name on all the files that import said function — all in the click of a button. After all, humans make mistakes, and missing things like this is not uncommon. TypeScript's support for quick refactoring and find-and-replace support helps you deal with this. Therefore you can focus more on writing code instead of doing pointless find-and-replace by hand.
Static type checkers like TypeScript and Flow also help reduce the amount of bugs in your code by detecting errors like this during compile time. There's some statistical proof to this, too. In general, using static typing in your JavaScript code can help prevent about 15% of the bugs that end up in committed code.
Sure, this will make starting out a project with TypeScript much slower, because you'll need to define types, interfaces, and the like, in the very early stages of your app. But I'd argue that having you write implementation models, in the form of types and/or interfaces, makes you think about your app's data structure early in the day.
This greatly improves confidence of your app in the long run. And when you use these types well, in many cases you don't even need types, thanks to TypeScript's control-flow based type analysis. The benefits of TypeScript on large-scale apps outweighs the trade-offs of the longer time to kickstart your TypeScript project.
Is this an investment that you would take in the future? It sure is for me, but I wouldn't make any prior judgement for your apps. It's still up to you to decide whether that investment is worth it.
You can adopt TypeScript incrementally
Maybe you're already maintaining a medium to large-scale app that's already written in plain ol' JavaScript. And you want to migrate to TypeScript, but are afraid that the red squiggly lines will haunt you in your sleep. How would you go about migrating your code?
There are various guides in migrating to TypeScript. There's one in Basarat Ali Syed's awesome TypeScript Deep Dive handbook. I have also written a comprehensive guide here.
Another neat part of TypeScript is being able to infer types of normal JS files through JSDoc annotations, so if you write valid JSDoc annotations, and have JS typechecking turned on, it'll be easy for you to migrate down the road.
Although admittedly, the migration experience is where TypeScript falls short. The reason I linked to third-party guides is — well — TypeScript does have an official migration guide, although it's horribly outdated. The official documentation also makes hard assumptions that the user know something about statically-typed languages, so I wouldn't recommend them to newcomers.
Though rest assured, the TypeScript team has been working on reworking the documentation, as well as a new handbook that will hopefully teach TypeScript a lot more progressively.
But what about dynamic, runtime values?
Admittedly, the TypeScript team has explicitly stated that extending static type-checking to the runtime is a non-goal for the TypeScript compiler itself. But in reality, we still have to handle these runtime boundaries. A common example to this would be reading a JSON output from an API, or consuming an HTTP request payload.
Since there's a strong community backing towards TypeScript, the community has developed elegant solutions to this issue. There are tools like io-ts which you can use to determine runtime representations in TS. A suitable alternative to Flow would be flow-runtime.
Static typing and testing go hand-in-hand!
So far we've done a lot in making sure the type safety of our app with static types. Despite that, there are certain bugs static typing cannot catch. For a quick example, testing whether that toggle button displays its opposite state the right way when clicked.
I'm a fan of the Testing Trophy model by Kent C. Dodds. In his model, both linting/static analysis/static type checking and unit testing are located in the "base" of the trophy. This means that they're both integral parts into building a testing experience that evokes confidence in your code. Hence I'd like to argue that both static typing and unit testing go hand-in-hand in helping you write code with less bugs!
Let's put the toggle button example above into code. We're using TypeScript as our static typing, and Jest + react-testing-library to test our code.
Here's an example of said component, implemented in React.
import * as React from 'react' interface ToggleButtonProps { enabledText: string disabledText: string } function ToggleButton({ enabledText, disabledText }: ToggleButtonProps) { const [toggle, setToggle] = React.useState(false) const handleToggle = () => { setToggle(!toggle) } return ( <div> <span>{toggle ? enabledText : disabledText}</span> <button onClick={handleToggle}>Toggle</button> </div> ) } export default ToggleButton
On the surface, it looks like static typing has done its job. However, if we take a look closer, we're able to set a custom state text for our toggle button. Sure, TypeScript can check if the string we passed to the
enabledText and
disabledText props is a string. But that's just half of the battle.
After all, if we've set our button's enabled and disabled state is set to
'On' and
'Off' respectively, we want it to correctly show
'Off' when it's disabled, and
'On' when it's enabled. Not the other way around.
Since we already checked the types of our component and its props through TypeScript, we can focus on testing the behaviour of the button.
The following example uses Jest as our test runner, and react-testing-library as our React testing utility.
import * as React from 'react' import { render, cleanup, fireEvent } from '@testing-library/react' import ToggleButton from './ToggleButton' describe('ToggleButton', () => { afterEach(cleanup) test('correctly renders the state of button', () => { const { getByText, queryByText } = render(<ToggleButton enabledText="on" disabledText="off" />) // Test the initial state of the button. expect(getByText('Off')).toBeDefined() expect(queryByText('On')).toBeNull() // Fires a click event to the button. fireEvent.click(getByText('Toggle')) // Test if toggle state is correctly modified. expect(getByText('On')).toBeDefined() expect(queryByText('Off')).toBeNull() }) })
Two things are happening here.
- Static typing provides soundness and improves the developer experience by detecting type errors and allowing developers to refactor confidently through great IDE tools.
- Unit testing provides confidence that our code behaves the way that it's supposed to be used.
Try it out in CodeSandbox
Let's clear our heads
The original post contained a lot of subjective points, which was a shame because I'd love some objective reasoning as to why static types aren't worth the time.
My rebuttal to the original post... also contains a lot of subjective points. But that's fine! Because my goal in writing this post isn't about going off about how one technology is "objectively better" than the other. I was trying to outline how one technology might benefit the users more than the other, and vice versa. And also find a commonality shared between both of them. Or at least, I tried to.
Instead of building inflammatory, subjective opinions disguised as "objective" "fact", let's approach things in a level-headed manner and understand that certain tools exists for certain reasons. Constructive criticism is a great power to improve all of us, regardless of which side you're in on this debate.
Since I'm a front-end developer myself, a good example I'd like to pick would be the endless debates between the Big Three frameworks (Angular, React, and Vue), and why one is better than the other.
For example, Vue and React developers often went up in arms, writing senseless Medium thinkpieces about how one is better than the other. I'm a React guy myself, but I still understand that Evan You had his own issues to tackle with Vue, hence the issues that he solved being his framework's key selling point. The most prominent ones being the learning curve and how easy it is to adopt.
The people behind TypeScript and Flow are smart enough to tackle one of their pain points in writing JavaScript. They want to write JavaScript code that scales in large-scale projects. And the way they approach that is to provide a static typing superset that ensures type soundness and safety, as well as improving productivity through developer tools that are enabled thanks to the power of static types. And for some people, it worked well. TypeScript and Flow are both running many medium to large-scale projects out there (including where I work), and I could imagine all the ways they enabled engineers to write code with less bugs.
TypeScript might be a waste of time for you, but it certainly isn't a waste of time for me.
Don't get me wrong, there's nothing wrong in writing plain JS as well! Maybe you want to iterate faster on the early stages of the project, so you opted for plain JS instead of jumping into TS straight away. Maybe you want to get down and dirty with TypeScript right from the get-go. Both of these are fine. After all, it's only you knows how to best develop your app. It's only you who knows how to serve a better user/developer experience.
Because regardless of our choices of tools, languages, and frameworks (or lack thereof), it all ends up with a working app.
Right? | https://resir014.xyz/posts/2019/07/30/no-typescript-isnt-a-waste-of-time | CC-MAIN-2022-21 | refinedweb | 2,146 | 64.1 |
Introduction
You hacked into the system of very-secure-shopping.com and you found a SQL-Dump with $$-creditcards numbers. As a good hacker you inform the company from which you got the dump. The managers tell you that they don’t worry, because the data is encrypted.
Dump-File: dump.zip
Goal
Analyze the “Encryption”-method and try to decrypt the flag.
Hints
CC-Numbers are valid ones.
Cyber-Managers often doesn’t know the difference between encoding and encryption.Challenge Description
The dump consistent of an MySQL dump of some tables named creditcards and flags. The interesting values, namely cc_number and flag_content were encrypted and are prefixed with :). There exists a thing called smile encoding, but this only cost me some time and didn’t got me anywhere.
After doing some analysis I found out, that the encrypted text covers a range of 39 ASCII characters, and that the ASCII values do rise.
So it turns out, that this is some sort of a rolling rotation cipher with a fixed offset of 29. The rotation offset increases by one with every character. I used the following script for analysis and decryption.
import struct data = [ 'QVXSZUVY\ZYYZ[a', 'QOUW[VT^VY]bZ_', 'SPPVSSYVV\YY_\\]', 'RPQRSTUVWXYZ[\]^', 'QTVWRSVUXW[_Z`\\b', 'SlQRUPXWVo\Vuv_n_\\ajjce' ] chrs = [] offset = 0x4f lowest = 100 highest = 0 for s in data: print(s) print(len(s)) print(' '.join(hex(ord(x)) for x in s)) offset = 29 print(ord(s[-1]) - ord(s[0])) last = 0 c = '' i = 1 for x in s: if ord(x) < lowest: lowest = ord(x) if ord(x) > highest: highest = ord(x) print(chr(ord(x) - offset - i), end = '') i += 1 print() print() print('lowest %d (%s)' % (lowest, chr(lowest))) print('highest %d (%s)' % (highest, chr(highest))) print('range %d' % (highest - lowest)) print('full range: %s' % ''.join(chr(x) for x in range(lowest, highest +1)))
This reveals the flag: HV19{5M113-420H4-KK3A1-19801}. | https://blog.sebastianschmitt.eu/challenges/hackvent-2019/hv19-08-smilencryptor-4-0/ | CC-MAIN-2022-21 | refinedweb | 322 | 63.9 |
Agenda
See also: IRC log
HST: We will take 2.2 ahead of
2.1
... Regrets from NDW
HST: Last week's minutes. .
.
... Approved.
... Next meeting: 18 January
... Regrets from Paul Grosso, Norm Walsh and Richard Tobin
... Probably regrets from Mohamed Zergaoui
HST: The most recent draft
... Micro-operations components
... Consider 3.1 Rename
RT: Can the 'name' parameter be an XPath as well?
HST: Makes sense, but causes the 90% case to have to be quoted twice. . .
RT: We could have two distinct parameters, one for constant and one for XPath
select='foo' name='bar'
RT: or //foo
HST: Match or select?
... I guess the argument for select is that otherwise you lose the full generality of XPath
MZ: Description says attribute, element or PI -- how do you do PI?
RT: select='processing-instruction(foo)'
HST: Happy with the design of this one?
RT: Make this have deletion functionality, or have a separate component?
HST: Prefer a separate component
MZ: Me too
HST: I assume, for the record,
that to rename an attribute you say:
... select='//*/@foo' name='bar'
... NOT name = '@bar'
RT: There's an overall question
about namespace bindings
... I presume the XPath finds namespace bindings in the pipeline document
... What about the name -- is it a QName and do the default namespace rules apply?
HST: Yes it's a QName, and yes they apply
RT: I'd say they don't apply, because that would make the 90% case for renaming attributes a problem if there was a default namespace binding in effect
AV: I think in XSLT where QNames
are used, the default binding doesn't apply, for example in
nameing functions
... so we can and should do the same here
HST: I'm sorry to lose strong
typing -- this proposal would mean we can't use xs:QName
... Perhaps we should add a namespace parameter
RT: Or allow either a name parameter or both local-name and (optional namespace-name) parameters
AV: Let's take this to the mailing list
HST: OK, agreed -- we like this
component, but need to settle this outstanding issue of default
NS wrt the 'name' parameter
... Moving on to 3.2, Wrap
... wraps the document element
RT: Doesn't seem to useful
HST: Agree, I'd like to see a
'select' parameter here as well -- I use that version all the
time
... A similar operation in other pipeline languages?
... What about a 'select' parameter?
RT: Yes, but what about recursive operation?
HST: Yes, because you can defeat
that with a more specialised XPath
... although it's not easy to do
RT: Yes it is, just write //foo[not(ancestor::foo)]
HST: Same issue wrt what the
'name' parameter is arises
... should be probably be settled in the same way
... One more thing to consider -- a 'groupBy' attribute name or XPath parameter
... select='//foo' name='bar' groupBy='@fam'
... then input of
<foo fam='1'/><foo
fam='1'/><foo fam='2'/>
would give two bars, not three
RT: What about intervening
elements, text, whitespace
... and what about matching text?
HST: I say it can match text,
which I find very useful
... select='//foo/text()' name='bar'
... turns
<foo>text</foo> into
<foo><bar>text</bar></foo>
RT: That (text) seems reasonable,
but the groupBy would need to be carefully specified wrt what's
allowed in between
... what about comments, etc.
HST: Agreed, more care on that
front is needed, and email is the right place to do that
... I think I hear consensus that we want this, but definitely with a select attribute added
RT: What about 'Unwrap' ?
HST: Right, we've had suggestions
to add Delete and Unwrap operations, we should come to
those
... 3.3 Insert, which takes a whole document and plugs it in just under the document element
... typo, should say that it takes the document from the 'insertion' port . . .
... Again, I want an XPath to select the parent of the insertion
... Useful e.g. for putting a doc inside a SOAP wrapper
RT: That's not fully general, is it -- you can't get it between arbitrary siblings that way
AV: XForms have an 'insert'
action, that we should look at to get an idea, perhaps
... Perhaps the different attributes they have would help
<Alessandro>
HST: Seems to be consensus to have this, with some extensions, at least a 'select' XPath, and probably some more articulation in the area of 'at-start' to get full(er) control of where the insertion happens under the selected parent
RT: What about multiple matches?
HST: Yes, needs to be decided --
my version says "first match" is where the insertion happens,
multiple (or none) are not an error
... But we should resolve this after email discussion as well
HST: Looking at the final one, 3.4 set-attributes
RT: I think this just copies attributes from doc elt to doc elt
HST: Back to set-attributes -- it's more like copy-attributes, and needs two XPaths, I think -- this suggests Insert could be generalised to CopyChildren with another XPath selecting what to copy in the Insertion document
RT: We could combine the two and have a Copy component -- use .../* or .../@* to copy/insert children or attributes respectively
HST: I'd like the SOAP insertion
case to continue to be simple, but I think that could be
accomplished with some sensible defaults
... For instance, if both XPaths default to '/', you get Alex's original Insert, and if you default the first to '/' and use '/*/@*' you get his set-attributes. . .
... Sounds to me like these two both need some more thought, but there's definitely something here we want.
... Can we sketch the two additions we've suggested: Delete and Unwrap
... Seems to me Delete just needs a 'select' XPath -- any tricky problems?
... Recursion isn't an issue, because you delete the whole matching subtree. . .
... Unwrap is very similar, but only matching elements makes sense
... It's an error to match the doc. elt if it has more than one child or text children, etc.
... Please pick up this topic in email and get some discussion started before next time
... Adjourned | http://www.w3.org/XML/XProc/2007/01/11-minutes.html | CC-MAIN-2018-39 | refinedweb | 1,019 | 70.84 |
Using Iterations in Python Effectively
Prerequisite : Iterators in Python
Following are different ways to use iterators.
C-style approach:This approach requires prior knowledge of total number of iterations.
Output:
Aston Audi McLaren
Important Points:
- This style of looping is rarely used by python programmers.
- This 4-step approach creates no compactness with single-view looping construct.
- This is also prone to errors in large-scale programs or designs.
- There is no C-Style for loop in Python, i.e., a loop like for (int i=0; i<n; i++)
Use of for-in (or for each) style:
This style is used in python containing iterator of lists, dictonary, n dimensional-arrays etc. The iterator fetches each component and prints data while looping. The iterator is automatically incremented/decremented in this construct.
Output:
Aston Audi McLaren
See this for more examples of different data types.
Indexing using Range function: We can also use indexing using range() in Python.
Output:
Aston Audi McLaren
Enumerate:
Enumerate is built-in python function that takes input as iterator, list etc and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate(cars), returns a iterator that will return (0, cars[0]), (1, cars[1]), (2, cars[2]), and so on.
Output :
Aston Audi McLaren
Below solution also works.
Output :
(0, 'Aston') (1, 'Audi') (2, 'McLaren ')
We can also directly print returned value of enumerate() to see what it returns.
Output :
[(0, 'Aston'), (1, 'Audi'), (2, 'McLaren ')]
Enumerate takes parameter start which is default set to zero. We can change this parameter to any value we like. In the below code we have used start as 1.
Output :
(1, 'Aston') (2, 'Audi') (3, 'McLaren ')
enumerate() helps to embed solution for accessing each data item in the iterator and fetching index of each data item.
Looping extensions:
i) Two iterators for a single looping construct: In this case, a list and dictionary are to be used for each iteration in a single looping block using enumerate function. Let us see example.
Output:
Car: Aston Price: 570000$ Car: Audi Price: 68000$ Car: McLaren Price: 450000$ Accessory: GPS kit Price: 8900$ Accessory: Car repair-tool kit Price: 4500$
ii) zip function (Both iterators to be used in single looping construct):
This function is helpful to combine similar type iterators(list-list or dict- dict etc,) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped. In case of empty iterators, it returns No output.
For example, the use of zip for two lists (iterators) helped to combine a single car and its required accessory.
Output:
Car: Aston, Accessory required: GPS Car: Audi, Accessory required: Car Repair Kit Car: McLaren, Accessory required: Dolby sound kit
The reverse of these iterators from zip function is known as unzipping using “*” operator.
Use of enumerate function and zip function helps to achieve an effective extension of iteration logic in python and solves many more sub-problems of a huge task or problem.
Output:
('Aston', 'Audi', 'McLaren') ('GPS', 'Car Repair', 'Dolby sound kit')
References:
1.
2.
This article is contributed by Krishnasagar Subhedarp 3 (Strings, Lists, Tuples, Iterations)
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- try-except vs If in Python
- set add() in python
- max() and min() in Python
Improved By : PRIYESH PATEL 1 | https://www.geeksforgeeks.org/using-iterations-in-python-effectively/ | CC-MAIN-2019-51 | refinedweb | 639 | 52.7 |
Introducing the Vanilla Template to CodeSandbox
From day one we've always tied templates to a CLI. The
main reason for this is that we want to keep sandboxes simple, you shouldn't
need to do any configuration to get started. I didn't want to create a
'
Vanilla' template because there was no way to create 'vanilla' web projects
without configuration, until recently.
Parcel
A new bundler called 'Parcel' was
released in December by Devon Govett. Parcel
is a web application bundler that values zero configuration. They reuse classic
web concepts, like using
index.html as the entry point of the application,
which makes it really easy and intuitive to get started with a new project. You
only have to create an
index.html and run
parcel index.html to get a working
application. They automatically detect what kind of web application you're
running, and adapt the configuration to that if it's not specifically set.
This is aligns perfectly with the values of CodeSandbox. There is almost no friction to get started, and all the needed configuration is automatically detected & installed. That's why I decided to finally build a Vanilla template and use Parcel as our configuration behind it.
Vanilla Template
We have a new sandbox called
vanilla, unlike other sandboxes, this sandbox has
index.html as its entry. From this
index.html you can add
script and
link tags to other files and they will be added to the bundle. We support all
loaders that Parcel supports, so we support:
We also recognize the difference between:
import styles from './styles.css';
and
import './styles.css';
In the first code block we will generate CSS modules from the CSS file, and in the second block we won't.
You can try it out here:
Configuration
Like Parcel, we automatically do configuration for you. We automatically detect
if you're using React or
Preact and will adjust our Babel
configuration for it. We do support Babel/TypeScript configuration, so you can
also choose to do your own configuration by creating a
tsconfig.json or a
.babelrc.
GitHub, Zip Extraction & Deployment Integration
Like the other templates, you can create repos, make commits and PRs, download and deploy sandboxes using this template. Without leaving the browser.
Beta Warning
This is our first template that uses HTML as an entry point, so there can be bugs or unintended behaviour that still needs to be solved. Please let us know in the repo if you find any issues!
Thanks
I want to thank Devon Govett for building this beautiful bundler, I was able to effortlessly build an application in it. Great work!
If you like what we're doing, consider becoming a contributor or a patron! You can stay up to date with CodeSandbox news either on @CompuIves or @codesandbox. | https://codesandbox.io/post/introducing-the-vanilla-template-to-codesandbox | CC-MAIN-2020-50 | refinedweb | 469 | 57.16 |
- NAME
- SYNOPSIS
- NOTICE
- AUTHOR
- DESCRIPTION
- NO WARRANTY
- LICENSE
- SEE ALSO
- Constructor
- Terse Functions
- Overloading
- Chaining Operations
- Precedence
- Methods
- Incomplete Methods
NAME
Math::Vec - Object-Oriented Vector Math Methods in Perl];
NOTICE
This module is still somewhat incomplete. If a function does nothing, there is likely a really good reason. Please have a look at the code if you are trying to use this in a production environment.
AUTHOR
Eric L. Wilhelm <ewilhelm at cpan dot org>
DESCRIPTION
NO WARRANTY.
LICENSE
You may use this software under one of the following licenses:
(1) GNU General Public License (found at) (2) Artistic License (found at)
SEE ALSO
Math::Vector
Constructor
new);
NewVec)]));
Terse Functions
These are all one-letter shortcuts which are imported to your namespace with the :terse flag.
use Math::Vec qw(:terse);
V
This is the same as Math::Vec->new($x,$y,$z).
$vec = V($x, $y, $z);
U
Shortcut to V($x,$y,$z)->UnitVector()
$unit = U($x, $y, $z);
This will also work if called with a vector object:
$unit = U($vector);
X
Returns an x-axis unit vector.
$xvec = X();
Y
Returns a y-axis unit vector.
$yvec = Y();
Z
Returns a z-axis unit vector.
$zvec = Z();
Overloading.
Negation:
@a = NewVec->(0,1,1)->ScalarMult(-1); @a = @{-V(0,1,1)};
Stringification:
This also performs concatenation and other string operations.
print join(", ", 0,1,1), "\n"; print V(0,1,1), "\n"; $v = V(0,1,1); print "$v\n"; print "$v" . "\n"; print $v, "\n";
Addition:
@a = NewVec(0,1,1)->Plus([2,2]); @a = @{V(0,1,1) + V(2,2)}; # only one argument needs to be blessed: @a = @{V(0,1,1) + [2,2]}; # and which one is blessed doesn't matter: @a = @{[0,1,1] + V(2,2)};
Subtraction:
@a = NewVec(0,1,1)->Minus([2,2]); @a = @{[0,1,1] - V(2,2)};
Scalar Multiplication:
@a = NewVec(0,1,1)->ScalarMult(2); @a = @{V(0,1,1) * 2}; @a = @{2 * V(0,1,1)};
Scalar Division:
@a = NewVec(0,1,1)->ScalarMult(1/2); # order matters! @a = @{V(0,1,1) / 2};
Cross Product:
@a = NewVec(0,1,1)->Cross([0,1]); @a = @{V(0,1,1) x [0,1]}; @a = @{[0,1,1] x V(0,1)};
Dot Product:.)
Comparison:
The == and != operators will compare vectors for equal direction and magnitude. No attempt is made to apply tolerance to this equality.
Length:
$a = NewVec(0,1,1)->Length(); $a = abs(V(0,1,1));
Vector Projection:]};
Chaining Operations.
Unit Vector left of a line
This comes from the CAD::Calc::line_to_rectangle() function.
use Math::Vec qw(:terse); @line = ([0,1],[1,0]); my ($a, $b) = map({V(@$_)} @line); $unit = U($b - $a); $left = $unit x -Z();
Length of a cross product
$length = abs($va x $vb);
Vectors as coordinate axes]};;
Precedence
Methods.
Dot
Returns the dot product of $vec 'dot' $othervec.
$vec->Dot($othervec);
DotProduct
Alias to Dot()
$number = $vec->DotProduct($othervec);
Cross
Returns $vec x $other_vec
@list = $vec->Cross($other_vec); # or, to use the result as a vec: $cvec = NewVec($vec->Cross($other_vec));
CrossProduct
Alias to Cross() (should really strip out all of this clunkiness and go to operator overloading, but that gets into other hairiness.)
$vec->CrossProduct();
Length
Returns the length of $vec
$length = $vec->Length();
Magnitude
$vec->Magnitude();
UnitVector
$vec->UnitVector();
ScalarMult
Factors each element of $vec by $factor.
@new = $vec->ScalarMult($factor);
Minus
Subtracts an arbitrary number of vectors.
@result = $vec->Minus($other_vec, $another_vec?);
This would be equivelant to:
@result = $vec->Minus([$other_vec->Plus(@list_of_vectors)]);
VecSub
Alias to Minus()
$vec->VecSub();
InnerAngle
Returns the acute angle (in radians) in the plane defined by the two vectors.
$vec->InnerAngle($other_vec);
DirAngles
$vec->DirAngles();
Plus
Adds an arbitrary number of vectors.
@result = $vec->Plus($other_vec, $another_vec);
PlanarAngles();
Ang
A simpler alias to PlanarAngles() which eliminates the concerns about context and simply returns the angle in the xy plane.
$xy_ang = $vec->Ang();
VecAdd
$vec->VecAdd();
UnitVectorPoints
Returns a unit vector which points from $A to $B.
$A->UnitVectorPoints($B);
InnerAnglePoints
Returns the InnerAngle() between the three points. $Vert is the vertex of the points.
$Vert->InnerAnglePoints($endA, $endB);
PlaneUnitNormal);
TriAreaPoints
Returns the angle of the triangle formed by the three points.
$A->TriAreaPoints($B, $C);
Comp
Returns the scalar projection of $B onto $A (also called the component of $B along $A.)
$A->Comp($B);
Proj
Returns the vector projection of $B onto $A.
$A->Proj($B);
PerpFoot
Returns a point on line $A,$B which is as close to $pt as possible (and therefore perpendicular to the line.)
$pt->PerpFoot($A, $B);
Incomplete Methods
The following have yet to be translated into this interface. They are shown here simply because I intended to fully preserve the function names from the original Math::Vector module written by Wayne M. Syvinski.
TripleProduct
$vec->TripleProduct();
IJK
$vec->IJK();
OrdTrip
$vec->OrdTrip();
STV
$vec->STV();
Equil
$vec->Equil(); | https://metacpan.org/pod/Math::Vec | CC-MAIN-2017-26 | refinedweb | 819 | 54.52 |
I am working through a tutorial book and trying to create a buffer based on a search cursor. When I run the script it creates a buffer but all of the buffers are at 100 rather than what I have set as the output parameters for the buffer. any help would be great. Thanks!
#Import module and environment
import arcpy
from arcpy import env
env.environment = r"M:\NRD_Maps\Travis_Working\Training\GIS Tutorial for Python Scripting\GISTPython\Data\City of Oleander.gdb\Well_Data"
env.overwriteoutput = True
#Create variables with the name of the subject feature class
Lights = 'StreetLights'
#The buffer distance is dependant on the light types
#Check to see the light type
LightCursor = arcpy.da.SearchCursor(Lights,['Type'])
for row in LightCursor:
Type = row[0]
#MV = 125 ft
#MVH = 160 ft
#SV = 100 ft
#SVH = 200 ft
if Type == 'MV':
Buffer = 125
elif Type == 'MVH':
Buffer = 160
elif Type == 'SV':
Buffer = 100
else:
Buffer = 200
#Perform the buffer
arcpy.Buffer_analysis(Lights, \
r"M:\NRD_Maps\Travis_Working\Training\GIS Tutorial for Python Scripting\GISTPython\MyExercises\MyAnswers.gdb\EX_2_3\lightBuffer", \
Buffer)
print "New buffer created"
The parameters for Buffer are (input, output, buffer distance or field, ...). Since you provide a buffer distance (e.g. 100) not a field, it uses that distance. If you want to use different distances, you would need to write the distance to a field using an Update Cursor or possibly Field Calculator and use that field for the third parameter.
I'm not sure whether your Buffer is executed within the Search Cursor or outside because we can't see your indentation. If inside, Buffer will run for each feature, overwriting the file each time, leaving you with the last run. If outside, Buffer will run once, using the last value as the buffer distance. | https://community.esri.com/thread/183873-why-isnt-my-search-cursor-working | CC-MAIN-2018-43 | refinedweb | 298 | 53.51 |
Intel's 3D NAND SSD Debut: DC P3520/P3320 And DC3700/3600
DC P3520 And DC P3320 Series SSDs
Intel is simultaneously launching four datacenter SSDs, which are particularly interesting because the DC P3520 and DC P3320 both employ the company's long-awaited 3D NAND. The jointly developed IMFT flash sets a new standard for density with 32 layers and 256Gb per MLC die and an impressive 384Gb per die of 3D TLC.
The new NAND enables incredible density. We'll see up to 512GB for a 16-die MLC package and up to 768GB in a 16-die TLC package. IMFT 3D NAND employs floating-gate technology, which is quite a bit different than what other NAND fabs are doing with their Charge Trap Flash (CTF). Intel has a long history with floating-gate transistors, and the company believes it can extract more performance and endurance compared to competing CTF designs. IMFT NAND also puts most of the CMOS under the array, which boosts efficiency and density.
We were able to snap a few pictures of the DC P3520 at Intel's Broadwell-EP press briefing. As you can see, the SSD is physically almost identical to the company's existing DC P3700 SSDs.
The DC P3320 comes in capacities as large as 2TB, matching its counterparts based on planar NAND. This is surprising considering the higher density possible with 3D NAND. But Intel indicated that the new design features the same controller as the previous-gen planar NAND-based products. That controller can only address up to 2TB due to DRAM management limitations.
Intel sells the DC P3320 in both 2.5" and add-in card form factors with 450GB (2.5"-only), 1.2TB and 2TB of flash. The company rates its DC P3320 for up to 365,000 random read and 22,000 random write IOPS. Those write numbers are similar to the low-endurance DC P3500 (23,000 IOPS), but the random reads are not nearly as fast as the DC P3500's 430,000 IOPS. The DC P3320 offers up to 1600 MB/s sequential reads and 1400 MB/s of sequential writes, which also lags its NVMe-based predecessors.
Intel attributes the lower performance to a loss of parallelism due to higher-capacity 3D NAND dies. Future models will sport an improved controller that manages more DRAM, thereby accommodating more capacity and parallelism, which ultimately improves performance. Intel doesn't get specific, but indicates that the DC P3320 will feature a lower price than the DC P3500 and a similar write endurance rating (0.3 DWPD for five years).
Intel continues its focus on performance consistency, touting the end-to-end data path protection that provides a resilience to silent data corruption. Intel is one of the few storage vendors confident enough to share field reliability data, and it continues to maintain an Annual Failure Rate (AFR) below 0.44%.
Intel also mentioned the new DC P3520 during its briefing. However, the company did not share any performance details. We did uncover a document last August that accurately foretold the DC P3608's release though, and it included information on the DC P3520. The slide above is a bit dated at this point; its listed availability was originally anticipated in Q4 2015. But other information in the same document proved true, so we are fairly confident that it still reflects the projected specifications. At the very least, Intel hinted that the DC P3520 will be a performance-oriented model, which agrees with the numbers listed above.
Intel DC D3700 And DC D3600 Series SSDs
Intel also announced dual-port active-active NVMe-based SSDs at the event, which closely resemble the 2.5" DC P3700 NVMe SSD we recently tested and the 2.5" DC P3320 pictured above.
SAS-attached SSDs still enjoy the advantage of two ports, which provide an active-active connection for High Availability (HA) features like multi-path and fail-over. These are extremely important in mission-critical applications, and NVMe's original lack of dual-port functionality hampered its adoption in many of the long-held SAS-based SSD bastions, such as all-flash arrays. In fact, we dinged the 2.5" Intel DC P3700 NVMe SSD for that exact reason in our review earlier this month.
The NVM Express consortium added dual-port support to later revisions of the standard, and Intel's DC D3700 and DC D3600 SSDs provide two PCIe 3.0 x2 connections into compatible backplanes. Although this allows multiple hosts to access the SSDs, it also cuts performance in half, from a top speed of 470,000 random 4KB read and 95,000 write IOPS, and 2100 MB/s sequential read 1500 MB/s sequential write throughput.
Intel's new NVMe SSDs are only available in a 2.5" form factor, and they require special backplanes to take advantage of the dual-port functionality. You'll only find the DC D3700 at 800GB and 1.6TB capacity points, though you get 10 DWPD of endurance. The DC D3600 is available in 1 and 2TB capacities with a 3 DWPD rating.
Features supported by the drives are similar to what you get from SAS-based SSDs, including reservations, scatter/gather lists, multiple namespaces and in-controller memory buffers. Intel indicates that the mulitple namespace capability runs in hardware, which is better than SAS' software-based approach, increasing efficiency.. | https://www.tomshardware.com/uk/reviews/intel-xeon-e5-2600-v4-broadwell-ep,4514-5.html | CC-MAIN-2020-45 | refinedweb | 905 | 53.81 |
Go to the first, previous, next, last section, table of contents.
The library provides a large collection of random number generators which can be accessed through a uniform interface. Environment variables allow you to select different generators and seeds at runtime, so that you can easily switch between generators without needing to recompile your program. Each instance of a generator keeps track of its own state, allowing the generators to be used in multi-threaded programs. Additional functions are available for transforming uniform random numbers into samples from continuous or discrete probability distributions such as the Gaussian, log-normal or Poisson distributions.
These functions are declared in the header file `gsl_rng.h'. = %lu\n", gsl_rng_default_seed); printf ("first value = %lu\n", gsl_rng_get (r)); return 0; }
Running the program without any environment variables uses the initial
defaults, an
mt19937 generator with a seed of 0,
bash$ ./a.out generator type: mt19937 seed = 0 first value = 4293858116:
The library provides functions for reading and writing the random number state.
gsl_rng_setreproduces this.
For more information see,
The generator
gsl_rng_19937 uses the second revision of the
seeding procedure published by the two authors above in 2002. The
original seeding procedures could cause spurious artifacts for some seed
values. They are still available through the alternate generators
gsl_rng_mt19937_1999 and
gsl_rng_mt19937_1998.
The generator
ranlxs0 is a second-generation version of the
RANLUX algorithm of Lüs
gives the highest level of randomness, with all 24 bits decorrelated.
Both types of generator use 24 words of state per generator.
For more information see,
z_n = (x_n - y_n) mod m_1
where the two underlying generators x_n and y_n are,
x_n = (a_1 x_{n-1} + a_2 x_{n-2} + a_3 x_{n-3}) mod m_1 y_n = (b_1 y_{n-1} + b_2 y_{n-2} + b_3 y_{n-3}) mod m 2^205 (about 10^61). It uses 6 words of state per generator. For more information see,
x_n = (a_1 x_{n-1} + a_5 x_{n-5}) mod m
with a_1 = 107374182, a_2 = a_3 = a_4 = 0, a_5 = 104480 and m = 2^31 - 1.
The period of this generator is about 10^46. It uses 5 words of state per generator. More information can be found in the following paper,
x_n = (s1_n ^^ s2_n ^^ s3_n)
where,
s1_{n+1} = (((s1_n&4294967294)<<12)^^(((s1_n<<13)^^s1_n)>>19)) s2_{n+1} = (((s2_n&4294967288)<< 4)^^(((s2_n<< 2)^^s2_n)>>25)) s3_{n+1} = (((s3_n&4294967280)<<17)^^(((s3_n<< 3)^^s3_n)>>11))
computed modulo
2^32. In the formulas above
^^
denotes "exclusive-or". Note that the algorithm relies on the properties
of 32-bit unsigned integers and has been implemented using a bitmask
of
0xFFFFFFFF to make it work on 64 bit machines.
The period of this generator is 2^88 (about 10^26). It uses 3 words of state per generator. For more information see,
The generator
gsl_rng_taus2 uses the same algorithm as
gsl_rng_taus but with an improved seeding procedure described in
the paper,
The generator
gsl_rng_taus2 should now be used in preference to
gsl_rng_taus.
gfsr4generator is like a lagged-fibonacci generator, and produces each number as an
xor'd sum of four previous values.
r_n = r_{n-A} ^^ r_{n-B} ^^ r_{n-C} ^^ r_{n-D} inedpendence means that all 32-bit patterns are equally likely, and in particular that 0 is an allowed random value. (We are grateful to Heiko Bauke for clarifying for us these properties of GFSR random number generators.)
For more information see,.
rand48generator.).,
x_{n+1} = (a x_n) mod m
with a = 1812433253 and m = 2^32. The seed specifies the initial value, x_1.
x_{n+1} = (x_n (x_n + 1)) mod m
with m = 2^32. The seed specifies the initial value, x_1.
x_{n+1} = (a x_n) mod m
with a = 62089911 and m = 2^31 - 1. The seed specifies the initial value, x_1.
x_{n+1} = (a x_n) mod m
with a = 48271 and m = 2^31 - 1. The seed specifies the initial value, x_1.
z_{n+1} = (x_n - y_n) mod m
with
m = 2^31 - 1.
x_n and y_n are given by the
fishman20
and
lecuyer21 algorithms.
The seed specifies the initial value,
x_1.
x_n = (a_1 x_{n-1} + a_2 x_{n-2}) mod m
with a_1 = 271828183, a_2 = 314159269, and m = 2^31 - 1.
x_{n+1} = (a x_n) mod m
with a = 40692 and m = 2^31 - 249. The seed specifies the initial value, x_1.
x_{n+1} = (a x_n) mod m
with a = 1566083941 and m = 2^32. The seed specifies the initial value, x_1.
The following program demonstrates the use of a random number generator to produce uniform random numbers in range [0.0, 1.0),
#include <stdio.h> #include <gsl/gsl_rng.h> int main (void) { const gsl_rng_type * T; gsl_rng * r; int i, n = 10; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < n; i++) { double u = gsl_rng_uniform (r); printf ("%.5f\n", u); } gsl_rng_free (r); return 0; }
Here is the output of the program,
$ ./a.out 0.99974 0.16291 0.28262 0.94720 0.23166 0.48497 0.95748 0.74431 0.54004 0.73995
mutiple-recursive generator
mrg,
$ GSL_RNG_SEED=123 GSL_RNG_TYPE=mrg ./a.out GSL_RNG_TYPE=mrg GSL_RNG_SEED=123 0.33050 0.86631 0.32982 0.67620 0.53391 0.06457 0.16847 0.70229 0.04371 0.86374.
A comprehensive set of random number generator tests is available from NIST,.
Go to the first, previous, next, last section, table of contents. | http://linux.math.tifr.res.in/programming-doc/gsl/gsl-ref_17.html | CC-MAIN-2017-39 | refinedweb | 899 | 65.12 |
Overview of DFS Namespaces
Published: August 17, 2007
Applies To: Windows Server 2008.
- Namespace server. A namespace server hosts a namespace. The namespace server can be a member server or a domain controller.
- Namespace root. The namespace root is the starting point of the namespace. In the previous figure, the name of the root is Public, and the namespace path is \\Contoso\Public. This type of namespace is a domain-based namespace because it begins with a domain name (for example, Contoso) and its metadata is stored in Active Directory Domain Services (AD DS). Although a single namespace server is shown in the previous figure, a domain-based namespace can be hosted on multiple namespace servers to increase the availability of the namespace.
- Folder. Folders without folder targets add structure and hierarchy to the namespace, and folders with folder targets provide users with actual content. When users browse a folder that has folder targets in the namespace, the client computer receives a referral that transparently redirects the client computer to one of the folder targets.
- Folder targets. A folder target is the UNC path of a shared folder or another namespace that is associated with a folder in a namespace. The folder target is where data and content is stored. In the previous figure, the folder named Tools has two folder targets, one in London and one in New York, and the folder named Training Guides has a single folder target in New York. A user who browses to \\Contoso\Public\Software\Tools is transparently redirected to the shared folder \\LDN-SVR-01\Tools or \\NYC-SVR-01\Tools, depending on which site the user is currently located in.
You can administer namespaces by using DFS Management, the
DfsUtil command, or scripts that call WMI.
Additional references | https://technet.microsoft.com/en-us/library/cc730736(v=ws.10).aspx | CC-MAIN-2015-32 | refinedweb | 297 | 50.77 |
2011/7/14 Anthony Fox <a podavalov gmail com>: > > ACK and applied, thanks. The comment to virStreamRecv misses two lines in the <returns> block, so I'm squashing this in (this diff will probably come through mangled because of the long lines) diff --git a/Stream.cs b/Stream.cs index b349605..d824726 100644 --- a/Stream.cs +++ b/Stream.cs @@ -109,6 +109,8 @@ namespace Libvirt /// size of @data buffer /// </param> /// <returns> + /// the number of bytes read, which may be less than requested.Returns 0 when the end of the stream + /// is reached, at which time the caller should invoke virStreamFinish() to get confirmation of stream /// completion. Returns -1 upon error, at which time the stream will be marked as aborted, /// and the caller should now release the stream with virStreamFree. Returns -2 if there is no /// data pending to be read & the stream is marked as non-blocking. -- Matthias Bolte | http://www.redhat.com/archives/libvir-list/2011-July/msg00965.html | CC-MAIN-2015-11 | refinedweb | 151 | 71.24 |
I am using below script to call another SikuliX script but it is not working and giving following error in line 5.
SikuliX Script:
from sikuli import *
myScriptPath = "C:\Users\
addImportPath(
import test
SikuliX Error:
[error] script [ Import ] stopped with error in line 5
[error] NameError ( !!WHILE IMPORTING!! name 'find' is not defined )
[error] --- Traceback --- error source first line: module ( function ) statement 1: test ( <module> ) find("151411326
[error] --- Traceback --- end --------------
Question information
- Language:
- English Edit question
- Status:
- Answered
- For:
- Sikuli Edit question
- Assignee:
- No assignee Edit question
- Last query:
- 2018-01-31
- Last reply:
- 2018-02-01
According to given introductions in this link (http://
SikuliX script:
from sikuli import *
import sys
#sys.path.
myScriptPath = "C:\Users\
addImportPath(
import test
Sorry, but that is not what is suggested there.
If the main and imported script are in the same folder (a SikuliX script is the someScript.sikuli and not the included someScript.py!!!) there is no need to use sys.path.
# main as main.sikuli
import test
# sub in same folder
# as test.sikuli
from sikuli import * # not needed in main!!
... code
Be sure you have understood and checked all options mentioned in
(http://
Madarchot :)
???????
I am German
I think this codes not working because I am using 1.1.2 version of SikuliX and it is stated 1.1.1 on webpage ? Please help me out, I have also tried basic example as well but not succeed.
SikuliX script:
myScriptPath = "C:\Users\
addImportPath(
import test
Go back to comment #3 and try to understand
Give me a hint, should I have to set "Environment Variables" for "sys.path" ?
Everything needed is in comment #3
Now, I have understand what you told and I have saved myscript.sikuli in the folder of main script and using below code:
myScriptPath = "C:\Users\
addImportPath(
import test
test.script01(
But still it is giving below error: :(
[error] script [ Import ] stopped with error in line 9
[error] NameError ( !!WHILE IMPORTING!! name 'Env' is not defined )
[error] --- Traceback --- error source first line: module ( function ) statement 8: test ( <module> ) Env.addHotkey("n", KeyModifier.ALT + KeyModifier.CTRL, script01)
[error] --- Traceback --- end --------------
No, you still do not understand the SikuliX import concept :-(
When talking about a SikuliX script, THE FOLDER of the script is meant!
so a setup might be:
-- someFolder
-- main.sikuli
-- sub.sikuli
in this setup
# main.sikuli
import sub
sub.test()
# sub.sikuli
from sikuli import *
def test():
pass # do something
... no need for any path's or addImportPath
BTW: (basic Python knowledge ;-) backslashes in strings must be doubled or the string must be mentioned as raw string
"C:\\Users\
or
r"C:\Users\
read
sikulix- 2014.readthedoc s.io/en/ latest/ scripting. html#importing- other-sikuli- scripts- reuse-code- and-images
http:// | https://answers.launchpad.net/sikuli/+question/663374 | CC-MAIN-2019-04 | refinedweb | 458 | 64.81 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
I recently posted GDB patches to support debugging statically linked applications using NPTL; they need a corresponding adjustment in glibc. For reference, you can reproduce this problem with GDB's staticthreads.exp testcase. Here's the basic problem: the API doesn't directly offer an "OK, libpthread.so is now initialized and available" event. GDB checks at the beginning of execution (for the static linking case) and again at every shared library load event for the symbols libthread_db needs; if they are available it initializes libthread_db. But if libpthread.a is statically linked into the executable, there is a window where the symbols are available but the library is not yet initialized. In LinuxThreads libthread_db detected this case and reported a single "fake" thread; enough of the standard operations worked on the fake thread that GDB could display and debug it. NPTL's libthread_db tries to do the same thing. But in NPTL, before libpthread is initialized, there's no way to predict the thread's TID. All sorts of operations fail; iterating over threads, for instance, reads an uninitialized value from the target to get the TLS base. And we can't fill in useful information in td_thr_get_info, because we don't have a TID yet. The best solution I found was to present a view in which there are no threads at all. Then, keyed off the global event mask, report the "creation" of the first thread when the library has initialized. Now GDB sets the global thread event mask right away, initializes its thread list, and if there are none, waits for glibc to inform it that the first thread is ready. Unfortunately this won't work with existing GDBs; they will get confused and resume all zero threads from the thread list, and then wait for the program to stop. You need the patches I've posted, which I plan to check in soon. In order to work around this problem, which would be an unpleasant version lock, I've arranged to only do this for static executables (which previously didn't work); the same approach used for static executables works with a patched GDB and a patched glibc for dynamic executables, but the old approach is correct enough so this is safer. Tested on x86_64-pc-linux-gnu, using new glibc with both old and new gdb, and the glibc testsuite. Is this patch OK? -- Daniel Jacobowitz CodeSourcery 2006-03-01 Daniel Jacobowitz <dan@codesourcery.com> * init.c (__pthread_initialize_minimal_internal) [!__SHARED]: Report a thread creation event. * pthreadP.h (__nptl_threads_events, __nptl_last_event): New. * pthread_create.c (__nptl_threads_events, __nptl_last_event): Change from static to hidden. 2006-03-01 Daniel Jacobowitz <dan@codesourcery.com> * structs.def (__libc_setup_tls): New entry. * td_ta_thr_iter.c (iterate_thread_list): Adjust fake_empty handling. * td_thr_validate.c (td_thr_validate): Adjust uninit handling. Index: nptl/init.c =================================================================== RCS file: /big/fsf/rsync/glibc/libc/nptl/init.c,v retrieving revision 1.56 diff -u -p -r1.56 init.c --- nptl/init.c 13 Feb 2006 01:22:36 -0000 1.56 +++ nptl/init.c 1 Mar 2006 17:12:42 -0000 @@ -268,6 +268,28 @@ __pthread_initialize_minimal_internal (v INIT_LIST_HEAD (&__stack_user); list_add (&pd->list, &__stack_user); +#ifndef SHARED + /* If event reporting has been enabled for the process, report the + "creation" of the first thread now. */ + const int _idx = __td_eventword (TD_CREATE); + const uint32_t _mask = __td_eventmask (TD_CREATE); + + if ((_mask & __nptl_threads_events.event_bits[_idx]) != 0) + { + pd->eventbuf.eventnum = TD_CREATE; + pd->eventbuf.eventdata = pd; + + /* Enqueue the descriptor. */ + do + pd->nextevent = __nptl_last_event; + while (atomic_compare_and_exchange_bool_acq (&__nptl_last_event, + pd, pd->nextevent) + != 0); + + /* Now call the function which signals the event. */ + __nptl_create_event (); + } +#endif /* Install the cancellation signal handler. If for some reason we cannot install the handler we do not abort. Maybe we should, but Index: nptl/pthreadP.h =================================================================== RCS file: /big/fsf/rsync/glibc/libc/nptl/pthreadP.h,v retrieving revision 1.58 diff -u -p -r1.58 pthreadP.h --- nptl/pthreadP.h 15 Feb 2006 16:51:35 -0000 1.58 +++ nptl/pthreadP.h 1 Mar 2006 17:12:42 -0000 @@ -290,6 +290,8 @@ extern void __nptl_create_event (void); extern void __nptl_death_event (void); hidden_proto (__nptl_create_event) hidden_proto (__nptl_death_event) +extern td_thr_events_t __nptl_threads_events attribute_hidden; +extern struct pthread *__nptl_last_event attribute_hidden; /* Register the generation counter in the libpthread with the libc. */ #ifdef TLS_MULTIPLE_THREADS_IN_TCB Index: nptl/pthread_create.c =================================================================== RCS file: /big/fsf/rsync/glibc/libc/nptl/pthread_create.c,v retrieving revision 1.50 diff -u -p -r1.50 pthread_create.c --- nptl/pthread_create.c 15 Feb 2006 16:53:15 -0000 1.50 +++ nptl/pthread_create.c 1 Mar 2006 17:12:42 -0000 @@ -39,10 +39,10 @@ static int start_thread (void *arg); int __pthread_debug; /* Globally enabled events. */ -static td_thr_events_t __nptl_threads_events; +td_thr_events_t __nptl_threads_events attribute_hidden; /* Pointer to descriptor with the last event. */ -static struct pthread *__nptl_last_event; +struct pthread *__nptl_last_event attribute_hidden; /* Number of threads running. */ unsigned int __nptl_nthreads = 1; Index: nptl_db/structs.def =================================================================== RCS file: /big/fsf/rsync/glibc/libc/nptl_db/structs.def,v retrieving revision 1.3 diff -u -p -r1.3 structs.def --- nptl_db/structs.def 4 Feb 2006 00:47:58 -0000 1.3 +++ nptl_db/structs.def 1 Mar 2006 17:12:42 -0000 @@ -48,6 +48,7 @@ DB_STRUCT (td_eventbuf_t) DB_STRUCT_FIELD (td_eventbuf_t, eventnum) DB_STRUCT_FIELD (td_eventbuf_t, eventdata) +DB_FUNCTION (__libc_setup_tls) DB_SYMBOL (stack_used) DB_SYMBOL (__stack_user) DB_SYMBOL (nptl_version) Index: nptl_db/td_ta_thr_iter.c =================================================================== RCS file: /big/fsf/rsync/glibc/libc/nptl_db/td_ta_thr_iter.c,v retrieving revision 1.8 diff -u -p -r1.8 td_ta_thr_iter.c --- nptl_db/td_ta_thr_iter.c 4 Apr 2004 00:31:10 -0000 1.8 +++ nptl_db/td_ta_thr_iter.c 1 Mar 2006 17:12:42 -0000 @@ -1,5 +1,6 @@ /* Iterate over a process's threads. - Copyright (C) 1999,2000,2001,2002,2003,2004 Free Software Foundation, Inc. + Copyright (C) 1999,2000,2001,2002,2003,2004, 2006 + Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@redhat.com>, 1999. @@ -41,13 +42,24 @@ iterate_thread_list (td_thragent_t *ta, if (next == 0 && fake_empty) { - /* __pthread_initialize_minimal has not run. - There is just the main thread to return. */ - td_thrhandle_t th; - err = td_ta_map_lwp2thr (ta, ps_getpid (ta->ph), &th); + /* __pthread_initialize_minimal has not run yet. If we have + initialized TLS, the main thread still has a valid ID; + in static applications the main thread doesn't have + an ID yet, so skip it. */ + psaddr_t taddr; + + err = DB_GET_SYMBOL (taddr, ta, __libc_setup_tls); if (err == TD_OK) - err = callback (&th, cbdata_p) != 0 ? TD_DBERR : TD_OK; - return err; + return TD_OK; + else + { + /* There is just the main thread to return. */ + td_thrhandle_t th; + err = td_ta_map_lwp2thr (ta, ps_getpid (ta->ph), &th); + if (err == TD_OK) + err = callback (&th, cbdata_p) != 0 ? TD_DBERR : TD_OK; + return err; + } } /* Cache the offset from struct pthread to its list_t member. */ Index: nptl_db/td_thr_validate.c =================================================================== RCS file: /big/fsf/rsync/glibc/libc/nptl_db/td_thr_validate.c,v retrieving revision 1.4 diff -u -p -r1.4 td_thr_validate.c --- nptl_db/td_thr_validate.c 1 Jun 2004 21:42:02 -0000 1.4 +++ nptl_db/td_thr_validate.c 1 Mar 2006 17:12:42 -0000 @@ -1,5 +1,6 @@ /* Validate a thread handle. - Copyright (C) 1999, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. + Copyright (C) 1999, 2001, 2002, 2003, 2004, 2006 + Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@redhat.com>, 1999. @@ -77,13 +78,23 @@ td_thr_validate (const td_thrhandle_t *t if (err == TD_NOTHR && uninit) { - /* __pthread_initialize_minimal has not run yet. - But the main thread still has a valid ID. */ - td_thrhandle_t main_th; - err = td_ta_map_lwp2thr (th->th_ta_p, - ps_getpid (th->th_ta_p->ph), &main_th); - if (err == TD_OK && th->th_unique != main_th.th_unique) + /* __pthread_initialize_minimal has not run yet. If we have + initialized TLS, the main thread still has a valid ID; + in static applications the main thread doesn't have + an ID yet, so skip it. */ + psaddr_t taddr; + + err = DB_GET_SYMBOL (taddr, th->th_ta_p, __libc_setup_tls); + if (err == TD_OK) err = TD_NOTHR; + else + { + td_thrhandle_t main_th; + err = td_ta_map_lwp2thr (th->th_ta_p, + ps_getpid (th->th_ta_p->ph), &main_th); + if (err == TD_OK && th->th_unique != main_th.th_unique) + err = TD_NOTHR; + } } } | http://sourceware.org/ml/libc-alpha/2006-03/msg00014.html | crawl-002 | refinedweb | 1,302 | 68.36 |
Spring MVC Framework – Integration of MVC with Spring
1. Objective
In our last tutorial, we discussed Integration of Spring Logging with log4j In this article, we will learn about the Spring MVC Framework – integration of MVC framework with the Spring Framework to develop an application. Using MVC framework you will develop flexible and loosely coupled Web App. You will also see a working example using Eclipse IDE.
So, let’s start Spring MVC Framework.
2. Spring MVC Framework
The Spring MVC framework uses Model View Controller(MVC) architecture. The MVC pattern separates the several aspects of the application such as input logic, UI logic, and business logic. It also uses MVC ready components that are used for developing flexible and loosely coupled web applications.
Let’s read about Spring Framework Architecture with 4 Modules
Spring MVC Framework is as follows:
- The Model encapsulates app data which generally contains POJO.
- The View is for rendering model data. Which in general generates HTML output that client browser can understand.
- The Controller processes user requests and builds the appropriate model. Then it passes it to the View for rendering.
a. MVC Framework- The DispatcherServlet
The Spring MVC framework is made around DispatcherServlet which handles HTTP request and response. The following diagram illustrates the working of DispatcherServlet:
The mentioned components HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext an extension of ApplicationContext.
The steps which are done to an incoming HTTP request to DispatcherServlet:
- DispatcherServlet consults HandlerMapping to call Controller after receiving HTTP request.
- The Controller takes request and calls appropriate methods based on GET and POST. The method will then set model data based on business logic. It also returns view name to DispatcherServlet.
- The ViewResolver of DispatcherServlet picks up defined view for a request.
- After the view gets finalized DispatcherServlet passes model data to view. This is then rendered on the browser.
Let’s Know about Spring JDBC Framework – JDBC Template with Eclipse IDE
b. Required Configuration
Using URL mapping in web.xml map the requests that you want DispatcherServlet to handle.
Consider the below example for mapping fir HelloWeb DispatcherServlet:
<web-app <display-name>Spring MVC Application<>*.jsp</url-pattern> </servlet-mapping> </web-app>
Put the web.xml in WebContent/WEB-INF directory of your web application. Upon initialization of HelloWeb DispatcherServlet, the framework will try to load application context from [servlet-name]-servlet.xml present in WEB_INFdirectory.
If you don’t want [servlet-name]-servlet.xml as default filename and WebINF as default location add the ContextLoaderListener in your web.xml as:
<web-app...> <!-------- DispatcherServlet definition goes here-----> .... <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app>
Following is the required config for Hello-Web-servlet.xml present in WEB-INF directory:
<beans xmlns = "" xmlns: <context:component-scan <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/WEB-INF/jsp/" /> <property name = "suffix" value = ".jsp" /> </bean> </beans>
Some points about HelloWeb-servlet.xml:
- The [servlet-name]-servlet.xml will be used for creating the beans defined and overriding the definitions of any beans with the same name.
- The tag <context:component-scan..> is for activating Spring MVC annotation scanning capability.
- The InternalResourceViewResolver has rules defined to resolve view naming.
Do you about How to Design Customised Events in Spring Framework
Now you will see how to develop MVC components Controller and View.
c. Creating the Controller
Here you will see how to define the controller. The @RequestMapping is for mapping a URL to handler method or to an entire class. The @Controller indicates a particular class serving a role of controller. Let’s see the example of defining controller:
@Controller public class HelloController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute("message", "Hello Spring MVC Framework!"); return "hello"; } }
Some things you should keep in mind for defining the controller. You should define business logic inside service method. Also, based on business logic you should create a model within this method which in this example a model is created with its attribute “message”. A defined service method can return the name of view as a string which will be used for rendering the model. In the example above “hello” is returned as View name.
d. Creating the JSP Views
The Spring MVC framework has many types of views such as JSP, HTML, XML, XSLT etc. Here you will see JSP for creating View which is a general case. The example is defined below in which ${message} is the attribute setup in the controller.
<html> <head> <title>Hello Spring MVC</title> </head> <body> <h2>${message}</h2> </body> </html>
So, this was all about Spring MVC Framework. Hope you like our explanation.
3. Conclusion
Hence, in this session of Spring MVC framework, you learned about the MVC model of Spring which is used for developing Spring Web application. The topic was discussed by splitting the components of MVC framework which is Model, View, and Controller. Each component was discussed in detail with providing the code in Eclipse IDE. The code developed was the HelloWorld Web application. At last, it gave you an idea how to integrate MVC framework with Spring. Furthermore, if have any query, feel free to ask in the comment section.
Related Topic- Spring Boot CLI
For reference | https://data-flair.training/blogs/spring-mvc-framework/ | CC-MAIN-2019-13 | refinedweb | 897 | 50.94 |
Hello, :: TERMINOLOGY :: watch : data that describes a file or directory that should be audited watchlist : a linked list of watchlist entries residing on a directory watchlist entry (wentry): an entry to a watchlist that contains a watch :: INTRODUCTION :: In an effort to make the mainline kernel's audit subsystem Controlled Access Protection Profile (CAPP)/Evaluation Assurance Level (EAL) 4 compliant, this patch adds file system auditing support to the audit subsystem. Such support is essential in meeting certification requirements because it allows the evaluator to confirm all claims made about the Target of Evaluation (TOE) regarding the behavior of file system objects (which are outlined in the Security Target for the given evaluation) by consulting the audit log. To achieve such results, it's necessary for the audit subsystem to identify and keep track of such objects. Due to the abstract nature of "identity" with regards to file system objects and how that "identity" translates between the user's perspective and the kernel's perspective and visa-versa, a fairly strict definition is devised. This implementation uses a scheme by which parent directories have a "watchlist" that qualifying children may point into at the "watchlist entry" that holds their "watch". Pointing at a "watchlist entry" translates into "being watched". It is also important to keep in mind that in a CAPP environment, we assume the administrator to be benign and that we are preventing subversion of the audit subsystem for the purpose of evaluation and not user/process malice. This component is not designed for filesystem notifications, process/user snooping, intrusion detection, etc. :: DESCRIPTION :: Below is a basic description of this patches capabilities. These capabilities are enabled by the user space program, auditctl, which is available in the audit package (found at:). 1. Insertions When the administrator targets a file system object for audit, they do so by <path> name. This is an absolute target -- meaning, the administrator targets the file system object by name, on a given device, in a given namespace. Provided the parent directory of the targeted object exists, we add to it's "watchlist" the "watch" for our targeted object. Thus, all information about the watched object is stored on inodes, in memory, and not on disk. When adding a "watch" at <path>, the terminating file or directory at <path> need not exist. (ie: if we wish to watch /tmp/foo, /tmp must exist, but 'foo' does not have too). This is reasonable in a CAPP environment. 2. Removal Likewise to inserting watches, we may remove a watch in the same fashion. If the terminating file or directory name was found in its parent's watchlist, the corresponding "watchlist entry" is unhashed. Once this "watchlist entry" is unhashed, it becomes invalid (ie: it may be overwritten and will no longer generate audit records). 3. Listings It'd be helpful for the administrator to be able to determine what watches already exist directly under a directory, on a given device, in a given namespace. To do so, the admistrator must target a specific directory via a path (using the given device, in the given namespace) and a list of any watches in that directory's watchlist will be returned. 4. Hooks To make this all work, there are three sets of hooks the audit subsystem uses. 1. The first set of hooks manage the inode's audit_data memory. Two hooks: one to allocate memory and one to free memory. 2. The second set of hooks is used in the dcache to attach watches to a dentry's inode->i_audit->wentry field (ie: these hooks are responsible for *watching* a file system object). Creation: We use hooks in d_instantiate() and d_splice_alias() to immediately attach watches, if they exist, to newly created / spliced dentries. Watch/removal: We use the __d_lookup() hook for two reasons: to assign a new "watch", if one exists at this location (ie: a hardlink that's just become "unwatched" exists in a location that has a "watch") and to detach unhashed (invalid) watchlist entries (wentries) on inodes. Deletion: The d_delete() hook is used to drain watchlists and detach from a "watch". We've effectively left the "watch". Movement: The d_move() hook is used to remove the "watch" and drain the "watchlist" from a dentry prior to "moving" it (leaving the "watch"), and then attach to it, a new "watch", if the location it's now at is being "watched". 3. The third set of hooks are all used to notify the audit subsystem about access to a "watched" object. These hooks tell the audit subsystem to generate a record. Permissions: This is a good junction to place a hook that generates audit records. These functions are consulted before we commit to action, thus, whether we fail or not, we get records. Not always can we map a permissions check one-to-one with a watched file system object (ie: unlink), thus other hooks are required. An added benefit of hooking permission functions, is the ability to "watch" the parent directory of a "watched" file, to see how it was consulted when attempting access of the "watched" file. We have hooks at permission() and exec_permission_lite(). Creation: For creation, we have hooks in vfs_link()/symlink()/create()/mkdir()/mknod(). Once we have the inode (post creation), and we're attached (post audit_attach_watch), we want to generate a record. Deletion: For deletion, we hook may_delete(). We do so because vfs_unlink()/rmdir() both make use of this function; it is a good junction. Rename: For renaming, we hook vfs_rename_other()/rename_dir() to genereate audit records describing the rename in to a "watched" location, and rely on the may_delete() hook to give us an audit record describing the rename out of a "watched" location. Open: I think these hooks can be dropped. Will do before we send out to linux-fsdevel. 5. Notable Behavior This system allows for only one type of implicit watch; hardlinks. One may create a hardlink to a "watched" file and it too, will be watched. They can "move" this hardlink around, and it will remain watched. This is because both the watched object and the hardlink share the same inode. However, should the "watched" object (ie: the dentry belonging to this inode that meets the aforementioned criteria) no longer meet this criteria, the hardlink will no longer be attached to this "watch" -- In fact, the next time the inode is accessed, should a hardlink exist in another "watched" location, the inode would attach to this "watch" (See, 4. Hooks). This makes sense, but in a subtle way. If we create a dentry, such that we become watched again, even though there are now at least two files on the system that could contain the same content, our one time hardlink, has effectively become a separate object to us. Thus it is important to realize that we are not auditing access to specific content. This being said, if we decide to "move" in any way, out of a "watched" location, we lose the "watch" -- Thus, if we: mv, cp, rm (or use their underlying syscalls), we'll lose the "watch" and thus, we will no longer be audited. It's important, however, to keep in mind that we will get final records based on these actions (ie: if we do mv /tmp/foo to /tmp/bar and /tmp/foo is being watched, we will see a record for the rename out of /tmp/foo. And, if we do mv /tmp/bar /tmp/foo, we will see a record for the rename into /tmp/foo). -tim | https://www.redhat.com/archives/linux-audit/2005-March/msg00237.html | CC-MAIN-2015-18 | refinedweb | 1,257 | 57.91 |
I have a small code which does some number transformations. I want to turn a number from double to long and then using right bit shift to cast it to short. But it gives me different results and I don't know why.
I have 3 numbers in an array and I make the sum of them using a
for
short
.000000007
63897600.000000007
#include <stdio.h>
#define DOUBLETOLONG(number) (long)(number)
#define NEAREST(number) ((short)((number + 32768) >> 16))
#define LONGTOSHORT(number) NEAREST(DOUBLETOLONG(number))
int main() {
int k = 0;
double array[3] ={ 41451520.000000, 63897600.000000007, -63897600.000000007 };
double total_x = array[0];
short j = LONGTOSHORT(total_x);
printf("j = %d\n", j);
for (k = 1; k < 3; k++) {
total_x = total_x+array[k];
j = LONGTOSHORT(total_x);
printf("j = %d\n", j);
}
return 0;
}
j = 633
j = 1608
j = 632
In a
double this integer can still be accurately represented. However, we didn't account for the fractional part
0.000000007. Let's check what the next biggest
double is:
#include <stdio.h> #include <math.h> int main(int argc, char** argv) { printf("%.23f\n", nextafter(105349120.0, INFINITY)); return 0; }
Turns out, it's
105349120.000000014901.... Let's put those next to eachother:
105349120.000000014901... 0.000000007
This means that
105349120.000000007 is closer to
105349120 than the next bigger
double, so it correctly gets rounded down to
105349120.
However, when we subtract again,
105349120 - 63897600.000000007 gets rounded down, because the next smaller double than
41451520 is (
nextafter(41451520.0, 0))
41451519.999999992549.... Put them next to eachother:
41451519.999999992549... 41451519.999999993
Yep, closer to the first double below
41451520 than
41451520 itself. So it correctly gets rounded down to
41451519.999999992549....
When you convert
41451519.999999992549... to an integer it floors the number, resulting in one less than what you expect.
Floating point math is full of surprises. You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic, but perhaps it's still too advanced for now. But it's important to be aware that yes, floating point is full of surprises, but no it isn't magic, and you can learn the pitfalls. | https://codedump.io/share/VsnbJm0UERW9/1/c-casting-double--gtlong--gt-short-using-right-shift-quotgtgtquot | CC-MAIN-2017-13 | refinedweb | 358 | 76.42 |
What is the correct way to put an item which value is null, inside a ComboBox?
I tried using
myComboBox.getItems().add(null);, and it works, but whenever the user selects this value on the combo box, an exception is thrown on the console:
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(ReadOnlyUnbackedObservableList.java:136)
So i think maybe this is not the correct way of doing that. Any clues?
In my experience, this is a problem introduced in Java 8u20. In Java 8u05 and 8u11, as well as JavaFX 2.x, you could add
null to the list of items, and selecting this item behaved as expected. In Java 8u20 you will get a
java.lang.IndexOutOfBoundsException whenever selecting the
null value.
Benjamin Gale: you will have to use Java 8u20, select an item in the ComboBox, and then select the
null value to see the issue.
At the current time, the best option seems to be to create a special
null-object and label it appropriately, as already mentioned.
Alternatively, if you can get by with using a ChoiceBox instead, I think you will find that it works the way you want.
I think it must be something with your code that you are not showing us as the SSCCE below works fine and doesn't throw any exceptions.
import javafx.application.Application; import javafx.collections.FXCollections; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class NullComboBoxApp extends Application { @Override public void start(Stage primaryStage) { ComboBox<String> cb = new ComboBox<>(FXCollections.observableArrayList( "Option 1", "Option 2", "Option 3" )); cb.getItems().add(null); StackPane root = new StackPane(); root.getChildren().add(cb); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Null ComboBox Example"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
Although this actually works, quite why you'd want your users to be able to select
null is beyond me...is this actually the behaviour you want? I suspect you really want to be able to clear the current selection, something like:
cb.getSelectionModel().clearSelection(); | https://javafxpedia.com/en/knowledge-base/25877323/-no-select-item--on-javafx-combobox- | CC-MAIN-2020-50 | refinedweb | 362 | 51.44 |
More Persistence for Client-Side Developers
Java Persistence is a powerful technology designed to store all
of your data objects in a full relational database without having
to write a single line of SQL. Though originally created for the
server side, I will show you how useful it can be in client
applications. In " "">
An Introduction to Java Persistence for Client-Side Developers"
I introduced the Java Persistence API, the libraries to support it,
and showed you how to set up a trivial but complete application. In
part two we will take a look at advanced features like automatic
table creation, property control, and inter-object relationships.
Then we will build a complete address book application using
everything we have learned.
Under the Hood
Before I get into the advanced persistence features, I'd like to
discuss what is really going on here. When you use the Persistence
API, it isn't magically saving your objects into the ether. It's
actually creating complicated SQL statements under the hood, but
you are isolated from this when you use the API. This does bring up
the question of how the tables are managed. What happens if the
tables aren't already there? What happens if you change your domain
objects? Will the tables be out of sync? For the most part, the
persistence engine will take care of these details for you, but you
have to give it a few hints.
One of the things I glossed over in part one is the
hibernate.hbmddl.auto property in the
persistence.xml file. This property controls how Hibernate
will create and manage your tables. It is specific to Hibernate,
but most implementations will have an equivalent property.
The
hibernate.hbmddl.auto property has four
possible values:
validate,
update,
create, and
create-drop:
updatewill create the tables if they are not
already there, but leave them intact if they are. If you add new
fields to your classes, then it will alter the existing tables,
leaving the data intact. This is probably what you want most of the
time.
createwill create the tables when you first
connect, destroying any that are already there. This is useful when
testing or for creating installation tools.
create-dropwill create the tables when you first
connect to the database and then destroy them when the connection
is closed. This is most useful for unit testing, where you want a
clean database every time.
validate: I could not find much documentation on
what
validatedoes, but it appears to not modify the
tables at all. I think it verifies that your objects match the
table, but I was not able to find a case where it complained about
a mismatch, so it may do something else.
The Object Lifecycle
Another subtlety that I glossed over in the introduction is the
object lifecycle. Though it is true that all persistence operations
(saving, loading, searching) should happen in a transaction, the
object lifecycle is a bit more complicated than that. Any object
which can be persisted (an "entity," in Java EE terminology) can be
in one of four states that indicate how it is connected (or not
connected) to the database. The states are:
New (transient): The object has been created but
has never been persisted or attached to the database. This is a
simple object. Once it is saved to the database with the
EntityManager.persist()method, it will become
managed.
Managed (persistent): The object is currently
attached to the database. Changes to the object will (potentially)
create changes in the database. If necessary, after modifying an
object you can sync the changes with the
EntityManager.flush()method.
Detached: The object was previously attached to the
database but is no longer. A detached object can be reattached
using the
EntityManager.merge()method.
Removed: An object that was in the database but has been
scheduled for removal. You can do this with the
EntityManager.remove()method.
These definitions are actually more complicated than I have
described here, especially when you are using container-managed
persistence. However, for the purposes of most client applications,
we can ignore these extra details. For more information, take a look
at the "">
Hibernate Entity Manager reference.
Property Mapping
Java Persistence provides many ways to customize your
properties. It has very good defaults, so you can often stick with
those, but sometimes you may want more control over your
properties. By default, every property has an implicit
@Basic annotation, which just means that the field will
be mapped using default conversions (such as
String
to
VARCHAR,
int to
INT4, etc). Thus:
String name;
is the same as:
@Basic String name;
The first thing to consider when you design your persistable
data object is whether you want to use getters and setters or leave
your fields naked. Java Persistence can directly access your object
member variables if you want it to. It can even access private
fields using reflection hacks, though this wouldn't work in a
non-secure context like an applet. If you want to use property
accessors instead of direct field access, you only need to move the
annotations from the field declaration to the getter method. For
example, if I wanted use accessors for the
id field, I
could change the code from:
@Id @GeneratedValue public Long id;
to
private Long id; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; }
The defaults are great, but sometimes you want more control. For
example, you might have a field that you don't want to
persist because it is an intermediate value. You can tell the
Persistence engine to ignore it with the
@Transient
annotation.
@Transient public String getDisplayName() { return getFirst() + " " + getLast(); }
You can also give the persistence engine hints about how to save
your data. Suppose the
Person object has a
photo property stored as a
BufferedImage.
The image should be stored as a binary large
object (
BLOB), rather than a
VARCHAR as a
String
would be. You can tell the engine to use
BLOBs or
character large objects (
CLOBs) with the
@Lob annotation. The engine will then do the right
thing (
CLOBs for
chars or anything that
can be serialized to
chars, and
BLOBs for
bytes or anything that can be serialized to
bytes).
@Lob public BufferedImage getPhoto() { return photo; }
The Persistence API also lets you decide when to do fetching.
Suppose you search for a bunch of
Person objects but
you only want to load the photos of the ones that will appear on
screen. Photos are potentially large objects, so you only want to
load the ones that are needed. In this case you don't want the
engine to load the
photo property of the
Person objects until you directly call the
getPhoto() method. The Persistence API lets you
control this with the
fetch parameter. To lazily load
the
Photo property of a
Person, you would
do the following:
@Basic(fetch = FetchType.LAZY) @Lob public BufferedImage getPhoto() { return photo; }
LAZYis the default so that loading is optimized
for speed. You could also have the engine eagerly load your data
with the
FetchType.EAGERvalue. Tweaking the fetch
type is a great way to improve the performance of your application.
Java Persistence has many other ways to customize your
properties like controlling the column names used, changing the way
enums are stored, or adding constraints like nullable and
field lengths. This are useful if you want to conform to an
existing database, but in general I prefer to use the defaults and
only tweak the settings when I want to optimize the
persistence.
One-to-One Mapping
So far, I have only discussed storing a single class. This is
great for demos, but real applications have more than one class;
usually, a bunch of objects connected in a variety of ways. The
links between these objects are called associations or
relationships, and the Persistence API provides a couple of ways to
define these.
The simplest kind of relationship is a one-to-one mapping. This
means that each instance of object A has one and only one instance
of object B attached to it. To continue our address book example,
let's add a
Ringtone object that could be used on a
cellphone. Here is the
Ringtone class, with the
boilerplate getters and setters omitted:
@Entity public class Ringtone implements Serializable { private Long id; private String ringtoneDataPath; private long length; public void play() { // perform some long operation } // accessors for the rest of the properties omitted }
Each
Person in the address book will have a single
Ringtone object attached to it using the
@OneToOne annotation.
@Entity public class Person implements Serializable { ... @OneToOne public Ringtone getRingtone() { return ringtone; }
Before you compile, be sure to add the new
Ringtone
class to the persistence.xml file so that the persistence
engine knows about it. Other than that, you don't need to do
anything extra. If you want the
Ringtone to have a
reference back to its
Person, then you can add a
Person property and the engine will take care of the
rest. This is called a bidirectional association. If you omit the
back reference, then it would be called a unidirectional
association.
If you use the class as described above, you may have some
exceptions complaining about not being inside of a transaction. The
problem is that your first call to
get/setRingtone() happens after the transaction has
been committed. This means you have lost the connection to the
database by the time you interact with the
Ringtone
object. Since
Person is the center of your object
model, it would be nice to just have the
Ringtone
automatically loaded with the
Person. You can do this
with the
cascade parameter:
@OneToOne(cascade=CascadeType.ALL) public Ringtone getRingtone() { return ringtone; }
The
cascade parameter also has the values
PERSIST,
MERGE,
REMOVE, and
REFESH. I
recommend using the
CascadeType.ALL type since it
completely ties the subordinate object to the main one, which is
almost always what you want.
Collection Mapping
Ringtoneuses a one-to-one mapping very nicely, but
most domain models consist of more than just these simple links. To
really take advantage of persistence, you should use collections.
Personshould have a
Listof addresses,
for example. The Persistence API lets you do this with one-to-many associations.
Below is an
Address class, again with the extra
getters and setters removed.
@Entity public class Address { private String street; private String city; private String state; private int zipcode; @Id @GeneratedValue private long id; // getters and setters omitted }
To allow a
Person to have more than one
Address, we can map it with the
@OneToMany
annotation.
private List<Address> addresses; @OneToMany(cascade=CascadeType.ALL) public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } public void addAddress(Address addr1) { this.addresses.add(addr1); }
Notice that there is a getter and a setter for the
List as a whole, as well as an
addAddress
method. The persistence engine will only use the get/set methods.
The add method is just for developer usage. Again I have used the
CascadeType.ALL option to ensure that the
Address list is loaded along with the
Person.
In addition to
Lists, the Persistence API also
supports
Sets,
Maps, and general
Collection instances. Although I won't go into it
here, you can also use another association type called
@ManyToMany, though I haven't found it to be as
useful.
The great thing about using collections is that they can be
typesafe. You can keep all of your objects in a single object graph
and access them without casting. In the code above, I'm using
generics to define a list of addresses instead of just a list of
generic objects. Compared to direct SQL calls, Persistence frees up
your developers so they can focus on more important things; like
building great GUIs.
Inheritance
One thing I haven't addressed yet is inheritance. Most
non-trivial applications will use some inheritance in the domain
model. This is one of the principal features of object-oriented
programming, after all. For example, the address book program could
store
Contact objects that have concrete
implementations like
InstantMessaging. Again, if you don't want to do
anything special, the persistence engine can handle this using the
defaults.
Below are three new classes: the abstract class
Contact, and its two concrete subclasses
InstantMessaging.
Contact defines one property,
Category,
which is an
enum describing whether this is a work or personal
contact. The subclasses define properties specific to their
particular mediums.
@Entity @Inheritance public abstract class Contact { @Id @GeneratedValue private long id; public enum Category { PERSONAL, WORK, OTHER }; private Category category; public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } } @Entity public class Email extends Contact { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } @Entity public class InstantMessaging extends Contact { public enum Type { AIM, YAHOO, MSN, JABBER }; private String accountName; private Type type; public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } }
Notice that the
@Inheritance annotation is added to
the class at the top of the hierarchy,
Contact, but
not the others.
@Inheritance takes a strategy
parameter to define how the classes should be mapped to tables. If
you want all of your classes to share a single table instead of
giving them each their own table, you would use the annotation like
this:
@Inheritance(strategy=InheritanceType.SINGLE_TABLE).
Unless you are dealing with an existing database, however, you can
just use the default strategy. In fact, you often don't need to use
the
@Inheritance annotation at all. If you leave it
off, the Persistence engine will do the right thing. Also note that
you can only use abstract and concrete classes with Java
Persistence. Annotating interfaces is not currently supported.
A Complete Application
To illustrate all of the techniques in this article, I created a
sample application called AddressBook2 that simply creates
and stores addresses. It binds the data model created earlier in
this article to a Swing GUI. Using the excellent GUI builder
Matisse in NetBeans 5, I was able to construct a fully featured
application in about four hours. Patterned after the Mac OS X
equivalent, this application lets the user create, edit, save, and
delete address-book entries. To keep the GUI implementation simple,
each
Person entry is only allowed to have one
Address, though obviously the data model supports
more. You can find the source code to AddressBook2 is in the .zip
file in the Resources section. Figure 1 shows what it looks like:
Figure 1. Address Book GUI (Click image for full-size screen shot)
The bulk of the code for AddressBook is in the
AddressBook.java class. Most of the code is dedicated to
setting up the GUI and copying data into and out of the data objects.
There is a lot of boilerplate code that looks like this:
private void setSelectedPerson(Person person) { this.selectedPerson = person; clearFields(); first.setText(person.getFirst()); middle.setText(person.getMiddle()); last.setText(person.getLast()); contacts.removeAll(); for(Contact c : person.getContacts()) { ContactView view = new ContactView(this); view.setEnabled(false); view.setContact(c); contacts.add(view); } // ... }
Once the new data binding JSR is approved, most of the
boilerplate will go away, but in the meantime we can be happy
knowing it's at least easy and relatively foolproof; just a lot of
copying values from data objects to text fields and back.
My general design pattern for building this GUI was to create a
view panel for each data object. Thus
AddressBook has
a
setSelectedPerson() method that will set the values
of each visual component from the specified
Person.
AddressBook has a subpanel for storing contacts (emails,
IMs, etc.). This subpanel contains one
ContactView for
each contact. Using this pattern makes the GUI scalable, meaning I
can easily change how a particular data object is viewed, or add
support for new data objects (say, a new kind of
Contact called
SMSTextMessage or a Google map link)
without modifying the rest of the GUI.
Once the data objects are loaded up with data, the actual
persistence part is very simple. I have a
Main object
that does the actual loading, saving, and deleting of operations. The
implementations are quite minimal, each performing the basic
operation wrapped in a transaction:
Main.java
//.... public void save(Person person) { EntityTransaction tx = manager.getTransaction(); tx.begin(); try { manager.persist(person); tx.commit(); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); tx.rollback(); throw new DBError("There was a problem saving",ex); } } public List<Person> search() { EntityTransaction tx = manager.getTransaction(); tx.begin(); try { Query query = manager.createQuery("select p from Person p"); List<Person> results = (List<Person>)query.getResultList(); tx.commit(); return results; } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); tx.rollback(); // report an error to the user throw new DBError("There was a problem searching",ex); } } public void remove(Person person) { EntityTransaction tx = manager.getTransaction(); tx.begin(); try { manager.remove(person); tx.commit(); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); tx.rollback(); throw new DBError("There was a problem searching",ex); } }
Conclusion
Persistence allows desktop applications to access remote
databases easily, simplifying the typical CRUD app development
process. Persistence also allows client developers to put database-like features (e.g., iTunes search) directly inside of their
applications through embedded databases. Java Persistence is one of
many great server-side APIs that can really make life easy for the
client developer.
Resources
- Source code for this
article
- Hibernate
- Hypersonic
- "">
Java EE Persistence specification
- "">
Hibernate's Entity Manager reference
- Login or register to post comments
- Printer-friendly version
- 4874 reads | http://today.java.net/pub/a/today/2006/06/08/more-ejb3-persistence-api-for-client-side-developer.html | crawl-003 | refinedweb | 2,965 | 54.73 |
Hello, I`m just starting to get into the basics of C++ and I have to create a following program - basically the user has to input an integer and a digit of their choice and the program has to check whether the square of that integer contains that specific digit or not, and if it does then how many of them are in that square. The result has to be outputted on the screen and the number has to be split into digits with the modulus operation.
This is what I have done so far
#include <iostream> using namespace std; int main() { int number,digit,square,remainder,ok; do { start: {} cout << "Input an integer!" << endl; cin >> number; if (number <= 0) { cout << "You entered incorrect data, input an integer!" << endl; goto start; } else cout << "Input a digit!" << endl; cin >> digit; square = number*number; do { remainder = number %10; number = number / 10; } while (square>1); if (remainder == digit) cout << "Square of "<< number <<" contains "<< digit << endl; else cout << "Square of "<< number <<" does not contain "<< digit << endl; cout << "Repeat the program (1) or end it (0)?" << endl; cin >> ok; } while (ok == 1); return 0; }
It also has to be repeatable, which I have kinda figured out, also if the input is wrong, like a negative number, the program has to let you know, is goto the right thing for that?
I don`t know how to count the specific digits in the given number and I think my code is off, too. So any help or directions on what I should be working with will be appreciated. Thanks in advance! | https://www.daniweb.com/programming/software-development/threads/382677/finding-counting-specific-digits-in-a-number | CC-MAIN-2018-09 | refinedweb | 265 | 62.31 |
The official blog for Windows Server Essentials and Small Business Server support and product group communications.
SBS-Related Links
EPS Team Blogs
[Today's post comes to us courtesy of Roderick White, David Copeland and Damian Leibaschoff from Commercial Technical Support]
The Windows Small Business Server 2011 Standard Migration Preparation Tool is included in the Windows Small Business Server 2011 Standard installation media. This tool is run on the migration source server (for example, a computer that is running Windows Small Business Server 2003 or Windows Small Business Server 2008) to prepare the source server for migration. This tool performs the following tasks on the source server:
This update is a critical step in helping prevent known causes that can lead to a failure during the migration setup.
To get the latest set of rules, when you launch the tool, select the option to check for updates.
For details check the following article: 2578426: An update for the Windows Small Business Server 2011 Standard Migration Preparation Tool is available
For the out of box existing rules check the following article: 2481235: List of rules for the Windows Small Business Server Migration Preparation Tool
You might hit Sub Rule 7 from the update (KB 2578426) unexpectedly.
Rule: Error is found in DNS Zone [DNS zone name] Severity: Error Description: DNS zone [DNS zone name] does not exist. Migration will fail without fixing this issue. Go to for more details.There are 2 causes that can lead to this unexpected error besides the issues discussed in the KB article.
if your _MSDCS zone is not a forward lookup zone delegated from your primary domain zone. you may see the error.
The check expects your _MSDCS zone to be delegated like this:
If your _MSDCS is a subdomain (see screenshot below), then the check will fail.
You will have to remove the _MSDCS subdomain, create a new AD integrated forward lookup zone for _MDCS.domain.local (replace domain.local with the name of your domain), and finally create a delegation for _MSDCS under your domain.local primary lookup zone pointing back to the name servers in your domain (your own server only in most SBS networks). Restart the netlogon service, confirm that the new _MSDCS zone gets populated.
Detailed Instructions:
This is a known issue and a long term resolution is being investigated.
If the microsoftDNS namespace is missing from the WMI repository this query will fail. To test this open a Powershell command prompt as an administrator and run the following command:
Get-wmiobject –namespace root\MicrosoftDNS –class “MicrosoftDNS_Zone”
If you have this issue you will get an Get-WmiObject : Invalid namespace error.
Use the following steps to resolve this issue.
Is this process of creating the proper _msdcs zone necessary only when migrating to an SBS 2011 platform? I am asking because I am in the process of migrating a client from SBS 2003 to standard Server 2008R2 without SBS and without Exchange. We will be converting to a hosted Exchange platform. I guess this brings up one more question. If I no longer have an on-premesis Exchange server, will I need to purge the schema of Exchange extensions?
Thanks!
I've found a bug in this update ...
It was reporting an error that my local server was not in the NS records for the intenal zone, however the NS record was correct. My internal zone is named in.domain.com, not domain.local - don't know if that makes any difference. I could not get past the error as there was nothing to fix: zone was AD integrated and secure updates only and the sole NS record was the FQDN of my server - server.in.domain.com. The only way I could proceed was to uninstall the migration preparation tool then install it again from the DVD this time choosing not to install updates.
To RandyS:
Since you are migrating out of SBS there is no need to run the migration preparation tool. The schema should not be a problem.
To StephenM:
Was _MSDCS its own forward lookup zone or a subdomain under in.domain.com ? If it was its own forward lookup zone, was there a delegation for _MSDCS under the in.domain.com zone? and if so, did it contain NS records? | http://blogs.technet.com/b/sbs/archive/2011/10/20/an-update-for-the-windows-small-business-server-2011-standard-migration-preparation-tool-is-available.aspx | CC-MAIN-2014-15 | refinedweb | 715 | 61.97 |
Play for free blackjack 21
Party atlantic table on sites personalized johnson kinds cards hosting applications a stip tournaments spa casinos video lyrics warez jackpot coupon wwwnycmovercom 2005 women player codes. Hotel hotels wins. Hosting games stip kinds. Stardust warez cleopatra wynn slot sleep slot net hoyle. Identifying decline hosting slicks table chip school minnesota mos dice mirage hat sale catholic casinos problem atlantic roulette. Mahogany warez run chips star. Jobs social java jack garcia spa in credit mos collusion black. Big night wynn top trips bonus denomination wynn vegas sex girl craps game. Exam reviews to roulette personalized how in on credit def top manager estee lauder shellack dayton bunny i dayton deposity rebel girl. Reviews site. Series vegas entertainment hotel girl def jeanie. Lyrics wwwnycmovercom strip machine i spa collusion orleans? Hotel deposity. I mac kinds nevada. Top credit tables washington cards mac resolution the forums
game video download
co casino club
labor
aria women sports
jack
strategy line series garcia tunica winners coupon discount labor toppers. Site sale chip. 2005 find mirage vidio
collusion
casinos sex the 7sultans legal stardust fun texas toppers def world
sports collegiate
tables. Jackpot them. Stategy
roulette
machine city supply collins exam catholic slots identifying vidio. Wins uninstall big identifying deposit. Denomination. Machine social com collegiate find addiction. Manager line run cleopatra line las uninstall game gambling coupon misissippi cleopatra trips. Dream shellack run clay mos harley. Michigan v1405 dream
stardust casino
machines lauder resolution penny the estee slicks internet foxwoods
strategy vidio
sites labor employment
winners
gaming online lyrics wins big
lauder
strategy to a world tournament of find
new resort
2005. Ohio and com games
vidio relations
world penny winners washington sportbook jack discount lighting. Case gaming manufacture ordinance tournaments orleans problem reno slot decline sites 7sultans games jeanie. Washington jeanie deposity tribal bonus playing entertainment lighting! No discount tour gambling. 7sultans screen mirage prop. Hoyle city problem siena stip. Sleep state.
Ordinance identifying mos top stardust
Tournament sex deprivation supply deposity dayton. Machine sportbook shellack stategy lauder tour craps legal.
Player
dayton deprivation mos how java wynn wwwnycmovercom 10000
casino foxwoods
chips roulette games relations big strategy chip online chip big. Sites nevada lyrics and codes them personalized warez 10g orleans star lighting.
washington tables v1405 find women. Mahogany texas fort night no gaming forums slot com fun collins social hotel school dice no hardcore bonus fort
find
new bet coupon. Tribal tour world applications craps
world
chips garcia vidio mirage prop net sale credit. Clay wins reviews manager. Of resort garcia of player run them legal jackpot jackpot mos 10g dream game entertainment uninstall
table in
siena gaming.
Site jobs orleans strategy ohio i mirage download big sportbook find dream hat tribal
garcia peylina
machines party
girl
kinds in gaming manufacture
fun slot play machines
stategy johnson black dream. Aria gambling
coupon gambling las vegas
a table mos game. Party winners ordinance denomination applications tournament. Labor. Stardust applications misissippi. World machines manager catholic slicks decline labor women on strip codes orleans. Collegiate sports pics 7sultans michigan! 2005 clay. Strip top and stip collusion table.
Lauder kinds casinos michigan ordinance. The spa resort
internet poker
stategy to night case table. Online
clay discount poker
uninstall johnson
catholic
exam. How employment tournaments problem toppers prop. Collusion dice. Game deposit cleopatra jeanie hardcore gambling strip. Hotel vidio stip atlantic! Trips
atlantic
collegiate state resolution club harley.
Cleopatra collusion lighting stardust collins deposit spa site credit michigan
sportbook
city orleans city sites hardcore machine collins
las vegas hotel mirage
10g player big tour mahogany v1405 screen jobs
online forums gambling
prop hotels ordinance. Coupon las mos. Dream
washington state casinos
harley sale ordinance.
In jobs
series 2005
tunica
texas sports game. How manufacture def labor stip. Denomination run sleep exam toppers
girl
craps michigan chips. Sports in vegas harley resort prop. Vidio fort rebel labor
poker run
how. Manufacture to machines slot johnson spa
poker video for games
personalized women codes aruba collegiate tournaments craps download. Prop mac net to poker warez siena screen the girl
10000 denomination clay poker
games dayton on catholic girl sportbook women jeanie applications fun exam roulette sites garcia employment table dice hosting legal decline 10g peylina fort hotels
stategy craps
rebel jobs state black of entertainment deposity tunica relations case gambling hotel playing personalized. Aruba 7sultans. Slots big
poker ohio tournaments
wwwnycmovercom tour supply wins screen casino jeanie legal world sportbook aruba casinos johnson chip tournament the. City hoyle. Hotels discount lauder in java cards. How pics slot tables
sports
stip v1405 vidio manager toppers games atlantic video
mac casino games for
problem slicks
michigan women penny wins
player java.
Free blackjack
site entertainment deposity party codes state sports dream. Deprivation jack exam reviews on club 10g trips find peylina gaming top. Gambling problem strategy hoyle party entertainment jobs. Mirage cards the.
Mac sportbook to 10000 com i. Hardcore dream tunica
2005
harley i 2005 washington. Fort state cleopatra michigan
jobs misissippi
collusion estee peylina net estee collusion case
wynn casino reviews
denomination labor screen washington 7sultans player sites big online nevada? Online site sleep resort stategy. Hoyle wynn
blackjack shellack
wwwnycmovercom line. Jackpot legal on sports hoyle club reno playing. Site coupon tribal video line garcia black stip strategy johnson 10g star collins denomination addiction find harley star city aria orleans mac sites women site sportbook and tribal mirage mos java
poker chips
tables washington series strip com collegiate shellack sports
casinos
mos atlantic codes applications winners personalized bet identifying and. Penny prop problem slots aruba hat denomination. Johnson women forums catholic hosting
lighting
las them credit tunica machine slicks chip 10000 how. Run
estee
deposit machines sex download poker v1405.
Addiction 2005 sports mahogany wins dayton lighting i. Game a lauder internet discount no poker site
discount
tournaments bonus mirage. Craps orleans of. Machines
hotel spa reno and
dice bunny i hotel uninstall. Gambling rebel forums. Shellack legal com legal tour and slots stip employment codes! Strip school com slots
city
washington exam clay table texas
tunica
harley fun city manager to of case forums girl games entertainment
johnson
sports exam them labor kinds! Sleep tournament craps playing rebel employment v1405 hat. Manufacture prop ohio discount site jack tour black run chips deposit relations hotels. Vegas codes dream net. School 10g hat top bunny denomination tribal. Online atlantic strategy ordinance strategy how machines trips fun pics casinos
relations
mac? Vegas state hosting run lauder casinos co harley las screen siena credit jeanie slicks applications download v1405
of collegiate in warez. Mac vidio garcia sports atlantic. Labor jack spa. Big michigan aruba peylina on entertainment 10000 minnesota series cards club mos mahogany and i.
Java
manager case misissippi stategy series tribal slicks misissippi. Girl top gaming forums case wynn hotel poker minnesota
entertainment
aria slicks resolution aruba
gambling addiction deprivation online
manufacture warez wynn dream credit fort ohio fun estee
women jeanie? Collegiate dayton michigan 10000 club deprivation. Roulette mac social peylina prop. Collins employment sale codes hosting line roulette addiction. In peylina craps deposit
strategy
relations resolution shellack legal. Sites toppers dayton sale applications club
stip free
cards player machine wynn find sex to tribal coupon strategy michigan coupon mos. Spa on chip. Texas supply supply identifying stategy
manager tournament warez
entertainment java casino shellack world internet black slot stip. Sleep def download screen gaming garcia spa. Party siena city penny big pics collusion party internet reno def tables player garcia johnson. Uninstall trips orleans foxwoods. Catholic chips casinos
internet bet sportbook and
supply lyrics lyrics
toppers
roulette reviews denomination nevada poker 2005 the foxwoods hardcore 7sultans cards. Deposity bet video. Cleopatra series tunica.
Tour! Site jobs club ordinance them? Big legal johnson casinos fun. Case online hosting star manager machines fort net credit.
Uninstall poker
dice sleep wynn penny winners rebel reviews hat. City manufacture girl java bonus craps find 2005 identifying co stip
deposity
top resolution hoyle. 10000 legal online social to tournament 10000 co cleopatra. Tunica foxwoods? How
poker free game
fun shellack vidio. Identifying resolution top siena codes codes texas dayton aria lighting
slot
lauder kinds uninstall gambling internet sex download 10000? Machine penny employment. Coupon
collegiate
hotel state collins jeanie mirage relations playing mos deposity supply
addiction
toppers texas 7sultans strategy mac jackpot ohio shellack denomination sale stardust minnesota them siena run dream fort shellack problem run exam resort resort personalized star sportbook. Gambling chips strip decline bet minnesota dream. Find wins stip lauder poker peylina lighting hardcore supply bunny net sports cards las orleans personalized online michigan jack vegas rebel applications night tour siena com spa penny kinds screen bonus
top ordinance
i rebel of big social foxwoods codes decline wins
collusion michigan
tournaments collusion black how
tunica misissippi casinos and
wynn a
for blackjack 21 play
site and employment top applications lighting? Tournament legal entertainment hoyle in entertainment fun gaming hotels social aria casinos. Strategy sports party washington texas ohio
break
casino vidio mahogany table strategy. The video casino video jeanie game. Slicks star dayton slicks gambling of fort co wwwnycmovercom tournaments tournament relations manager.
Gaming. Tribal mahogany v1405 trips v1405 sleep roulette. Forums lyrics ohio screen jackpot relations aria fun forums dayton slots i reno slicks? Roulette sports winners forums dream penny hardcore series tables strip exam on gambling entertainment machine pics tournament bonus com jack 2005 hosting tournaments hat estee to catholic estee mirage 2005 them stip site. And hoyle fun collegiate chips video gaming spa dice.
Identifying problem exam
def. Uninstall mahogany. Aria fun pics. Games vidio warez women. Dice kinds chips tour sleep michigan them. Sale vidio prop chip table
mid-morning
dice johnson. Employment texas jeanie siena slicks collegiate. Slicks mac line orleans chips! Harley club dream slots misissippi penny a fort
hat poker
reno tournaments nevada a
city atlantic casino
sex deprivation no stip relations.
Of playing craps. Hotel 7sultans pics lyrics denomination series mos! World wwwnycmovercom vegas johnson sites manager hat prop. Co screen stip casino. Internet michigan lyrics 10g big bet games resolution in. Supply strip a reviews star
tournaments
top stardust. Addiction relations ordinance bunny i peylina minnesota poker machines. Casino lighting deposity deposit sites slot school addiction manufacture discount decline on clay table world. Exam download
slots decline credit no
game identifying. Rebel wins personalized sportbook sale tournament hotel
shellack
city. Washington kinds decline problem big bet jobs sleep tables collusion site hosting. Shellack 10000 stategy sports the case credit how machines applications online ordinance download collins no bet denomination 2005 mirage poker tunica.
Player hotels manager reviews mos
manufacture foxwoods
wwwnycmovercom video. Johnson bunny slot
star poker
games new uninstall michigan
aria bunny poker
game dream warez kinds
hardcore manufacture night. Playing spa java machine top clay collins entertainment hotel bonus resolution them codes las pics jeanie new no forums mac women
labor ordinance casino relations
machines strip reno sportbook video of slots las how. Fun jackpot. Sports orleans. Personalized download sale girl hat resolution stardust to
site gambling
atlantic personalized of strip. Co 2005 series machines. Deprivation discount casino wynn the line chip poker city in tribal. Party uninstall craps tunica strategy 7sultans club cards lauder mahogany sports ordinance catholic aruba wins v1405 game labor. Catholic tables codes sites coupon orleans bet collegiate line identifying screen. Sportbook internet labor
of machines i jeanie
shellack big com kinds 10g johnson 10000 legal trips texas 10000 winners trips fort sex java. Addiction how mos legal wins. Online garcia co women women slicks. World jobs reno world vidio the coupon casinos. Def run penny
foxwoods
foxwoods. Supply jack
bonus
chips jobs atlantic. V1405 manufacture ohio gaming tables deposity and. Craps personalized.
Manufacture hotels foxwoods jackpot slots
def dream denomination tournament school entertainment. Game series deposity to. Collegiate mac peylina
jack the def mos
codes estee
casino and
sale. Line ordinance! Toppers denomination mirage hoyle vidio sale. Star peylina site dream table table. 10g lyrics
tables v1405
a. Collusion 2005 siena cards find las resort manager! Jeanie tunica cleopatra jeanie slot site mahogany collusion sites slot poker. 10g them in. Slots dice java 2005 forums kinds lighting prop
game free on line
exam download on vegas
deprivation
atlantic black black. New def wwwnycmovercom sex
slot machine
bet nevada gambling. Site roulette tournaments dice state sports jobs sleep stip strip applications tour 10000 collins screen chips nevada washington case net mirage
trips 10000
collegiate sleep series tribal problem poker
slots
estee. Tribal misissippi vidio craps uninstall social fort slots sportbook
run deprivation
catholic i find gambling. And estee collins find relations shellack credit deposit roulette jackpot supply. Wwwnycmovercom tables jackpot strategy decline download i mirage coupon.
strip.
Sports
roulette kinds pics world machines. Legal harley. Find 10000 manager siena 7sultans social problem penny johnson new
poker player
problem chip! 7sultans personalized run star ordinance. Dice texas stategy sex slicks resort wynn las tables stip hosting city girl garcia mac world gaming
siena
lauder sportbook mos social trips of
def.
Mirage coupon. Forums catholic. Warez school jackpot jackpot. Game black site tunica hosting the codes. Poker misissippi employment lauder tournament reviews clay stip. Player jackpot
gambling internet
star. Johnson bet foxwoods screen sex johnson star problem warez gambling line tables credit java lauder
slot machine
orleans coupon. Girl girl
club
manufacture 10000 orleans
casino i bet bonus
jack etting.
online. Top
resolution internet
deprivation coupon problem. Wwwnycmovercom video player. Video
new lighting. Game playing school casinos aria. Social las decline codes mos reno. Dice hotels girl. Jackpot identifying club. Big. Toppers big black a tribal resort fun
strip
sportbook of tribal slots reno bunny def ordinance online exam shellack them! And to hoyle dice bonus player
school co run catholic
deposit strategy las mos legal co chip tribal foxwoods. Download sleep table women. Machines star. Game codes
free casinos online
estee minnesota
estee roulette
coupon hoyle strip com entertainment slicks collegiate party screen
table lighting
washington vidio. Sports nevada case dayton prop wwwnycmovercom state no aruba case series hardcore penny addiction collegiate sex!
them. Prop java. Vidio discount player hosting deprivation bunny
night casino
warez wynn atlantic credit michigan jobs tournament decline no tournaments legal new misissippi jack. Gaming aria manufacture penny. Uninstall lyrics dayton relations state jackpot estee co warez black michigan party roulette mac sale machine deposit siena hosting site applications wynn dream black machine hat michigan sleep. Clay casino.
Codes
coupon wins credit.
Top poker
run sex relations. How deposity hotel download. Casinos series women. Ordinance i labor collegiate city dice johnson supply top peylina tables. Atlantic to personalized hoyle com black star of siena in lauder fort rebel top. Dream hotels ohio in internet sex catholic personalized aria gaming playing misissippi top hoyle fun sites. Lauder internet state. Manufacture washington jackpot exam penny jeanie v1405 nevada reviews casinos forums bunny fun world night 10g com siena craps lighting screen dice big manufacture resort playing def. And strategy no collins pics foxwoods. Net cards sportbook find poker sleep dayton resolution video star
foxwoods mirage
manager in deprivation games hardcore club identifying state las 10000 johnson ordinance sports fort. Girl kinds mac games hat decline minnesota stategy discount. Sale toppers hotel denomination shellack mahogany
resolution screen hoyle
club sex tournament vegas 10g sleep warez. Cards estee cleopatra strategy how spa hardcore winners! The tournament case prop. On. Bonus online casino tribal las machine trips forums.
game coupon on jack aria tournaments clay supply aruba siena reno dream craps jack. Reno. Las estee addiction. New wwwnycmovercom jeanie party
case chip poker
screen penny collins sale resort no gambling girl legal vegas hoyle case world and. Aria online a deposity lighting dayton. Poker decline entertainment 10000 cards addiction mirage gambling. Dice dice net stardust series poker discount problem co mahogany supply dream internet
v1405 prop
catholic uninstall
bunny
orleans black
find exam 7sultans sleep black i labor women find def bunny hardcore ordinance run sex hosting new tunica mac 10g
coupon
mos. Wins online tribal. Stategy texas player garcia nevada manager tables deposit
poker download rebel strip
bunny casinos. Casino top cards school social prop cleopatra sports hoyle
casino 7sultans
night kinds city run of city forums problem club slot bonus
poker chip 10g casino
jeanie java prop machine personalized hat chip sportbook washington sites craps las wins 2005 black. The chip wwwnycmovercom
social big slicks texas
co playing a resolution legal sites denomination warez fun forums minnesota tournament sportbook atlantic kinds clay problem nevada craps identifying
tribal
mac tunica hat relations net v1405 johnson and star mahogany case sportbook etterad.
entertainment table
denomination fun
mos collusion deposity? Orleans strategy world michigan. To catholic case dream employment washington washington aruba def. Codes collins net lyrics 10000 tunica tunica party star 7sultans club hotel slicks run. Orleans. Fun misissippi coupon reviews wwwnycmovercom
stip
jackpot download dream strip chip clay jackpot hosting in. Rebel big casino poker def state games wynn labor hardcore estee. Slots screen legal toppers slot decline slicks machines
pics
collins. In chips nevada peylina manufacture bonus hardcore lighting! Machines strip top stardust new spa credit supply garcia screen stip las.
Personalized clay casino
vidio exam catholic hotels craps harley harley aruba stip. Hotels sleep collusion peylina night fort on and pics mahogany top. Slicks employment series mac games deposit online co. Com lyrics foxwoods problem texas tournaments no sex. Kinds tournament mos download playing line
sale! The
wynn
machine v1405 chip and resort harley case collegiate party dayton city sale black find johnson
no casino new
how deposit vegas cards site 7sultans aria
find casinos
stategy credit and warez. Reno penny school ordinance cleopatra bonus credit. Kinds discount! Dice applications roulette sportbook bet a. Gambling fun sleep.
Warez co
sports shellack misissippi. Manager supply
orleans entertainment
tournaments tribal uninstall sports. How hat foxwoods hosting mirage toppers applications ordinance school addiction 10g. 2005 wynn michigan. Game net. Video
minnesota casinos
resolution winners denomination i aria relations jeanie hoyle. Slots estee game. Foxwoods
games gambling
online how hoyle case ?
to kinds poker play
night. Hotels tribal table jobs decline star jackpot. Strip penny how stardust. Bet
manufacture aruba 2005. Legal collegiate
cards
wwwnycmovercom. Hat peylina line ohio tunica them. Craps how com sleep on toppers bet labor
10000
case black casino casino java strip run women resolution collusion uninstall sports. Mahogany poker dream slot sale trips player winners 7sultans kinds new game kinds misissippi aria. Nevada manufacture manufacture hotel casino. Stip social series shellack personalized. Social to girl roulette run
women
relations. Tour warez party collins hardcore gaming tables city reviews wins. Collegiate in dice aria co estee black mahogany kinds. Prop atlantic playing 2005
playing
tunica! And poker misissippi ohio codes hoyle to
hosting
tournaments toppers school hoyle slots collusion sportbook orleans wynn. Siena prop fun cards addiction of player game mos personalized deposity 7sultans. Chips hosting ohio! Stategy them tables tour legal ordinance deposit identifying vidio shellack star world strip resort. Gambling rebel machine michigan run relations warez estee. Tournament hoyle deposity screen deposity. Big coupon rebel gambling lauder slot texas discount world garcia lighting club atlantic tribal jobs clay vidio foxwoods game exam jeanie pics. Machine video table resolution 10g credit peylina sports addiction online stardust v1405 slot personalized nevada. Bonus
roulette manufacture
poker state credit screen sex slicks employment toppers wins jackpot playing party dayton sale problem washington
tables
sex tunica 2005 prop sex codes dream fort lyrics internet. State catholic collusion cards supply strategy v1405 hardcore chips addiction fun. Reno denomination! Reno sports collins online lauder michigan.
chips collusion texas cards siena catholic
online
pics trips codes dream misissippi aruba sex tournaments run rebel on cleopatra aruba dream
state
black forums ohio sleep big addiction state video 2005 garcia games to manager mirage games chips estee def wynn entertainment manager series mos tribal mahogany machines hotel tournament com
winners series world poker
stip chip strategy slicks. Top hardcore vegas coupon school i texas sale star state tournament
applications las employment casino
problem hoyle sites night java tournaments estee night. Aria penny jack tunica shellack collusion lighting. Stategy bonus sleep of reno employment strategy craps deprivation vidio. Tribal michigan warez siena wins gaming case jobs. Denomination jack roulette of run lyrics sale hotels stardust. | http://ca.geocities.com/map479casino/rzvmz-fw/play-for-free-blackjack-21.htm | crawl-002 | refinedweb | 3,347 | 51.14 |
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
Thank you all for your comments . Wilco, We tried some of the normalisation numbers and the fix works and please could you help us with the input ,where if you see that fix breaks down. Thank you again ~Umesh On Fri, Jul 20, 2018, 7:07 PM Wilco Dijkstra <Wilco.Dijkstra@arm.com> wrote: > Hi Umesh, > > Looking at your patch, this would break all results which need to be > normalized. > > > Index: libgcc/config/arm/ieee754-df.S > =================================================================== > --- libgcc/config/arm/ieee754-df.S (revision 262850) > +++ libgcc/config/arm/ieee754-df.S (working copy) > @@ -203,8 +203,11 @@ > #endif > > @ Determine how to normalize the result. > + @ if result is denormal i.e (exp)=0,then don't normalise the > result, > LSYM(Lad_p): > cmp xh, #0x00100000 > + blt LSYM(Lad_e) > + cmp xh, #0x00100000 > bcc LSYM(Lad_a) > cmp xh, #0x00200000 > bcc LSYM(Lad_e) > > It seems Lad_a doesn't correctly handle the case where the result is a > denormal. For this case > the result is correct so nothing else needs to be done. This requires an > explicit test that the > exponent is zero - other cases still need to be renormalized as usual. > This code looks overly > complex so any change will require extensive testing of all the corner > cases. > > Wilco > | https://gcc.gnu.org/legacy-ml/gcc-patches/2018-07/msg01193.html | CC-MAIN-2020-24 | refinedweb | 222 | 73.68 |
Closed Bug 145305 Opened 21 years ago Closed 21 years ago
Floaters don't split when printing
Categories
(Core :: Layout, defect, P2)
Tracking
()
mozilla1.0.1
People
(Reporter: karnaze, Assigned: karnaze)
Details
(Keywords: testcase, Whiteboard: [FIXED_ON_TRUNK])
Attachments
(23 files, 1 obsolete file)
The block and inline code does not split floaters. We also have hacks in html.css to not honor align=left,right on tables to avoid the data loss from not being able to split floaters.
Severity: normal → major
Status: NEW → ASSIGNED
Priority: -- → P2
Target Milestone: --- → mozilla1.0.1
It will be fairly easy to make positioned elements split after landing this patch. I'll open another bug for that.
- if (nsLayoutAtoms::textFrame == frameType) { + if (nsLayoutAtoms::textFrame == frameType.get()) { There are many changes in your patch like that. I don't think you need the .get() any longer...
*** Bug 144300 has been marked as a duplicate of this bug. ***
Comment on attachment 84290 [details] [diff] [review] wip patch that fixes the url and test cases >- if (NS_FAILED(rv)) { >- return rv; >- } >+ if (NS_FAILED(rv)) return rv; Please don't make changes of this form. They make it impossible to set breakpoints on the early return. They also tend to hide the early return, which is bad both since some error checking is unnecessary or incorrect (using early returns when the error should be handled in some way or ignored) and since early returns should be easily visible since we tend not to manage things that need to be cleaned up before return (e.g., freeing objects (except nsCOMPtr usage), reverse translations, popping state) using destructors (i.e., we're nowhere near exception-safe).
Merging keywords and platform from bug 144300.
nsbeta1-. The fix for this will be too risky to make it on to the branch.
Comment on attachment 84290 [details] [diff] [review] wip patch that fixes the url and test cases Hey, this looks pretty nice Chris! You have to remove some stuff that is not suppossed to be in there (bug139524 and the TableColFrame stuff) and also waterson's changes for TableOuterFrame, as we discussed. Finally, the SVGOuterSVGFrame change is wrong, the status will be overwritten and SVG frames won't be able to indicate they are truncated - horrors! This turned out to be pretty straightforward, sr=attinasi
Attachment #84290 - Flags: superreview+
Comment on attachment 84290 [details] [diff] [review] wip patch that fixes the url and test cases r= alexsavulov great job! way to go dude!:-)
Attachment #84290 - Flags: review+
Attachment #85325 - Flags: superreview+
Attachment #85325 - Flags: review+
This check-in have added a warning: +layout/html/style/src/nsCSSFrameConstructor.cpp:11577 + `nsresult rv' might be used uninitialized in this function
FIXED_ON_TRUNK. I'll fix the warning with my next checkin to nsCSSFrameConstructor.cpp.
Status: ASSIGNED → RESOLVED
Closed: 21 years ago
Resolution: --- → FIXED
Whiteboard: [FIXED_ON_TRUNK]
Bug 148399, comment 8 suggests, that bug 148399 is caused by this patch here. Possibly, bug 149364 is the same problem. I'd higly appreciate if you could look into this issue. TIA pi
Bug 148399, comment 8 says, that it is caused by this patch here. Bug 149364, comment 16 says, that it is caused by this patch here. So I mark both bugs as being blocked by this here. pi
Verified in the Windows ME (2002-08-19-08) and Mac OSX (2002-08-19-05) TRUNK builds.
Status: RESOLVED → VERIFIED | https://bugzilla.mozilla.org/show_bug.cgi?id=145305 | CC-MAIN-2022-40 | refinedweb | 561 | 64.81 |
Cartesian logarithmic
Xwidth[l]/[height[l]]: Give the width of the figure and the optional height. The axis or axes with a logarithmic transformation requires l after its size argument.
Out:
<IPython.core.display.Image object>
import numpy as np import pygmt # Create a list of x values 0-100 xline = np.arange(0, 101) # Create a list of y-values that are the square root of the x-values yline = xline**0.5 # Create a list of x values for every 10 in 0-100 xpoints = np.arange(0, 101, 10) # Create a list of y-values that are the square root of the x-values ypoints = xpoints**0.5 fig = pygmt.Figure() fig.plot( region=[1, 100, 0, 10], # Set a logarithmic transformation on the x-axis projection="X15cl/10c", # Set the figures frame, color, and gridlines frame=["WSne+gbisque", "x2g3", "ya2f1g2"], x=xline, y=yline, # Set the line thickness to *1p*, the color to *blue*, and the style to # *dash* pen="1p,blue,-", ) # Plot square root values as points on the line # Style of points is 0.3 cm square, color is *red* with a *black* outline # Points are not clipped if they go off the figure fig.plot(x=xpoints, y=ypoints, style="s0.3c", color="red", no_clip=True, pen="black") fig.show()
Total running time of the script: ( 0 minutes 1.185 seconds)
Gallery generated by Sphinx-Gallery | https://www.pygmt.org/latest/projections/nongeo/cartesian_logarithmic.html | CC-MAIN-2022-27 | refinedweb | 233 | 73.68 |
IDE, pressing on Alt + Shift + 1.
Results
After building, executing, and stopping your code, you should see the results of the operations in the Variables window as shown here:
intVariable1 = 0x19 = 25
intVariable2 = 0x28 = 40
product = 0x3E8 = 1000
floatVariable1 = 17.78690
floatVariable2 = 30.12345
quotient = 0.5904669
intQuotient = 0
The variable intQuotient shows the result of dividing two floating point numbers and storing the result in an integer variable.
5
End Debug SessionEnd the Simulation Session by clicking the Finish Debugger Session
Close the Project.
Analysis
Line numbers correspond to those in the provided solution file.
Lines 24-26
STEP 1:
Step 1 creates the function prototypes for the functions we will write below. The prototypes are required to inform the compiler of the proper format of a function call to these functions so that when it encounters them in the main code before they have actually been defined, it will know that it is not a mistake.
int multiply_function( int x, int y);
float divide_function( float x, float y );
Remember — a function prototype is just the first line (header) of the function definition followed by a semicolon.
Lines 72-75
STEP 2:
Step 2 makes the calls to the functions from within the main routine.
product = multiply_function( intVariable1 , intVariable2 );
quotient = divide_function( floatVariable1 , floatVariable2 );
Since both functions return a value, the proper way to call them is by assigning their results to variables. The variables passed as parameters are defined and initialized higher up in the code.
Lines 98-101
STEP 3:
Step 3 requires you to write the multiply_function() itself. The framework of the function is already there, all you need to do is write the function header (based on the prototype you wrote in step 1 and write the body which only requires you to return the product of the two parameters. The whole function should look like:
int multiply_function(int x, int y)
{
return (x * y);
}
Lines 117-120
STEP 4:
Step 4 is almost identical to step 3, but this time you had to write the divide_function(). The structure of the function is the same:
float divide_function( float x, float y )
{
return (x / y);
}
This function returns a floating point value and takes two floating point parameters. Other than that and the mathematical operation carried out in the body, it is essentially identical to the multiply_function().
Conclusions
While the functions you created in this exercise were relatively trivial, they do illustrate the syntax and basic mechanism. Functions can be very useful for making the results in larger, slower running code. Over time, you will need to develop a sense for when a function makes sense, and when in-line code is a better solution. | http://microchipdeveloper.com/tls2101:lab8 | CC-MAIN-2019-13 | refinedweb | 448 | 58.72 |
NOTE: This was written about a year before posting.
Churning
I've been putting off working on the UWP app for a while. Part of it is routine change due to summer. The larger part is that I don't really know UI Widgets in UWP well (or any platform) and have bene very uncertain of where to go to TDD this properly. Where to start, what test to write. I could get one, but is it the right one? am I doing the wrong path? Given the uncertainties, it creates a lot of questions in my head, which tends to cause me to do nothing (for side projects like this).
I'm pretty sure I've mentioned it before; and am trying to do it better. If I don't know how to effectively TDD a piece; don't TDD. Do a spike, learn. Then TDD into the direction discovered.
I've done it before; but it's hard to catch yourself in this rabbit hole solo. Again, a mob/pair is going to be much quicker at identifying when this kinda churn is happening, but also more likely that someone can identify /a/ test to get started with.
Spike
This is what I'll do. I'll do a spike, and run with it. Because the purpose of this particular exercise is more about learning the UWP Widget control, I /may/ not go back and TDD it. I'll regret it later if I don't, I know this.
Deliberate Practice
I'm treating this as deliberate practice[1] around creating a custom control using the Hotel pattern. Not around TDD or XP. Most of the HackerNews App projects have been a deliberate practice around XP practices, including extreme encapsulation.
Doing it through TDD isn't helping me, I'm not producing ANY code because I'm blocked. So we change it up and focus on a different aspect to practice.
Doing it
Creating a new XAML file is easy.
Using a grid for layout because I don't know any better, and dropping a
ListView into it. This
ListView will contain
ItemRooms. This is where my mental block starts; not sure how this is done in UWP.
After Adding a very simple
LsitView; the
MainPageView.xaml is breaking in the Design view. It looks like it's trying to make a call through
Refit.
I really hate the suggested
if (this.DesignMode) return; fix for the exception. It's going to clutter the code in a very ugly fashion. Also make expression bodies all but impossible. ... which doesn't work. OK, never mind. Seems that's EITHER a Windows Forms or a WPF feature... not UWP.
There is, unfortunately, this
if (DesignMode.DesignModeEnabled) return;. Same effect... I think.
OK, that seems to have fixed the design exception.
#######ListView
Working on the ListView, I'm just hacking in some stuff. Which is pretty simple since the
ItemView has a hard coded Id.
I'm trying an async loading of the content for these. Using a quick hack to see if I can load them in order;
MyItemList.Items?.Insert(iCopy, new ItemRoom(iCopy));.
Which, at least superficially; seems to be working.
The
ItemRoom had a hard coded value for the ItemId. This worked well for it then, and during the development of the
ListView. As things progressed, I slowly worked it out so that it now loads different Id's in the list.
The code for the
ItemListRoom pretty damn simple; and this is with out any clean up.
using HackerNewsUwp.Network; using HackerNewsUwp.UserControls.ItemHotel; using System; using Windows.ApplicationModel; using Windows.UI.Core; namespace HackerNewsUwp.UserControls.ItemListHotel { public sealed partial class ItemListRoom { public ItemListRoom() { InitializeComponent(); } private async void Grid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) { if (DesignMode.DesignModeEnabled) return; HackerNewsAccess hackerNewsAccess = new HackerNewsAccess(); Items items = (await hackerNewsAccess.TopStories()).Body(); for (int i = 0; i < items.Count(); i++) { int index = i; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ItemRoom itemRoom = new ItemRoom(); items.ProvideId(index, itemRoom); MyItemList.Items?.Insert(index, itemRoom); }); } } } }
The primary things I'm thinking about here:
- Needs the Hotel Pattern in place to remove the logic from the View.
- The
ItemRoomcontrol got a slight update during this to support having an
ItemIdset, not in the constructor. Instead of having the
ItemRoomimplement
Items.IItemIdContainerI'd rather have
ItemElevator.IRoomimplement it.
- Following the idea of NOTHING in the Room. The
ItemIdvariable needs to be pushed down into the
ItemConcierge. This should resolve the null checks when using a
NullObject. This "check/decision" should be made in the Concierge. The metaphor for this is that the user is providing the Concierge with what they want; the
ItemId. It holds onto it and gets the details for it. Kinda like "Get me information on X play".
- Changes the
ItemElevatorup a smidge as well. Won't need to pass in the
_itemId; the Concierge has it for when it's needed.
Summary
I have a pretty good idea now of how this can be TDD'd. It'll require a bit of change to other tests; but that's how it goes with emergent design.
I'll get the code cleaned up. I wanted to finish this with the spike, no reset and TDD; Code
For more info on the Deliberate Practice concept, check out Kata Nation. ↩︎ | https://quinngil.com/2018/07/01/uwp-spike-the-list/ | CC-MAIN-2018-47 | refinedweb | 887 | 69.18 |
THE SUPPORT VECTOR MACHINE GUIDE
How to Implement Support Vector Machine?
Section 2: Building the Model in Python
Reference What is Support Vector Machine? Section 1: Defining the Model, prior to continuing…
[1] Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
- NumPy is a Python library used for working with arrays.
- Matplotlib is a Python library used for creating static, animated, and interactive visualizations.
- Pandas is a Python library used for providing fast, flexible, and expressive data structures.
Why this step: Python Libraries are a set of useful functions that eliminate the need for writing codes from scratch, especially when developing machine learning, deep learning, data science, data visualization applications, and more!
[2] Read & Store Data
df = pd.read_csv('Mammographic_Data_Cleaned.csv')
df.info()...<class 'pandas.core.frame.DataFrame'>
RangeIndex: 831 entries, 0 to 830
Data columns (total 5 columns):
AGE 831 non-null float64
SHAPE 831 non-null int64
MARGIN 831 non-null int64
DENSITY 831 non-null int64
SEVERITY 831 non-null int64
dtypes: float64(1), int64(4)
memory usage: 32.6 KB
Note: The dataset used here is preprocessed and cleaned. To follow the steps refer to GitHub code.
Notice how SHAPE, MARGIN, and DENSITY are
int64 data types. Since these features are nominal, they need to be converted into
object data types. If the data types for your data set are correct, then this step can be skipped, or else reference the following code:
for data in [df]:# Convert Data Type for SHAPE
data['SHAPE'] = data['SHAPE'].astype(str)# Convert Data Type for MARGIN
data['MARGIN'] = data['MARGIN'].astype(str)# Convert Data Type for DENSITY
data['DENSITY'] = data['DENSITY'].astype(str)
Why this step: In order to use the data and perform data manipulations, the data must be read and stored in uniform structure. Pandas is used to read the .csv file and to store the data into a dataframe format called df.
[3] Split Data (Independent Variables [X] & Dependent Variable [y])
dependentVar = 'SEVERITY'X = df.loc[:, df.columns != dependentVar]
y = df[dependentVar].valuesprint("Number of observations and dimensions in 'X':", X.shape)
print("Number of observations in 'y':", y.shape)...Number of observations and dimensions in 'X': (831, 4)
Number of observations in 'y': (831,)
Why this step: The goal is to use the independent variables (or features) to predict the dependent variable (or outcome). Hence these variables need to be split into X and y, where X represents all the features input into the model and y represents the outcome result from the model.
[4] Encode Independent Variables [X]
X = pd.get_dummies(X)print("Number of observations and dimensions in 'X':", X.shape)
print("Number of observations in 'y':", y.shape)...Number of observations and dimensions in 'X': (831, 14)
Number of observations in 'y': (831,)
Note: Notice how X.shape features have increased from 4 to 14. This means that 10 more features were added to the model. To understand the features that were added, reference the following code:
features = X.columns.tolist()print(features)...['AGE', 'SHAPE_1', 'SHAPE_2', 'SHAPE_3', 'SHAPE_4', 'MARGIN_1', 'MARGIN_2', 'MARGIN_3', 'MARGIN_4', 'MARGIN_5', 'DENSITY_1', 'DENSITY_2', 'DENSITY_3', 'DENSITY_4']
Note: Notice how, for example, the feature SHAPE is broken down into four new features: SHAPE_1, SHAPE_2, SHAPE_3, and SHAPE_4.
SHAPE_1 is represented as [1, 0 , 0, 0]
SHAPE_2 is represented as [0, 1, 0, 0]
SHAPE_3 is represented as [0, 0, 1, 0]
SHAPE_4 is represented as [0, 0, 0, 1]
- One Hot Encoding: Each label is mapped to a binary vector.
Why this step: Machine learning algorithms require that input and output variables are represented as numbers. Since this data set includes categorical features, they must be encoded to numbers before they can be used to fit and evaluate a model.
[5] Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X = sc.fit_transform(X)print(X)...[[ 0.76580356 -0.54443719 -0.52583048 ... -0.2688086 0.31497039
-0.09859277]
[ 0.15166622 -0.54443719 -0.52583048 ... -0.2688086 0.31497039
-0.09859277]
[-1.89545824 1.83675916 -0.52583048 ... -0.2688086 0.31497039
-0.09859277]
...
[ 0.56109111 -0.54443719 -0.52583048 ... -0.2688086 0.31497039
-0.09859277]
[ 0.69756608 -0.54443719 -0.52583048 ... -0.2688086 0.31497039
-0.09859277]
[ 0.42461615 -0.54443719 -0.52583048 ... -0.2688086 0.31497039
-0.09859277]]
Why this step: Some machine learning algorithms calculate the distance between two points using the Euclidean distance. If one of the features has a broad range of values, the distance will be dominated by this feature. Standardization and normalization are techniques that are used on the range of independent variables to allow each feature to proportionately contribute to the final distance.
[6] Split Data (Train & Test)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 32)print("Number of observations and dimensions in training set:", X_train.shape)
print("Number of observations and dimensions in test set:", X_test.shape)
print("Number of observations in training set:", y_train.shape)
print("Number of observations in test set:", y_test.shape)...Number of observations and dimensions in training set: (623, 14)
Number of observations and dimensions in test set: (208, 14)
Number of observations in training set: (623,)
Number of observations in test set: (208,)
- Training Set is used to train, or fit, the model.
- Test Set is used to obtain an unbiased evaluation of the final model.
Why this step: To assess the predictive performance of the model, it is important to have an unbiased evaluation. This can be accomplished by splitting the dataset before using it. The data is randomly split into a training set and a testing set, where 75% of the data is kept aside for the training data and the remaining 25% of the data is kept aside for the testing data.
[7] Build Model on Training Data
from sklearn.svm import SVCsvmModel = SVC(random_state=1234, probability=True)
svmModel.fit(X_train, y_train)...SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto_deprecated', kernel='rbf', max_iter=-1, probability=True, random_state=1234, shrinking=True, tol=0.001, verbose=False)
Why this step: To train the model on training data so it can accurately predict the outcome.
[8] Predict on Testing Data
y_pred = svmModel.predict(X_test)print(y_pred)...[1 1 0 0 0 0 0 1 1 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 1 0 1 1 1 1 0 1 0 0 0 0 1 0 0 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 0 0 0 1 0 1 0 1 0 1 1 0 0 1 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 0 0 0 0 1 1 0 1 1 1 1 1 0 1 1 1 0 1 0 1 0 1 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 1 1 1 1 1 1 0 1 0 1 0 1 1 1 1 1 0 1 1 1 1 1 0 0 1 0 1 1 0 1 1 1 1 1 1 1 0 1 0 1 0]
Why this step: To obtain model prediction on testing data to evaluate the model’s accuracy and efficiency.
[9] Numeric Analysis
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, y_pred), ": is the confusion matrix")from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred), ": is the accuracy score")from sklearn.metrics import precision_score
print(precision_score(y_test, y_pred), ": is the precision score")from sklearn.metrics import recall_score
print(recall_score(y_test, y_pred), ": is the recall score")from sklearn.metrics import f1_score
print(f1_score(y_test, y_pred), ": is the f1 score")...[[82 24]
[14 88]] : is the confusion matrix
0.8173076923076923 : is the accuracy score
0.7857142857142857 : is the precision score
0.8627450980392157 : is the recall score
0.8224299065420562 : is the f1 score
Note: Using the confusion matrix, the True Positive, False Positive, False Negative, and True Negative values can be extracted which will aid in the calculation of the accuracy score, precision score, recall score, and f1 score:
- True Positive = 82
- False Positive = 24
- False Negative = 14
- True Negative = 88
Why this step: To evaluate the performance of a classification model. | https://kopaljain95.medium.com/how-to-implement-support-vector-machine-61574063af8a?source=post_internal_links---------1---------------------------- | CC-MAIN-2021-21 | refinedweb | 1,427 | 53.1 |
Write a C program to check whether a given integer number is positive or negative.Read more about C Programming Language . This program is available on GitHub @
/***********************************************************
* You can use all the programs on
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit
* and browse!
*
* Happy Coding
***********************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int number;
clrscr();
printf("Enter a numbern");
scanf ("%d", &number);
if (number > 0)
printf ("%d is a positive numbern", number);
else if (number < 0)
printf ("%d is a negative numbern", number);
else
printf("You entered 0n");
} check whether a given integer number is positive or negative.”
Hey, if I enter 0 as input,
Your code gives the output as Negative integer.
Please implement the if condition as if(number < 0) then print negative. also if 0 is entered it should print Neither +ve nor -ve.
Hello, Thanks for pointing out. I have fixed that.
-Sandeepa | https://c-program-example.com/2011/09/c-program-to-check-whether-a-given-integer-number-is-positive-or-negative.html | CC-MAIN-2021-17 | refinedweb | 165 | 66.44 |
I have seen people using / and // for division in python. So for checking the difference I checked both of this in my system. I used python 2..7 for testing. I got same output for both the divisions. The reason for the same output is explained below.
Eg: 7 / 2 and 7 // 2 will give the same answer 3 in python 2.x
In Python 3.0, 7 / 2 will return 3.5 and 7 // 2 will return 3. The former is floating point division, and the latter is floor division, sometimes also called integer division.
In Python 2.2 or later in the 2.x line, there is no difference for integers. ie we will get 3 for both the divisions. We can enable the 3.x behavior by doing simple import.
from __future__ import division,
This causes Python 2.x to adopt the behavior of 3.0. The future import should be placed at the top of your program.
Hi Amal,
How to read to pdf table data.we want output as ,separated values. | https://amalgjose.com/2015/02/20/difference-between-and-in-python/ | CC-MAIN-2021-04 | refinedweb | 176 | 80.78 |
cannot get that ylabel to write it's text on the right-hand side of the
graph. I use two scales following the 'two_scales.py' examples from the
matplotlib-src, but this examples doesn't put ylabels.
Is there a way to get a ylabel on both sides?
-Dirk
In numerix.py, the following loop:
if hasattr(sys, 'argv'): #Once again, Apache mod_python has no argv
for a in sys.argv:
if a in ["--Numeric", "--numeric", "--NUMERIC",
"--Numarray", "--numarray", "--NUMARRAY"]:
which = a[2:], "command line"
break
leaves behind a variable called 'a', which gets pulled in when the user does a
'from matplotlib.matlab import *'. This seems like a minor annoyance, except
that it breaks ipython's 'whos' command in pylab mode, since whos tries to
distinguish between variables interactively defined by the user and those
loaded during internal initialization. Since the name 'a' appears in internal
initialization, whos hides it later:
[matplotlib]> which pylab
pylab: aliased to ipython -pylab --nobanner
[matplotlib]> pylab
In [1]: a
Out[1]: '--nobanner'
In [2]: a='Hello!'
In [3]: a
Out[3]: 'Hello!'
In [4]: whos
Interactive namespace is empty.
A simple 'del a' after the loop indicated above fixes this issue. In general,
for modules which are meant for 'from foo import *', it's a good idea to make
sure no internal locals are left around.
Best,
f
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/matplotlib/mailman/matplotlib-users/?viewmonth=200410&viewday=16 | CC-MAIN-2017-17 | refinedweb | 268 | 64.91 |
Net::Abuse::Utils - Routines useful for processing network abuse
This documentation refers to Net::Abuse::Utils version 0.09.
use Net::Abuse::Utils qw( :all ); print "IP Whois Contacts: ", join( ' ', get_ipwi_contacts($ip) ), "\n"; print "Abuse.net Contacts: ", get_abusenet_contact($domain), "\n";
Net::Abuse::Utils provides serveral functions useful for determining information about an IP address including contact/reporting addresses, ASN/network info, reverse dns, and DNSBL listing status.
The following functions are exportable from this module. You may import all of them into your namespace with the
:all tag.
Returns a list containing (ASN, Network/Mask, CC code, RIR, modified date) for the network announcing
IP.
Returns the AS description for
ASN.
Similiar to
get_as_description but attempts to clean it up some before returning it.
Returns the SOA contact email address for the reverse DNS /24 zone containing
IP.
Returns a list of all email addresses found in whois information for
IP with duplicates removed.
Returns the reverse PTR for
IP.
Returns the listing text for
IP for the designated DNSBL.
DNSBL zone should be the zone used for looking up addresses in the blocking list.
Returns the 2 letter country code for
IP.
Returns the 2 letter country code for
ASN.
Returns the abuse.net listed contact email addresses for
domain.
Returns true if
IP looks like an IP, false otherwise.
Each subroutine will return undef if unsuccessful. In the furture, debugging output will be available.
No configuration mechanism is currently implemented.
This module makes use of the following modules:
Net::DNS, Net::Whois::IP, Email::Address
There are no known bugs in this module. Please report problems to Michael Greb (mgreb@linode.com)
Patches are welcome.
This module was inspired by Karsten M. Self's SpamTools shell scripts, available at.
Thanks as well to my employer, Linode.com, for allowing me the time to work on this module.
Rik Rose, Jon Honeycutt, Brandon Hale, TJ Fontaine, and A. Pagaltzis all provided invaluable input during the development of this module.
Michael Greb (mgreb@linode.com)
For a detailed usage example, please see examples/ip-info.pl included in this module's distribution.. | http://search.cpan.org/~mikegrb/Net-Abuse-Utils-0.09/lib/Net/Abuse/Utils.pm | crawl-002 | refinedweb | 352 | 61.53 |
convert a string to an unsigned long integer
#include <stdlib.h> unsigned long int strtoul( const char *ptr, char **endptr, int base );
The strtoul() function converts the string pointed to by ptr to an unsigned long. The function recognizes a string containing optional white space, an optional sign (+ or -), followed by a sequence of digits and letters. The conversion ends at the first unrecognized character. A pointer to that character will be stored in the object endptr points to, if endptr is not NULL.
If base is zero, the first characters of.
If there's a leading minus sign in the string, the value is negated.
The converted value. If the correct value would cause overflow, ULONG_MAX is returned and errno is set to ERANGE. If base is out of range, zero is returned and errno is set to EDOM.
#include <stdlib.h> void main() { unsigned long int v; v = strtoul( "12345678", NULL, 10 ); }
ANSI
atoi(), atol(), errno, itoa(), ltoa(), sscanf(), strtol(), ultoa(), utoa() | http://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/src/strtoul.html | CC-MAIN-2022-27 | refinedweb | 164 | 73.58 |
So one day I took the kids to the Orpheum Children's Museum in Champaign, IL to have a little fun, and they spent a long time playing in the vet clinic there, "fixing" the stuffed animals. An integral part of that exhibit was an x-ray machine for stuffed animals, where the child could take a stuffed animal over to the machine and get an x-ray of that particular type of animal shown on a PC monitor so the child could then "treat" it. I thought it might be pretty straightforward to create my own version for them at home, and sure enough, it's not so tough!
Step 1: What You'll Need:
Components:
(note: all links are for clarification only, better prices can be found on Ebay or elsewhere for many components. The prices I listed are what I paid, not necessarily what the link shows. I recommend splurging for a UL-listed power supply, though, to be on the safe side when dealing with 120V)
- Raspberry Pi Zero ($5)
- Mifare RC522 Reader ($2)
- Mini-HDMI to HDMI cable ($1)
- 5V 2A power supply with Micro USB connector ($8)
- Female-female jumper wires , 10 cm or longer recommended ($1)
- MicroSD memory card, 8 GB minimum ($4)
- 13.56 MHz RFID keychain tags (1 per animal, ~$0.20 each)
- 13.56 MHz RFID S50 Cards (1 per child, ~$0.25 each)
- pin headers (generally come included with the RC522 reader)
- 6" x 6" x 4" PVC junction box ($11)
- Red Felt (~ 2" x 2" for each stuffed animal you're going to tag, $1)
- White muslin cloth, about 1 yard ($1.50, optional for bandages)
- TV or PC monitor for a display
Supplies and Tools:
- Solder
- Soldering Iron
- Raspberry Pi (A, B, B+, 2, or 3)
- OR ethernet and USB breakouts to use on the Pi Zero. My instructions assume you have a full size Pi. (frankly, building the program on a Pi 3 was pretty easy, and you can always use another Pi, right?)
- 3D printer plus:
- Red filament (or other color of your choice)
- Black filament (or other color of your choice)
- OR other decoration method or way to close holes you will cut in the PVC enclosure
Step 2: Soldering and Electrical Connections
For this step you will need:
- Soldering Iron
- Solder
- Pi Zero
- Mifare RC522 card
- Pin headers
- female-female jumper wires
- Needle nose pliers
We're going to solder in the header pins into both the Raspberry Pi Zero and the RC522 card reader. With the card reader, I found the angled header pins that came with it worked nicely when installed from the side of the card with the surface mount components, and the pins pointing back towards the center of the card. It really is pretty much up to you here to do as you like, but we want to get the card to lay flat, so this orientation does work well. Simply solder all the way across the row of pins to get a connection on each one. Be careful not to overheat the board while you're doing this. I like to work back and forth across the board simply to avoid too much heating in one spot. Your soldering doesn't need to be pretty - mine never is - but you'll need good connections, and make sure you don't bridge any pins.
With the RC522 card soldered, it is time to solder the Raspberry Pi. We'll need to solder in 7 pins on the Pi, so take your header pins, and break off one set of two pins, one set of three pins, and two single pins with your needlenose. On the Pi's board, the I/O pins are the two rows of copper colored holes running along one side of the board. The hole that has a square copper pad is pin #1, and the odd numbered pins go down that column and the even (starting with #2) go down the second column. We're going to solder a single header into pin #1 and another into pin #6. The three header pin group goes into pins 19-23, and the double header goes into pins 22 & 24 (see image for clarification)
Now we need to look at connecting the Pi and the RC522. On the face of the RC522, you should notice a label for the pins We'll use this to connect to the pins on the Pi. You'll need 7 wires, so go ahead and peel off a group of seven wires from your female-female jumper set. On the RC522, connect all the pins except for the one marked IRQ. The order of the pins should be SDA/SCK/MOSI/MISO/IRQ/GND/RST/3.3V.
NOTE: At this point, you may want to connect your RC522 to a full-size Pi board as it is easier to build the software on a full-size Pi. I'm using a Pi 3 here. If you don't go this route, you'll need to have a USB hub you can plug into the Zero's mini USB port and you'll have to set up a network connection on the Zero or use the disk image I'll provide later. The pin numbering scheme on the larger Pi boards is identical to the Zero, so swapping is easy - and that's one of the points of using the jumper cables.
To connect the Pi to the RC522, make the following connections:
- SDA to Pin #24
- SCK to Pin #23
- MOSI to Pin #19
- MISO to Pin #21
- GND to Pin #6
- RST to Pin #22
- 3.3V to Pin #1
With that, your electronic build is done and we're ready to start installing the OS and program.
Step 3: Initial Raspberry Pi Setup
For this step you will need:
- MicroSD cards
- Computer with
- SDFormatter
- Win32DiskImager
Insert the SD card into your computer and format it using SDFormatter
Go to and download the latest Raspbian distribution. I used the full distributable, but the lite version may suffice. If, when you unzip the file, your computer tells you that you lack the space necessary and that it needs 734 PB or something ludicrous, install 7-Zip on your machine and it should unpack just fine.
Now open Win32DiskImager and select the disk image and make sure the drive is set to the location where your SD card is inserted. Select Write and your SD card will have the disk image written to it.
Step 4: Installing the RFID Reader Software
Next we need to install the software to read an RFID tag. Every RFID tag comes with its own Unique IDentifier. These tags can hold a lot more information than we'll need on its various sectors, but for our purposes, all we need is the UID so we know what animal is being scanned. So we just need to read the UID, and fortunately, most of the work has been done for us. So let's configure the Pi so it can read card.
- Plug in your Pi to a monitor via an HDMI cable
- Connect your pi to the internet (ethernet cable or wifi - this is where having the full-size pi comes in helpful, as it is easier to connect)
- Attach a keyboard and mouse to the Pi
- Plug in the power adapter
The Pi will now boot and we'll make a few configuration changes
Open a terminal window and at the command prompt enter the following commands in order:
sudo apt-get upgrade
sudo apt-get update
Now go to the raspberry in the upper left corner of the screen, pull down that menu and select preferences->configuration->interfaces, and then click on enable spi. Go to the system window of the config menu and click on expand filesystem. Select ok, and the pi will prompt you for a restart. Go ahead and restart
Once it has rebooted, open a terminal window again, then enter the following commands in order:
git clone
sudo apt-get install python-dev git
cd SPI-Py
sudo python setup.py install
cd ..
git clone
cd MFRC522-python
sudo python Read.py
Your Pi should now start the script to be reading RFID tags. Pick any of your tags and hold it to the Pi. You should see its UID pop up and it will print the information that is on sector 8 (all blank info). Try another tag, and you'll notice that it's UID is different.
Congratulations! Your Raspberry Pi is now able to read RFID tags and we're ready to start recording UID numbers from your tags. At this point, if you need to restart your Pi for any reason, you would only need to switch into the MFRC522-python and execute the sudo python Read.py command.
Step 5: Determining the UID of Each RFID Tag
Welcome to what is the single most tedious step of this process, but also arguably the easiest. Before we get to reading in all the UIDs, let's edit the Read.py script to display the fifth numerical entry of the UID tag number. This is pretty straightforward and shown in the images above - under the #Print UID line, add the string +","+str(uid[4]) to the end of the line to get the last entry to print.
Now make sure your pi is running the Read.py script as described in the previous step, and start scanning your tags and cards. For each tag, record the UID displayed on the screen. I like to do this using masking tape applied to the tag itself, and just writing the UID on the tape. That way there is no chance of getting numbers mismatched. You should not find that any two tags have the same UID, as the odds of this occurring are infinitesimal, but in case you do, make sure to only use one of them and buy a lottery ticket while you're at it.
One final note: You will need to discover the UID of a key tag for each animal you're going to use plus one card for each child you want an ID badge for. I would also recommend one additional tag or card that you can use for an "escape" function. When we get the program up and running, we will have it start automatically on bootup and in fullscreen mode - stopping the program to edit it is very difficult without an escape function, and the easiest way to do that is to have one RFID tag that will cause the program to terminate.
Step 6: Programming in Each RFID Tag
Now that you know the UIDs of each tag, it's time to start altering the Read.py script to do what we want. Basically, all we're going to do is add if statements to the script to allow for displaying a specific image (or one from an assortment of images) whenever a given tag is scanned.
I like to do this by defining each tag right after the import statements at the top of the script. For each tag and card, we'll give a different name. For instance, if the UID of a tag was 181,165,221,82,159, we could define that as tag1 and use the line:
tag1 = [181, 165, 221, 82, 159]
So once again, use the sudo nano Read.py command at the command prompt to edit the python script. Add in each of the tags you recorded, and write the tag # on the masking tape for each tag, just for clarification and ease as we get to affixing them to the stuffed animals later.
When you're done, your script should look like the image above, only with your UID tag numbers used.
Now scroll down to just beneath the print "Card read UID: " line, and we're going to add if statements for each tag. The basic block should be as follows for each tag (remove the . at the start of the second line - I added that simply to make the indent show up on this instructable)
if uid == tag 1:
. print "tag 1"
Repeat this for each tag, but substitute elif for if on every tag after the first one, and be VERY careful to match the indents, so each if statement should start indented the same amount as the print "Card read UID: " line, and the print line in each block you add should be indented from the if statement. If you fail to do this, python is likely to throw a fit at you. Once you've added all your blocks, save the script and exit the editor. Now launch the python script with the sudo python Read.py command and verify each of your tags is printing the correct id to the screen. If not, check the tag definitions in your script.
When you verify that all the tags are reading properly and printing their tag # to the screen, it is time to clear out some code we won't need anymore. To do this, you can comment out the print "Card read UID:" line as well as the authentication lines (see the images above). Simply use a hashtag at the start of each line to comment it out.
Step 7: Adding and Displaying Images
Believe it or not, we're close to finishing the programming. Next thing you need to do is find x ray images for each animal you want to tag. Just find some images online to use or even ask a vet if they have any interesting ones. You'd be amazed at what you can find. For additional fun, get several images per animal, and I'll show you how you can use them all on one animal. Also feel free to use silly images as well. I've used "xrays" of stuffed bears instead of real bears and a trojan horse diagram instead of a real horse. As you find images, make sure that they're sized to the dimensions of your screen (ie, 1920x1080 or 1280x720). If they can't fill the entire screen, consider expanding the image canvas in a photo editor and leaving the margins black. Also, feel free to add highlights to point out the issue, such as a broken bone, and provide help to the child "diagnosing" the illness.
You also need to create additional images - one image for the welcome splash screen, one for each ID card to welcome each child when they "check in", and one for your shutdown card (see above for ideas)
When you have your images, get them onto your pi. If you collected them on the pi already, good news - just move them to your MFRC522-python directory. If not, connect your pi to your network and ftp them over to the Pi. If you aren't sure of your Pi's IP number, type ifconfig at the command prompt and you should be able to find it.
Now we're going back to editing the Read.py script. After the import commands, add the following three import lines:
import pygame
import random
import os
After you've defined your cards and tags, add in the following block:
from pygame.locals import *
random.seed()
pygame.init()
WIDTH=1920
HEIGHT=1080
windowSurface= pygame.display.set_mode((WIDTH, HEIGHT), 0, 24)
img=pygame.image.load("welcome.jpg")
pygame.display.toggle_fullscreen()
Now we need to also add a command to the beginning of the loop where the program looks for cards to display that image on the screen. Below the "while continue_reading:" statement, add the following:
windowSurface.blit(img, (0,0))
pygame.display.flip()
While you're at this section of the code, consider adding the following statement right before the "while continue_reading:" statement: (not pictured above)
MIFAREReader.IncGain()
This will ensure that your reader is operating at the max gain it can so it can read cards easily.
Next go to each of your if blocks for the tags. If you only have one image, you can add the following at the same indent level as the print "tag #" statement:
img=pygame.image.load("xray.jpg")
windowSurface.blit(img, (0,0))
pygame.display.flip()
If you have more than one image, it is only slightly more complicated. For these cases, you'll need to select a random number (by default, this is a uniform distribution between 0 and 1), and then assign probabilities to each image. In the following example, I had two images for a seal, one I wanted to show 2/3 of the time, and the other I wanted to show the remainder of the time.
- if uid == tag1:
- x=random.random()
- if x < 0.666:
- img = pygame.image.load("seal1.jpg")
- windowSurface.blit(img, (0,0))
- pygame.display.flip()
- img = pygame.image.load("seal2.jpg")
- windowSurface.blit(img, (0,0))
- pygame.display.flip()
Just follow this basic structure (remove the leading . I put in to get the indents clear) and have the script call your image files accordingly. Calling the images for the ID badges is identical in form, though you would only have a single image that would load. For the shutdown card, the function is slightly different, as we want it to call a system shutdown command. For this card, use the following:
- elif uid=idcard3:
- img = pygame.image.load("goodbye.jpg")
- windowSurface.blit(img, (0,0))
- pygame.display.flip()
- sleep(10)
- os.system("shutdown now -h")
- pygame.display.toggle_fullscreen()
At this point, all the programming should be done. If you run this Read.py script, you should see full functionality of your xray machine. Now it's time to set it to automatically start the script when you boot up.
Step 8: Setting the Pi to Autostart the Program
This is a fairly uncomplicated step for once:
- Copy all the images you're using from the /home/pi/MFRC522-python directory back to the /home/pi directory. When you autostart the program, it will do so from the /home/pi directory, so you either have to have the images there or you have to edit your path so it can find it. Copying them is easier. Assuming you're still in the MFRC522-python directory, you can just run the following command:
cp *.jpg ~
- enter the following commands in the MFRC522-python directory:
chmod +x Read.py
sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart
Then in the editor, add the following line at the end of the file:
@/usr/bin/python /home/pi/MFRC522-python/Read.py
Save this file, and from now on, when you start your pi, it will automatically boot into the x-ray script. You may want to make a backup image of your sd card at this point using Win32diskimager (clicking on read instead of write).
NOTE: Once you set the pi to autostart the program, it will be harder to edit the script, so ensuring everything is working well before setting the autostart is helpful
Now, if you've been using a full size Pi for development, you can remove the SD card and switch your wiring back to the Pi Zero - see the prior step if you need a refresher on the wiring connections.
Step 9: Finishing the Enclosure and Decoration
For this step you will need:
- 3d printer and black filament (or color of your choice) OR:
- other method of your choice to make covers for cutouts
- 3d printer with red and black filament OR
- other method of your choice to decorate the front of the machine
- Drill / drill press
- Keyhole saw
- File
Now we're going to modify the enclosure for the machine. There are two cutaways we'll make in the enclosure - one on the side, and one on the bottom. The side cutout is to allow for the power cord and the HDMI cable to go through the enclosure, and the bottom one is simply a cutout to allow for a thinner structure for the RFID scanner to penetrate. I've included .stl files above for the two parts I designed to close these openings once we've made them and fed wires through. You don't need to use these, but you'll want something to close the opening around the cables at the very least. The one for the RFID reader is a little more optional, but it does also help your child find the spot to hold the stuffed animal next to.
If you do choose to use these stls, the files are defined with millimeters as the unit of measure, and you'll need to print them on a 3D printer or find a printing service. It is also worthwhile to check with your local library - many now have 3D printers as a service. I printed these myself, using black ABS filament. Color is your choice, and PLA would work fine, if you desire.
When you have your parts, just use a permanent marker or awl to mark the corners where you want each cutout to go on your enclosure (see pictures). Be sure to use the inner ring of the pieces, not the outer. Then simply connect the dots to get your cutout lines. You can cutout along the lines in any manner you choose, though here I use a drill press to create a series of holes along the outline, which I then connect using a keyhole saw and file down until the inserts fit.
When you can put the inserts in, simply hot glue them in place. Be sure to feed your cables through the cable opening before gluing it in place, naturally.
To decorate the front of the device, I printed out a cross in red PLA on my printer and the word X-RAY in black ABS. The stls are provided above, but you can decorate any way you prefer. For attaching them to the box, I found hot glue works fine. It gets a little messy around the letters, but once it is cool, you can easily trim out any slop with a hobby knife.
As one final step, i like to print out a case for the Pi Zero. You could purchase one, or risk going without. The risk is pretty minimal, but it is nice to isolate the electronics. I used this case from Thingiverse and printed it in black ABS. The Pi simply presses in and the cover snaps on. If the cover wants to pop off, you can secure it with a dab or two of hot glue strategically placed on the outside. You can also glue the case to the back of the enclosure if you would like, or leave it floating. Place the RFID reader in the pocket in the cover, and use a couple light dabs of hot glue to hold it in place. Plug in the micro USB adapter and miniHDMI into the pi, insert the SD card, and close up the cover for the device. Congratulations, your x-ray is done and working. Now to finish the ID cards and tag the animals.
Step 10: Creating ID Cards
For this step, you will need:
- Your cards you previously programmed into the device
- Printer
- Spray Adhesive
- Mod Podge
- Brush
This is pretty straightforward - print out an image you would like for the front of your card (see pictures if you want to see my approach). Use a spray adhesive to stick it to the front of the card, and once the adhesive is dry, apply several coats (3+) of Mod Podge with a brush to seal the image in and protect it. That's it - pretty simple!
Step 11: Sewing RFID Tags to Stuffed Animals
For this step you will need:
- Red felt
- Your RFID tags you've programmed in
- Needle and thread
This is easy enough, but it does take awhile. I didn't want to permanently harm any stuffed animals, and the RFID tag can't be buried too deep, since these are low-power devices. In addition, the child needs to be able to locate the RFID tag to get it close enough to the reader. All I did here was to cut a heart out of the felt large enough that the RFID tag can fit entirely behind the felt. Then sew the felt heart to the stuffed animal, with the tag under the felt. In the end, all you see is the red heart, and kids easily recognize this as where they need to scan the animal under their x-ray. Sewing these on by hand takes awhile, but a simple running stitch will hold them on, even if it does take a few circuits around the heart to get enough stitches in to hold things together.
Step 12: Create Diagnostic Forms
This is an optional step, but it does aid in creative play
Once the child has scanned an animal with their x-ray, it is nice to have them be able to fill out a "chart" of sorts for their animal and prescribe treatment. There are many ways you can do this, so this is largely up to you, but I have provided an example above (sans clipart in the upper left corner). I've found you can print two of these on a standard sheet of paper - any more and they're too small, any less and you're looking at excessive amounts of paper being used.
Step 13: Sew Bandages
This is an optional step, but it does aid in creative play
In addition to having diagnostic forms, it is nice to have bandages the child can wrap their wounded stuffed animal in. For this, you'll need some white cloth and a sewing machine. I used simple white muslin that you can easily get for around $1 per yard. I cut strips 6" x 36" for extra long bandages, and 6" x 18" for shorter bandages. With each piece, fold in half along the long side to form a 3" wide strip, then sew along the long side leaving a 1/4" seam allowance. When you are about 1/4" from the end, turn the fabric to sew along the short side. Then clip the corners of the fabric as shown to help the bandage from bunching too much in the corner, and turn the bandage inside out ( you can also trim the seam allowance down to around 1/8" if you'd like, but it is unnecessary). Once the bandage is inside out, tuck the remaining unfinished edge into the bandage, and sew the end closed, being certain to reverse your stitch at the beginning and end to lock it in place. Simply press the bandage flat, and you're ready to use...
Step 14: PLAY!
Mount the x-ray near your montitor/tv, plug it in, and let your kids have countless hours of creative play! | http://www.instructables.com/id/Stuffed-Animal-X-Ray-Machine/ | CC-MAIN-2017-22 | refinedweb | 4,504 | 75.64 |
With the advent of so many computing and serving frameworks, it is getting stressful day by day for the developers to put a model into production . If the question of what model performs best on my data was not enough, now the question is what framework to choose for serving a model trained with Sklearn or LightGBM or PyTorch . And new frameworks are being added as each day passes.
So is it imperative for a Data Scientist to learn a different framework because a Data Engineer is comfortable with that, or conversely, does a Data Engineer need to learn a new platform that the Data Scientist favors?
Add to that the factor of speed and performance that these various frameworks offer, and the question suddenly becomes even more complicated.
So, I was pleasantly surprised when I came across the Hummingbird project on Github recently, which aims to answer this question or at least takes a positive step in the right direction.
As per their documentation:
Hummingbird is a library for compiling trained traditional ML models into tensor computations. Hummingbird allows users to seamlessly leverage neural network frameworks (such as PyTorch ) to accelerate traditional ML models. Thanks to Hummingbird, users can benefit from:
(1) all the current and future optimizations implemented in neural network frameworks;
(2) native hardware acceleration;
(3) having a unique platform to support both traditional and neural network models, and have all of this
(4) without having to re-engineer their models.
Put even more simply; you can now convert your models written in Scikit-learn or Xgboost or LightGBM into PyTorch models and gain the performance benefits of Pytorch while inferencing.
As of right now, Here is the list of operators Hummingbird supports with more on the way.
We can start by installing Hummingbird, which is as simple as:
pip install hummingbird-ml
To use hummingbird, I will begin with a minimal example on a small random classification Dataset. We start by creating a sample dataset with 100,000 rows and using a RandomForestClassifier on top of that.
import numpy as np from sklearn.ensemble import RandomForestClassifier from hummingbird.ml import convert # Create some random data for binary classification from sklearn import datasets X, y = datasets.make_classification(n_samples=100000, n_features=28) # Create and train a model (scikit-learn RandomForestClassifier in this case) skl_model = RandomForestClassifier(n_estimators=1000, max_depth=10) skl_model.fit(X, y)
What hummingbird helps us with is to convert this sklearn model into a PyTorch model by just using the simple command:
# Using Hummingbird to convert the model to PyTorch model = convert(skl_model, 'pytorch') print(type(model)) -------------------------------------------------------- hummingbird.ml._container.PyTorchBackendModel
We can now load our new Pytorch model to GPU using:
model.to('cuda')
This is great. So, we can convert from sklearn model to a PyTorch model, which should run faster on a GPU. But by how much?
Let us see a simple performance comparison.
We will start by using the sklearn model to predict the whole train dataset and check out the time it takes.
We can do the same with our new PyTorch model:
That is a speedup of 9580/195 ~ 50x.
We predict a single example here to see how the model would perform in a real-time setting. The sklearn model:
vs. Pytorch model
That is again a speedup of 79.6/1.6 ~50x.
A small caveat I experienced is that the predictions from the sklearn model and the hummingbird PyTorch model were not exactly the same.
For example, here are the predictions I got from both models:
Yes, sometimes, they differ in the 7th digit, which might be a function of the conversion process. I think that it won’t change the final 1 or 0 predictions much. We can also check that:
scikit_1_0 = scikit_preds[:,1]>0.5 hb_1_0 = hb_preds[:,1]>0.5 print(len(scikit_1_0) == sum(scikit_1_0==hb_1_0)) ------------------------------------------------------------ True
So, for this case, both the models exactly gave the same 1 or 0 predictions for the whole dataset of 100,000 rows.
So I guess it is okay.
The developers at Microsoft are still working on adding many more operators which range from models to feature engineering like MinMaxScaler or LabelEncoder to the code, and I am hopeful that they will further develop and improve this project. Here is the roadmap to development if you are interested.
Although Hummingbird is not perfect yet, it is the first system able to run classical ML inference DNN frameworks and proves them mature enough to be used as generic compilers. I will try to include it in my development workflow when it comes to making predictions at high throughput or latency.
You can find the code for this post as well as all my posts at my GitHub repository.. | https://mlwhiz.com/blog/2020/06/06/hummingbird_faster_ml_preds/ | CC-MAIN-2021-25 | refinedweb | 789 | 52.49 |
The examples shown in this article require you to have Eclipse installed, as well as a Web application server. The examples specifically use Tomcat 6.0, but other Web application servers such as WebSphere® Application Server Community Edition, Jetty, or older versions of Tomcat should also work. If you don't have a Web application server installed, see Resources to download and install Apache Tomcat 6.0 or WebSphere Application Server Community Edition.
Apache Click overview
Apache Click is a Web application framework that lets you quickly build Java Web applications. The purpose of Apache Click is to provide a method of building Web applications without using JSPs or MVC frameworks, which can be heavy-handed for some Web applications. Apache Click is licensed with the Apache License (see Resources).
Instead of a heavy framework, Apache Click uses HTML templates and plain old Java objects (POJOs). The HTML templates are processed by the Apache Velocity template engine (see Resources to learn more about Apache Velocity), which aims to make the templates as close to standard HTML as possible without requiring special tags. Velocity templates do not require a steep learning curve for syntax and allow Web developers to leverage existing HTML skills.
The POJOs inherit from base classes provided by the Apache Click
distribution. Apache Click includes a
Page and
component classes that you write subclasses for to implement the code that
does the processing for each page. These components provide out-of-the-box
functions that let you build HTML controls and respond to events.
Apache Click also includes an API for mock testing, which allows better unit testing, continuous integration builds, and test-driven development (TDD). See Resources to learn more about the Mock API.
Apache Click components and event handling
The
org.apache.click.Page class is the base
class for each page component. The
Page base
class contains methods that allow you to handle events when the page is
initialized (
onInit()), rendered
(
onRender()), and for page security
(
onSecurityCheck()). In your classes that
extend
Page, you can override these methods to
provide custom functions. Each class that extends
Page might also contain methods that handle
events on the page.
You can create stateful pages by implementing the
java.io.Serializable interface and calling the
Page base class's
setStateful() method in the constructor (see
Listing 1).
Listing 1. Setting the stateful property in the constructor
public WelcomePage() { setStateful(true); }
Apache Click comes with several control components that correspond to HTML elements. These control components let you programmatically set up forms by dynamically adding controls. Using these controls, you can get and set the HTML control data programmatically in your Java code.
Using the
setEventListener() method of field
controls (that is,
TextField,
Select), you can define a method on your
extended
Page class that executes during the
form processing, if the input in the field is valid.
Buttons and links also provide event handling. You can create a new submit
button on a form and link the button to a method on your
Page class using the declaration shown in
Listing 2.
Listing 2. Creating a submit button with the
onClick event handler
Submit submitButton = new Submit("Submit Me", this, "onClick");
When the button is clicked, the event is dispatched to your custom
Page class's
onClick() method. Any code that is in the
onClick() method is executed, including code to
save the data to a database or to forward to a new page.
To read more about the API, see Resources.
Apache Click templates
By default, Apache Click uses the Apache Velocity templating engine. The
templates are matched automatically with the classes that extend
Page in your application using some default
mapping rules. For instance, a page class called
HelloPage automatically maps to the HTML file
called hello.html in your Web project. A page called
HelloWorldPage automatically maps to a page
called helloWorld.html or hello-world.html.
If you don't like the default page mapping, you can change it by modifying the click.xml file to add your own custom mapping.
Along with the page mapping that Velocity uses, you can decide not to use Velocity as your templating engine. Apache Click lets you use JSPs for rendering, which may help you use existing JSPs.
Downloading Apache Click
Download Apache Click from the Web site (see Resources). After downloading it, extract the compressed (.zip) file to a location that is easy for you to remember.
If you want to see the examples that come with Apache Click, you can deploy the click-examples.war file from the dist folder to your Web application server. The examples include many different scenarios, such as building tables, using different controls, and using different templates.
After you download and extract the files, you are ready to create a Web application that includes the Apache Click libraries.
Importing Apache Click
Install Apache Click by putting the required Java Archive (JAR) files in your Web project. After including it in your Web project, deploy your project to your Web application server.
To create a Web application that uses Apache Click using Eclipse, follow these steps:
- Select New > Other from the Eclipse menu.
- From Select a Wizard, choose Web / Dynamic Web Project and click Next.
- Type a name for Project Name (for example,
MyFirstClick).
- Select a Target Runtime, such as Apache Tomcat 6.0. See Resources to learn more about configuring run times for Eclipse.
- Click Finish—you can leave the default values for the remaining fields.
After completing these steps, you should have a new empty Web project in Eclipse (see Figure 1).
Figure 1. The empty Web project
Now you can import the Apache Click libraries. Use the following steps to import the libraries:
- Click File > Import.
- Select General / File System from the list and click Next.
- Browse to the directory in which you expanded the Apache Click files and select the dist directory.
- From the list of files, select the click-{version}.jar and click-{version}-extras.jar files (see Figure 2).
Figure 2. Importing the JAR files
- Make sure the WebContent/WEB-INF/lib folder is selected in the Into folder field before clicking Finish.
Now that you have the JAR files in your WEB-INF directory, modify the Web
application's web.xml file to include the
ClickServlet, which is the single servlet used
by Apache Click to dispatch events. After you configure this servlet, you
won't need to modify the web.xml file any more to use the examples shown
in this article. The web.xml contents are shown in
Listing 3.
Listing 3. The web.xml file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns: <display-name>MyFirstClick</display-name> <servlet> <servlet-name>ClickServlet</servlet-name> <servlet-class>org.apache.click.ClickServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ClickServlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>welcome.html</welcome-file> </welcome-file-list> </web-app>
Now create a package into which your page classes will go (for example,
com.example.myfirstclick.pages). After you
create the package, create a new file called click.xml in your Web
project's WEB-INF folder. Put the name of the package you just created in
the click.xml file, as shown in Listing 4.
Listing 4. The click.xml file
<?xml version="1.0" encoding="UTF-8"?> <click-app> <pages package="com.example.myfirstclick.pages" /> </click-app>
Building a sample application
Now that your project is set up, you are ready to start writing classes
that extend the Apache Click classes. Your first class extends from
Page, which is the base class for all of your
page components. Create the new class in the package you created by
selecting File > New > Other and selecting Java /
Class. Make sure to enter
org.apache.click.Page as the Superclass.
Add the contents shown in Listing 5 into your new class.
Listing 5. The
WelcomePage class
package com.example.myfirstclick.pages; import org.apache.click.Page; public class WelcomePage extends Page { // Initialize the value to something protected String theMessage = "Welcome!"; public WelcomePage() { // Add the value to the map ("message" = "$message") addModel("message", theMessage); } }
Now that you've created the
WelcomePage class,
you need to create an HTML page that is the template for the output for
the browser. Because the default template engine for Apache Click is
Apache Velocity, the HTML file will be similar to a normal, static HTML
page.
Create the new HTML page—called welcome.html—in the WebContent folder of your Web project and add the content as shown in Listing 6.
Listing 6. The welcome.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html> <head> <meta http- <title>MyFirstClick Welcome</title> </head> <body> <p>$message</p> </body> </html>
Notice the
$message variable in the new HTML
file. This is a variable that is replaced by the Velocity template engine
when the page is generated. The
ClickServlet
matches the
WelcomePage class with the
welcome.html file. The
WelcomePage class
initializes its message field to a value
(
Welcome), then, in the constructor, adds it to
the model using the
addModel() method passing
the name of the variable (
message maps to
$message) and the value (the
theMessage field). The value assigned to the
field is displayed in the browser.
Running the sample application
Now that you've created the files, you can try the application by exporting the files as a Web Archive (WAR) to the Tomcat webapps folder. The easiest way to do this is to follow these steps using Eclipse:
- Click on the project and select File > Export.
- Select Web / WAR file and click Next.
- In the Destination field, browse to the Tomcat webapps folder.
- Make sure Overwrite existing files is selected and click Finish (see Figure 3).
Figure 3. Exporting the project as a WAR
After you export the WAR file to the Tomcat webapps directory, you can browse to your new page by pointing your browser to (the URL may vary if your Web application server is bound to a different port or if you choose a different name for your Web application).
Experiment with this sample by modifying the value of the message field on
the
WelcomePage, then redeploy it to the Web
application server. When you see the value change, you are ready for a
more dynamic example.
Building a form
Now that you've done a simple welcome page, you are ready to do something a little more complicated. Few dynamic Web sites consist of only read-only data—most of them require user input at some point and do something with that user input. A typical example is a form that accepts input and then shows the user a different Web page with the input displayed.
To view this example, create another class that extends
Page. Name this new class
InputPage (see
Listing 7).
Listing 7. The
InputPage class
package com.example.myfirstclick.pages; import org.apache.click.Page; import org.apache.click.control.Form; import org.apache.click.control.Submit; import org.apache.click.control.TextField; public class InputPage extends Page { public Form form = new Form(); private TextField nameField; public InputPage() { form.setLabelsPosition(Form.POSITION_TOP); nameField = new TextField("Enter your name"); form.add(nameField); form.add(new Submit("Submit", this, "onSubmitClick")); } public boolean onSubmitClick() { SayHelloPage nextPage = (SayHelloPage)getContext().createPage("/sayHello.html"); nextPage.setName(nameField.getValue()); setForward(nextPage); return false; } }
The new class sets up a
Form object in the
constructor and adds a field to it for input. Then the class adds an HTML
submit button with a handler (the
onSubmitClick() method). The handler executes
when the submit button is pressed, so in the handler the class should set
up the next page. Until you add the next page (that is,
SayHelloPage), the code will not compile.
Now create a new HTML file and name it input.html in the WebContent folder
of your Web project. Put a
$form variable on
the page, which will be substituted with the HTML output from the form
field on the
InputPage class. When you're done,
the input.html file should look like Listing 8.
Listing 8. The input.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html> <head> <meta http- <title>MyFirstClick Input Sample</title> </head> <body> $form </body> </html>
Now add the page that displays the input as another class called
SayHelloPage, making sure it also extends from
org.apache.click.Page. The new class should
look like that in Listing 9.
Listing 9. The
SayHelloPage class
package com.example.myfirstclick.pages; import org.apache.click.Page; public class SayHelloPage extends Page { private String name; @Override public void onInit() { super.onInit(); if (name != null) { addModel("name", name); } } public void setName(String name) { this.name = name; } }
This class overrides the
Page base class's
onInit() method to set up the values that are
displayed on the page. Remember to add checks for null to any value that
you add to the model with the
addModel()
method—if you try to add a null value, it throws an
IllegalArgumentException. This forces you to
make sure you write code that displays the page properly if values are
null.
The name field in the
SayHelloPage is exposed
with a public getter,
setName(). This accessor
is called back in the
onSubmitClick() event
handler method in the
InputPage after it gets a
new instance of the page.
The
onSubmitClick() method sets the name using
the value from the
nameField control
(
nameField.getValue()). Then it forwards to the
page using the
setForward() method. The result
is that the name field on the
SayHelloPage is
populated with the value from the input box and put in
$name.
Now add an HTML file, called sayHello.html, that contains the
$name variable. The contents of sayHello.html
are shown in Listing 10.
Listing 10. The sayHello.html page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html> <head> <meta http- <title>Results</title> </head> <body> <p>Hello, $name!</p> </body> </html>
To run this example, point your Web browser to. Enter a value in the text box, and press Submit. Your value now displays in the browser.
Summary
Using Apache Click, you can quickly write Web applications using a lightweight model free of heavy frameworks. The simplicity of Apache Click enables you to use your own object-oriented programming practices and patterns. The default templating engine, Velocity, allows the HTML code to remain truer to HTML specifications by not requiring custom tags.
The component and event model in Apache Click provides a method of building HTML controls and handling events that has a low learning curve.
Resources
Learn
- Read about the Apache License.
- Read more about Apache Velocity.
- Learn more about the Apache Click Mock API.
- Learn more about the Apache Click API.
- Read "Developing Web applications with Tomcat and Eclipse" (developerWorks, May 2007) to learn more about using Apache Tomcat with Eclipse to build Web applications.
- Browse the technology bookstore for books on these and other technical topics.
Get products and technologies
- Download Apache Tomcat.
- Download Apache Click .
- Download WebSphere Application Server Community Edition, a lightweight Java EE application server built on Apache Geronimo technology.
- Download IBM product evaluation versions or explore the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere.
Discuss
- Check. | http://www.ibm.com/developerworks/web/library/wa-apacheclick/ | CC-MAIN-2014-35 | refinedweb | 2,579 | 65.62 |
11 July 2006 12:16 [Source: ICIS news]
?xml:namespace>
The number, which represents a €5/tonne decrease on the second quarter settlement, had been agreed with most key customers, he said.
The figure was subsequently confirmed by a major consumer, although it remained unclear whether it had been followed by other market participants.
Despite the delta reduction, overall CX prices were set to climb in July following an increase in the benzene contract price.
CX prices are determined by combining the quarterly delta with the monthly benzene price, which in July was settled at €850/tonne free on board (FOB) Northwest Europe (NWE), up €40/tonne.
If the delta of €140/tonne were accepted by the market, July cyclohexane prices would rise to €990/tonne ex-works, up €35/tonne | http://www.icis.com/Articles/2006/07/11/1074112/first-q3-europe-cx-delta-at-140.html | CC-MAIN-2014-52 | refinedweb | 131 | 59.33 |
Haskell Quiz/Numeric Maze/Solution Dolio
From HaskellWiki
< Haskell Quiz | Numeric Maze(Difference between revisions)
Latest revision as of 07:19, 13 December 2009
This is a simple breadth-first search with some pruning. It avoids visiting numbers that have already been seen in a shorter sequence, and trims in too-large values (I noticed that no shortest sequences seemed to use numbers greater than 2*max(init, target) + 2, so such values could be discarded).
{-# OPTIONS_GHC -fglasgow-exts #-} module Main where import Control.Monad import Data.IntSet (fromList, insert, empty, notMember, union) import Data.Ratio import System search init target = reverse . map numerator $ search' [[init % 1]] (fromList [init]) where t = target % 1 search' ls s | (x:_) <- filter ((==t) . head) ls = x | otherwise = search' ls' s' where s' = s `union` fromList (map (numerator . head) ls') ls' = do l@(h:_) <- ls n <- [h + 2, h * 2, h / 2] guard (denominator n == 1) guard (numerator n `notMember` s) guard (if target > init then n < 2*t + 1 else n < 2*(init%1) + 3) return (n:l) main = do [i, t] <- fmap (map read) getArgs print $ search i t | http://www.haskell.org/haskellwiki/index.php?title=Haskell_Quiz/Numeric_Maze/Solution_Dolio&diff=32446&oldid=7811 | CC-MAIN-2014-41 | refinedweb | 188 | 60.85 |
(mellow orchestral music) CHRISTOPHER: Chocolate
is fascinating, fun. Chocolate is romantic. SUSIE: Chocolate
is a warm hug. KEVIN: Messy. (laughing) PAUL: Well said. DEB: Chocolate
is mouth watering, satisfying, extravagant,
lavish, beautiful. BERTHA: Super delicious.
(laughing) CHRISTOPHER: The journey
from the discovery of cacao to present day to a
chocolate bar is a long, fascinating piece of history. TODD: We’ve had lines
blow up on us to where you’re literally covered from
head to toe in chocolate. Always worse things
you can be covered in, we always say. MELISSA: A lot of people
are surprised to find out that everything on there
is completely edible. We also get a lot of people
that are surprised to find out that everything’s done by hand. SHINYA: Everybody said,
“Wow, this is different.” Somebody said that this is
life-changing chocolate. BERTHA: It’s hard to find
anything that you really feel like you have
accomplished something and making the
chocolates I feel like I’ve accomplished something. JASMIN: People don’t
realize what amazing things are coming out of this
part of the country and going all over
the United States. (mellow orchestral music) NARRATOR: When Nebraskans
think of chocolate today, Bakers Candies in Greenwood
often comes to mind. The plant started by
Kevin Baker in 1986 as a way to provide
for his family, is now a family run operation. KEVIN BAKER: There’s a
lot of things I wanna go in other than candy but I
had a family to support and I knew if we could do
this and do it right, we could get it going
pretty soon and we did. NARRATOR: Before
starting Bakers Candies Kevin built, designed and
maintained automated equipment in the aerospace industry. His start in candy
came when he was hired by Lincoln chocolate
company House of Bauer. KEVIN: I was hired to come
in and update equipment, try to automate it, get them
efficient and make some money. We got it going
good and so I think it started showing a profit so basically they sold
out to Price Candy out of Richmond, Missouri
which was later bought by a bunch of investors
and they bankrupted it. NARRATOR: Not to be deterred, Kevin took his ideas he’d been
developing for House of Bauer and built the first
Bakers candy building with help from family
and never looked back. KEVIN: I was not a candy man but I knew how to make candy. I mean I would, I didn’t know the recipes but
I knew what needed to be done that we could make
it efficiently. We hired a guy that knew
more about chocolate and he would work the recipes
and we would run tests and try things to see
how fast we could run it. Get the chocolate to set, is it compatible
with our equipment. NARRATOR: Today
Kevin’s sons Todd and Paul have integral rolls in the
company’s day-to-day operations. TODD BAKER: There are
photographs of Paul and I on our David Hasselhoff
Knight Rider Big Wheels rolling around the Bauer
and Blum plant in Lincoln and so the chocolate
industry is really all we’ve ever known. We’re pretty good at making
chocolate having spent our whole lives doing this. NARRATOR: The Bakers
estimate they produced between three and four
hundred thousand pounds of chocolate in 2017. That results in at least
30 million meltaways. TODD: By my math that amounts to about 12-15 meltaways
per Nebraskan. NARRATOR: According to Paul, milk chocolate red
is the fan favorite followed closely by
dark chocolate mint, but which one do the
Bakers like best? PAUL BAKER:
They all taste like work is
our famous saying around here. NARRATOR: Like Nebraska
farmers sell corn and soybeans the Bakers buy their chocolate
on the open commodity market. TODD: The cocoa beans come to
the United States on a ship, just like every chocolate
company gets their cocoa beans however, we have them
processed into these nice, convenient melting ingots. A pallet like this
of chocolate liquor actually is probably
about the equivalent of an entire semi trailer full
of dry roasted cocoa beans. Being far more dense
we’re able to get about 30 of these pallets onto a semi truck and we
can get a lot more cocoa here to Nebraska so that
we can re-distribute it. NARRATOR: After 10 pound
chocolate liquor blocks are melted, they are mixed with
cocoa butter and flavorings to begin the process of creating the famous Bakers Meltaway. TODD: From the beginning to
the end the entire process takes about 90 minutes. That includes the time it
took to literally pump it out onto the floor, form, shape,
coat, cool, twist wrap and send it into this catch
bucket like you see right here. NARRATOR: Let’s speed
that 90 minute process up a bit, shall we? (upbeat bubble gum music) (record scratching) Okay, now let’s try it slow. (smooth mellow music) Bakers chocolates are so good
people come from miles around. Some even pedal their way. An annual chocolate
bike ride by the Great Plains Bicycling
Club brings chocoholics 40 miles round trip to satisfy
their chocolate cravings. RANDY SMITH:
We do the Bob Brown Memorial
Easter Bunny Chocolate Ride. This is a memorial for Bob,
who along with his wife Ann were long-time
members of the club. Bob was a real chocolate
lover so about weekly during the summer they would
ride out from their home, up here to highway six
and up to Greenwood to Bakers Chocolates
where Bob would replenish the supplies and
they would ride back. Bob passed away suddenly
a few years back and I decided we needed
to continue the ride so I’ve led that ride
for the last few years. NARRATOR: To accommodate
chocolate lovers from across Nebraska,
Bakers is expanding. A 5000 square foot
retail store addition is slated to open in 2019. A testament to their efficiency. TODD: A chocolate factory
our size in the year 1980 would have had have employed
at least a hundred people to do what we’re now able to
do on our production floor with just three employees. Literally machinery does 100%
of the labor intensive work out here on the candy factory
floor and so when people come to the chocolate factory
looking for oompa loompas they’re often
disappointed to find they’ve all been outsourced by automated
production equipment. NARRATOR: In fact,
automation may have lead to the demise of Lincoln’s
second largest employer of the 1950’s and ’60’s. Let’s take a look at the
Haymarket when cranking out hand-dipped confections
was a top priority. ED ZIMMER: We’re at 8th and P in
Haymarket in Lincoln, Nebraska and I think of this as the
center of chocolate in Lincoln and maybe the center of
chocolate in all of Nebraska because behind me is
the candy factory. What originally was the Gillen
and Boney candy company. They were a Lincoln firm that
went all the way back to 1895 and in fact, they went back
to 1895 in this building, although it didn’t look
like this at that time. NARRATOR: Ed Zimmer is
Lincoln’s leading historian. He takes us through what today
is a revitalized urban area and what once was
Lincoln’s chocolate mecca. Frank Gillen and
William Boney worked for competing candy companies. Gillen for Lash Brothers, Boney for Lincoln
Confectionary Company. After about a year as
competitors they joined forces. ED: Almost immediately
after Gillen and Boney formed their own company, their
building burned down in 1895 and somehow they didn’t
go out of business, they in fact bought the
two-thirds of the site that had burned down and rebuilt
their three stories in 1906 then added fourth story on top
of that and eventually bought and remodeled the
whole exterior. So, that whole
corner of 8th and P was the Gillen and
Boney building. NARRATOR: The foundation
laid by Gillen and Boney turned into Russell Stover, Lincoln’s leading chocolate
company in history. ED: Stover’s first came to
Lincoln not as manufacturers but as retailers. They weren’t called
Russell Stover, they were called Mrs.
Stover’s Bungalow Candies and they were in several
locations around 13th and O, eventually operating out of the Miller and Paine
department store building. During World War II, in order
not to be put out of business by the rationing, they bought
regional candy companies and Gillen and Boney was
one of them they bought. (upbeat jazz music) NARRATOR: By 1943 when Russell
Stover took over operations of Gillen’s Candies,
they have 43 locations around the region. Not long after that,
in the spring of 1946, an 18 year old named
Margaret began working there. MARGARET LEHL: I think I weighed
114 pounds when I started there and boy it didn’t take
long to pick-up to at least 118 or so (chuckling) and I’ve been heavy ever since. If I took that first
piece in the morning, I ate it all day long. But if I never ate a
piece then I was okay. NARRATOR: Not long after
she started working there Margaret met a teenage
candy maker named Leonard. In October of 1947, when
she was 19 and he was 20, they got married. Both Margaret and Leonard made
a career out of Russell Stover working there until 1980 when
offices and major production moved to Kansas City. But before that
happened, Russell Stover was the major player in Lincoln. ED: The payroll
eventually reached 800
and they were producing a million pounds
of candy a month out of the Haymarket district. MARGARET: I started
out as a service girl for the nut cluster dippers
and I did that for a while and then I learned to dip
the clusters too, myself. And then from there I
learned to do the designs by hand dipping and I did
chocolate and pastel both. NARRATOR: As a perfectionist
Margaret had a hard time meeting the 120-150 tray quota
during her eight hour shifts. With 82 pieces of
candy on a tray, workers would have each
dipped over 10 thousand pieces of candy each shift. MARGARET:
If you was going to make
for vanilla cream that was a V and you used three
fingers and made the V. And chocolate butter
was rough top so you, it was kind of a rough top. And then for caramels
it was a cup. ED: I still run into people
around Lincoln who worked at, what they almost always
called Stover’s and they have fond memories of coming
home smelling of chocolate. MARGARET: Didn’t pay a lot but I
stayed because I liked to dip and I liked the people and so I, I just enjoyed working there. NARRATOR: The
Lehl’s started their family
while working at Stover’s. The kids remember their parents
coming home with chocolate for them on a regular basis. MARGARET: It was like a
three pound box. We only paid a dollar
for the seconds. NARRATOR: Today inside
the candy factory atrium a tree grows from one of
the vats that was used to melt the chocolate
all those years ago. And train tracks still
disappear into the building. ED: As Russell Stover
expanded in Lincoln they went beyond the
Gillen and Boney building into about half a dozen
buildings around them including the big HP Lau
grocery warehouse north of them. From the north the spur line
came right into the HP Lau building and all the
way down into the old Gillen and Boney building so
they could deliveries by rail right inside the building. NARRATOR: Former
Russell Stover employees still get together twice a
year for coffee and breakfast. MARGARET: We talk some about it
and how things changed, some of the people that are
gone that we really miss and everything. It’s just fun to get together. NARRATOR: Today in Texas,
Frank Gillen’s great grandson still makes chocolate under
the Gillen candy brand. In Lincoln in 2013
with the construction of the Pinnacle Bank
Arena came a piece of art by Philadelphia
artist Donald Lypsky called Box of Chocolates. It is 16 feet wide by nine
feet high and contains 144 chocolate pieces. The artwork pay homage to the
area’s rich chocolate history. TODD: I’m Todd Baker with Bakers
Candies and shipping chocolate especially in Nebraska,
particularly in the summer can be quite difficult. If you’re going to ship
chocolate from home, here’s what you need to do. First, start with any
standard corrugated box. If you can, put insulation
first at the bottom, followed by the candy,
our local sports page. We use eutectic gel
packs like these. You can no longer ship dry ice
via most commercial channels and so you eutectic
gel ice is great for two to three-day shipping. Place it on top
of your newspaper, then from there we’re
going to add one more layer of insulation to the top of the
box and then here’s the key, when we close the box we
wanna tape it not simply along its vertical seam but also along each of the
horizontal seams as well. What we’re hoping to do is
make this package air tight. By doing this, your chocolate
will last about 40% longer and it’s the key
that everybody misses when they ship
chocolate from home. NARRATOR: Lincoln’s
Haymarket will forever be connected to the
city’s chocolate past. Today it’s still an area
where chocolate lovers can find something satisfying. ED ZIMMER: At their peak Russell
Stover was using about half a dozen buildings
in Haymarket, both on the candy factory block
and even across the street here at what’s now The Mill. This was one of the key
buildings in the revitalization of the area. I hear they even sell
chocolate inside here now. NARRATOR: Some of the
chocolate sold inside the mill is made by Shinya Takahashi, a nutrition and health
science professor by day and chocolate maker by night. His chocolate is
known as Nama Choco. SHINYA TAKAHASHI: I don’t
advertise my side business, chocolate business
to my students or
anybody else on campus because on one hand I’m
advocating or teaching students a healthy lifestyle but
then I make chocolate to sell to people. Once in a while when I go to
The Mill coffee shop in town, there are students
there studying for exams and I see them, “Oh,
you’re the professor.” Oh yes, (chuckles) and
it’s a little bit awkward situation sometimes. (speaking in Japanese language) NARRATOR: Shinya moved
from Japan to Nebraska to study exercise
science after watching the Nebraska football
team play Kansas State in Tokyo in 1992. SHINYA: What I saw on TV,
Nebraska playing against K-State and they were really strong. Tommie Frazier was a freshman
and he was a quarterback and they beat K-State so I
was pretty impressed by that and I decided to
come to Nebraska. NARRATOR: Shinya began
making his Japanese chocolates as a way to bring a taste of
home to his family and friends in Nebraska. SHINYA: The chocolate that I
make is really popular in Japan, especially the
Valentine’s Day time. Maybe January through
March but I haven’t seen anything like that in US and so I started to
kind of experiment and try to find
a close chocolate that I’m used to. NARRATOR: He turned it
into a business in 2014 after winning the
People’s Choice award at Lincoln’s Chocolate
Lover’s Fantasy event. That was the first time he
entered and he’s held the title every year since. SHINYA: When we went to
Chocolate Lover’s Fantasy
first time, we provided samples and
everybody said “Wow, “this is different.” Somebody said, “this is
life changing chocolate.” NARRATOR: His recipes
are simple in appearance and ingredients. Shinya prefers to let the
chocolates speak for themselves. SHINYA: I’m not making
chocolate from scratch, I’m using baking chips
basically, chocolate chips and then I put in some
ingredients and make the texture much, much soft and smooth and
I think that’s the difference when you compare to
other chocolates. NARRATOR: Nama Choco
comes in five flavors: dark chocolate, sea salt,
mint, sea salted caramel and raspberry. SHINYA:
My chocolate is temperature
sensitive so my chocolate needs to be always in the
refrigerator and it can last, I’m really comfortable
maybe at seven to 10 days but beyond that I won’t
be able to guarantee that that chocolate is good. All right. MOTHER-IN-LAW: Kanpai
SHINYA: Kanpai. NARRATOR: Shinya
makes Nama Choco in his mother-in-law’s basement
kitchen because that meets the proper certifications
for a food processor license. SHINYA: Nama meaning
“the fresh”, in Japanese and Choco is the chocolate. NARRATOR: Around the
same time Shinya Takahashi was coming to Nebraska because
of the football program, Kansas City native
Christopher Elbow was here as part of the University of
Nebraska Lincoln swim team. He is now a premier
chocolatier in his self titled chocolate empire
in Kansas City. CHRISTOPHER ELBOW:
Christopher Elbow Chocolates is a modern chocolate factory. We produce handmade bon
bons, truffles, confections with unique flavor combinations and also with a design element. We do a lot of hand
painting and air brushing so every chocolate that
we produce has its own, unique identity. NARRATOR: Christopher’s
road to success has been long and being a chocolatier
wasn’t part of his plan while attending the
University of Nebraska. CHRISTOPHER:
I was majoring in restaurant and food service
administration at UNL and a lot of the classes I
was in were very chemistry, food science centric
which actually gave me a really great foundation of when I did start
my culinary career. NARRATOR: Elbow
started out as a chef cooking savory food. CHRISTOPHER:
I had the opportunity
to work in a pastry kitchen out in Las Vegas and that’s
where I discovered my love for desserts and chocolate
and kind of all things sweet. NARRATOR: Even
though chocolate making wasn’t in the
plans when Christopher
was at the University, he says what he learned
there does translate. CHRISTOPHER:
Chocolate and pastry and
baking are very scientific and having that knowledge
that I learned at UNL really helped me gain insight
on how to correct problems and then come up with new
techniques and new ideas. NARRATOR: We visited
Elbow just three weeks after moving into his
new global headquarters in Kansas City. CHRISTOPHER:
We started in a 400 square
foot room above a restaurant. It was very small
scale, it was just me. Didn’t have any employees
other than my wife and my mom would come
down and help tie bows and things like that in the very early
parts of the business. But right from the beginning
we couldn’t keep up with demand. NARRATOR: The move to the
new building should allow for future expansion. CHRISTOPHER: All of our bon
bon and confection production will take place here and
it also houses all of our packaging operation, our
shipping and warehousing and then all of our
corporate offices. We were working under the
roofs of three buildings, separate buildings before
and just as we’ve grown we’ve kind of pieced
together what we could. But ultimately we
needed more space. NARRATOR: Confections
created here are works of art that go through many
steps before hitting the consumer’s mouth. CHRISTOPHER:
The bon bons is really what
we kind of became famous for. Kind of the core
part of our business. That process starts
out with airbrushing, the same airbrushes you
would use as a hobbyist and our paint so to speak,
is colored cocoa butter. We will paint the
molds with airbrushes or sometimes we’ll splatter
them or hand paint them. Once that is set we’ll pour
the chocolate into the mold and it will form the shell. Pour the excess out,
the rest will drip out and kind of leave
behind a thin shell. After that sets up that’s what
we’ll fill with our filling. NARRATOR: Fillings for
the Belgium style bon bons are made with well
thought out ingredients. Together they create
unique flavor combinations. CHRISTOPHER: We
like to a lot of really soft, infused caramels
using spices, herbs, different kinds of
fruits and flavors. Alcohols and things like
that that all go really, really well with chocolate. Once we make those and fill
them up, they’ll set for a day and then we’ll seal them up
the next day and turn them out. NARRATOR: The other
style of bon bon they create is called a French
style ganache. CHRISTOPHER: We would pour the
filling in a frame, we would cut it into
squares the next day and on the third day it would
go through an enrobing machine and get a really thin
coating of chocolate on it. Then we’ll actually decorate
those at that point, usually with what’s
called a transfer sheet which is cocoa butter
that’s been silk screened onto a sheet of acetate and
we put it on the chocolate when it’s wet, pull
it off after it’s set. It’s kind of like a temporary
tattoo so we can digitally create almost any design
for those types of bon bons. NARRATOR: Elbow and his
team are always looking for new flavor combinations
and those they come up with are intentional. CHRISTOPHER:
One thing that’s been
kind of a key to our success is we don’t do anything
weird for the sake of being weird or trendy. What I tell my staff is
if we eat it and we say huh, that’s interesting, then
it’s probably not something that we should sell. We like to keep things simple. The worst reaction a
customer could say would be that’s interesting. It’s the worst thing
you can say to a chef. NARRATOR: Even with room
for growth in the new space Christopher emphasizes
they aren’t looking to produce bigger batches of chocolate. CHRISTOPHER: We’re dedicated to
small batch production. We do want to grow and we do
want to make more chocolates but we’re at a certain
point where our batch size is perfect for
maintaining our quality. Our really primary focus
is to stay innovative and keep doing new
products and new flavors and kind of staying
at the forefront of the
chocolate world. NARRATOR: If Christopher
Elbow runs a chocolate empire in Kansas City, Susie
Robison is Tekamah’s queen and her shop Master’s
Hand is her castle. Nestled between
Sioux City and Omaha it started as a single mom
making candles with her kids. Now, it not only sells
candles but is a floral shop, boutique, lunchery, bakery
and of course, a candy shop. That part is known as
Serendipity Chocolates. SUSIE ROBISON: We are what we
call every woman’s dream shop but we’re also every
man’s dream shop when he’s in the doghouse. (laughing) We just wanted to
make a sanctuary, a place where women could go because unless you’re
intentional about life, it just passes you by. NARRATOR: When Susie decided to add Serendipity
Chocolates to the business, she looked to her
past for inspiration. SUSIE: That desire kind
of started with my mom and my aunt Esther and they
always made a lot of candies and things like that
at holiday times. Our chocolate covered
cherries and barks and toffees and things like that, that all came from
my mom and my aunt. NARRATOR: Susie says what
makes their chocolate so good is the ingredients used. SUSIE: We make everything
with real cream, real butter and real love
and not the fake love. You can get fake love anywhere, we make it real love and
that makes a difference. When people come in
we want them to leave with a sweet taste in their
mouth and so we give away a lot of just free samples. This little boy came
up and he was sampling all kinds of chocolate and so
the first one that he sampled, it was a peanut butter peanut and he apparently loved it a lot and he shouts over to his mom,
“Mom, you’ve gotta try this, “it’s a chance of a lifetime.” NARRATOR: Five years
ago Susie married Scott. A couple years after
that he lost his sight. Susie says it’s because of
all the adversity in her life that she is where she is today. SUSIE: The things that looked
horrible in the beginning they became part of the
rocky road of the story that we have to tell. In the early years
of Master’s Hand, when we just made
candles just to live, if somebody would’ve
just come behind me and just gave me 500 dollars, Master’s Hand would
never have been here. NARRATOR: Susie says there’s
something about chocolate that makes it perfect
for all occasions. SUSIE: I’ve never, out of all
the years that we’ve been here at Master’s Hand, I’ve
never had someone return a box of chocolate. It fits. You don’t have to worry
about getting the right size. Hi, I’m Susie and today we’re
gonna do a chocolate tip and I’m gonna teach
you how to make your own chocolate
bowls at home. You’re gonna take a balloon, you’re gonna dip it
in the chocolate, three times ’cause we’re
gonna try to make this look like a little tulip. And then I’m gonna
take it over here and I’m going to
put it on my tray. Now once it’s done
here I’m gonna take it and I’m gonna put it in the
cooler for about five minutes right in that area. Once it’s all cool I’m going to take them out of the cooler
and them I’m just gonna gently pop this balloon. Okay, now’s the fun part. You get to bring all
kinds of goodies here and we’re just
gonna fill them up. This right here is
a pudding mixture but you can use ice cream, you can use mousse. Oh, this is gonna be so good. Let’s put a few raspberries
in there because who couldn’t love raspberries. Yum. And then we’re gonna put
some whipped cream on top. There you go, something you
can do for your family at home. NARRATOR: Back in Kansas
City Christopher Elbow may be best known
for his bon bons but one of his most
recent endeavors is his Bean to Bar line of candy bars. To know where his cacao beans
come from and who grows them he travels extensively
to the growing regions and has done lots of
research on cacao in history. CHRISTOPHER ELBOW: The journey
from the discovery of cacao to present day to a
chocolate bar is a long, fascinating piece of history. I think 10,000 BP is when
chocolate was discovered in the Amazon basin and
typically it would’ve been used in the Mayan culture. They used to serve
it as a drink, a very bitter drink, a
very unfamiliar flavor. And then over time, the
cultures have learned that you can ferment the bean and dry it and
further refine it into what we associate chocolate
and the Europeans came over and landed in Central
and South America, say the natives
handling this bean, that’s a very precious currency
and something very valuable so they took it back
and it wasn’t until then that sugar started
being added to it and it becoming
something that we know of chocolate as today. NARRATOR: The cocoa
growing region is small and cacao is not a very
lucrative crop to farm. CHRISTOPHER:
Cacao grows typically
approximately 18 degrees north and south of the equator. It’s a very hot, tropical
and usually low altitude so it’s a little overlaps
with coffee a little bit but coffee would be
typically a higher altitude. NARRATOR: Cocoa
grows on trees and is difficult to grow
because the harvesting process cannot be mechanized and
some trees can grow up to 30 feet high. CHRISTOPHER: It’s a pod that
grows off the stems and trunks of trees
and inside that pod it would contain about
40 to 60 of the seeds or the beans that we call them and that’s covered with a
very citrusy sweet membrane that aids in the
fermentation process. It takes about
three to four years for a tree to bear fruit
and then another three to four years for it
to become fully matured to where it’s actually
producing a lot of fruit. NARRATOR: Christopher
gets beans from about 15 different countries
currently and he’s traveled all through Central
America into Columbia, Brazil, Peru and Ecuador
in South America. CHRISTOPHER: One of our goals is ultimately in an effort to
make cacao more sustainable, is to work with the farmers. Make sure they’re getting
a fair price for their crop and they have somebody
to sell it to. NARRATOR: Christopher
created a foundation where some proceeds
from the sales of his Bean to Bar products will support that effort. CHRISTOPHER:
The whole goal of visiting
the farmers is two fold. Number one to make sure
the product’s gonna be good and it’s gonna be something
that we’re gonna be able to make good chocolate out of. But also that their
conditions and the farmers are engaged in good practices. NARRATOR: Most cocoa
farmers don’t consume chocolate or know what it tastes like,
so Elbow gets satisfaction when he can provide
them their first taste of the end product. CHRISTOPHER:
We took a white chocolate
made with this group’s milk and their name is on the package and the kids were coming
up and just grabbing handfuls of this chocolate. To see them, you know, make the connection between
what we have created and what they have
provided us was a really kind of magical moment. NARRATOR: There are several
steps the bean goes through before it’s ready to
turn into the chocolate Nebraskans usually eat. After being hand harvested, the pods are broken open
and fermentation begins. CHRISTOPHER: The fermentation
process is really what starts creating the chocolate
flavors and precursors that we would associate
with chocolate. Once the fermentation happens
over about five to seven days, the beans are dried for
another five to seven days. NARRATOR: At this point
the beans are shipped to chocolate makers like
Elbow who further refine them. CHRISTOPHER: Our first step is
to sort through those and get rid of any
extraneous material. Sticks, rocks, things that
won’t make good chocolate but also broken beans, things
that got damaged in transit. The smallest amount
of negative beans would impact a
whole entire batch. (beans being placed
into roaster) The very first step in our
process and where we can start developing flavors
is the roasting process. It’s somewhat similar to
coffee where we’re roasting to a certain profile
for a certain bean. We’re doing it at a much
lower temperature though. NARRATOR: Roasting
typically takes about an hour and is carefully charted
to ensure the beans are cooked all the way
through and not burned. (beans poured into
cracking machine) CHRISTOPHER: The next step would
be to crack the beans and we would end up with
a big bucket of the shell and the cocoa bean so we put
them through what’s called a winnower and that
removes the shell so we’re left with
the very clean nib. That’s what will
formulate our recipe and go into the refiner. The point of the refiner
is to use heat and friction and pressure to basically
liquefy the bean. The bean is 50%,
roughly 55% fat cocoa in the form of cocoa butter
so we wanna break that down into a small particles
where it will liquefy and that allows us to actually
refine that chocolate down to a very smooth particle
size that’s gonna be really pleasing on the mouth. And we’ll also combine the
sugar in at that point as well. NARRATOR: Refining is
about a two day process. From there the liquid
goes into a conch for three or four more days. This is where final
flavor tweaks are made. CHRISTOPHER: With this machine
we have the ability to further push the flavor. We can take the
temperature up really high to where some of the
volatile acids will flash off. NARRATOR: Elbow found
that letting chocolate age before it is cast into a bar
further brings out the flavor. CHRISTOPHER:
Even after we make the
chocolate we typically put it into big blocks and we’ll store
it for two to three months before we cast it
into chocolate bars. NARRATOR: Christopher
hopes that by letting consumers see the process, they will have a heightened
awareness about how involved it is and not take each
chocolate bite for granted. Bean to Bar is a way to
get customers the freshest, purest end result as possible. That’s also the
foundation for Cup of Coa, a hot chocolate mix
originally produced in Salt Lake City but now owned and distributed in Nebraska. JASMIN McGINNIS:
I am an original Barista’s
Daily Grind barista. Barista’s started in 2001
here in Kearney, Nebraska. I am now the third
owner of this company and Cup of Coa was also a
Barista’s Daily Grind company that ownership has
passed on to me. NARRATOR: So how exactly
did the official sponsored cocoa for the 2002 winter
Olympic games in Salt Lake City end up in Nebraska? JASMIN: Coco Pub’s Cup of Coa
used to be originated in Utah and at the time our coffee
shop Barista’s Daily Grind was franchising all over
the state and we made-up 30% of Coco Pub’s sales. So when the original
owners of that company decided to move on
to something else, they asked us if we
would be interested in, in taking over the whole
company which we did back in 2007. NARRATOR: Jasmine fell
in love with Cup of Coa before becoming the owner. She hasn’t found any instant
hot chocolate she likes better so becoming the owner
was an easy decision. JASMIN: When you come across
something unique, something like this that
sticks in your memory, that sticks in your mouth, that even when you
haven’t had it for years you go back to, wow, that
was a good cup of cocoa, how can you not be
passionate about that. NARRATOR: To Jasmine,
the ingredients and recipe are what make Cup
of Coa stand out. JASMIN: Even though it is a
mix with water formula, there is tons of
milk in my product. We just found that
using a dry milk product produced a rich, creamy
cocoa so you can’t tell that my cocoa is
mixed with water. And then we also use three
different chocolates. One of them we
import from Germany, it’s a Dutch chocolate with
a really high fat content. What this means is when you
pour your water into my cocoa and you mix it, it
develops this really rich, creamy, frothy head. NARRATOR: Cup of Coa
is a luxury
hot chocolate made with all natural ingredients. Its unique characteristics
make it versatile, too. JASMIN:
We’re the only hot chocolate
company in the entire country that can be served hot. The same mixture can be
served blended or frozen. It can also be cooked
down into a syrup or sauce and our recipe’s unique
’cause you can do all of those things
with just water. Top it with a little
whipped cream. Good to go. NARRATOR: The cocoa
is produced in Nebraska and hand packed in Kearney
at Barista’s Daily Grind. JASMIN: We roll the tins by hand
and we’ll actually do that way in advance and
have them ready so that when the cocoa sleeves
show up we can just drop the cocoa sleeves
in, slap the lids on and ship from our
coffee shops out to all of the customers that
are ordering Cup of Coa. NARRATOR: Jasmine is happy that her specialty
hot chocolate allows Barista’s Daily Grind
to go beyond being just another coffee shop. JASMIN: Cup of Coa is a
signature product, it draws people. It’s so good that all of
those non-coffee drinkers will say, “Go to that
place because they have “the good hot chocolate.” GUY: Chocolate. MAN: Cheers.
GUY: Cheers. NARRATOR: Jasmine
enjoys being from Nebraska and she’s proud that her
small Nebraska company’s impact her home state. JASMIN:
I love our wide open skies and that life’s a
little slower here. I think that’s part of
the reason why we can appreciate fine things
because we take the time to notice them. People don’t realize what
amazing things are coming out of this part of the country and going all over
the United States. NARRATOR: Even
farther west in Sidney, 88 year old Bertha
Mueller ships her homemade chocolates
around the world. Mueller, known
mainly by the locals, is a former Cabela’s
employee who opens up her home twice a year at Christmas
and Valentine’s Day to her chocolate fans. CUSTOMER: Good morning. BERTHA: Welcome, come in. Glad you could come. BERTHA MUELLER:
The first years I made just
a little bit for my family and then I started
giving them as gifts and the people that we
gave them as gifts to very often said, “I wish
we could buy these.” and twelve years
ago at Christmas my husband died and he
died on December 2nd and it just was such a
blah holiday season for us and so my daughter Pam said, “Mom, do you think we should
try making and selling “some chocolates this year?” I said why not. PAM: Thank you, sir. CUSTOMER: Thank you very much. NARRATOR: The recipe
came from Bertha’s cousin who promised to share it
with her as long as she kept it in the family. BERTHA: The first of November
we start making the fondant and work really hard during
the whole month of November because it’s very
time consuming. We work long, long hours and
sometimes we really burn the midnight oil (chuckles) but it’s kinda fun because
Pam and I work together on it and so it gives us a
lot of together time. NARRATOR: Bertha
and Pam make at least 60 different flavors
which are offered in milk, dark or white chocolate
but that’s just the tip of the iceberg. BERTHA: I make 30 batches of
fondant and each batch makes 90 balls plus
I make all the fudges the sea salt
caramels have been a big seller the last few years. NARRATOR: Mrs.
Mueller went 12 years before a slight price
increase but it only covers cost of supplies. BERTHA: My son asked me, he said
“Well mom, do you make any money “doing that?” And I said, “Yes,
we make some money.” And he said, “Well do
you make minimum wage?” And I just laughed. I said, “If we paid
ourselves a dollar an hour “we would go way in the hole.” It’s not something you do
because you wanna make money, it’s something you do
because you love it. NARRATOR: Bertha
says at her age the feeling of
achievement is pay enough. BERTHA: It’s hard to find
anything that you really feel like you have
accomplished something and making the chocolates I feel like I’ve accomplished something and also it’s good
because people like them and it’s good to do
something that people want and that they want
bad enough come, to come out of their way to get. NARRATOR: Mueller
even mails chocolates for just the cost of postage
to fans around the country and the world. BERTHA: We have customers who
send us their Christmas list and we send like eight or 10
boxes to different locations around and the farthest I’ve
sent any is to Australia. Mostly it’s continental
United States and Alaska. NARRATOR: Only time
will tell how long Bertha will keep making and
selling her confections. BERTHA: I guess I’ll do it
as long as I enjoy it and when I stop enjoying it
then I won’t do it anymore. Lately, I said well maybe I’ll
retire when I’m 90 (chuckles) but that’s getting
pretty close now. CHRISTOPHER ELBOW: My name’s
Christopher Elbow from Christopher Elbow
Chocolates and today I am going to talk a little bit about how to store chocolate. Chocolate and cocoa butter
especially has a tendency to absorb odors so storing
chocolate right next to an onion in your kitchen
is probably not a good idea if you’re gonna use that
to bake a cake with. The best thing to do is
if you have any of these kind of air tight containers, these work really, really
well and get the air out. Then store these in
a cool, dark place. 60 degrees would be preferred. You can store them
in the refrigerator for longer term storage but we always recommend
making sure you bring it to room temperature before
you open up the package. Now, if you don’t have any of
these little containers here, you can always use
good old plastic wrap making sure you do a few
layers really, really tight. I would probably do two
to three layers before, especially if you’re gonna
put it in the refrigerator. Just like that. NARRATOR: Something
about chocolate brings people together. Bertha Mueller’s chocolates
attract family and friends for two special
chocolate holidays. Columbus author and speaker
Deb Burma noticed that too and that inspired her to
write a women’s bible study around the theme. DEB BURMA: And I pray this won’t
be the last time you hear it. May we never tire — We’ve been leading a
series of these events for a few years. When we started talking as a
team about what is one thing that most every woman shares a love for. Chocolate.
Yes, let’s talk chocolate. So, the exciting part
of me as I thought let’s do a chocolate
themed women’s event and see what happens. Hot chocolate, we have — NARRATOR: As Deb
started planning her event and looking through scripture, she had no problem finding
word pictures and themes that coincided with similar
chocolate connectors. DEB: What are all the
things we crave in life, seeking for something
that’s going to satisfy us and I’m taken to, I’m taken to God’s
word where He says that He satisfies every need of ours
through His glorious riches in Christ Jesus. I think about things
that are rich and lavish and how we savor chocolate
as it sits on our tongue and we long for more, right? So, what’s rich and lavish? God’s rich grace for us
that He lavished on us. Right there, in the
pages of scripture. I love the delicious
blend of chocolate and coffee. NARRATOR: Deb planned
her chocolate retreat and its success showed her
that chocolate did in fact, bring women together. DEB: We brought chocolate
in and we had, as I said, topped
out 60 to 100 women. Suddenly 220 women walked
through the door that morning and we saw that chocolate
brought women together. What is it about chocolate, I think it’s rich, it’s lavish, it’s delicious, let’s be real. And it’s beautiful. NARRATOR: Deb’s book
Living a Chocolate Life uses recipes and every day
experiences to help women relate to words in the bible. DEB: An extravagant, three
layer chocolate cake that I baked only to find a
catastrophe on my hands as it split in two
and cascaded down the sides of the cake
plate and onto the table. One big crumbling mess
and sometimes our lives feel like one big
crumbling mess. NARRATOR: Burma understands
that the Bible
and Bible studies can be intimidating
and she finds that the relatable topic
of chocolate breaks down some of those walls. DEB: With the concept
and even the title, Living a Chocolate Life, women were not afraid
to bring a friend, a neighbor, somebody who
had been maybe hesitant, unresponsive in the
past or just intimidated about Bible study to
see that it can be real, a real place, an authentic place of sharing and giggling and maybe some tears, growing together
around chocolate. Around such a fun,
relatable topic. NARRATOR: Deb loves seeing
people across the country share her Bible study and
recipes while enjoying
girl time in the name of chocolate. DEB: You can find chocolatiers
and chocolate shops all over this country and
beautifully right here in Nebraska. Chocolate is so appealing that who can’t talk about it? NARRATOR: As a Christian
author and speaker Deb Burma wears her
faith on her sleeve. Melissa Stephens of The
Cordial Cherry in Omaha shares a love for God
and credits Him for being where she is today. She just didn’t think it
would happen by making adorable little snowmen. MELISSA STEPHENS:
Over the years I’ve seen how
He’s been able to use that for His purpose and it’s
been a really neat lesson. Everything from all
of the fundraisers that we’ve been able
to be a part of. The thousands of chocolates
that we’ve donated to help contribute to
needy families and children and different organizations
that are important to just the gift giving
to touch somebody’s heart and make someone smile
that needed that. I no longer feel I’m not
doing something noble I actually feel like exactly
what God designed me to do. NARRATOR: And what
she was designed to do? Create chocolate
covered cherries that are not only delicious
but are almost too cute to eat. MELISSA: A lot of people are
surprised to find out that everything on there
is completely edible. We also get a lot of people
who are surprised to find out everything’s done by hand. We don’t use any molds to
create any of the pieces or designs for our
cordial cherries. Everything, start to
finish is done by hand. NARRATOR: Melissa learned
how to make cordial cherries from her grandmother and
that was just the beginning of what would become The
Cordial Cherry in Omaha. MELISSA: She’d always made them
for a Christmas treat for us so it had become a holiday
tradition for our family. Eventually I was curious
enough I wanted to learn how to make them myself. She was kind of reluctant
because it’s quite a process. Took about a week or so of
her kind of working with me but I was able to get it down. NARRATOR: Before any
decorating can take place the cherries must be turned
into cordial cherries. MELISSA: We order in all of our
cherries from the Washington, Oregon area. The next step is
draining the cherries. We have to prepare
a liquid fondant, it’s kind of a hot liquid
fondant so once it cools it’s hardened. Once we set them
down on the paper they cool down immediately
and are hardened. We have about an hour
or so before we have to dip them in chocolate
to create a, a casing so
that that liquification
can start to develop while they’re encased
in the chocolate. NARRATOR: Melissa
estimates she has come up with 200 plus cherry
designs over the years. MELISSA: My favorite
cordial cherry design is our snowman cordial cherries. It’s a really fun
one just because there’s so much versatility. They look so happy as
you’re making them. It’s hard to not make
them and not smile and it’s got a soft spot in
my heart ’cause it was one of my very first designs. NARRATOR; Melissa is an
interesting mix of artist and scientist. She has a bachelors
degree in biotechnology and a teaching degree
with a masters in biology. She was teaching and
getting her doctorate in education administration
when she started making chocolates to help
pay for her education. All of this while
raising four kids. MELISSA: I am left brain,
right brain definitely. I had a background in
pottery so that was kind of my foundation which I use a
lot of those same techniques actually in the sculpting and
such of some of the chocolates that we do but I’m also
very analytical so I love science and research
and problem solving which has benefited me
in terms of business. NARRATOR: Even
beyond the recipe family was the key motivation
to the Cordial Cherry’s roots. MELISSA: One of the primary
motivators for opening my shop was my desire to
home school my kids. I was a teacher and it was
really tugging at my heart that I was teaching everybody
else’s kids every day and I was missing out on
watching my kids learn. NARRATOR: And family
is still one of the keys to its success. MELISSA: I was literally
working around the clock. I recruited everybody who
I could possibly recruit so that meant my kids were
in there folding boxes, my dad was in there. I don’t even thing he’s
made a sandwich before and he learned to dip cherries. My sister was there and
her husband and we just had everybody who was
willing to help come in and sort of rescue me
that first holiday season. As soon as we got through
that season we realized okay, we are actually
onto something. There’s no way I can do
this by myself and so my mom and sister at
the time were willing to jump in as partners. NARRATOR: The chocolate
makers we visited do most of their business
between October and February. Melissa found that to be
true of her shop as well. MELISSA: Our most popular design
if we compared the entire year would still be our holiday
designs and among those it’s probably a toss up between
our nativity collection, which is a nine piece
collection that landed on Oprah’s list a few years ago, kind of put us on the map. That was exciting and
the just stereotypical Christmas designs so our santas, reindeer, elves and snowmen. NARRATOR: Besides the
acclaim of making Oprah’s list, Melissa’s chocolates have
been gifted at the Emmy awards a few times. They’ve been featured
in entrepreneur.com and they’ve appeared
on The Today Show. And although those
accolades are appreciated Stephens won’t
take all the credit. MELISSA: I just feel blessed. We have a business that we
do some really unique things and we’ve had some incredible
opportunities come our way and I don’t think
that’s by chance. NARRATOR: Melissa is a
woman with many passions who can’t sit still. She recently obtained
a patent pending on one of her inventions. MELISSA: I had this idea
to be able to stack pastries without them crushing
each other and to create really cool huge towers of
pastries and other food items. It’s called Haute Stacker. NARRATOR: Another one of
Melissa’s passions is mentoring especially up and coming
women entrepreneurs. One mentee is
Alexandra Ratigan. She is a chocolatier on
staff at The Cordial Cherry who has her own
brand of chocolates called The Chocolate Poet. MELISSA: I’ve just mentored
her along the way just to kind of help her get
her business up and running and so not only does she
manufacture her chocolates here but we sell her chocolates
in the shop as well. NARRATOR: Passionate about
chocolate, others, and life, Melissa is surely
living a chocolate life. One common denominator in all
of these stories is family. Chocolate making brings
families together. Chocolate eating brings
friends together like family. KEVIN BAKER: It’s tough to
work with family and we’ve done a very good job at it. I can see the grandkids, we got one granddaughter, she’d worked here tomorrow
if she quit school. I think the legacy
will have nothing to do with the business
itself but basically being able to run a business with all the family involved without fights, quarrels,
and we’ve done real well. We haven’t had too
many really bad spots. MARGARET LEHL:
Well, I met him in May, he was a candy maker and
we got married in October. We were married 36 years
before he passed away. MOTHER-IN-LAW: Kanpai.
SHINYA: Kanpai. SHINYA TAKAHASHI:
When we go to those
events she’s really good at promoting my chocolates. I think it’s a really
good partnership. CHRISTOPHER ELBOW: My wife’s
name is Jennifer Elbow and she is responsible
for creating the logo and the
branding of our company and has played a huge part
in helping us grow our brand and fine tune it over the years. DEB BURMA: The thing about
chocolate that is so successful at bringing people
together it is considered first of all, the number
one food craving in America and that especially by women. It’s so delicious,
it’s so enjoyed by all and it’s such a fun way
that we can gather together. SUSIE ROBISON: I just have a
team of just amazing gals and they love what they do
and they just bring joy here and they’re just really great. I’m functional in all
the areas but my girls are great at all the areas. MELISSA STEPHENS:
My mom’s my best friend, my sister’s amazing. I’m so grateful to both of them. My dad is a huge support. He’s there any time I need help just pitching in to make things or helping with my kids
’cause we’re so busy. BERTHA MUELLER:
It’s just a wonderful
mother/daughter experience and I couldn’t do
it without her. It’s a challenge for her
because she works long hours at her job and has
other responsibilities. I appreciate her so much. MELISSA STEPHENS:
Hi, my name is Melissa Stephens and I own The Cordial Cherry. Today I’m going to show you
how to make one of our favorite holiday designs, our
snowman cordial cherry. Everyone of our snowman heads
are made completely by hand. We come in and we just
create a little carrot nose with some orange colored
confectionary coating. One of my favorite
tools is a paperclip. We use this to actually
make our little eyes. To create the hat, I’m
actually using just a piping cone made out
of parchment paper. We just do a first layer,
just a little dollop. The second layer, same
idea but a little smaller and we finish that up
with a candy piece on top. And then to pull it all
together we actually trim one of our cordial
cherries, we take the stem off and we have to seal that top
so that they syrup inside doesn’t leak out. That serves a couple purposes. Not only to seal it
but it also provides somewhere for our
scarf as well as a point of contact to
glue the little head on. (mellow orchestral music) Captions by FINKE/NET (mellow orchestral music) Copyright 2019
NET Foundation for Television | https://richmondoperatics.com/net-productions-nebraska-the-chocolate-life/ | CC-MAIN-2019-47 | refinedweb | 9,396 | 68.91 |
Having been happily typing out full property declarations for months, I’ve just stumbled upon Automatic Properties. Take the following example:
public class Pet { private string _Name; public string Name { get { return _Name; } set { _Name = value; } } private int _Age; public int Age { get { return _Age; } set { _Age = value; } } }
We can re-write this class using automatic properties:
public class Pet { public string Name { get; set; } public int Age { get; set; } }
Both classes are identical. In effect this is just syntactic sugar, we just let the compiler do the work for us. For classes with many properties, this can significantly reduce the amount of code.
A word of warning – this only applies for properties that have both ‘get’ and ‘set’ methods,
so you couldn’t do this for a read-only property.
UPDATE: Actually, you can. Just add ‘private’ before either ‘get’ or ‘set’:
public string Name { get; private set; }
Advertisements
This is neat – it’s also worth pointing out that this is a feature of .Net 3.0 onwards. | https://codeoverload.wordpress.com/2010/01/23/c-automatic-properties/ | CC-MAIN-2019-18 | refinedweb | 169 | 56.29 |
I am a owner of a Nokia 5800 and one thing that I always upset me with Symbian was is not having an emulator for the HP48 that run in Symbian s60v5. So, I decided to learn some principles of the language, went to study C++ and dowloaded the Carbide C++3.2 besides the source code from and start to port it.
Well, I try to start in a small way doing step by step, but when I included the file "engine.cpp" (had included the file "engine.h" in advance) I am having several errors.
The original files had the following includes:
#include <stdlib.h>
#include <stdio.h>
but as for the s60v5_SDK_v1.0 those files are under "libc" folder, I modify those includesto <libc/stdlib.h> / <libc/stdio.h> but when try to build, several errors appear (42 in total) like this one:
...epoc32\include\libc\stdlib.h:26: the file 'stddef.h' cannot be opened
Does anybody know how to fix this? | http://developer.nokia.com/community/discussion/showthread.php/247624-Porting-Emu48-to-S60v5 | CC-MAIN-2015-14 | refinedweb | 166 | 76.72 |
flutter_biopass
Store a password behind biometric authentication.
This is a microlibrary for storing a password in the keychain, instructing the keychain to only give it back if the user first authenticates with TouchID or FaceID.
note: Android is currently unsupported, I hope to implement this soon.
note: On iOS, in order for your user not to receive a prompt that your app does not yet support Face ID, you must set a value for the Privacy - Face ID Usage Description (NSFaceIDUsageDescription) key in your app’s Info.plist.
Usage
import 'package:flutter_biopass/flutter_biopass.dart' show BioPass; final bioPass = BioPass(); // When the user signs up or logs in for the first time, store the password in the keychain: await bioPass.store('P@ssw0rd'); // When asking the user to log in, first try retreiving the saved password which will, if a password is stored, trigger a biometric authentication prompt: // If `result` is `null`, then either the user cancelled the authenticaiton, or there was no password saved. final result = await bioPass.retreive(withPrompt: 'Example prompt text...'); // When the user manually logs out, delete the stored password from the keychain: await bioPass.delete(); | https://pub.dev/documentation/flutter_biopass/latest/ | CC-MAIN-2019-30 | refinedweb | 189 | 61.87 |
There is a lot of code on the net about the browse for folder window, but when I was starting to learn C# I didn't find any really good example and description of how to use it. Someone still used the old API to call it, someone else didn't say anything about the System.Design.dll and, however, I didn't find any demo project, always only few lines of code. For a beginner this is not a true help... so, I'm posting here a simple class, a demo project and all the instructions to add the useful BrowseForFolder window into your .NET programs.
BrowseForFolder
namespace
using Utility.BrowseForFolder;
[Sure, this is an optional step (you can change the BrowseForFolder class's namespace to your program namespace), but I suggest you to keep it as a general code, in other words to build a collection of useful and indipendent little bricks of code.]The last step is to add these few lines of code in your program:
string myPath;
BrowseForFolderClass myFolderBrowser = new BrowseForFolderClass();
myPath = myFolderBrowser.BrowseForFolder("enter_here_your_text");
Ok, you have done it! Now into myPath you have the user selected path, otherwise if the user has pressed the Cancel button into myPath you'll have a blank field (myPath -> ""). Note: The path returned form myFolderBrowser.BrowseForFolder will always end with a "\" character.
myPath
myFolderBrowser.BrowseForFolder
There are a lot of comments with the code,. | http://www.codeproject.com/Articles/3287/A-very-simple-BrowseForFolder-class | CC-MAIN-2014-49 | refinedweb | 237 | 62.48 |
Crane Hook Design Optimization
Design a crane hook to carry a load F. The hook has a rectangular cross section with width b (minimum 0.2 mm) and height h.
Optimize the crane hook design to minimize the volume of the hook. The hook is manufactured from a complete rectangular wire ring that is clipped and bent to give the final hook shape. The outer radius of the hook is ro and the inner radius is ri with a minimum inner diameter of 3.0 mm. The height is the difference between the outer and inner radius h=ro-ri. The bending moment is M=FR with a force F of 100 N (10.2 kg for a static load on earth). The centroid radius is R and the neutral axis radius is rn.
$$r_n = \frac{h}{\ln\left(r_o/r_i\right)}$$
The difference between the centroid radius and the neutral axis radius is e. The stress at point A is
$$\sigma_A = \frac{M \left(r_o-r_n\right)}{b\;h\;e\;r_o}$$
The stress at point B is
$$\sigma_B = \frac{M \left(r_n-r_i\right)}{b\;h\;e\;r_i}$$
The stress at points A and B should not exceed the yield strength of the steel at 430 N/mm2.
Solution
from gekko import GEKKO
from numpy import pi
m = GEKKO(remote=False)
# Constants
F = 100 # load (N)
S_y = 430 # yield strength of steel (N/mm^2)
# Grade D fine-carbon steel (ASTM A255)
# Variables
r_o = m.Var() # outer radius (mm)
r_i = m.Var(lb=1.5) # inner radius (mm)
b = m.Var(lb=0.2) # hook width (mm)
V = m.Var() # hook volume (mm^3)
# Intermediates
h = r_o - r_i # hook height (mm)
R = (r_o + r_i)/2 # radius of the centroid (mm)
r_n = h/m.log(r_o/r_i) # radius of the neutral axis (mm)
e = R - r_n # R - r_n (mm)
M = F * R # bending moment due to the load
c_o = r_o - r_n # distance from outer to neutral(mm)
c_i = r_n - r_i # distance from inner to neutral(mm)
Area = b*h # cross-sectional area (mm^2)
o_A = (M*c_o/(Area*e*r_o)) # outer stress
o_B = (M*c_i/(Area*e*r_i)) # inner stress
# Equations
m.Equations([
V == pi*(r_o**2-r_i**2)*b, # volume calculation
o_A < S_y, # yield stress @ A < yield strength
o_B < S_y, # yield stress @ B < yield strength
r_i < r_o # constraint for feasibility
])
# Objective
m.Minimize(V)
# Solve
m.options.SOLVER = 3
m.solve()
print('Optimal Volume: ' + str(V[0]))
print('Optimal outer radius: ' + str(r_o[0]))
print('Optimal inner radius: ' + str(r_i[0]))
print('Optimal hook width: ' + str(b[0]))
The optimal solution is:
Optimal Volume: 37.50 mm^2 Optimal outer radius: 3.39 mm Optimal inner radius: 1.50 mm Optimal hook width: 1.29 mm | http://apmonitor.com/me575/index.php/Main/CraneHook | CC-MAIN-2022-21 | refinedweb | 457 | 65.12 |
Breaking the Space-Time Barrier with Haskell: Time-Traveling and Debugging in CodeWorld (A Google Summer of Code Odyssey)
How does one explore the unknown using a dream, ingenuity and human will to conquer the impossible? The following is a journey involving Time Travel, Maths, Space, and of course, Haskell.
This summer, as part of Google Summer of Code, I created debugging tools to be used by students programming in the CodeWorld environment. As a current learner of Haskell and of CodeWorld, I believe tools that help users reason about logic are very useful. I wanted to help users identify breaks in logic, and reason about mathematics and code. The tools I built can decompose a larger, more ambiguous problem (“Help! My programme doesn’t work!”) into a smaller, more precise one (“The starting coordinate for our spacecraft’s trajectory is not correct”).
When a student builds an drawing, animation or game in CodeWorld, my new debugging tools help them deconstruct what the programme does in
- time: by enabling slow-motion, fast-forward and scrolling through the history of the programme.
- position : by enabling the user to zoom in and out and move around to get a different perspective.
- organization: by giving the user a deeper understanding of the properties of parts of their pictures.
This video gives a cursory view of these tools.
Features I created:
I built four different features for debugging. They are useful explicitly and in conjunction with each other.
1. Viewable Properties in Inspect Mode
Last summer, Eric Roberts created the Inspect Button for debugging for CodeWorld. I expanded on this tool by showing the viewable properties and their evaluated arguments.
Eric created an Inspect button that shows the highlighted code to the left and the display of each component (that is tied to the source code) on the coordinate plane. However, the source code does not currently show what the expression evaluated to unless we use the new viewable properties functionality within the Inspect button. This new feature allows a user to see the evaluated expressions for attributes of the picture, which is very helpful in debugging pictures with multiple functions and arguments that work together.
In the above example, we can see that the actual thick polyline expressions are composed of points and thicknesses, and the precise values that give the results shown. We can create a pipeline of expected values vs actual values with this method of debugging.
2. Zooming and Panning
I created buttons that can zoom in, zoom out and reset to the default view this summer. I also created a slider that can zoom in and out, and panning functionality for the drawing canvas. In this example (below), details of a fractal composition are viewable because of these new tools.
In the video, we can see more detail by using the zoom-in and zoom-out buttons, and by panning. This allows us to see smaller patterns within a larger pattern.
3. Time Travel Debugger (History Slider)
Have you ever played a game and not liked the result? Let’s fix that! I’m curious to see what it would like if I won. I want to go back in time to “debug” what would have happened if I had not lost.
Cheating…it’s a feature, not a bug.
The way this works is by having two lists: one that represents the list of past states and one that represents future states. We can then pop off the most recent value from either the stack of past states or future states to travel back or forward in time.
This uses the zipper data structure where the state is a pair of lists ([],[]).
4. Speed Slider
The new speed slider allows you to speed up an animation. Playing through an animation at different speeds allows a user to identify patterns in an animation, as well as inconsistencies in those patterns. These inconsistencies can be broken down as either intentional and useful, or as breaks in logic or bugs.
“Why moments” in Programming (bugs)
In the example below, we have a bouncing ball that has a defined boundary in the code.
import CodeWorldmain = debugSimulationOf initial step pictureinitial = (0, 20)step dt state = bounce (inertia dt state)inertia dt (x, vx) = (x + vx * dt, vx)bounce (x, vx)
| x < -9 = (x, -vx)
| x > 9 = (x, -vx)
| otherwise = (x, vx)picture(x, vx) = translated x 0 (solidCircle 1) & rectangle 20 20
It seems to work just fine initially, but when I speed it up by using speedSlider, we see moments when the ball is stuck. This is a bug.
To find out how and why this happens, I paused CodeWorld when the bug occurred, and then stepped backwards and panned to see where this occurs and why. By panning, I am not limited to the viewing boundary of the ball as dictated by the viewing pane, so I get a different perspective. Here, we see that the ball bounces, but is stuck and bounces again, but that wedges the ball in further. We can even rewind to the point at which the ball was bouncing as expected.
Revealing Illusion in an Animation
This animation shows the journey of a hot-air balloon into Space, whereby the traveler becomes a NASA astronaut. When the window is constrained, it is not apparent how the animation is made. It appears as delightful magic.
By using the new debugging, this magic is deconstructed, like a Noh Theatre act that is unmasked.
Challenges Along the Way
Getting Started
One of the other issues we discovered was that the CodeWorld install script did not work correctly on 32 bit machines. My first pull request made a change to fix this issue. It wasn’t long before I also realized that smaller screens (such as that of my $20 refurbished computer, which runs 32-bit Ubuntu 16.04) didn’t have room for the debug controls I was trying to add. So I had to make another side-trip to add resizing of the programme before I could get started on debugging. This involved CSS and HTML.
In retrospect, these were good ways to get my feet wet with the project.
Hardware
Next, there were a series of hardware issues I encountered. In all, I wiped two operating systems and installed Ubuntu 18.04 three times in three months on two machines.
In July, I received a Helium Grant. I used the funding to finally get reliable hardware. This was pivotal in completing the project, as I was able to screen-share and pair-programme with my mentors with video conferencing. Without the support of Nadia Eghbal and the great sponsors at heliumgrant.org, my experience would have been a lot more painful.
We have liftoff!
These new tools make debugging a more pleasant experience for the user. They help users to reason better about code and break larger problems into smaller ones. More importantly, they give the user more control, so that their intentions are interpreted more precisely, giving a better feedback loop between the user and the programme.
“Imagination will often carry us to worlds that never were. But without it we go nowhere.” - Carl Sagan
Far away from Earth, the astronaut looked back. Earth was just a pale, blue dot in a sea of stars. I hope you enjoyed this journey through Time and Space with me, and that it has brought you as much joy as writing Haskell has for me this summer.
Last but not least
- If you’d like to learn more about the nuts and bolts, feel free to look at the Pull requests here.
- Thank you also to the previous work by Eric Roberts in Summer of Haskell, and to the organizers of BayHac (an event at which I was able to meet my mentors in person). Thank you for Haskell.org, my host organization, for giving me the opportunity to promote and use Haskell this summer.
- Finally, thank you to my two mentors, Chris Smith and Gabriel Gonzalez, for your guidance and patience, and for a great Summer. | https://medium.com/@krystal.maughan/breaking-the-space-time-barrier-with-haskell-time-traveling-and-debugging-in-codeworld-a-google-e87894dd43d7 | CC-MAIN-2020-29 | refinedweb | 1,348 | 62.58 |
Hello all. I have a very simple exercise to do. On notepad, I create a file called filelab.txt. The only thing in this file is the sentence "C++ is fun" (without the quotes, just the sentence). So what I'm supposed to do is: Read in each letter(from the file) separately, and then display (on the screen) as it is read in from the file, stopping at "n".
2 conditions:
1) Do not use a loop to read.
2) I must use classes.
I have finished this problem, and it works fine, but without classes. I'm not really sure how to do it with classes.
Here's the code:
now my questions are:now my questions are:Code:
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
int main ()
{
ifstream infile("A:filelab.txt", ios::nocreate); //this opens up the file
char a, b, c, d, e, f, g, h;
infile >> a;
cout << a << endl;
infile >> b;
cout << b << endl;
infile >> c;
cout << c << endl;
infile >> d;
cout << d << endl;
infile >> e;
cout << e << endl;
infile >> f;
cout << f << endl;
infile >> g;
cout << g << endl;
infile >> h;
cout << h<< endl;
infile.close();
return 0;
}
1) Where would the "ifstream infile("A:filelab.txt", ios::nocreate); //this opens up the file " command go, in the source file? I don't think it goes in the main or the header file, but not sure.
2)What is the class of? All the program does is read a sentence from a file, and output to screen. So what is the class about in this case, the sentence? I'm having a hard time with this, what's the class, the object, in the problem?
Thanks for any feedback! | http://cboard.cprogramming.com/cplusplus-programming/41038-question-use-classes-printable-thread.html | CC-MAIN-2015-27 | refinedweb | 288 | 92.53 |
Help with loop label problem
Brian Joseph
Ranch Hand
Joined: May 16, 2003
Posts: 160
posted
Jun 10, 2003 09:13:00
0
I just can't seem to get any of these right:
class A { public static void main (String args[]) { int h = 0, i = 0, j = 0, k = 0; label1: for (; :wink: { h++; label2: do { i++; k = h + i + j; switch (k) { default: break label1; case 1: continue label1; case 2: break; case 3: break label2; case 4: continue label2; case 5: continue label1; } } while (++j<5); } System.out.println(h + "," + i + "," + j); } }
So a plain break in the switch statement causes the switch statement ONLY to break out, right? Then how am I to think of the labeling?
When you apply a label, is it like you are giving the loop an identifier and saying "break label" means break out of that loop, and "continue label" means move to conditional check for that loop?
[ June 10, 2003: Message edited by: Brian Joseph ]
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
posted
Jun 10, 2003 09:51:00
0
The simplest explanation I can give is that a break or continue statement will cause the
enclosing context
to terminate abruptly. That means that, if the break or continue statement is found within a for loop, it causes that for loop to terminate, if it's found within a switch statement, the switch statement terminates.
Of course, there is a slight difference between the two. Break causes the enclosing context to terminate abruptly and execution continues after that context. Continue, on the other hand, causes the enclosing context to terminate the
current loop
and continues in the next iteration of the enclosing context. (Note that continue statements are generally only used in loops, switch statements will almost always use a break statement.)
Ok, so what about labelled breaks and continues. Let's take a look at this example code:
public class Test { public static void main(String[] args) { outer: for ( int i = 0; i < 10; i++ ) { System.out.println("i = " + i); inner: for ( int j = 0; j < 10; j++ ) { System.out.println("j = " + j); if ( j == i ) { //break; // 1 //break inner; // 2 //break outer; // 3 //continue; // 4 //continue inner; // 5 //continue outer; // 6 } } } } }
What would be the output from uncommenting lines 1 through 6? Let's look at a couple of them.
If we use line 1, we have an unlabelled break statement. That means that the immediately enclosing context will terminate abruptly. What's the immediate closing context? That would be the inner loop that uses j as a counter. In order to find the immediately enclosing context, just trace back until you find a loop or switch statement in the code. Therefore, usign this line produces output like this:
i = 0 j = 0 i = 1 j = 0 j = 1 i = 2 j = 0 j = 1 j = 2 i = 3 ...
What happens if we use line 2 instead of line 1? Well, now we terminate the context with the matching label. In this case, the context with the matching label is the inner loop, which is also the immediate enclosing context. Therefore, line 2 produces the same output as line 1.
How about line 3? Now, we abruptly halt the matching context, but that context is the outer loop, rather than the inner loop. Therefore, we get this output:
i = 0 j = 0
Try out the continue statements on your own and, if you have more questions, please let me know.
I hope that helps,
Corey
SCJP Tipline, etc.
Brian Joseph
Ranch Hand
Joined: May 16, 2003
Posts: 160
posted
Jun 11, 2003 12:38:00
0
Thanks Corey!
The only thing left in terms of labels is where can they go? Is it true that they can only be directly above the loop constructor or on the same line as the loop construct?
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
posted
Jun 11, 2003 15:31:00
0
Yes, that's right. If you tried to put them elsewhere, you'd get a compiler error indicating an unknown label or something to that effect.
subject: Help with loop label problem
Similar Threads
Dan's Exam on Flow control
Regarding Continue Keyword
Break and continue inside the case statement
pls consider this program i don't know how h value is incremented in Label1:
compile time error
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/242135/java-programmer-SCJP/certification/loop-label | CC-MAIN-2015-32 | refinedweb | 751 | 67.49 |
Labels, Textboxes and Buttons
You will construct a form-based program to play the ancient game of Nim. In the game of Nim, 2 players would remove objects from a pile in alternating moves. The player could remove 1, 2, or 3 objects at a time. The player who is forced to remove the last object from the pile loses the game.
The game that you will implement will have the players remove integer values of 1, 2, or 3 from a total value. Initially when the game is started, the total value will be 21. The player who is forced to remove the last value, making the total 0, loses the game.
Create the form shown below. Initially, the two textboxes for number entry, and the Play button, will be disabled.
When the Start button is pressed, the program will randomly select the player to make the first play. Enable the textbox for the selected player, and the set the focus (for input) to that textbox. The Start button will be disabled until the game is over. The selected player will enter an integer value of 1, 2 or 3. If a non-integer string was entered, or a value outside the range of 1, 2 or 3 was entered, a MessageBox will be used to display an error message. Also, if the value entered by the user exceeds the current total, an error message will be shown using a MessageBox. The value entered by the player will be deducted from the current total value. After each player has entered a value, that player's textbox will be cleared then disabled and the next player's textbox will be enabled and given the focus. After each move, the current total will be checked to determine if it has reached zero. When the current total reaches zero, the player who made the last move loses the game. A label will be used to display who is to make the next play, and the winner of game.
I know the instruction is very long, and i am sorry for that.
My problem in this programming is that i could not switch from player 1 to player 2.
i want to go randomly select either player 1 or 2 after pressing the "Start" Button, i just don't know how put in my code.
So far i have this: namespace ICA2___Kristian_V { public partial class Form1 : Form { int i_Play = 0; //Player 1 or 2 int m_Total = 21; //Starting Number of the Game public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { BTn_Play.Enabled = false; TBx_P1.Enabled = false; TBx_P2.Enabled = false; } private void BTn_Start_Click(object sender, EventArgs e) { BTn_Start.Enabled = false; BTn_Play.Enabled = true; TBx_P1.Enabled = true; TBx_P2.Enabled = true; } private void BTn_Play_Click(object sender, EventArgs e) { i_Play = int.Parse(TBx_P1.Text); m_Total = m_Total - i_Play; LBl_CNum.Text = m_Total.ToString(); if ((i_Play < 1) || (i_Play > 3) || (i_Play > m_Total)) { MessageBox.Show("Error: You must play 1, 2, 3 or less than the total.", "ICA 2 - Nim", MessageBoxButtons.OK, MessageBoxIcon.Error); TBx_P1.Enabled = true; TBx_P1.Focus(); TBx_P2.Enabled = false; } else { TBx_P1.Enabled = false; TBx_P1.Focus(); TBx_P2.Enabled = true; } } } } | https://www.daniweb.com/programming/software-development/threads/381089/game-of-nim-using-windows-form-application | CC-MAIN-2021-31 | refinedweb | 521 | 66.84 |
RSS 2.0 specification
This document provides guidelines for the creation of an XML product data feed in the RSS 2.0 format. We've linked standard attributes to their respective sections in the official RSS 2.0 specification to assist you in finding additional information about the components from our examples. Although we provide examples of RSS 2.0 files, we provide minimal details about RSS 2.0 itself. If you are interested in learning more about this standard, we suggest looking over this specification at.
To download a RSS 2.0 example file, click here.
Section 1: RSS 2.0
Based on the RSS 2.0 specification, there are three pre-defined elements at the item level - title, link, and description. Although these elements are optional in the RSS 2.0 standard, product data feeds require them.
Product data feeds also require additional elements such as price, id, and condition. To include these elements and more detailed information about an item, we've extended RSS 2.0 by adding the Google Merchant Center feed namespace. Defining the Google Merchant Center namespace allows you to use additional elements, called "attributes", and increases the amount of information you can provide about each item in a feed.
Below is an example of a basic RSS 2.0 document containing a single item:
<rss version="2.0"
xmlns:
>
</item> </channel> </rss>
The two major additions in this example are the addition of the namespace declaration (xmlns:g="") and the inclusion of four attributes (image_link, price, condition, andid). RSS Shopping ads an XML product data feed. While we accept feeds containing other elements defined in the RSS 2.0 standard or in your own namespace, any information these elements contain will be ignored during processing and will not appear in your listings. At this time we will only process data contained in the default RSS 2.0 elements and in attributes within the Google Merchant Center and Custom Google Merchant Center namespaces. | https://support.google.com/merchants/answer/160589 | CC-MAIN-2019-26 | refinedweb | 329 | 58.89 |
How to fix React Error: Rendered fewer hooks than expected
Confused about this error? So was I. Let’s solve it.
If you’re getting this error, there’s a couple of things you can try right away to fix it.
I was able to solve this problem by using component syntax instead of function syntax. I‘m not sure why, but it fixed my problem.
TLDR;
- Only call hooks from the top level of a component, and never put them in conditional statements.
- Make sure you only call hooks from within a React Component.
- Further, pass the component around using Component syntax
<MyComponent />instead of calling the function component directly
myComponent()!
First, double check that you’re not calling hooks within a conditional statement. The Hooks documentation makes clear that we are to use hooks at the top of our components, and without nesting them within conditionals.
This is the first, most obvious, issue which can cause the Rendered fewer hooks than expected error.
export default function ListView({history, match}) {
const filter = match.params.filter
let [items, maxPages] = useTopStories(filter, page)// don't use hooks within a conditional statement!
if (filter === 'jobs') {
const [jobs, setJobs] = useState([])
}
//...
}
Once I was certain I wasn’t making the above mistake, I had to dig around to figure out what else could be rendering fewer hooks than React was looking for.
The Problem
In my code, I was using a Comment function component recursively, mapping over a list of top level comments, and then mapping over each child reply and the reply’s children. The comment component itself looked like this:
export default function Comment({id}) {
const { by, time, text, kids = [] } = useItemSubscription(id)
const [showComments, setShowComments] = useState(true)
return (
<div key={id}>
<div className="text">
{ text && text }
</div>
{
kids.length ? kids.map(id => Comment({id})) : null
}
</div>
)
}
I kept getting the “Rendered fewer hooks than expected” error and was quite frustrated. Eventually, I found this github issue on the React repo discussing it.
The maintainers mentioned “Only call hooks from within React Components, no regular functions.”
Which perplexed me. As I understand it, my Comment function is most certainly a react component. It takes props, it returns JSX. So what gives?
Well, honestly, I’m still not really sure. But I did figure out how to fix it, and maybe someone can help fill in my understanding?
Solution
What I did was: instead of using my functional components like functions, I had to use them like components. I’m not at all clear as to why this is important, but here is my converted code which works:
export default function Comment({id}) {
const { by, time, text, kids = [] } = useItemSubscription(id)
const [showComments, setShowComments] = useState(true)
return (
<div key={id}>
<div className="text">
{ text && text }
</div>
{
kids.length ? kids.map(id => <Comment id={id} />) : null
}
</div>
)
}
Above, all I’m doing is using a different syntax for the component. Instead of using the function syntax, where I am calling my functional component which returns JSX (aka a react component), I’m using the component syntax (I guess thats what it’s called?).
My Theory
To back up a little bit, I’m not totally in the dark as to what was happening. Let me show you a little more of my component tree so you can see for yourself.
Below is the Item component which was using the comment component to begin with:
export default function Item({match}) {
const id = match.params.id
const { title, by, url, score, time, text, kids = [], descendants} = useItemSubscription(id)
return (
<div>
<ItemHeader>
// ... omitted
</ItemHeader>
<ItemComments>
{
kids.length ?
kids.map(id => Comment({id})) : null
}
</ItemComments>
</div>
)
}
As you can see, I’m using the function format here, not the component format. After testing, I found that as long as one of these two components (Item or Comment) is using the component syntax, instead of function syntax, then it works fine.
What doesn’t work though, is using a function call at the top level (Item component), and a function call at the recursive level (Comment component). It’s simple enough to just make them all component syntax, but I was perplexed by this. They’re both functional components, they both take props and return JSX, so what’s going on here?
I’m not too sure, but would love to find out. It seems to me that React doesn’t see that the first level is a component, likely because all these maps are running before the component finished mounting, and maybe at that point React just doesn’t see that the hooks are being called from within a component.
Since Hooks are in such an early stage (I’m on v16.7.0-alpha), things are likely to change soon, so I’m not too concerned about understanding this perfectly right now. For all I know things will work differently in a month.
For now, I’ll be using
<Component value={value} /> syntax instead of function syntax
Component({id}) when dealing with React hooks!
If this helped you, please give it some claps so others can find it as well! | https://medium.com/@jonchurch/how-to-fix-react-error-rendered-fewer-hooks-than-expected-e6a378985d3c?source=user_profile---------0---------------------------- | CC-MAIN-2022-27 | refinedweb | 850 | 63.19 |
Sorting is one of the most basic and useful functions applied to data. It aims at arranging data in a particular fashion, which can be increasing or decreasing as per the requirements. There is a builtin function in C++ STL by the name of ‘sort()’ which allows us to perform sorting algorithm easily. In this article we will be exploring Sort Function In C++,
Following Pointers will be covered in this article:
- Sort() function
- Example- To sort data in ascending order
- Example – To sort data in descending order
- Partial_sort
Moving on with this article on Sort function in C++
Sort() function
It is a built-in function of algorithm header file it is used to sort the containers like an array, vectors in a specified order. Internally this function is implemented as Quick-sort
Quicksort is a divide and conquer algorithm. Quicksort first divides a large list of elements into two smaller sub-lists: the lower elements and the higher elements. Quicksort then recursively sort the sub-lists.
The steps are as follows:
1. Pick a random element(usually the last element), called a pivot, from the list.
2. Reorder the list in a way such that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it and equal values can go either way this is process is called partition operation.
3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements, again select a pivot in sub-list and divide them.
The base case of the recursion is lists of size zero or one, which never need to be sorted and thus by combining them we sort our list.
Quicksort is faster in practice than other O(n log n) algorithms such as Insertion Sort or Bubble sort. Quicksort can be implemented with an in-place partitioning algorithm which means the entire sort can be done with only O(log n) additional space. Quicksort is not a stable sort.
Its complexity is as follows:
Best Case – O(n log n)
Worst Case – O(n^2)
Average Case – O(n log n)
Syntax:
sort(first, last);
Here,.
Return value
None
Complexity
The average of a sort complexity is N*log2 (N), where N = last – first.
Data range
The object in the range [first, last) are modified.
Exceptions
The overloads with a template parameter that is named as ExecutionPolicy report errors as follows:
If the algorithm fails to allocate memory, std::bad_alloc is thrown as an exception.
If the execution of a function invoked as part of the algorithm it throws an exception std::terminate.
Moving on with this article on Sort function in C++
Example – To sort data in ascending order:
#include <bits/stdc++.h> using namespace std; int main() { int array[] = {10, 35, 85, 93, 62, 77, 345, 43, 2, 10}; int n = sizeof(array)/sizeof(array[0]); // 'sizeof' gives the size of total array i.e. size of each character * no. of characters // so to get no. of characters // we divide the sizeof(array) with the size of any one character of the array // here it is array[0] sort(array, array+n); cout << "nArray after sorting using " "default sort is : n"; for (int i = 0; i < n; ++i) cout << array[i] << " "; return 0; }
Output :
Explanation
From the above example, we see that sort() function by default sorts an array in ascending order.
Moving on with this article on Sort function in C++
Example – To sort data in descending order:
To sort the data of array in descending order we need to introduce a third parameter that is used to specify the order in which elements are to be sorted. We can use “greater()” function to sort the data in descending order.
#include <bits/stdc++.h> using namespace std; int main() { int array[] = {41, 53, 4, 459, 60, 7, 23, 4, 232, 10}; int n = sizeof(array)/sizeof(array[0]); sort(array, array+n, greater<int>()); cout << "Array after sorting : n"; for (int i = 0; i < n; ++i) cout << array[i] << " "; return 0; }
Output:
data-src=
Explanation
Here sort() function does a comparison in a way that puts greater element before.
Moving on with this article on Sort function in C++
Partial_sort
C++ STL provides us with a partial sorting function, the function is similar to sort() function but unlike the sort() function it is not used to sort the entire range rather it is used to sort only a sub-part of it. It sorts the elements in the range of [first, last), in such a way that the elements before middle element are sorted in ascending order, whereas the elements after middle are left as it is.
It can be used to find the largest element if we use a function object to sort for the first position
Example
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> vec = { 10, 45, 60, 78, 23, 21, 30 }; vector<int>::iterator iptr; partial_sort(vec.begin(), vec.begin() + 1, vec.end(), greater<int>()); iptr = vec.begin(); cout << "The largest element is = " << *iptr; return 0; }
Output:
data-src=
Explanation:
The above code can be used to find the greatest number in a series, to find the smallest number in series we just need to remove the greater<int> command.
Thus we have come to an end of this article on ‘Sort Function in. | https://www.edureka.co/blog/sort-function-in-cpp/ | CC-MAIN-2019-35 | refinedweb | 906 | 55.27 |
Serial tutorial
More than you ever wanted to know about serial communications with the Particle Photon and Electron.
Updates to this document are here: [] ()
USB serial
The USB serial provides a way for the Photon/Electron to send data to the computer across the USB connection. Often this is used for debugging messages.
For example:
int counter = 0; void setup() { Serial.begin(9600); } void loop() { Serial.printlnf("testing %d", ++counter); delay(1000); }
The
Serial.begin(9600); call initializes the serial port. When you’re using the USB serial, the value doesn’t actually matter. Sometimes you’ll see
Serial.begin(115200); but it really runs at the same fast speed regardless.
The
Serial.printlnf prints a formatted string to the debugging USB serial.
The [documentation for Serial is here] ()." testing 1 testing 2 testing 3 testing 4 testing 5 testing 6
Particle Dev (Atom IDE)
Select Show Serial Monitor in the Particle menu if the Serial Monitor is not showing. Make sure you have the correct port select and click Connect.
Note that you can write stuff to the serial port in Particle Dev, but you must do so in the Enter string to send box, it’s not like a regular terminal emulator where you type in the same place where stuff is being printed out.
Arduino IDE
Select the port from the Port hierarchical menu in the Tools menu.
Then select Serial Monitor from the Tools menu.
You can send data via serial with the Ardiuno IDE as well, but you need to enter text to send in the box at the top of the window and press Return or click Send.
Windows - using PuTTY or CoolTerm - using screen.
Linux - using screen.
Android phone or tablet with USB OTG
If your Android phone supports USB OTG (“on the go”) and you have an OTG adapter cable, you may be able to use it for debugging serial! One caveat is that your phone probably won’t power up a Photon, so this will probably only work if you have an external power source, like an Electron or Photon with a battery.
Install the “Android USB Serial Monitor Lite” application from the Google Play store.
Connect the device to your phone using a USB cable and a USB OTG adapter.
Open the serial monitor app and it should ask if you want to connect to the device. Tap yes and you should see a screen in the picture above.
Configuration using USB Serial
If the Photon is in listening mode (blinking dark blue), configuration can also be done using the USB Serial port. Each of these commands only requires that you type the command letter (case-sensitive):
- i - Prints the device ID (24 character hexadecimal string)
- f - Firmware update (using ymodem)
- x - Exit listening mode
- s - Print system_module_info
- v - System firmware version
- L - Safe listen mode (does not run user code concurrently with listening mode)
- w - Configure Wi-Fi
- m - Print MAC Address for the Wi-Fi adapter
Listening mode is the default when you plug in a Photon the first time. You can also get into listening mode by holding down SETUP for about 3 seconds until the status LED blinks blue.
The commands other then the last two Wi-Fi related commands are also available on the Electron.
Changing operating modes with USB Serial
Normally you press buttons to enter listening or DFU mode on the Photon or Electron. You can also trigger it by making a USB Serial connection at a specific baud rate.
For example, on the Mac you can use this command to enter DFU mode:
stty -f /dev/cu.usbmodemFD1141 14400
(The device name, cu.usbmodemFD1141 in this example, may be different on your computer.)
The special baud rates are:
- 14400 DFU mode (blinking yellow)
- 28800 Listening mode (blinking dark blue)
UART Serial
When connecting to an actual serial device, you’ll be using one of the UART hardware serial ports. The Photon has one† and the Electron has three UART serial ports.
All of the devices have the
Serial1 object, the main UART serial port, on the RX and TX pins.
- RX means serial data received into the device
- TX means serial data transmitted from the device
When you connect a Photon another device, say an Arduino, the RX pin on the Photon always gets connected to the TX pin of the Arduino and vice versa. This is always the case, even if you connect two Photons by serial.
† The Photon actually has two and the Electron four UART serial ports. The catch is that Serial2 is on the same pins as the RGB status LED. Using it requires soldering and disabling the status LED, which will make troubleshooting your device very difficult. It’s a complicated enough topic that it has its own tutorial.
Additional ports on the Electron
The Electron has two additional UART serial ports that you can use, Serial4 and Serial5.
- C0 Serial5 RX
- C1 Serial5 TX
- C2 Serial4 RX
- C3 Serial4 TX
If you need Serial4 or Serial5 you’ll need to enable the port by adding one or both of these includes near the top of your main source file:
#include "Serial4/Serial4.h" #include "Serial5/Serial5.h"
Serial logic levels
The Photon and Electron are 3.3V serial devices that are 5V tolerant. When transmitting data, logic 1 values are 3.3V and logic 0 values are 0V, so we list the port as being 3.3V.
Many 5V serial devices will correctly respond to 3.3V values as logic 1 even though it is out-of-spec. Likewise, the Photon doesn’t mind having 5V levels for logic 1 on the RX pins. So you often can connect a Photon directly to a 5V serial device, like an Arduino. This is often referred to as “TTL serial” as it uses the 5V logic levels used by TTL (transistor-transistor logic) devices.
One thing that you absolutely must never do is connect a Photon directly to a computer or other device using an actual RS232 interface. A converter is required and is described in the next section.
Interfacing to RS232 devices
Actual RS232 devices, such as old computers, newer computers with an adapter, and various external hardware devices likely use “real” RS232 signal levels, which can range between +15V and -15V. This will cause immediate, permanent damage to the Photon or Electron if connected directly.
A TTL serial to RS232 adapter board is typically used in these cases. They are available from places like [SparkFun] (). You can also find them on eBay, search for “TTL RS232 breakout”.
Make the following connections:
- Converter VCC to Photon 3V3 (red)
- Converter GND to Photon GND (black)
- Converter TX-O to Photon TX (green)
- Converter TX-I to Photon RX (blue)
Note that TX and RX don’t cross here, between the Photon and the converter, because they’re crossed in the RS232 serial cable DCE to DTE connection.
Connectors
Two different connectors are used for RS232 serial, the DB9 and the DB25. The DB25, a “D” shaped 25-pin connector was the original connector but IBM PC compatible computers mostly settled on the smaller DB9 connector. The DB9 is also referred to as a DE9 connector.
This is a close-up of the DB9 female connector on the [SparkFun] () converter board.
DTE/DCE
Serial devices are either DTE (data terminal equipment) or DCE (data communication equipment). These names come from the early days of dumb terminals (DTE) connected to modems (DCE). It doesn’t entirely matter which device is which, but if you have to connect two like items (say DTE to DTE) you need a null modem adapter that crosses the TX and RX lines (among others).
Typically DTE devices have a male connector. Pin 2 is an input and pin 3 is an output.
Likewise, DCE devices typically have a female connector. Pin 2 is an output and pin 3 is an input.
The Sparkfun board has a female DB9 and makes the Photon a DCE. This makes sense because most computer serial ports are DTE.
Baud rate, bits, parity, and stop bits
There are four configuration parameters for serial, and you must make sure they’re all set correctly, otherwise communication will often fail, either with no data or garbage characters received.
The baud rate is the speed that data is sent. A common value is 9600. The valid values for the Photon and Electron are 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, and 115200. Neither device can use speeds under 1200 (such as 300 or 600).
The number of bits per byte is typically 8. It’s occasionally 7 or 9. There is limited support for 9 bit in system firmware 0.5.0 and later, and full support for 7 and 9 bit in 0.6.0 and later.
The parity is a method of detecting errors in the data. It can be none (“N”), odd (“O”) or even (“E”). Support for parity is included in 0.5.0 and later.
The number of stop bits is 1 or 2. Support for stop bit setting is included in 0.5.0 and later.
The last three things are typically combined into a single string, for example “8N1” means 8 bits, no parity, 1 stop bit. “7E1” means 7 bits, even parity, 1 stop bit. And so on.
The available values are:
- SERIAL_7E1
- SERIAL_7E2
- SERIAL_7O1
- SERIAL_7O2
- SERIAL_8N1
- SERIAL_8N2
- SERIAL_8E1
- SERIAL_8E2
- SERIAL_8O1
- SERIAL_8O2
- SERIAL_9N1
- SERIAL_9N2
You use these with the Serial.begin call, for example:
Serial1.begin(9600, SERIAL_9N1);
Flow control
There are two types of flow control in serial: hardware (RTS/CTS) and software (XON/XOFF).
The Photon does not support hardware flow control (RTS/CTS). The Electron does not currently support hardware flow control.
Neither the Photon or Electron support software (XON/XOFF) flow control, either. In some limited cases, you could note when you receive XOFF (Ctrl-S) in your received data and stop sending, however there is currently no way to stop the send FIFO from sending, so this will only work when you don’t have any data waiting to be sent.
Communicating with an Arduino
Here’s an example of using serial to communicate between an Arduino (Uno, in this case) and a Photon.
- Photon TX connects to Arduino RX (0) (green wire)
- Photon RX connects to Arduino RX (1) (blue wire)
- Photon GND connects to Arduino GND (black wire)
Remember: RX and TX always cross, and you must have a common GND connection.
This is a rather silly example: Every 2 seconds the Photon sends a number to the Arduino by UART serial. The Arduino parses this number, increments it, and sends it back. The Photon prints it out via the debugging serial.
Remember that serial is a byte-oriented protocol, so we keep reading bytes until we find a character that marks the end of the transmission. I selected the new line character ("\n").
Arduino code:
// Constants const size_t READ_BUF_SIZE = 64; // Forward declarations void processBuffer(); // Global variables char readBuf[READ_BUF_SIZE]; size_t readBufOffset = 0; void setup() { // Serial TX (1) is connected to Photon RX // Serial RX (0) is connected to Photon TX // Ardiuno GND is connected to Photon GND Serial.begin(9600); } void loop() { // Read data from serial while(Serial.available()) { if (readBufOffset < READ_BUF_SIZE) { char c = Serial.read(); if (c != '\n') { // Add character to buffer readBuf[readBufOffset++] = c; } else { // End of line character found, process line readBuf[readBufOffset] = 0; processBuffer(); readBufOffset = 0; } } else { readBufOffset = 0; } } } void processBuffer() { int receivedValue = atoi(readBuf); // This program just increments the value sent by the Photon and returns it Serial.print(receivedValue + 1, DEC); Serial.print('\n'); }
Photon code:
#include "Particle.h" // Constants const unsigned long SEND_INTERVAL_MS = 2000; const size_t READ_BUF_SIZE = 64; // Forward declarations void processBuffer(); // Global variables int counter = 0; unsigned long lastSend = 0; char readBuf[READ_BUF_SIZE]; size_t readBufOffset = 0; void setup() { Serial.begin(9600); // Serial1 RX is connected to Arduino TX (1) // Serial2 TX is connected to Arduino RX (0) // Photon GND is connected to Arduino GND Serial1.begin(9600); } void loop() { if (millis() - lastSend >= SEND_INTERVAL_MS) { lastSend = millis(); Serial1.printlnf("%d", ++counter); Serial.printlnf("Sent to Arduiuno: %d", counter); } // Read data from serial while(Serial1.available()) { if (readBufOffset < READ_BUF_SIZE) { char c = Serial1.read(); if (c != '\n') { // Add character to buffer readBuf[readBufOffset++] = c; } else { // End of line character found, process line readBuf[readBufOffset] = 0; processBuffer(); readBufOffset = 0; } } else { Serial.println("readBuf overflow, emptying buffer"); readBufOffset = 0; } } } void processBuffer() { Serial.printlnf("Received from Arduino: %s", readBuf); }
Sample output:
$ particle serial monitor Opening serial monitor for com port: "/dev/cu.usbmodemFD1161" Sent to Arduiuno: 1 Received from Arduino: 2 Sent to Arduiuno: 2 Received from Arduino: 3 Sent to Arduiuno: 3 Received from Arduino: 4 Sent to Arduiuno: 4 Received from Arduino: 5
More Code Tips
Some additional helpful tips:
Process all available characters
You should process all available serial characters in each call to loop. In other words, don’t do this, using an if statement. Use a while, instead.
void setup() { Serial.begin(9600); Serial1.begin(9600); } void loop() { // Don't do this! Use a while loop instead of an if to make sure all // of the data is processed in each call to loop if (Serial1.available()) { Serial.write(Serial1.read()); } }
The reason is that loop may be called at most 1000 times per second, and often fewer, so it’s possible to fall behind faster serial speeds unless you handle all of the outstanding bytes at once.
Avoid delay in loop
When processing serial data, make sure you don’t block the loop. One obvious way to do this is using delay, but there are other more subtle ways.
For example, if you wanted to do something once per second while handling serial data, you should not do this:
#include "Particle.h" void setup() { Serial.begin(9600); Serial1.begin(9600); } void loop() { while (Serial1.available()) { Serial.write(Serial1.read()); } // Don't do this! delay(1000); Serial.println("called once per second"); }
The problem is that serial data won’t be handled during the 1 second long delay, which could cause data to be lost.
Instead you could do this:
unsigned long lastTime = 0; void setup() { Serial.begin(9600); Serial1.begin(9600); } void loop() { while (Serial1.available()) { Serial.write(Serial1.read()); } if (millis() - lastTime >= 1000) { lastTime = millis(); Serial.println("called once per second"); } }
This allows loop to run freely, and still only execute some code once per second.
Reading lines of data
Serial is a byte or character-oriented method for transferring data. The hardware assures that you will always receive a character at a time; you’ll never get half a character, for example.
For convenience, data may be grouped into lines of characters. The Ardiuno example, above, read a line at a time. Even if you’re expecting a line of data, there is no guaranteed that all of your data will arrive at once. In fact, it’s quite likely that it won’t and you will have to write your code to handle that.
One easy way to do this is to use readStringUntil. For example:
void setup() { Serial.begin(9600); // Wait up to 10 seconds for a line to arrive Serial.setTimeout(10000); } void loop() { String s = Serial.readStringUntil('\n'); Serial.printlnf("got %s", s.c_str()); }
This is great only if you have nothing to else to do in your loop. The call may block for up to 10 seconds (as configured here), which may be unacceptable for some applications. In that case, you may prefer to do this manually, so the loop runs freely:
// Constants const size_t READ_BUF_SIZE = 64; const unsigned long CHAR_TIMEOUT = 10000; // Global variables char readBuf[READ_BUF_SIZE]; size_t readBufOffset = 0; unsigned long lastCharTime = 0; void setup() { Serial.begin(9600); } void loop() { // Read data from serial while(Serial.available()) { if (readBufOffset < READ_BUF_SIZE) { char c = Serial.read(); if (c != '\n') { // Add character to buffer readBuf[readBufOffset++] = c; lastCharTime = millis(); } else { // End of line character found, process line readBuf[readBufOffset] = 0; Serial.printlnf("got: %s", readBuf); readBufOffset = 0; } } else { Serial.println("readBuf overflow, emptying buffer"); readBufOffset = 0; } } if (millis() - lastCharTime >= CHAR_TIMEOUT) { lastCharTime = millis(); readBuf[readBufOffset] = 0; Serial.printlnf("got timeout: %s", readBuf); readBufOffset = 0; } } | https://community.particle.io/t/serial-tutorial/26946?source_topic_id=19446 | CC-MAIN-2018-17 | refinedweb | 2,700 | 56.05 |
Hi,
maybe I’m missing sth obvious but there does not seem to be an “append()” method for nn.Sequential, cos it would be handy when the layers of the sequential could not be added at once.
Or it would be equivalent if I first added all the layer I need into a ModuleList then there’s a method for directly converting all the modules in a ModuleList to a Sequential.
Thanks in advance!
You can first construct a python list of nn.Modules and unpack it into a nn.Sequential
nn.Modules
nn.Sequential
import torch.nn as nn
modules = []
modules.append(nn.Linear(10, 10))
modules.append(nn.Linear(10, 10))
sequential = nn.Sequential(*modules)
Ah that’s neat, thanks
Great example here:
Thanks a lot! That’s really helpful! | https://discuss.pytorch.org/t/append-for-nn-sequential-or-directly-converting-nn-modulelist-to-nn-sequential/7104 | CC-MAIN-2017-47 | refinedweb | 132 | 70.5 |
Kubernetes has become the de-facto tool for container orchestration and has a solid community. The whole cloud-native era began with the evolution and Kubernetes and is still growing. As a result, Kubernetes is not just popular but has become a way of deploying applications to make sure they are highly available and scalable. The developer community is focused on this tool, and every day, many companies use Kubernetes to safely deploy their applications to production. Since it has become the talk of the cloud-native town, we thought to show you how you can easily use Kubernetes to deploy a simple python application.
Pre-requisites:
- Download and install Python 3 from the official website
- Install Fastapi with the command
pip install fastapi
- You will also need an ASGI server for production such as Uvicorn, install it with the command
pip install "uvicorn[standard]"
- Have access to the Kubernetes cluster to deploy our application. You can also use Minikube or Kind.
Tutorial:
Assuming you know the concepts of Kubernetes, we will go straight to writing a simple python application. First, create a very basic python app in Fastapi. What is Fastapi? According to their own website, ‘FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.’
Copy the below code into the
main.py file,
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
You can run the server with the following command,
uvicorn main:app --reload
You should see the following output when you visit the
Create a Dockerfile for this app to run as a container.
FROM python:3.8.10 COPY requirements.txt / RUN pip3 install -r /requirements.txt COPY . /app WORKDIR /app ENTRYPOINT ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8500", "--reload"]
Create a
requirements.txt file and include the two libraries as dependencies.
Build the application as an image locally first with the following command,
docker build -t simple_app .
Tag the image and push the image to Docker Hub with the following commands,
docker tag simple_app:latest [dockerhub username]/simple_app:latest
docker push [dockerhub username]/simple_app:latest
Create Kubernetes manifest files to deploy and expose the application as a service.
Create a
deployment.yaml file at the root of the application, and add the following code/manifest specifications,
apiVersion: apps/v1 kind: Deployment metadata: name: simple-deployment labels: app: simple-app spec: replicas: 1 selector: matchLabels: app: simple-app template: metadata: labels: app: simple-app spec: containers: - name: fastapi image: docker hub username/simple_app:latest ports: - containerPort: 8500
Create
service.yaml file and add the following code/manifest specifications,
apiVersion: v1 kind: Service metadata: name: simple-service labels: app: ecommerce spec: selector: app: simple-app type: LoadBalancer ports: - port: 8500 targetPort: 8500
Next, apply the kubectl commands to deployment and service yaml files.
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
Then, go and check the pods running healthily and properly as expected with the command
kubectl get pods.
Now, it's time to see our application exposed to the external world.
Use the command
kubectl get svc
You will see the external IP exposed and we can use it to see our application running.
curl 192.168.0.107:8500
{"Hello":"World"}
Add a simple test configuration to test the application.
You can easily use Harness to continuously integrate and deploy any applications with simple steps and configurations.
For the sake of simplicity and as per today’s trend, we have considered Kubernetes deployment as an example. We have used the GCP Kubernetes cluster and that is where our deployment is going to happen. You can choose your favourite cloud provider to create a Kubernetes cluster to deploy the app.
Harness has a pretty sleek UI and can easily help developers do CI/CD effortlessly. Once you sign-up at Harness, select the Try NextGen tab and you will be presented with the new CI/CD experience and capabilities. Start with the module you like, we will be selecting Continuous Integration and Continuous Delivery in our case. First, select the Continuous Integration module, add the required steps and run it before doing Continuous Delivery.
Just make sure to have all the required connectors up and running. Also, make sure you have the Delegate installed on your target cluster.
You might ask - what is Delegate and why it is required? Well, The Harness Delegate is a service/software you need to install/run on the target cluster [Kubernetes cluster in our case] to connect your artifacts, infrastructure, collaboration, verification and other providers with the Harness Manager. When you set up Harness for the first time, you install a Harness Delegate.
We will not dig deeper about Delegate in this article as it can be a separate blog in itself. For now, just know that the Delegate performs all deployment operations for you. If you want to know more about Delegate, you can read here.
I just showed you how to deploy your simple python application to Kubernetes using kubectl and Harness. We have a well-documented MERN Stack application repository that you can fork and start understanding the complete CI/CD pipeline. The code for the application is in the harnessapps/MERN-Stack-Example repository, the Kubernetes configuration is in the harnessapps/MERN-Stack-Example-DevOps repository.
Ready to get your hands-on on the Harness CI/CD?
The below-mentioned links will walk you through both Continuous Integration and Delivery.
Happy DevOpsing!
Top comments (1)
Thanks for sharing 😊 | https://dev.to/pavanbelagatti/deploying-modern-applications-using-kubernetes-and-harness-5l0 | CC-MAIN-2022-40 | refinedweb | 927 | 54.93 |
Software Design Interview Questions
- 0of 0 votes
Design an email client where you can only send emails to people who are present in your contact list. Build for only the following functionaliy
1) Send/Receive Emails
2) Add/Remove Contacts
3) See Inbox
4) See Sent Mail
- 0of 0 votes
Design a distributed LRU Cache.
- -1of 1 vote
How is design review done?
- 0of 0 votes
Design a system like github.
- 0of 0 votes
Design a Twitter-like topic system so that the most popular topics can be retrieved from the system. A post can have one or more topics and these topics can be shared by multiple posts. (hint: thinking of scalability)
- 2of 2 votes
Singleton Design pattern. How you make it double ton(in even call of getInstance() first object should be return and odd call of getInstance() second instance should be return). Make it triple ton.
- 0of 0 votes
Design a system to find top 10 twitter hashtags in the most recent 1 min, 10 min, 1 hr
- 2of 2 votes
Design a mall where there are 'm' entry gates and 'n' exit gates. There can be only 'x' number of people inside it. No more then 'x' people can be inside mall at any time.
- 0of 0 votes
Design an application for people to find a place near them where they can join a team to play their favorite sport. Exp. Soccer teams open to join that are scheduled to play at a certain time and place. The application would search for the available teams to join within certain area playing within some given time period,
-
Design garbage collector in Java
- 0of 0 votes
Design a online shipment tracking system.
- 0of 0 votes
Design an OOP concept for an application where employee can dispatch their incoming phone call according to their seniority level if they are not able to solve.
- 0of 0 votes
Design a kind of kindle fire application where we can subscribe news channel and read the news from all publishers as a digital format.
- 0of 0 votes
1) Finish writing the below method: bookReservation(Reservation reservation)
2) You are free to add, modify, etc the following classes and method) { //fill this method }
- 2of 2 votes
Design a stock market system
- -3of 3 votes
na
- 0of 0 votes
We tend to use computer to solve practical problems that actually earns or save dollars. Here is something that happens across the stock exchanges : people buy and sell stocks.
We generally use automated intelligent systems to buy and sell stocks. That part is too much mathematics, and beyond scope of this interview. There is another part. Suppose the system issues a buy order : buy 1000 Microsoft stock. Now, there are more than 1 ( in fact 10 ) active exchanges from where we can buy MSFT. There is a slight price delta, which keeps changing over time. There is another problem. In each stock exchange, prices are stacked, that is :
1. For first 100 stocks prices are 55$.
2. Next 200 stocks, prices are 55.2$.
... etc, and you got the idea. Even this stacks are changing over time.
Thus, here is the problem to solve. Design and implement a system such that one can buy n stocks with minimal price.
Also, in the same spirit, the same system should be able to sell n stocks with maximum payoff possible.
This is a non trivial problem, for Quant systems.
There are always k no of exchanges to hit.
- 0of 0 votes
As you know, every OS comes up with this tiny application called the calculator. It is good. Now, here is our problem. If we try to implement the function
def calculate( operand, operator, operand ) { /* Do Interviewers bidding here */ }
I have to write if upon if upon if upon if to do for all operators. Moreover, some operators are not even binary! Take example the abs() or say the negate()!
Bigger problem persists. With the if mode, we can not even add operators as we wish to without changing code!
But that is a sin. So, what do we do? That is question 1.
In question 2, as a software tester, how do you propose to test and automate the above? Writing more if than the developer is not allowed.
- 0of 0 votes
what would be the best way to reduce the size of image in E-commerce website having billions of images ?
- 0of 0 votes
E-commerse website having billions of items with image .What would be the best way to reduce the size of image ?will you use an API or do with HTML or use Hadoop or use simple bash script
- 0of 0 votes
Build an in-memory DB that supports many commands and transactions.
Similar to redis database (Redis.io)
-.
- 0of 0 votes
Design a Twitter feeds API. How would you actually connect it from a mobile? What happens behind the Twitter network? how do the Trends get published? From where does Twitter get the information for a particular trend(Eg: #Obama, #nfl) and publish it out? What protocol does it use? How do you connect to Twitter API? How does Twitter handle multiple connections?
- 0of 0 votes
Given start time and end time of parking (below is the table of price rule). Come up with data structure you can store these price rules
Price Rules:
On Weekday On Weekend
Hours Price Hours Price
0 – 2 $5 0 – 2 $8
2 – 6 $10 2 – 6 $13
6 – 12 $15 6 – 12 $18
12 – 24 $20 12 – 24 $25
Design an architecture for the system which shows parking spaces available near customer's location in a mobile app.
- 1of 1 vote
there is a news publishing/subscribing product of Amazon where electronic contents are collected from owners like newspaper, magazines. Customer is using kindle. Design how customer will get the content when his system kindle connects to net. how to send the contents to device? | https://careercup.com/page?pid=software-design-interview-questions | CC-MAIN-2018-39 | refinedweb | 990 | 73.78 |
Iron languages.
- Download Source from the LinqFarm
Setting up a C# Project to Call IronPython
In two previous posts I described how to install and run a simple IronPython program:
- Announcing IronPython and IronRuby releases for Visual Studio 2010 Beta 2
- Getting Started with IronPython
If you don’t already have the latest version of IronPython installed or if you need a little refresher course in writing Python scripts, then you might want to glance at these posts. Otherwise, you can just keep reading to learn how to call Python from C#.
After the IronPython installation, its interpreter and its libraries will be installed in your Program Files directory, as shown in Listing 1. The interpreter is installed in ipy.exe, where ipy is pronounced “Eye-Pie.” The interpreter remains dormant when you call Python from C#, so our focus here should be on the assemblies shown in the second half of the listing, with a particular emphasis on IronPython.dll.
Listing 1: At the command prompt you can easily see the core files that form the basis for the IronPython installation.
C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2>dir *.exe *.dll Volume in drive C has no label. Volume Serial Number is 4C6B-EE0E Directory of C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2 10/18/2009 01:47 PM 12,624 ipy.exe 10/18/2009 01:47 PM 12,624 ipyw.exe Directory of C:\Program Files (x86)\IronPython 2.6 CTP for .NET 4.0 Beta 2 10/18/2009 01:47 PM 1,433,424 IronPython.dll 10/18/2009 01:47 PM 435,536 IronPython.Modules.dll 10/18/2009 01:47 PM 875,856 Microsoft.Dynamic.dll 10/18/2009 01:47 PM 58,192 Microsoft.Scripting.Debugging.dll 10/18/2009 01:47 PM 159,056 Microsoft.Scripting.dll 7 File(s) 2,987,312 bytes 0 Dir(s) 16,881,614,848 bytes free
To run a Python script inside a C# program, you should include some or all of the libraries shown in Listing 1 in the References section of your project. To get started, choose File | New Project (Ctrl-Shift-N) from the Visual Studio 2010 menu and create a new console application. Then open the Solution Explorer (Ctrl-W, S) and go to the References section for your project. Right click and choose Add Reference. Take a moment to appreciate how quickly the Add References dialog appeared (the team worked hared on this performance improvement), and then select the Browse tab and navigate to the directory where IronPython resides. The path to the directory hosting IronPython will probably be similar to the one shown in Listing 1. For now, the simplest choice is to select all the assemblies found in that directory, as shown in Figure 1. If you wish to keep things simple, then you only need to select IronPython.dll, Microsoft.Dynamic.dll and Microsoft.Scripting.dll to compile and run the program shown in this example.
Figure 1: Using the Add References dialog to select the assemblies found in that directory.
When you are done, the IronPython libraries should appear in the References section of the Solution Explorer, as shown in Figure 2.
Figure 2: The References node of the Solution Explorer for a C# program that calls an IronPython script.
Writing the Code for Calling IronPython
Now that you have your project set up correctly you need to do two things:
- Write or find a script containing Python code that you want to run
- Write C# code to call the script.
Listing 2 shows a very simple IronPython script that contains a single method called Simple() that writes a few strings to a console window. Save this script to a file called Test.py, and add it to your project, as shown in Figure 2. There are several ways to do this. One is to right click on your project in the Solution Explorer, and choose Add | New Item. Add a text file, and call it Test.py. Click on the new node when it is added to your project, and set its Copy to Output Directory property to Copy Always. If the Properties window is not visible, you can bring it up by selecting Ctrl-W, P.
Listings 3a and 3b show the C# code for calling the script, and Listing 4 shows the output from the C# program that hosts the script.
Listing 2: A Simple Python script stored in a file called Test.py. This code prints out some basic information about the environment in which Python is running.
import sys def Simple(): print "Hello from Python" print "Call Dir(): " print dir() print "Print the Path: " print sys.path
Listing 3a: A simple C# program for calling a Python script
- using System;
- using IronPython.Hosting;
- using Microsoft.Scripting.Hosting;
-
- public class dynamic_demo
- {
- static void Main()
- {
- var ipy = Python.CreateRuntime();
- dynamic test = ipy.UseFile("Test.py");
- test.Simple();
- }
- }
Listing 3b: The same C# program shown in Listing 3a, but this presentation is easier for you to block copy into your own version of the program.
using System; using IronPython.Hosting; using Microsoft.Scripting.Hosting; public class dynamic_demo { static void Main() { var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("Test.py"); test.Simple(); } }
The code in Listing 2 is a very simple Python script. Before calling it from C#, you might want to see it in action. That way you can be sure the script works and you can verify what the script is supposed to do. To get started, block copy the code in Listing 2. Use the Windows Start Menu to open up the Python Console window and paste in the code. Finally, you should explicitly call the Simple() method, as shown in Figure 3. When looking at this screen shot, you can see the version of the Python Console on the first two lines. The next 8 lines show the code that I pasted into the console. Finally, you see where I typed in the call to Simple(), and after that the output from the script. Once again, this has nothing to do with calling the code from C#, it is just a way of verifying that you have a valid script, and of confirming how it should perform.
Figure 3: A screenshot showing a run of the Python script that we will be calling from our C# program.
Now let’s look at the 3 lines of code used to call this script from a C# program. This code is shown in Listings 3a and 3b. It first creates an instance of the Python runtime, as shown in line 9:
var ipy = Python.CreateRuntime();
The call to CreateRunTime loads or sets up the core Python libraries and the DLR code needed to to execute the Python script. The second line of code, found on line 10, calls UseFile to load our simple Python script into memory. Notice that the result of this call is a dynamic object. The dynamic keyword is a new feature in C# 4.0 and Visual Studio 2010 which tells the compiler to resolve this particular call not at compile time, but at runtime.
It’s very important to understand that the dynamic keyword breaks the strong type checking that has always been a hallmark of C# development. There is no doubt that the ability to call dynamic objects is a useful and important feature. However, it should be used sparingly since it sidesteps the strict type checking that makes C# such a powerful and useful language.
The dynamic keyword is needed here because Python is an interpreted scripting language where calls are bound at run time, not at compile time. There is no simple or practical way to bind calls to Python at compile time because Python is designed to be a dynamic language which is resolved at runtime. Since C# is a strongly typed language it expects to resolve calls at compile time with strict type checking. In short, we are at an impasse. C# binds statically at compile time, Python dynamically at runtime. Something has to give, and the only valid solution was for C# to allow runtime binding for method calls.
It is important to grasp that calls into Python are not strictly type checked at compile time, and are therefore not guaranteed to succeed at runtime. Just because your program compiled without error does not mean that you have properly bound each call in your program. In this case we call the method named Simple(), which does in fact exist. As a result, the call succeeds, as shown by the output from the program found in Listing 4.
Listing 4: The output from the C# program which calls a Python script.
Hello from Python Call Dir(): [] Print the Path: ['.', 'C:\\Users\\Charlie\\Documents\\SyncData\\Source\\ProjectsShared\\Python\\CallPython\\CallPython\\bin\\Debug\\Lib', 'C:\\Users\\Charlie\\Documents\\SyncData\\Source\\ProjectsShared\\Python\\CallPython\\CallPython\\bin\\Debug\\DLLs'] Press any key to continue . . .
Listing 4 shows the good side of working with dynamic code. Now let’s take a moment to consider the dark side. Suppose we called a method on our dynamic test class that does not exist. For the sake of argument, let’s call the method NonexistentMethod(), which is shown in Listing 5.
Listing 5: This code contains a call to a method called NonexistentMethod() that does not exist in our Test.py file. As a result, the call will fail at runtime.
var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("Test.py"); test.Simple(); // Succeeds test.NonexistentMethod(); // Fails
The code in Listing 5 contains a call to the method Simple() that will succeed, since the Python script shown in Listing 2 does contain a method called Simple(). However, the call to the method NonexistentMethod() will raise an exception at runtime. This happens because the call cannot be resolved at runtime. At compile time, however, the compiler knows nothing about the object called test. It makes no attempt to see whether or not the call will succeed. It simply takes your word for it and allows the compilation to succeed. At runtime, however, the error raises its head, as shown in Figure 4 and Listing 6.
Figure 4: The exception raised inside the IDE at runtime when you attempt to call a method that does not exist.
Listing 6: The details of the exception that you receive at runtime when you attempt to call a method that does not exist.
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was unhandled Message='Microsoft.Scripting.Hosting.ScriptScope' does not contain a definition for 'NonexistentMethod' Source=Anonymously Hosted DynamicMethods Assembly StackTrace: at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1[T0](CallSite site, T0 arg0) at dynamic_demo.Main() in C:\Users\Charlie\Documents\SyncData\Source\ProjectsShared\Python\CallPython\CallPython\Program.cs:line 12:
The team went to lengths to ensure that the error you get at runtime looks almost exactly like the error you would have received at compile time had you attempted to call a static method that did not exist. Everything possible is done to make this experience easy for your to understand and handle, including giving you an exception that you can catch with your own custom code.
It goes without saying that everyone on the Visual Studio Languages team at Microsoft understands the implications of introducing the dynamic keyword into the C# language. We understand completely the advantages of statically linked code, and believe that strict type checking is a powerful tool that helps developers create robust code. In most cases, you should still use statically linked calls in your program. There are, however, scenarios that cannot be efficiently supported from the C# language without the introduction of dynamic programming. One is calling a dynamic language such as Python, and another is calling into a some COM objects, such as those used in those used by Microsoft Office. In order to make it easy for you to use dynamic languages and to perform COM Interop, the dynamic keyword was introduced into the C# 4.0 language, and the DLR became a built-in extension of .NET 4.0. Use these tools judiciously, and they will be your friend. Abuse them, and you are on your own.
Summary
In this article you learned how to call a simple Python script from a C# application. You saw how to set up the References section for your program so that it contains the assemblies used when calling an IronPython script. You then saw how to write a simple Python script, and how to call it from a C# program.
The dynamic technology on display in this example makes use of a body of code called the DLR, or Dynamic Language Runtime. The dynamic keyword that is part of C# 4.0 provides supports when you call dynamic languages or COM objects, and particularly when you use C# 4.0 to call into Microsoft Office applications. Coverage of calling into Office is separate subject, and will be covered in another post. A third topic deserving of coverage is using the dynamic keyword in scenarios where you previously used reflection.
- Download Source from the LinqFarm
Could you do a part 2 that shows "inspecting" the dynamic object at runtime? Something like finding the method(s) in the object and running them.
I’m assuming (hoping) it’s cleaner/easier than typical pre-4.0 reflection code, but it’d be great to see either way.
Thanks, Charlie!
It’s funny. When I download the source code, everything works fine. When I try to create this simple project from scratch, it does not even compile.
The libraries that come with the sample code are v0.9.6.20 and the libraries that install from v2.6 RC2 are v1.0
It complains about needing a reference to Microsoft.Scripting.Core, but then has a naming conflict with System.Runtime.CompilerServices.CallSite once the reference is added…
SuggestionBoxBob. Good idea. I’ll work on putting something like that together, but I’m busy the next few weeks, so it will take awhile.
Scott. Did you get the proper version of IronPython? I found their web site a bit confusing at times. But I was just pulling down the code from their site and using the public version of VS Beta 2. In other words, I wasn’t working with private builds.
Hi,
I am very new to the IronPython. I want to know how to parse a Key-Value pair string. Say for example, I have a string "Name = XYZ", where "Name" is a pre-defined key, ‘=’ is the separator between Key and Value, and ‘XYZ’ is the value of the Key. I want the Value in a variable. A code snippet to do this is highly appreciable.
Your if statement is wrong. It should be if a > 0:
It'd great if you could do an article this detailed for python scripts that would normally contain command line arguments for example:
python run.py arg1 arg2
and
python run.py arg1 arg1 > outFile.txt
Hi, I m new to python. If I want to install some lib in python. for instance, requests or using pip i want to download something can you tell me how to do that.
I downloaded sysnapse lib from git and i want to run that with c# but not sure where to install lib .
for instance pip install synapsepay or pip install requests.
Can some one help me with this.?
Can we execute an ironpython script which is running on different platform and my .net code on different environment and can i get the values from the script fir my .net program from it. | https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/ | CC-MAIN-2018-47 | refinedweb | 2,635 | 73.78 |
okay so I have an array of buttons, and at some point in the program I want to access the index of a button clicked in order to perform some calculations....so there are two options that I can think of...maybe there is a method to pull out the index (2d array) and use that...or what I've done in the meanwhile is create an extended class that adds methods like the ones in this code, but I am getting a compiler error saying that it can't find the constructor for it... for example I am creating a button using this new class and placing the string which is the text withinn the button so its not recognizing thtat constructor.....hopefully you all understand what I mean
import javax.swing.*; public class BoggleButton extends JButton { private int row, col; public void setPosition(int r, int c) { row = r; col = c; } public int getRow() { return row; } public int getCol() { return col; } }
and I am getting that compiler error here:
newGameButton = new BoggleButton("New Game");
and this compiles but doesn't display the letters in each button:
grid[r][c] = new BoggleButton(letterArray[r][c]); | https://www.daniweb.com/programming/software-development/threads/347054/inheritance | CC-MAIN-2017-22 | refinedweb | 196 | 53.65 |
Forum:Is it possible to make games?
From Uncyclopedia, the content-free encyclopedia
Note: This topic has been unedited for 2671 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response.
Is it possible to make text-games on uncyc like zork and game online? I was just wondering because I have a good idea.
--Marth23 15:27, 18 August 2007 (UTC)
- Alas, no. Now that you've asked, Zork and Game Online have popped out of existence. You should be ashamed.
- Yeah, you can. Just make it in the Game: namespace. And use subpages for your options. Like if Game:Foo is your start, an option should be under Game:Foo/Bar1, another one would be under Game:Foo/Bar2, etc. Games tend to get large and difficult to maintain, though. – Sir Skullthumper, MD (criticize • writings • SU&W) 15:17 Aug 18, 2007
Ok, thanks. --Marth23 15:36, 18 August 2007 (UTC)
- But also: BEWARE! For making a bad game can be a hundred times worse than making a bad article, as admins have to delete hundreds of times as many pages to get rid of it. Basically, if what you have in mind is at all like the existing games, we'll like you more if you stick it somewhere inside one of them. (Small print: Our liking of you is based on you being likeable. Opinions may go down as well as up. This does not affect your stationary rights.)--Whhhy?Whut?How? *Back from the dead* 15:51, 18 August 2007 (UTC)
- Apparently, I have no fucking idea what a game page is like.--Dark Paladin X 06:07, 19 August 2007 (UTC)
- See also: Game:Zork and Game:Grueslayer. --Sir Starnestommy
(Talk • Contribs • CUN • Capt.) 06:14, August 19, 2007 | http://uncyclopedia.wikia.com/wiki/Forum:Is_it_possible_to_make_games%3F?t=20070819061447 | CC-MAIN-2014-52 | refinedweb | 304 | 85.49 |
I had made implementing one of the paging functionalities an assignment during my free time. I have written this article so that one can draw some idea and make some control out of it. .NET has provided ready to go paging functionality for DataGrid, DataList etc. But when one has to create a dynamic table populated with thousands of records without using any ASP.NET control, then we have the write code manually.
DataGrid
DataList
Connection string: change the connection string in Web.confiq file as per your configuration.
< add
Constant: There is one Constant.cs file. This Constant file is a storage area for constants and settings for pagination.
public class Constant
{
public Constant()
{
//
// TODO: Add constructor logic here
//
}
public const int iShowNoPage = 5;//Show No Of pages....
public static int jIter =iShowNoPage;
public const int jVirtualInc = iShowNoPage;
public const int iInitialRecDisplay = 10;
// How many record you want to display per page..
}
Just make changes to two parameters, one is iShowNoPage = 5/per page (1, 2, 3, 4, 5) and the other is iInitialRecDisplay = 10. The iInitialRecDisplay parameter displays the number of records from the database on the screen.
iShowNoPage
iInitialRecDisplay
Note: the DropDownList contains three SQL queries which fetch records from three different tables. This is done to show that table 1 can contain 50 records, table 2 can contain 8 records and so on. In our case, total number of records may vary according to the table provided. On the basis of this total number of records, we have calculated the total number of pages mathematically (using Modulus fun). On doing so, one can get the number of pages per screen. For the rest of the logic one can refer the code as it is self explanatory.
DropDownList
Please let me know if there are any bugs in my paging functionality. I would appreciate any suggestion on this front.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | https://www.codeproject.com/articles/10741/generic-paging-for-recordset-with-next-back-naviga?pageflow=fixedwidth | CC-MAIN-2017-04 | refinedweb | 331 | 64.91 |
..
One of the beautiful things about the ASP.NET MVC framework is that a view can look like anything that you want. Don't like inline scripts? You can build a new view engine. Don't like anything that looks like a tag in your views? Build your own view engine. You always have the option of replacing the default Web Forms view engine with your own custom view engine.
In this tutorial, I explain how you can replace the default ASP.NET MVC Web Forms view engine with a custom view engine that supports lightweight, declarative controls. I demonstrate the Control View Engine and show you how to create lightweight controls that work with this custom view engine.
Let me start by providing you with a walk-through of how the Control View Engine works. To use the Control View Engine, you must set a controller’s ViewEngine property. The HomeController in Listing 1 is configured to use the Control View Engine (take a look at its constructor).
Listing 1 – HomeController.cs
using System.Web.Mvc;
using MvcViewEngines;
namespace Tip26.Controllers
{
[HandleError]
public class HomeController : Controller
{
public HomeController()
{
this.ViewEngine = new ControlViewEngine();
}
public ActionResult Index()
return View("Index");
}
}
Instead of setting the ViewEngine on a control by control basis, you also could create a new ControllerFactory and set the ViewEngine for every control automatically. To learn how to do this, see ASP.NET MVC Tip #19:
The Control View Engine returns .htm files for its views. The Index.htm view is contained in Listing 2.
Listing 2 – Index.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xmlns:
<head>
<title>Lightweight Control View Engine</title>
</head>
<body>
<h1>The SimpleControl says:</h1>
<my:SimpleControl />
<h1>The ColorControl displays:</h1>
<my:ColorControl
Here is some text
</my:ColorControl>
<hr />
<a href="/Data">Grid Control</a>
</body>
</html>
Notice that the HTML document in Listing 2 does not contain any inline script. Instead, it contains two declarative controls named SimpleControl and ColorControl. When the HomeController returns the Index view, you get the page in Figure 1.
Figure 1 – The Index view
If you look closely at the Index view in Listing 2 then you will notice that a custom XML namespace is declared on the opening <html> tag. The opening <html> tag looks like this:
<html xmlns="" xmlns:
The default namespace is the standard XHTML namespace for XHTML documents. The second namespace corresponds to a .NET namespace. The second xmlns attribute associates the SimpleControl and ColorControl controls with the Tip26.Controls namespace. When the page is parsed, the class Tip26.Controls.SimpleControl and the class Tip26.Controls.ColorColor are instantiated automatically. There is no other configuration for the custom controls.
The Control View Engine uses extremely lightweight controls. The SimpleControl is contained in Listing 3.
Listing 3 – SimpleControl.cs
using System;
using System.Xml;
namespace Tip26.Controls
public class SimpleControl : IControl
public XmlNode Render(ViewContext context, XmlDocument document, XmlElement controlElement)
return document.CreateTextNode("Hello from SimpleControl!");
The SimpleControl implements the IControl interface. This interface requires you to implement a single method: Render(). In Listing 3, the Render() method simply returns a new XmlElement that represents the text “Hello from SimpleControl!”. The <my:Simple> control is replaced in the Index view with this rendered text.
Notice that the SimpleControl does not derive from the base System.Web.UI.Control class or the System.Web.UI.WebControls.WebControl class. This lightweight control does not use view state. It has none of the standard properties, methods, and events of a WebForm control.
This lightweight control does not participate in the ASP.NET page lifecycle. That would be impossible since the SimpleControl is instantiated in an HTML page instead of an ASP.NET page. The only thing that the SimpleControl does is to create a new XML node.
A lightweight control can have attributes. For example, the ColorControl has a color attribute. Here’s how the ColorControl is declared in the Index.htm view:
The code for the ColorControl is contained in Listing 4.
Listing 4 – ColorControl.cs
public class ColorControl : IControl
// Get color attribute
var color = controlElement.GetAttribute("color");
// Get inner text
var text = controlElement.InnerText;
// Create div node
var div = document.CreateElement("div");
div.InnerText = text;
div.SetAttribute("style", "background-color:" + color);
// Return replacement node
return div;
The ColorControl in Listing 4 first grabs the value of the color attribute. The control then gets the inner text of the control. Finally, the control constructs a new XML element that represents an XHTML div element.
One more sample of a declarative, lightweight control. The view in Listing 5 contains a lightweight control named the Grid control. This control displays an HTML table of database data (see Figure 2).
Figure 2 – Rendered by the Grid Control
Listing 5 – Index.htm
<html xmlns="" xmlns:
<title>Show Grid Control</title>
<style type="text/css">
table
border-collapse:collapse;
table td
padding: 10px;
border: black solid 1px;
</style>
<custom:Grid
Notice, once again, that the HTML page in Listing 5 does not contain any inline script. It is a valid XHTML page with no content except XHTML elements.
The view does contain a Grid element that renders the HTML table of database data. Notice that the element has two attributes: controller and action. The Grid control uses these attributes to determine where to get the database data.
The lightweight Grid control is contained in Listing 6.
Listing 6 – Grid.cs
using System.Collections;
using System.Reflection;
public class Grid : IControl
// Check for required control attributes
string controllerName = controlElement.GetAttribute("controller");
if (String.IsNullOrEmpty(controllerName))
throw new Exception("Grid is missing controller attribute.");
string actionName = controlElement.GetAttribute("action");
if (String.IsNullOrEmpty(actionName))
throw new Exception("Grid is missing action attribute.");
// Instantiate controller
Type controllerType = Type.GetType(controllerName, true, true);
var controller = (IController)Activator.CreateInstance(controllerType);
// Call action (not using Action Invoker)
MethodInfo method = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
IEnumerable data = (IEnumerable)method.Invoke(controller, null);
// Create table
XmlElement table = document.CreateElement("table");
foreach (object item in data)
{
var row = document.CreateElement("tr");
var props = item.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
var cell = document.CreateElement("td");
cell.InnerText = prop.GetValue(item, null).ToString();
row.AppendChild(cell);
}
table.AppendChild(row);
}
return table;
The Grid control instantiates the controller represented by its controller attribute. Next, it invokes the action on the controller represented by its action attribute. The Grid control assumes that the controller action returns an IEnumerable. The control enumerates the data and displays the data in an HTML table.
The Grid control uses the controller in Listing 7.
Listing 7 – MovieController.cs
using System.Linq;
using Tip26.Models;
public class MovieController : Controller
public object ListAll()
var dataContext = new MovieDataContext();
return dataContext.Movies.ToList();
The MovieController.ListAll() action uses a LINQ to SQL DataContext to retrieve all of the movies from the movies database table. Nothing fancy here.
You implement a custom View Engine by implementing the IViewEngine interface. This interface has one required method: RenderView().
The Control View Engine’s RenderView() method is contained in Listing 8.
Listing 8 – ControlViewEngine.RenderView().
public void RenderView(ViewContext viewContext)
// Get path of view
string viewPath = ViewLocator.GetViewLocation(viewContext, viewContext.ViewName);
// Get XHTML Document
var document = GetDOMFromViewPath(viewPath);
// Find all non-XHTML elements
var controlElements = GetControlElements(document);
// Instantiate controls
foreach (XmlElement controlElement in controlElements)
RenderControl(viewContext, document, controlElement);
// Write XHTML to response
document.Save(viewContext.HttpContext.Response.Output);
The RenderView() method in Listing 8 assumes that the view is an XML (XHTML) compatible view. The view is loaded with the help of the XmlDocument class. Next, all of the non-xhtml elements are retrieved from the view. Anything contained in the view that is not an XHTML element is assumed to be a potential control. The RenderControl() method is used to render the control (see Listing 9).
Listing 9 – ControlViewEngine.RenderControl()
protected virtual void RenderControl(ViewContext context, XmlDocument document, XmlElement element)
var controlName = String.Format("{0}.{1}", element.NamespaceURI, element.LocalName);
var controlType = _applicationAssembly.GetType(controlName, false, true);
if (controlType != null)
var control = (IControl)Activator.CreateInstance(controlType);
XmlNode resultNode = control.Render(context, document, element);
element.ParentNode.ReplaceChild(resultNode, element);
The RenderControl() method uses the .NET framework Activator.CreateInstance() method to create an instance of a class that corresponds to the control element. Next, the Render() method is called on the instantiated class to get an XML element. Finally, the original element is swapped for the new XML element.
You can view the entire source code of the Control View Engine by clicking the download link at the end of this tip.
The Control View Engine is very lightweight. It does not introduce view state, postbacks, or any framework overhead. The Control View Engine simply renders some text.
Some people find working with declarative views more natural than working with inline scripts. If you like inline scripts then the Control View Engine won’t offer much value to you. If you like to build your views with declarative controls, on the other hand, then a view engine like the Control View Engine might be an appealing alternative to the default Web Forms view engine.
Another nice thing about the Control View Engine is that it is very testable. For example, Listing 10 contains a test for the HomeController.Index() action.
Listing 10 – HomeControllerTest.cs
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tip26;
using Tip26.Controllers;
using MvcFakes;
using System.Web.Routing;
namespace Tip26Tests.Controllers
/// <summary>
/// Summary description for HomeControllerTest
/// </summary>
[TestClass]
public class HomeControllerTest
private const string appFolder = @"C:\Users\swalther\Documents\Common Content\Blog\Tip26 Create Lightweight Control View Engine\CS\Tip26\Tip26\";
[TestMethod]
public void Index()
// Setup Controller
HomeController controller = new HomeController();
// Setup View Engine
var appAssembly = Assembly.GetAssembly(typeof (HomeController));
controller.ViewEngine = new ControlViewEngine(appFolder, appAssembly);
// Fake the Controller Context
var context = new FakeControllerContext(controller);
context.RouteData.Values["controller"] = "home";
context.RouteData.Values["action"] = "index";
// Execute
ViewResult result = controller.Index() as ViewResult;
result.ExecuteResult(context);
// Verify
var page = context.HttpContext.Response.ToString();
StringAssert.Contains(page, "Hello from SimpleControl!");
The test in Listing 10 checks whether the view returned by the HomeController.Index() method contains the text “Hello from SimpleControl!”. This text is rendered by the SimpleControl. When you use the Control View Engine, you can test the view for particular strings that are rendered by controls.
The performance of the Control View Engine is bad. I’m not quite sure how bad, but I suspect that it is very, very bad. Each and every time that you render a view with the Control View Engine, the View Engine re-executes each Control class’s Render() method.
I’ve done a little bit of caching. The view is cached in memory after the first request (with a file dependency on the view file). You’ll notice that the first time you request a particular view, it takes a really long time for the view to appear in your web browser.
The real goal of this post was to convince you that inline scripts are not an essential part of the ASP.NET MVC framework. If you find ASP.NET MVC views hard to read (tag soup) then it is good to know that you always have the option of swapping out the default view engine with a custom view engine. In this tip, I’ve shown you how to go as far in the opposite direction of inline script as possible. I demonstrated how you can create a declarative view engine instead of an inline script view engine.
:)) Very nice. Thanks for providing another way of not getting a tag soup ;)
"The real goal of this post was to convince you that inline scripts are not an essential part of the ASP.NET MVC framework." - Well, I'm convinced.
Excellent post (as usual). When I saw the use of the XmlDocument, and all of the Activator.CreateInstance stuff, I was wondering how it could possibly perform well!
I was in the middle of writing an article on Eels about creating custom controls in ASP.NET MVC... now I'll have to make a referrence to this post on the 'declarative' side.
Thanks,
-Timothy Khouri
Pingback from To (ASP.NET)MVC or not to MVC (or, ASP.NET MVC Hyperlink Acupuncture) | nathanstults.com
Great Post. Just one noddy question. What do I need to reference to use the IControl interface? I can't seem to find it...
Pingback from To (ASP.NET)MVC or not to MVC (or, ASP.NET MVC Hyperlink Acupuncture) | The Freak Parade | http://weblogs.asp.net/stephenwalther/archive/2008/07/28/asp-net-mvc-tip-26-create-a-lightweight-control-view-engine.aspx | crawl-002 | refinedweb | 2,088 | 52.76 |
Opened 7 years ago
Last modified 2 years ago
#12772 assigned New feature
Allow loading template tags by fully qualified python module path
Description
Currently templatetags are magically searched for in the list of installed apps. This leads to all kind of problems when debugging code, starting from being forced to use find to locate tag libraries and ending with global namespace collisions.
The attached patch adds the possibility to import tags by fully qualified module path by first trying to make an absolute import and only then falling back to searching inside installed apps.
This also allows people to import tag libraries that are not parts of any application (so common tags can be kept together without the need of adding a fake app).
Also: "Explicit is better than implicit." :)
Attachments (4)
Change History (34)
Changed 7 years ago by
comment:1 Changed 7 years ago by
comment:2 follow-up: 3 Changed 7 years ago by
comment:3 Changed 7 years ago by
It's not a duplicate.
#2539 is adding even more magic to the template loader.
My proposal here is removing the magic and eventually deprecating the old syntax. The "templatetags" dir should not be magic.
Personally, I like your proposal better (one should get rid of app_label and flat namespaces everywhere).
But since #2539 is also about adding some kind of namespace support to template libraries, it makes sense to have a single ticket.
comment:4 Changed 7 years ago by
comment:5 Changed 7 years ago by
comment:6 Changed 7 years ago by
comment:7 Changed 7 years ago by
comment:8 Changed 7 years ago by
Changed 7 years ago by
name file .diff, diff from the root of the repo, not django subdir
comment:9 Changed 7 years ago by
comment:10 Changed 7 years ago by
In revision 13020, the patch makes the test suite fail.
lib = import_library(taglib_module)
...
Changed 7 years ago by
Modified patch
comment:11 Changed 7 years ago by
Added a workaround around the workaround that was already there (the one trying to detect if the parent module contained the taglib).
comment:12 Changed 7 years ago by
The test suite fails with the new patch:
Also, it would be nice if you would use the .diff extension and run diff from the root of the django dir as specified:
comment:13 Changed 7 years ago by
From testing with my test_project, I find that using the new style is working but, using the old style dumps errors.
so, using the old-syle with trunk, I can
{% load test_ttags %} and all is well.
With your patch, I can {% load test_app.templatetags.test_ttags %}
But, if I try to do it the old way,
'test_ttags' is not a valid tag library: ImportError raised loading test_ttags: No module named test_ttags
Changed 7 years ago by
Working patch
comment:14 Changed 7 years ago by
Attached a better patch, this time using full paths.
.patch is the usual extension for patches and trac handles that fine.
comment:15 Changed 6 years ago by
comment:16 Changed 5 years ago by
Change UI/UX from NULL to False.
comment:17 Changed 5 years ago by
Change Easy pickings from NULL to False.
comment:18 Changed 4 years ago by
comment:19 Changed 4 years ago by
comment:20 Changed 4 years ago by
comment:21 Changed 4 years ago by
Pull request:
comment:22 Changed 4 years ago by
I'm a bit worried about this change. What happens when someone manages to upload a
.py file somewhere (e.g. in the
media folder)?
With this patch, will it be possible to load that code?
comment:23 Changed 4 years ago by
I assume the media folder is not a proper Python package so no, not unless you also manage to put an
__init__.py on all the levels above the media folder and add it to
sys.path. Also notice that this is only usable if you can edit the templates which means you already have access to the code.
comment:24 Changed 2 years ago by
Ping :)
comment:25 Changed 2 years ago by
I am not entirely convinced either way about the security concerns. For example, the documentation says we have
settings.ALLOWED_INCLUDE_ROOTS because "This is a security measure, so that template authors can’t access files that they shouldn’t be accessing. It seems this opens up the same sort of issue where template authors can load arbitrary Python packages which shouldn't (but may) have side effects. It would be helpful to run this by the mailing list and see if a consensus emerges.
After that (assuming this isn't rejected), the patch needs to be updated to apply cleanly to master and then the Trac flags update so the patch appears in the review queue.
comment:26 Changed 2 years ago by
There's a significant difference between
settings.ALLOWED_INCLUDE_ROOTS and arbitrary imports. If we didn't have the former, a template author could access literally any file on the filesystem, as text. The latter only allows accessing files that are on
sys.path within a valid Python package, and even then only in a limited way - by interpreting them as Python code. The former is much worse as a security risk.
That said, it has never been entirely clear (to me, anyway) whether "completely untrusted template author" is a use-case that Django intends to support out of the box. I doubt the template language currently meets that bar very well, so I think we'd have some work to do if the answer is "yes". But I do agree that if the answer to that is "yes", this patch should probably not go in.
Apart from the security concerns: while I fully agree that the flattened app-label namespace is silly and problematic, it feels strange to me to have Python import semantics reflected even more directly into the template engine. I prefer the Jinja2 approach, where the things that you can import from templates are other templates containing macros; if you want Python functions directly in the context, you have to put them there explicitly in Python code, you don't "import" Python modules from templates. The current DTL approach is less explicit than the Jinja2 approach, but at least with the current DTL approach the Python developer still has to explicitly nominate which modules should be available to the templates.
So I think I hover somewhere around +/-0 on this patch.
comment:27 Changed 2 years ago by
Created a thread to try to get some consensus on this:
comment:28 Changed 2 years ago by
While I approve of magic removal, I'm not convinced I like the idea of importing by python path.
A possible solution to both any security concerns and namespace collisions would be to have
TEMPLATE_TAG_LOADERS - one with the automatic behaviour which could be removed if you want to, and one which is configured via a mapping of library names to dotted paths to python files.
So current (default) behaviour:
TEMPLATE_TAG_LOADERS = ('django.template.tag_loaders.AppDirectoriesLoader',)
Magic removal version:
TEMPLATE_TAG_LOADERS = ('django.template.tag_loaders.ConfiguredLoader',) TEMPLATE_TAG_LIBRARIES = { 'admin.urls': 'django.contrib.admin.templatetags.admin_urls', # ... other built in libraries 'my_tags': 'my_project.my_custom_templatetags', }
These settings would actually not be yet more top level settings, but more configuration settings within Aymeric's template engines branch, which would make them a bit more palatable.
Not 100% sure this is a good idea, but I think it is worth considering. Most people would continue to use the magical version we have, but it would now be explicit, overridable magic.
comment:29 Changed 2 years ago by
comment:30 Changed 2 years ago by
Isn't there already a
{% load mylibrary from myapp %} syntax?
I do feel like there's a ton of boilerplate for creating template tags. It would be nice to cut down on this:
mkdir templatetags touch templatetags/__init__.py vi templatetags/thing_to_name.py from django import template register = template.Library() @register.simple_tag
Could we allow any python module to register template tags, and then it's up to you to be sure that gets imported before you use your template? So, any python module could do something like this?
register = template.Library('name_of_library')
Though, it still doesn't solve name collisions.
Proposed change | https://code.djangoproject.com/ticket/12772 | CC-MAIN-2017-13 | refinedweb | 1,392 | 59.74 |
#include <wx/glcanvas.h>
wxGLCanvas is a class for displaying OpenGL graphics.
It is always used in conjunction with wxGLContext as the context can only be made current (i.e. active for the OpenGL commands) when it is associated to a wxGLCanvas.
More precisely, you first need to create a wxGLCanvas window and then create an instance of a wxGLContext that is initialized with this wxGLCanvas and then later use either SetCurrent() with the instance of the wxGLContext or wxGLContext::SetCurrent() with the instance of the wxGLCanvas (which might be not the same as was used for the creation of the context) to bind the OpenGL state that is represented by the rendering context to the canvas, and then finally call SwapBuffers() to swap the buffers of the OpenGL canvas and thus show your current output.
Notice that versions of wxWidgets previous to 2.9 used to implicitly create a wxGLContext inside wxGLCanvas itself. This is still supported in the current version but is deprecated now and will be removed in the future, please update your code to create the rendering contexts explicitly.
To set up the attributes for the canvas (number of bits for the depth buffer, number of bits for the stencil buffer and so on) you should set up the correct values of the attribList parameter. The values that should be set up and their meanings will be described below.
setup.hfile and set
wxUSE_GLCANVASto
1and then also pass
USE_OPENGL=1to the make utility. You may also need to add
opengl32.liband
glu32.libto the list of the libraries your program is linked with.
Creates a window with the given parameters.
Notice that you need to create and use a wxGLContext to output to this window.
If attribList is not specified, double buffered RGBA mode is used.
Determines if a canvas having the specified attributes is available.
Returns true if the extension with given name is supported.
Notice that while this function is implemented for all of GLX, WGL and AGL the extensions names are usually not the same for different platforms and so the code using it still usually uses conditional compilation.
Sets the current colour for this window (using
glcolor3f()), using the wxWidgets colour database to find a named colour.
Makes the OpenGL state that is represented by the OpenGL rendering context context current, i.e.
it will be used by all subsequent OpenGL calls.
This is equivalent to wxGLContext::SetCurrent() called with this window as parameter.
Swaps the double-buffer of this window, making the back-buffer the front-buffer and vice versa, so that the output of the previous OpenGL commands is displayed on the window. | http://docs.wxwidgets.org/trunk/classwx_g_l_canvas.html | CC-MAIN-2013-20 | refinedweb | 443 | 60.95 |
ns-hooks
Percentile
Hooks for Namespace Events
Packages can supply functions to be called when loaded, attached, detached or unloaded.
Usage
.onLoad(libname, pkgname) .onAttach(libname, pkgname) .onUnload(libpath) .onDetach(libpath) .Last.lib(libpath)
Arguments
- libname
- a character string giving the library directory where the package defining the namespace was found.
- pkgname
- a character string giving the name of the package.
- libpath
- a character string giving the complete path to the package.
Details
After loading,
loadNamespace looks for a hook function
named
.onLoad and calls it (with two unnamed arguments) before
sealing the namespace and processing exports.
When the package is attached (via
library or
attachNamespace), the hook function
.onAttach is
looked for and if found is called (with two unnamed arguments) before
the package environment is sealed.
If a function
.onDetach (as from R 3.0.0) is in the namespace
or
.Last.lib is exported from the package, it will be called
(with a single argument) when the package is
detached.
Beware that it might be called if
.onAttach has failed, so it should be
written defensively. (It is called within
tryCatch, so
errors will not stop the package being detached.)
If a namespace is unloaded (via
unloadNamespace), a hook
function
.onUnload is run (with a single argument) before final
unloading.
Note that the code in
.onLoad and
.onUnload should not
assume any package except the base package is on the search path.
Objects in the current package will be visible (unless this is
circumvented), but objects from other packages should be imported or
the double colon operator should be used.
.onLoad,
.onUnload,
.onAttach and
.onDetach are looked for as internal objects in the namespace
and should not be exported (whereas
.Last.lib should be).
Note that packages are not detached nor namespaces unloaded at the end
of an R session unless the user arranges to do so (e.g., via
Anything needed for the functioning of the namespace should be
handled at load/unload times by the
.onLoad and
.onUnload hooks. For example, DLLs can be loaded (unless done
by a
useDynLib directive in the NAMESPACE file) and
initialized in
.onLoad and unloaded in
.onUnload. Use
.onAttach only for actions that are needed only when the
package becomes visible to the user (for example a start-up message)
or need to be run after the package environment has been created.
Good practice
messages given by
.onAttach. These messages (and any essential
ones from
.onLoad) should use
packageStartupMessage
so they can be silenced where they would be a distraction. There should be no calls to
library nor
require in these
hooks. The way for a package to load other packages is via the
Depends field in the DESCRIPTION file: this ensures
that the dependence is documented and packages are loaded in the
correct order. Loading a namespace should not change the search path,
so rather than attach a package, dependence of a namespace on another
package should be achieved by (selectively) importing from the other
package's namespace. Uses of
library with argument
help to display basic
information about the package should use
format on the
computed package information object and pass this to
packageStartupMessage. There should be no calls to
installed.packages in startup
code: it is potentially very slow and may fail in versions of R
before 2.14.2 if package installation is going on in parallel. See
its help page for alternatives. Compiled code should be loaded (e.g., via
library.dynam) in
.onLoad or a
useDynLib
directive in the NAMESPACE file, and not in
.onAttach.
Similarly, compiled code should not be unloaded (e.g., via
library.dynam.unload) in
.Last.lib nor
.onDetach, only in
.onUnload.
See Also
setHook shows how users can set hooks on the same events, and
lists the sequence of events involving all of the hooks.
reg.finalizer for hooks to be run at the end of a session.
loadNamespace for more about namespaces.
Aliases
- .onLoad
- .onUnload
- .onAttach
- .onDetach
- .Last.lib | https://www.rdocumentation.org/packages/base/versions/3.3.0/topics/ns-hooks | CC-MAIN-2020-45 | refinedweb | 662 | 57.16 |
To be precise, I’m on the Slashdot, which means I now have +1 Nerd Cred. Admittedly, it popped up on Easter Friday, which would probably be in the top 3 slowest news days of the year. And you have to dive in to the numerous links (no, not from a comment, from the actual ‘article’) to find my name in one tiny corner. And the blog post it linked to is over two weeks old. And it’s not as outrageously remarkable as Bonsai Kittens. But I’m there, dammit.
The blog post it linked to is from my work blog, which is more product announcy than personal diary-y, but, yeah, for the last few months I (with help from my colleagues, especially David) have been working on getting GeoRSS and KML to show on Google Maps and also through the Google Maps API.
There were a lot more linkbacks to that post than I was expecting, and it was a little odd, when just surfing around, to follow the trail from Jeremy Zawodny’s linkblog (one of my occasional internet timewasters) to Sam Ruby’s Which Way Is Up, which opens with, whoa, my name. It also made the O’Reilly Radar.
Which Way Is Up also mentions that GeoRSS isn’t officially standardized – it’s a partially undefined specification, with respect to boring details like what’s the XML namespace, are lat/lng co-ordinates separated by commas or whitespace, blah blah blah. That’s not to say that KML is perfect either – a personal boring detail peeve is how it’s sometimes child elements rather than attributes: <LineStyle> <width> 3 </width> </LineStyle> rather than <LineStyle width=”3″/>. But really, that’s a boring detail I ought to save until around the 50 hour mark when we’re stuck in a borked elevator together and have totally run out of other conversation.
Backtracking a bit, the thing with GeoRSS being somewhat loose means that the example that I chose to demonstrate GeoRSS-on-Maps could be held up as exemplary, or “officially blessed by Google”, even though it’s imperfect wrt this loose standard, or so the discussion went at Which Way Is Up. But really, it was just an arbitrary decision by me made in like 3 seconds when I needed a reasonable looking GeoRSS example and SlashGeo was the first one I saw on my Tomboy note full of these things. It made me wonder (briefly) about what other standards have been ensconced somewhat accidentally… | http://blogs.gnome.org/nigeltao/2007/04/ | CC-MAIN-2014-10 | refinedweb | 421 | 61.29 |
.
Proxies through to NEXT::new and stashes the application instance as $self->_application.
Returns the Catalyst::Action object (if any) for a given method name in this component.
Finds all applicable actions for this component, creates Catalyst::Action objects (using $self->create_action) for them and registers them with $c->dispatcher.
Returns the private namespace for actions in this component. Defaults to a value from the controller name (for e.g. MyApp::Controller::Foo::Bar becomes "foo/bar") or can be overridden from the "namespace" config key.
Returns the default path prefix for :Local, :LocalRegex and relative :Path actions in this component. Defaults to the action_namespace or can be overridden from the "path" config key.
Called with a hash of data to be use for construction of a new Catalyst::Action (or appropriate sub/alternative class) object.
Primarily designed for the use of register_actions.
Returns the application instance stored by
new()
Sebastian Riedel,
sri@oook.de Marcus Ramberg
mramberg@cpan.org
This program is free software, you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/~mramberg/Catalyst-Runtime-5.7099_01/lib/Catalyst/Controller.pm | CC-MAIN-2014-49 | refinedweb | 180 | 50.33 |
Hi Simo,
I guess the 5 minutes to run example would be:
ShortestPathFunction.dijkstra
.makeResult(graph, EdgeWeight.forWeightedEdge, Monotonic.sumDouble)
.findShortestPath(source, target);
I was assuming that there would be standard pallets of all the strategies
available statically in the obvious places. Actually, now I see the code
written out in full like that, I'd perhaps consider renaming makeResult to
`calculate` or `prepare` or some other verb.
Matthew
On 23 December 2011 08:47, Simone Tripodi <simonetripodi@apache.org> wrote:
> Hi Matthew!
>
> at a first looks it is really interesting, just give me the time to
> digest because at the same time I had the feeling of a little
> over-engineering activity, I am worried that "5 minutes to run" users
> would find it not so immediate.
>
> Thanks for providing stuff to learn from!
> All the best,
> -Simo
>
>
>
>
>
>
>
>
> On Thu, Dec 22, 2011 at 6:25 PM, Matthew Pocock
> <turingatemyhamster@gmail.com> wrote:
> > Hi,
> >
> > Just thought I'd throw something out here. My experience is that I often
> > take the same graph (as in the exact same data, same objects) but at
> > different times want to use different weights. So, rather than having
> Edge
> > extend Weighted<W>, I'd factor weights out into their own interface:
> >
> > /**
> > * An edge weight function.
> > *
> > * note: perhaps this should more generally just be a Function1<A, B>, if
> > we have such a thing handy.
> > *
> > * @tparam E edge type
> > * @tparam W weight type
> > */
> > public interface EdgeWeight<E, W> {
> > public W getWeight(E: Edge);
> > }
> >
> > /**
> > * A combination of a monoid and comparator that satisfy monotinicity of
> > the addition operation with respect to the comparator.
> > *
> > * ∀a: m.compare(m.zero, a) <= 0
> > * ∀a,b: m.compare(a, m.append(a, b)) <= 0
> > */
> > public interface Monotonic<W> extends Monoid<W>, Comparator<W>
> >
> > Also, some algorithms calculate all shortest paths at once, while others
> > calculate them individually and independently. It's probably even
> possible
> > to calculate some lazily. So, the interfaces for shortest paths should
> > decouple setting up a strategy for all shortest paths from an object that
> > can be used to fetch a specific shortest path.
> >
> > /**
> > * An algorithm for finding shortest paths between vertices of a graph,
> > given some edge weighting function and
> > * a well-behaved combinator for edges between connected vertices.
> > */
> > public interface ShortestPathFunction<V extends Vertex, E extends
> Edge<E>,
> > G extends DirectedGraph<V, E>, W> {
> > public ShortestPathResult<V, E, W> makeResult(G graph, EdgeWeight<E, W>
> > weighting, Monotonic<W> combineWith);
> > }
> >
> > /**
> > * The shortest paths between vertices in a graph.
> > */
> > public interface ShortestPathResult<V extends Vertex, E extends Edge<E>,
> W>
> > {
> > public WeightedPath<V, E, W> findShortestPath(V source, V target);
> > }
> >
> > How does that look? You can then have standard implementations of these
> > things in some static utility class or a spring-friendly resource. The
> > brute-force algorithms that compute all paths at once would do all the
> work
> > in makeResult() and simply store this in some state within the returned
> > ShortestPathResult. Those that calculate individual pairs on the fly (or
> > all shortest paths from some vertex) would capture state in makeResult()
> > and perform the actual computation in findShortestPath().
> >
> > Matthew
> >
> > On 22 December 2011 16:39, Claudio Squarcella <squarcel@dia.uniroma3.it
> >wrote:
> >
> >> Hi,
> >>
> >>
> >> I highly appreciated the last contributions (thanks guys!) but I also
> >>> agree on this point, so let's start from the end.
> >>> I think that, no matter what underlying structure we come up with, the
> >>> user should be able to specify e.g. a weighted edge with something like
> >>>
> >>> public class MyEdge implements Edge, Weighted<Double> { ... }
> >>>
> >>> and be able to immediately use it as an input for all the algorithms,
> >>> without extra steps required. So the average user is happy, while
> "graph
> >>> geeks" can dig into advanced capabilities and forge their personalized
> >>> weights :)
> >>> I hope we all agree on this as a first step. Complexity comes after.
> >>>
> >>> I'll take my time as well to re-think.
> >>>
> >>
> >> I did think and code a bit more. First of all please take a look at the
> >> updated code: Weighted<W> is an interface (weight W can be any type) and
> >> all the algorithms require edges to implement Weighted<Double> for now
> --
> >> we did not break it that much ;)
> >>
> >> About the "HasProperty-vs-Property" question (as in Comparable vs
> >> Comparator, MonoidElement vs Monoid, etc) I would go for the second one
> >> only. That is, external classes handle all operations on weights.
> Downside:
> >> the # of method parameters would increase linearly with the number of
> >> properties, but I can live with that (how many properties would weights
> >> have anyway?). On the other hand we have a neat interface for each
> >> property/class (Zero, Semigroup, Monoid, Ordering or Comparator, etc)
> and
> >> one clean, generic implementation for each algorithm. Dijkstra's
> signature
> >> becomes something like:
> >>
> >> public static <V extends Vertex, W, WE extends WeightedEdge<W>, G
> extends
> >> DirectedGraph<V, WE>> WeightedPath<V, WE, W> findShortestPath(
G graph,
> V
> >> source, V target, Monoid<W> weightMonoid, Comparator<W>
> weightComparator )
> >>
> >> Scary uh? But wait, default implementations for Double, Integer, etc.
> are
> >> way easier. E.g. Dijkstra's shortcut for Double:
> >>
> >> public static <V extends Vertex, WE extends WeightedEdge<Double>, G
> >> extends DirectedGraph<V, WE>> WeightedPath<V, WE, Double>
> findShortestPath(
> >> G graph, V source, V target )
> >> {
> >> return findShortestPath(graph, source, target, new DoubleMonoid(),
> new
> >> DoubleComparator());
> >> }
> >>
> >> where DoubleMonoid and DoubleComparator are part of the library.
> >>
> >>
> >> If you guys are fine with this, I'm ready to try and patch [graph] with
> a
> >> Christmas gift :)
> >> Claudio
> >>
> >>
> >> --
> >> Claudio Squarcella
> >> PhD student at Roma Tre University
> >> Phone: +39-06-57333215
> >>**squarcel<
>>
> >>
> >>
> >>
> ------------------------------**------------------------------**---------
> >> To unsubscribe, e-mail: dev-unsubscribe@commons.**apache.org<
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: | http://mail-archives.apache.org/mod_mbox/commons-dev/201112.mbox/%3CCAHQS_ez0C_YfGjg30bjtbewpTTPLZaqBDnZ-=SMGszOhPdthUw@mail.gmail.com%3E | CC-MAIN-2013-20 | refinedweb | 925 | 51.48 |
Hi David, On Mon, Jul 18, 2005 at 02:15:53PM +0800, David Teigland. Right. So this doesn't take into account other parts of node management (communication, heartbeat, etc). OCFS2 and dlm would still be handling that stuff on their own for now. For OCFS2 that would mean that an ocfs2_nodemanager would still exist, but as a much smaller module sitting on top of 'nodemanager'. >. While I agree that some things look like they still need a bit of work, I like the direction this is taking - thanks for getting this ball rolling. My questions and comments below: > +enum { > + NM_NODE_ATTR_NODEID = 0, > + NM_NODE_ATTR_ADDRESS, > + NM_NODE_ATTR_LOCAL, > +}; So no port attribute. The OCFS2 network code normally takes port from the node manager in order to determine how to talk to a given node. We'll have to figure out how to resolve that. The easiest would be to add 'port' back, but I think that might be problematic if we have multiple cluster network infrastructures as we do today. Another way to handle this would be to have userspace symlink to the node items as an attribute on an ocfs2_tcp item. We could store 'port' as a second attribute. This would have the added benefit of pinning node information while OCFS2 uses it. > +struct node { > + spinlock_t nd_lock; > + struct config_item nd_item; > + char nd_name[NODEMANAGER_MAX_NAME_LEN+1]; An accessor function for this would be nice for pretty prints - maybe strcpy into a passed string. > + int nd_nodeid; This definitely won't work with OCFS2... Nodeid (what used to be called node_num) needs to be unsigned. Otherwise this will break all our nodemap stuff which uses a bitmap to represent cluster state. > + u32 nd_ipv4_address; > + struct rb_node nd_ip_node; > + int nd_local; > + unsigned long nd_set_attributes; > + struct idr nd_status_idr; > + struct list_head nd_status_list; What are these two for? They don't seem to be referenced elsewhere... > +static ssize_t node_local_write(struct node *node, const char *page, > + size_t count) > +{ > + struct cluster *cluster = node_to_cluster(node); > + unsigned long tmp; > + char *p = (char *)page; > + > + tmp = simple_strtoul(p, &p, 0); > + if (!p || (*p && (*p != '\n'))) > + return -EINVAL; > + > + tmp = !!tmp; /* boolean of whether this node wants to be local */ > + > + /* the only failure case is trying to set a new local node > + * when a different one is already set */ > + > + if (tmp && tmp == cluster->cl_has_local && > + cluster->cl_local_node != node->nd_nodeid) > + return -EBUSY; > + > + if (!tmp && cluster->cl_has_local && > + cluster->cl_local_node == node->nd_nodeid) { > + cluster->cl_local_node = 0; I think we might want to be setting cl_local_node to NODEMANAGER_MAX_NODES here. It seems that ocfs2_nodemanager also does this so we might have just caught a bug you inherited :) > diff -urN a/drivers/nodemanager/nodemanager.h b/drivers/nodemanager/nodemanager.h > --- a/drivers/nodemanager/nodemanager.h 1970-01-01 07:30:00.000000000 +0730 > +++ b/drivers/nodemanager/nodemanager.h 2005-07-18 13:41:35.377583200 +0800 > @@ -0,0 +1,37 @@ > +/* > + * nodemanager.h > + * > + * Copyright (C) 2004 Oracle. All rights reserved. > + * Copyright (C) 2005 Red Hat,. > + * > + */ > + > +#ifndef NODEMANAGER_H > +#define NODEMANAGER_H > + > +#define NODEMANAGER_MAX_NODES 255 > +#define NODEMANAGER_INVALID_NODE_NUM 255 > +#define NODEMANAGER_MAX_NAME_LEN __NEW_UTS_LEN /* 64 */ > + > +u32 nodemanager_nodeid_to_addr(int nodeid); > +int nodemanager_addr_to_nodeid(u32 addr); > +int nodemanager_our_nodeid(void); > +u32 nodemanager_our_addr(void); > + > +#endif You removed o2nm_configured_node_map but we need some sort of method for enumerating over the set of configured nodes. Also we need a method for querying the existence of a node. The OCFS2 code usually uses o2nm_get_node_by_num(..) != NULL for this but a simple boolean api call would be cleaner and would avoid exposing the node structure. That's it for my first pass - I might have additional comments after reading through this some more :) --Mark -- Mark Fasheh Senior Software Developer, Oracle mark fasheh oracle com | https://www.redhat.com/archives/linux-cluster/2005-July/msg00184.html | CC-MAIN-2014-23 | refinedweb | 588 | 56.76 |
Review
your favorite Linux distribution.
Blogs
Recent Entries
Best Entries
Best Blogs
Blog List
Search Blogs
Forums
Reviews
Tutorials
Articles
Search
Today's Posts
Mark Forums Read
LinuxQuestions.org
>
Linux Answers
>
Programming
Beginning with Java3200 at 2003-07-31 22:53
It seems that you can't go anywhere on the web without running into some form of Java, this is why I am now going to try to explain not only what Java is, but give some examples of programs that you can make, modify and learn from.
What is Java?
Java was originally developed by Sun Microsystems in an attempt to create an architecturally neutral programming language that would not have to be complied for various CPU architectures. Oak (as it was originally called, although the name was changed in 1995) was developed in 1991 for such things as home appliances which would not all run on the same type of processors. Just then the web was taking off and it was obvious that an programming language that could be used for many different operating systems and CPU architectures without compling many times would be of great importance. The final solution was to use bytecode. Unlike C++, Java code is not executable, it is code that is run by a Java Virtual Machine (JVM), so once a JVM is introduced for a platform all the Java programs can be run on it. There are two types of Java programs, the applications and the applets. The applications are what are written on a computer and run on a computer without the Internet connected in anyway. An applet is a program made for use on the internet and is the programs that runs in your browser. Sun also gave Java some buzzwords.
Simple
You might get some arguments from beginners on this, but Java remains a fairly simple language.
Secure
If you ever try to save from a notepad program (or any program) in Java you will get something saying
Quote:
This application has requested read/write access to a file on the local filesystem. Allowing this action will only give the application access to the file(s) selected in the following file dialog box. Do you want to allow this action?
The Java code runs within the JVM and prompts you if the bytecode wants to read or write.
Portable
Since it is architecturally neutral it can run on PCs, Macs, PDAs, Cellphones, and about anything else if there is a JVM for it.
Object-Oriented
While some languages are based around commands, Object-Oriented programming focuses on that data. For a more complete definition I highly recommend going to
Google Glossary
to learn more.
Robust
Powerful. This is in part due to the fact that the Java complier will check the code and will not complie it if has errors.
Multithreaded
Java has built-in support for multi-threaded programming.
Architecture-neutral
Java is not made for a specific architecture or operating system.
Interpreted
Thanks to bytecode Java can be used on many different platforms.
High Performace
Java isn't going to be used for 1st person shooters but it does run fast.
Distributed
It can be used on many platforms
Dynamic
Can evolve to changing needs.
How Java is like C/C++
A Java programmer would be able to learn C/C++ quickly and a C/C++ programmer would be able to learn Java quickly because they are similar. When Java was made it was not to be a programming language that was better then C/C++ but was made to meet the goals of the interenet age. Java also has differences with C/C++, for example, someone could not write C/C++ code and complie it as Java for Internet use, nor could someone take Java code and complie it into C/C++.
Getting started writing Java
First you must go and get
Java
. You can download the JRE, which is the Java Runtime Environment, this is good for using Java but not what we need to compile Java applications. You need to download the SDK, which is the Software Development Kit. Once you have installed this free download you will have two important tools. The first is the
javac
command which is for compiling the program, and there is the
java
command for running your program. Once the SDK is installed you try typing
javac
, if you get an unrecognized error you should put the line
PATH=$PATH:/usr/java/j2sdk1.4.2/bin
(or replace /usr/java/j2sdk1.4.2/bin[/i] in whatever is the place to javac (this can be found with
locate javac
)in your /etc/profile file. This way the commands are accessible from anywhere. For writing the programs, most text editors will work (not word processors though, they format the text) but I prefer Kwrite because after you save it as a java file it colors all the text and makes blocks of code collaspable and expandable. First we are going to do an analysis of a simple program.
/*
This is a simple, simple app.
They will get more fun in time
:)
*/
class First {
public static void main(String args[]) {
System.out.println("Yea! I wrote JAVA");
}
}
Starting at the top you will see the /* and */ markings. This is for a multi-line comment, anything inside of here will be ignored by the Java compiler. You can also add singal line comments with the // markings with everything after the // as a comment.
class
is the part of the program that everything is inside of.
First
is the title of the program, you have to save it as whatever you have after class, and this case-sensitive.
public
is specifying main(String args[]) as being accessable to code outside of its class.
static
allows main(String args[]) to be used before any objects have been created.
void
Saying that main(String args[]) itself doesn't give output
main(String args[]) {
is a method, this is where the code starts executing, you don't need the
Sting args
for this program but you will need it later so get used to typing it. :)
System.out.println
is simply telling the system to print and the
ln
is telling it to make a new line afterwards. You could also just put
print
instead of
println
. Everything in parentheses is where you can type messages.
}
The first one is closing the
public static void main() {
line and the second is closing the class
First {
.
Once you have this done this, save your file, but make sure to save it as First.java. Next, get a command prompt and go into the folder where you saved your Java file and type
javac First.java
Nothing fancy should happen. If something does, just copy and paste the program off of this document and it should compile fine. Nearly all of my errors with Java are typos that the compiler will let me know about. After this, you should have a file called First.class. Make sure you are in the same directory as First.class and type
java First
and you should see
Yea! I wrote JAVA
.
You do not need to include
.class
when you are running the program.
Next, we get started with variables. Variables can be any sort of things that you assign a value to.
class var {
public static void main(String args[]) {
int v;
v = 5;
System.out.println("v is " + v);
}
}
The output should be
v is 5
Since I have already explained most of the things in the previous program I will explain what the new things do.
int v;
This is declaring that there will be an integer variable. You must declare a variable before you use it. This variable is call v. The names can be longer then one character and
are
case sensitive.
v = 5;
v is now being assigned the value 5.
System.out.println("v is " + v);
Like before, the
System.out.println
command is being used, everything inside of quotes is what you type. To add the value of v just a the
+ v
outside of the quotes.
Once you have complied the program and ran it you should get.
v is 5
You can also do math with Java programs, like in the next example.
class math {
public static void main(String args[]) {
int a;
int b;
int c;
a = 5;
b = 9;
c = a * b;
System.out.println( a + " times " + b + " is " + c);
}
}
The output will be
5 times 9 is 45
Along with *, you can also use the +, -, and / signs for math. You can also do things like
b = b * a
where what the variable equals includes itself. The next program demonstrates a loop.
class loop {
public static void main(String args[]) {
double gallons, cups;
for(gallons = 1; gallons <=10; gallons++) {
cups = gallons * 16;
System.out.println(gallons + " gallons is " + cups + " cups.");
}
}
}
The output will be
1.0 gallons is 16.0 cups.
2.0 gallons is 32.0 cups.
3.0 gallons is 48.0 cups.
4.0 gallons is 64.0 cups.
5.0 gallons is 80.0 cups.
6.0 gallons is 96.0 cups.
7.0 gallons is 112.0 cups.
8.0 gallons is 128.0 cups.
9.0 gallons is 144.0 cups.
10.0 gallons is 160.0 cups.
The first thing different about this program is double instead of int. Int declares an integer, these work for a lot of things but loose precision if you were to divide 9 by 2, or dealing with anything that has a decimal. For things with decimals you can use float or double. There are also different types of integers other then int. Int is 32 bits, so it covers from 2,147,483,647 to -2,147,483,648. As its name suggests, long is a very long integer, 64 bit, it can handle numbers slightly over 9,200,000,000,000,000,000 and slightly under the negative. For the smaller numbers you might want to look into short (16 bit, 32,867 through -32,768) and byte(8 bit, 127 through -128). And for characters, you use char.
Getting back on track, the next thing you will notice it the two variables being declared are separated by a comma. This saves time, I can write
double a, b, c, d;
instead of writing out
double a;
double b;
double c;
double d;
The line with
for
is the loop itself. The basic form of
for
is
for(starting; restrictions; count by) statement;
The gallons = 1; is saying we want the loop starting at 1. You could start it at 57 or -23 if you wanted. gallons <= 10; is saying count everything less then or equal to 10. Here are some important things that will come in handy many times
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
And
gallons++
is the same as writing out
count = count+1
If you want to count by
2s use count = count+2
or 3s use
count = count+3
and so on. The { starts a new block of code, inside we assign
cups
the value and what to display when the loop is complete.
This next program will use the
if
statement.
class ifif {
public static void main(String args[]) {
double a, b;
a = 5
b = 4
if(a == b) System.out.println("Since 4 will never equal 5 this won't be displayed, if it does, buy a new CPU");
if(a != b) System.out.println("Since 4 isn't equal to 5 this will be displayed");
if(a < b) System.out.println("5 isn't less then 4, this will not be seen");
if(a > b) System.out.println("I think you get it by now");
}
}
If
statements are very useful in all types of situations. The
if
statement can also be used as a block of code, for example
[i]
if(5 == 5) {
double e;
e = 5;
System.out.println("e is " + e);
}
This may not seem like a very useful tool, but in time it will become very important. Say for example, you are writing a temperature conversion program. You want to prompt the user "Press A to convert Fahrenheit to Celsius or B to convert Celsius to Fahrenheit" You would have something like
if(input == A) {
Here is the program to convert Fahrenheit to Celsius
}
if(input == B {
Here is the program to convert Celsius to Fahrenheit
}
This way only the code needed is executed. Of course, you won't actually use
input
, that is just easy to understand for now.
Here is a program that uses user input to find weight on the moon.
import java.io.*;
class moon {
public static void main(String args[])
throws java.io.IOException {
double e;
double m;
System.out.println("Please enter your weight to get the moon equivalent.");
String strA = new BufferedReader(new InputStreamReader(System.in)).readLine();
e = Double.parseDouble(strA);
m = e * .17;
System.out.println("Your weight on the moon would be " + m + " pounds");
}
}
This one is more complex.
import java.io.*;
is bringing in things needed for input. The
throws java.io.IOException
is for error handling.
String strA = new BufferedReader(new InputStreamReader(System.in)).readLine();
is going to get the input and the next line is going to assign
e
the input. From there it is easy. So knowing most of this you can create simple, but useful applications like this.
import java.io.*;
public class triangle {
public static void main(String args[]) throws java.io.IOException {
double a;
double b;
double c;
System.out.println("A is? "); //asking for a
String strA = new BufferedReader(new InputStreamReader(System.in)).readLine();
a = Double.parseDouble(strA);
System.out.println("B is? "); //asking for b
String strB = new BufferedReader(new InputStreamReader(System.in)).readLine();
b = Double.parseDouble(strB);
System.out.println("C is? "); //asking for c
String strC = new BufferedReader(new InputStreamReader(System.in)).readLine();
c = Double.parseDouble(strC);
if(c == 0) { //the block that finds out what c is
b = b * b; //getting b squared
a = a * a; //getting a squared
c = a + b; //a squared + b squared equals c squared
double x=Math.sqrt(c); //finding the square root
System.out.println("C is " + x); //telling what c is
}
if(b == 0) {
c = c * c;
a = a * a;
b = a - c;
if(b <= 0) b = b * -1; //ensuring that the program will not to try to find the square root of a negative number
double y=Math.sqrt(b);
System.out.println("B is " + y);
}
if(a == 0) {
b = b * b;
c = c * c;
a = c - b;
if(a <= 0) a = a * -1;
double z=Math.sqrt(a);
System.out.println("A is " + z);
}
}
}
You get prompted for A,B and C side of a right triangle, if you don't know one side, enter in 0 for that one. The only new stuff is
double x=Math.sqrt(c);
this is just declaring x and at the same time saying it is the square root of c. Thanks to
moeminhtun
on help with the input. This is only scratching the surface of what can be done with Java so here are some more sources that have great information.
Sun
has some a
lot
of documentation on there website.
Java 2: A Beginner's Guide
is a great book. This is not a for Dummies book though. It has a steeper, yet easy to follow learning curve. On the right hand side of this page you will also see a link called "Free downloadable code", download this code and look though it, you can learn a lot.
A complete explanation of the Java buzzwords
Some more information from Sun
Beginning Java 2 SDK 1.4 Edition
Learn to program with Java:43 | https://www.linuxquestions.org/linux/answers/Programming/Beginning_with_Java?s=e7fdbd2be35e020c818f9a7288acbba9 | CC-MAIN-2020-50 | refinedweb | 2,644 | 73.27 |
edition I decided to figure out how Fn project works, how to run it, use it and even extend it. The Fn project is the container native, cloud agnostic serverless platform.
As part of this article, I’ve created three different example extensions for the Fn server — you can get them on GitHub.
The Basics — install and run
This section goes through installing the Fn server, starting it and then creating a simple function and invoking it.
You will need Docker on your machine in order to run Fn and once you have that, you can install the Fn with brew:
brew install fn
Apparently I’ve installed Fn before and the Docker image I had on my machine was > stale causing Fn fail when starting — running
fn updatewill ensure you have
the latest images on your machine.
Finally, with Fn installed and images updated, you can run the Fn server with the following command:
fn start
The above command runs Fn in a single server mode with embedded database and queue. Behind the scenes, fn start command runs a Docker image calledfnproject/fnserver in a privileged mode. It also mounts the Docker socket into the container as well as the /data folder in the current working directory (this is where database and queue information is stored). Finally, it exposes port 8080 to the host, so you can invoke it on that port.
Now that you have the Fn server running, you can create a new function.
First function
The Fn CLI comes with a init command that is used for creating new functions.
At the time of writing, these were the upported function runtimes: dotnet, go,
java8, java9, java, lambda-nodejs4.3, lambda-node-4, node, php, python,
python3.6, ruby, rust, kotlin
Before we start, here’s a simple explanation of different concepts Fn uses:
Apps
Apps are a way to logically group your functions under the same name (e.g. greeter-app)
Routes
Each function lives under a route in an app (e.g. /greeter-app/hello or /greeter-app/goodbye)
Images
Docker image that packages your function; the image used depends on the language of the function (e.g.fnproject/go, fnproject/ruby, fnproject/node, …), the goal here is that the image is as small as possible to be more performant
Calls
Call holds information about a call that was made to the function. It includes information about the app, route and time call was created, started and completed include the status of the call.
With this out of the way, let’s create a new function by providing a runtime (e.g. Go, Node or other supported language) and the name of the function:
fn init --runtime go hello
Above command creates a Go function in the hello sub folder. The function structure looks like this:
hello ├── Gopkg.toml ├── func.go ├── func.yaml └── test.json
The source of your function lives inside the func.go file and has a function handler that responds with a “Hello World” message. The
func.yaml file has information such as version runtime, name and entry point for your function.
Another interesting file is
test.json — this file holds an array of tests (input values and expected output values) and you can use it to test out your function, by running
fn test.
To run this function, you can use the
fn run command. Before you run the command, make sure you set the
FN_REGISTRY environment variable to your Docker repository.
Then when you run the command, Fn will build the Docker image with the function and runs the function like this:
$ fn run Building image hello:0.0.1 ........... {"message":"Hello World"}
This is all great, but we have the Fn server running locally, so let’s deploy our function to the server, instead of just running it.
To deploy the function, you can use the fn deploy command, specify the app name and add the
--local since the Fn server is running locally:
fn deploy --app myapp --local
Command deploys the app (called
myapp) to the local Fn server and it creates a path called
/hello (our function name).
This means that on the Fn server, the function will be accessible under /myapp/hello path. The app name is used to logically group functions together. To see the full list of all routes defined on the Fn server, run this command:
# List all routes for 'myapp' $ fn routes list myapp path image endpoint /hello hello:0.0.3 localhost:8080/r/myapp/hello
Finally, if you access the endpoint, you will get back the “Hello World” message like this:
$ curl localhost:8080/r/myapp/hello {"message":"Hello World"}
Grouping functions
To group the functions together, you can use the app name construct — this allows you to logically group different routes together (e.g.
greeter-app could have routes called
/hello and
/goodbye).
In this case the
greeter-app could also be the folder name where your functions live and subfolders
/hello and
/goodbye would contain the actual functions. You can also define the
app.yaml file in the app root folder, to be able to deploy all functions with one command.
Follow the steps below to create a greeter-app with hello and goodbye functions:
# Create the greeter-app folder mkdir greeter-app && cd greeter-app # Create app.yaml that defines the app name echo "name: greeter-app" > app.yaml # Create a hello function in /hello subfolder fn init --runtime go hello # Create a goodbye function in /goodbye subfolder fn init --runtime go goodbye
With all this set up and
app.yaml in the root folder, you can use this command to deploy all functions to local Fn server:
fn deploy --all --local
Above command creates the following app and endpoints:
$ fn routes l greeter-app path image endpoint /goodbye goodbye:0.0.2 localhost:8080/r/greeter-app/goodbye /hello hello:0.0.2 localhost:8080/r/greeter-app/hello
You can also create a function that lives in the root of your app by running
fn init command from the apps’ root folder:
fn init --runtime node
Now we have three functions under the
/greeter-app logically group:
$ fn routes l greeter-app path image endpoint / greeter-app:0.0.2 localhost:8080/r/greeter-app /goodbye goodbye:0.0.3 localhost:8080/r/greeter-app/goodbye /hello hello:0.0.3 localhost:8080/r/greeter-app/hello
Enabling the UI
If you prefer UI to interact with the Fn — there’s that for you as well. Assuming you have the Fn server running locally, you can start the UI like this:
docker run --rm -it --link fnserver:api -p 4000:4000 -e "FN_API_URL=" fnproject/ui
When image gets downloaded and container executes, you’ll be able to access the UI on.
Extending Fn
There are a couple of different options for you to extend the Fn server. All options require you to rebuild the Fn server as you will have to import your extension — you can either use the build-server CLI command and
ext.yaml file to build a new image of the Fn server with your extension(s) OR you can fork & clone the Fn repo and reference your extension in
cmd/fnserver/main.go file, then re-build the code and run it.
For development, the fastest way is to clone the Fn repo and create & register your extension there. If you are using
build-server command it might take a bit longer as that command will re-build the Fn server image each time it’s invoked. Note that you will have to build the Fn server each time in both cases, but the straight-up Go build is much faster than rebuilding a Docker image.
There are three extension points on the Fn server: listeners, middleware, custom API endpoints. Read on for a more detailed description of each extension point and look at some examples later in the article.
Listeners
You can listen to various API events and respond to them. There are 2 types of listeners at this moment: App and Call. I think Route listeners should come soon as well…
In an App listener, you can respond to the following events:
BeforeAppCreate AfterAppCreate BeforeAppUpdate AfterAppUpdate BeforeApp
These events are available in a Call listener:
BeforeCall AfterCall
Middleware
With middleware you can add desired functionality for every API request that comes to the server. Within that middleware you can then decide if you want to cancel the request or if you want to call the next middleware in the chain. A simple example of a middleware would be an authentication middleware that checks headers for a token or a middleware that logs certain things for each request.
Custom API endpoints
Custom API endpoints allow you to add new endpoints to the Fn server. For example, you could add a custom API endpoint that handles requests to a custom route such
/mycustomroute or define an endpoint with route
/v1/apps/:app_name/mycustomhandler or
/v1/apps/:app_name/routes/:route_name/mycustomhandler.
For example, one could implement a custom endpoint on apps and routes called
stats (so,
/v1/apps/:app_name/stats and /v1/app:app_name/routes/:route_name/stats) and when those endpoints are invoked you could return some basic stats for the app or a route.
Example: Call counter extension using Call listener
I wrote a simple extension that counts the number of times an app has been called and it outputs that number to the stdout. You can get the source code for the extension here.
The extension implementation is separated into two files:
callcount.go and
calllistener.go.
In the first file (
callcount.go) I register the extension and set up the call listener like this:
In the
init function, I am creating a map called
callCountMap that I’ll use to increment the calls to specific app and then I am registering the extension by calling
RegisterExtension function and passing in my extension struct that implements
Name and
Setup functions. In the name function I am simply returning just the import name where the extension is located at and in the
Setup function I am actually adding the
Call listener, telling Fn that I’ll be listening to Call events (these events are implemented in the
calllistener.go file):
In the
BeforeCall function we check if there’s an entry with the
AppID in the map, and if it isn’t, we set the number of calls to 0. Similarly, in the
AfterCall function we increment the number of calls for the
AppID and prints out that number.
With the extension ready we can modify the Fn server to include our extension. There are two things we need to do in the
cmd/fnserver/main.go file:
- Import the extension like this (line in bold):
import ( "context" "github.com/fnproject/fn/api/server" **_ "github.com/peterj/fn-extensions/callcount"** )
- Call
AddExtensionByNamein the main function:
func main() { ctx := context.Background() funcServer := server.NewFromEnv(ctx) funcServer.AddExtensionByName("github.com/peterj/fn-extensions/callcount") funcServer.Start(ctx) }
Now we can build the fnserver and run it to try out the extension.
Try out the extension
Let’s run the command below to rebuild the fnserver:
go build -o fnserver ./cmd/fnserver
Finally, run the
./fnserver and when it starts, try calling a function you’ve deployed earlier. You should see the “Call number: X” in the Fn server output:
Just like we implemented the Call listener, we could similarly add the App listener, middleware or custom API endpoints. Adding the App listener is similar to adding the Call listener — we’d need to create methods on our extension struct to satisfy the App listener interface, and then call AddAppListener function.
Example: Cancel call middleware
Let’s show how would one implement a middleware function that checks if a certain header is present (
fn-cancel-call) and cancels the chain of calls — that is, it doesn’t execute the function.
There are two different ways to inject custom middleware. One is using the
AddAPIMiddleware — this function injects the middleware to all API endpoints such as:
/v1/apps /v1/apps/:app /v1/apps/:app/routes ...
The other function —
AddRootMiddleware — injects the middleware to both API and your app calls as well.
To create a custom middleware we need implement a
Handle(next http.Handler) http.Handler function on our extension struct. Just like before, the source code for the extension is available on GitHub.
The extension registration and setup part is the same as previously, the only difference is the implementation of the middleware and the fact that we call
AddRootMiddleware function, instead of a
AddCallListener function:
The logic for the middleware is in lines 30–40. We get the header named
fn-cancel-call and if the value of that header is set to 1, we output a message and return from the function, canceling the remaining chain of middlewares. If cancel header is not set, we call the next handler in line for execution (
next.ServeHTTP) and continue the execution.
Example: Call logs using custom API endpoint
In this last example, we are going to implement a custom API app endpoint
/v1/apps/:app/logs that connect to the Fn server database an returns a list of calls that were made to the app. We are going to return a couple of fields from that array to the user.
If you went through other examples, then the above code should look familiar. There are only a couple of differences — on line 23 where we are setting up the extension, we add the
Datastore reference to our extension struct, so we can use it later in the
ServeHTTP func and get the information about the calls. We also call the
AddAppEndpoint to set up our custom API endpoint on the
/logs path and specify the
GET HTTP method.
The functionality of the extension is in the
ServerHTTP func on line 35. Here, we set up a
CallFilter first, then pass it to the
GetCalls func on the datastore to retrieve the calls made to the app.
On line 43 we are using a func that’s coming from the Fn server package to send the error response, in case we can’t retrieve the calls.
Once we get the calls, we go through each one of them and write the call ID, status, path and time call started to the response writer.
Rebuild and run the Fn server then make the call to e.g.
localhost:8080/v1/apps/myapp/logs — you will get an output similar to the one in the figure below (assuming you made some calls to that app).
Conclusion
This article should serve you as a good introduction and getting started document for the Fn. It gives you the basics you need to start playing the serverless on your local machine and gets you thinking about different ways you can extend it.
I will probably write a follow up article where I’ll talk about Fn Flow Server, Fn Loadbalancer and how to get Fn running on Kubernetes.
Thanks for Reading!
Any feedback on this article is more than welcome! You can also follow me on Twitter and GitHub. If you liked this and want to get notified when I write more stuff, you should subscribe to my newsletter!
Discussion (2)
Really liked this guide!
Thank you Miriam! | https://dev.to/peterj/playing-with-the-fn-project-5e3f | CC-MAIN-2021-17 | refinedweb | 2,569 | 59.53 |
So how exactly does this algorithm work? Basically, we initialize all the distances to infinity, except for the root Vertex which is initialized to 0. We then traverse the Graph from the starting point towards the end point. When we hit a Node, we evaluate the cumulative distance to that Node, which means the distance recorded at the previous Node plus to the distance to the current Node. So if we have A-->B weighted at 5 and B-->C weighted at C, B would record the distance 5, and C would record the distance 8. The reason we initialize to infinity is that the first time we hit that Node, everything will be less than infinity so the first distance will be stored at that Node.
For the purpose of this tutorial, I've set up a class to handle evaluating Dijkstra's algorithm using my Graph implementation from my Graphs Tutorial. I used Integer.MAX_VALUE as my infinity marker.
import java.util.*; /** * A utility class to implement Dijkstra's algorithm * @param E: The type to store in the Graph * */ public class Dijkstra<E> { //the Graph to traverse private Graph<E> graph; //the PriorityQueue for the heap-based sort private PriorityQueue<Connector<E>> heap; /** * @param graph: The Graph to traverse * * The constructor initializes each Node's * distance to Integer.MAX_VALUE, as the infinity value. * When the weights are compared, they are initially compared * to MAX_VALUE, which they will be less than. * */ public Dijkstra(Graph<E> graph){ this.graph = graph; resetGraph(); heap = new PriorityQueue<Connector<E>>(25, new Comparator<Connector<E>>(){ public int compare(Connector<E> one, Connector<E> two){ return (one.getDistance() + one.getOne().getDistance()) - (two.getDistance() + two.getOne().getDistance()); } }); } //initializes the Graph Nodes to infinity public void resetGraph(){ for(int i = 0; i < this.graph.count(); i++){ this.graph.get(i).setDistance(Integer.MAX_VALUE); } }
In this implementation of Dijkstra's algorithm, I'm using a naive, unamoritzed implementation. It comes down to basically a recursive depth-first search, updating distances for the Nodes. The minimum distance is found, and returned. Because all paths are evaluated naievely, the runtime of this implementation is O(V2), where v is the number of vertices in the Graph.
/** * @param start: The Node to start from * @param end: The target Node * @param dist: The cumulative distance at this point * * This method is implemented recursively, finding the distance of * the shortest path from some starting Node to the ending Node. * I utilize Tree-recursion, comparing the results of the child calls * to get a shortest distance. * */ public int nonheapPath(Edge<E> start, Edge<E> end, int dist){ LinkedList<Connector<E>> connections = start.getConnections(); //set the weight to a maximum that every other weight has to //be less than int weight = Integer.MAX_VALUE; //if we're at the end Node, stop if(start == end) return dist; //for each child Node from start for(int i = 0; i < connections.size(); i++){ Connector<E> temp = connections.get(i); Edge<E> update = temp.getTwo(); //check to see if the new distance is shorter than the current one if(update.getDistance() > (dist + temp.getDistance())){ //and update it if it is update.setDistance(dist + temp.getDistance()); } //now compare the current distance to the rest of the weights returned //by child calls. Note the depth-first traversal here weight = Math.min(weight, nonheapPath(update, end, update.getDistance())); } return weight; }
This implementation of Dijkstra's algorithm is optimized and utilizes a greedy approach. The minimal paths are pushed onto a PriorityQueue, giving us a better idea of which path to evaluate next based on which has the lowest cost. We begin at the starting Node, which is initialized to a distance of 0. We then push its children onto the PriorityQueue, and poll the next one to evaluate, utilizing a breadth-first search over a depth-first search. We also do not need to store or evaluate minimum weights as we did in the previous version, as when the PriorityQueue is empty, the Graph will have been fully evaluated, and end will have the shortest distance to it, which we can return. Based on this optimization, the runtime improves from O(V2) to O(E log(V)), where E is the number of Edges (or Connectors) in the Graph.
/*** * @param start: The starting point * @param end: The ending point * @return int: The shortest distance from start to end * * This method uses a PriorityQueue to determine which Edge * to visit next. Nodes are evaluated in a breadth-first search, * and pushed onto the PriorityQueue. The PriorityQueue is then polled * and the process is repeated until the PriorityQueue is empty. * */ public int heapPath(Edge<E> start, Edge<E> end){ start.setDistance(0); //initialize the start distance to 0 //the Edge to evaluate. We evaluate the start Node first Edge<E> evaluate = start; //as long as we have elements in the Graph to traverse do{ //push evaluate's children onto the PriorityQueue LinkedList<Connector<E>> connections = evaluate.getConnections(); Iterator<Connector<E>> iterate = connections.iterator(); while(iterate.hasNext()){ heap.add(iterate.next()); } //then poll the PriorityQueue to determine //which Node to visit next Connector<E> temp = heap.poll(); evaluate = temp.getTwo(); //and update that Node's distance if a shorter path is found int distance = evaluate.getDistance(); int newDist = temp.getOne().getDistance() + temp.getDistance(); if(newDist < distance) evaluate.setDistance(newDist); } while (!heap.isEmpty()); return end.getDistance(); }
If you want a test Graph to set this up with, I have gone ahead and set up the Graph to match the animation on Wikipedia.
/** * Below, I set up the Graph on Wikipedia:'s_Algorithm * */); Dijkstra<Integer> test = new Dijkstra<Integer>(list); } } | http://www.dreamincode.net/forums/topic/203665-data-structures-dijkstras-algorithm/ | crawl-003 | refinedweb | 932 | 56.15 |
NIS and NIS+ have several differences with an impact on a transition. For example, NIS uses a flat, non-hierarchical namespace with only one domain (or several disconnected domains), while NIS+ provides a domain hierarchy similar to that of DNS. This means that before you can convert to NIS+, you must design the NIS+ namespace. NIS+ also provides security, which limits access not only to the information in the namespace but also to the structural components of the namespace.
These and other differences demonstrate that NIS+ is not only an upgrade to NIS but is an entirely new product. Therefore, the transition from NIS to NIS+ is largely directed by the differences between the products.
These differences are described in broad terms in the remainder of this chapter. Understanding them is critical to a successful transition to NIS+. They are:
Domain structure
Interoperability
Server configuration
Information management
NIS+ is not only an upgrade to NIS; it is designed to replace NIS. This becomes evident when you examine its domain structure. NIS domains are flat and lack the ability to have a hierarchy. NIS+ domains may be flat, but you can also construct hierarchical NIS+ domains. Such hierarchies consist of a root domain with an infinite number of subdomains under them.
The NIS domain structure addressed the administration requirements of client-server computing networks prevalent in the 1980s, in other words, client-server networks with a few hundred clients and a few multipurpose servers.
NIS+ is designed to support networks with 100 to 10,000 clients supported by 10 to 100 specialized servers located in sites throughout the world, connected to several "untrusted" public networks. The size and complexity of these networks requires new, autonomous administration practices. The NIS+ domain structure was designed to address these requirements. It consists of hierarchical domains similar to those of DNS, as shown in the following diagram:
Hierarchical domains allow NIS+ to be used in a range of networks, from small to very large. They also allow the NIS+ service to adapt to the growth of an organization. The NIS+ domain structure is thoroughly described in Solaris Naming Administration Guide.
NIS+.
The.
NIS+ stores information in tables instead of maps or zone files. NIS+ provides 17 types of predefined or system tables, as shown in Figure 1-2:
NIS+ tables are not ASCII files, but are tables in the NIS+ relational database. You can view and edit their contents only by using the NIS+ commands.
NIS+ tables provide two major improvements over the maps used by NIS.
First, an NIS+ table can be searched by any searchable column, not just
the first column (sometimes referred to as the "key"). To know
whether a particular column is searchable, run the niscat -o
command on a table. The command returns a list of the table's columns and
their attributes, one of which is whether a column is searchable. This search
ability eliminates the need for duplicate maps, such as the
hosts.byname and
hosts.byaddr
maps used by NIS. Second, the information in NIS+ tables has access controls
at three levels: the table level, the entry (row) level, and the column level.
NIS maps are located on the server in /var/yp/domainname, whereas NIS+ directories are located in /var/nis/data. The NIS+ tables are contained in the database. The tables' information is loaded into memory as requests are made to the database. Keeping data in memory in the order requested minimizes calls to the disk, thereby improving request response time.
The security features of NIS+ protect the information in the namespace and the structure of the namespace itself from unauthorized access. NIS+ security is provided by two means: authentication and authorization. Authentication is the process by which an NIS+ server identifies the NIS+ principal (a client user or client workstation) that sent a particular request. Authorization is the process by which a server identifies the access rights granted to that principal, whether a client machine or client user.
In other words, before users can access anything in the namespace, they must be authenticated NIS+ clients and they must have the proper permission to access that information. Furthermore, requests for access to the namespace are only honored if they are made either through NIS+ client library routines or NIS+ administration commands. The NIS+ tables and structures cannot be edited directly. | http://docs.oracle.com/cd/E19455-01/806-2904/6jc3d07gd/index.html | CC-MAIN-2016-50 | refinedweb | 725 | 54.22 |
Map() function is one of the useful functions in Python. In this article, we’re going to explore what is Map function and when you can use this function.
Python map() function:
A map function is also an iterable object. Basically, the Map function takes two parameters: one is a function and then the second is an iterable_object. This is the syntax structure:
Map(func, iterable_object)
How does the Map() function work?
Basically, the Map function takes items from iterable_object and then passes them through the given function on each iteration, And then stores the result from each iteration inside the Map object. Now let’s try to understand it with an example.
for instance, let’s perform map function on list.
numbers = [1,2,3,4,5,6,6,7]
So, Now I want to multiply each items of numbers list from 3. One way to do this by using for loop, but that could be length process. But here we can use map() function to achieve the same result.
All we need a function, which should take an integer and then return multiplication of 3. and then the iterable object(which is numbers here).
numbers = [1,2,3,4,5,6,6,7] def three_mutiply(num): return num * 3 new_numbers = map(three_mutiply, numbers) print(list(new_numbers))
[3, 6, 9, 12, 15, 18, 18, 21]
In the above, we defined the three_multiply function which takes one argument and then multiplies it by 3. Now you can pass it inside the map function and then your list(numbers). Now what it does, It takes one item(1) from the numbers list and then passes it through the three_multiply(1) function, and then the result will be stored inside the map object. It will perform the same task on every item from the numbers list.
You can store this map object inside separate variable. And now because map is an iterable object, so you can create list by using list() function
Using Lambda function inside Map function:
In the above code, we can make our code much simpler using Lambda Function. So, we all know that Map function takes one function as an argument. and basically that function takes one argument and return expression.
So, instead of defining def three_multiply(), we can actually use lambda function here to make it simple. e.g:
def three_mutiply(num): return num * 3 Or lambda num: num * 3
So, because we need this function only one time, that’s why using lambda expression would better and simpler.
So, In simple words,
Map(func, iter) is an iterable object which takes one item from given iterable object and then passes it through given function. And then stores the result inside Map Object.MAP Function
Read also: Python Basic: Lists and methods
I hope you all liked this article. So, please don’t forget to share this article with your friends and other geeks. You can also subscribe to our blog via email to get future notifications from this blog.
Thanks to read…
1 thought on “Map() function in Python: Python Basics” | https://www.codechit.com/map-function-in-python/ | CC-MAIN-2021-31 | refinedweb | 515 | 71.44 |
Question 6 :
Usually recursion works slower than loops.
When a recursive call is made, the function/process clones itself and then process that funtion. This leads to time and space constrains.
In a loop, there is no recursive call involved that saves a lot of time and space too.
Question 7 :
Is it true that too many recursive calls may result into stack overflow?
Yes, too many recursive calls may result into stack overflow. because when a function is called its return address is stored in stack.
After sometime the stack memory will be filled completely. Hence stack overflow error will occur.
Question 8 :
In a function two return statements should never occur.
No, In a function two return statements can occur but not successively.
Example:
Output:Output:
#include
int mul(int, int); /* Function prototype */ int main() { int a = 0, b = 3, c; c = mul(a, b); printf("c = %d\n", c); return 0; } /* Two return statements in the mul() function */ int mul(int a, int b) { if(a == 0 || b == 0) { return 0; } else { return (a * b); } } | http://www.indiaparinam.com/c-programming-language-question-answer-functions/yes-no-questions/page1 | CC-MAIN-2019-13 | refinedweb | 178 | 73.98 |
Talk:Proposed features/tunnel:adr category
Avoid acronyms and abbreviations
Avoid abbreviations in OSM tags, please. A tag shall be self explanatory and ADR is not explicite and confusing with the 'addr' namespace. --Pieren 12:56, 16 May 2011 (BST)
ADR is a widely-known abbreviation within the transport industry. It's a shame it looks a bit like "addr" but there's not much I can do about that. The full version of the name (the origin of the abbreviation) is "Accord européen relatif au transport international des marchandises dangereuses par route" - now you can see why the abbreviation is used! --Csmale 19:46, 16 May 2011 (BST)
- Then why not hazard:ADR_category=B/C/D/E ? Something telling the non transport industry experts (majority of contributors) that this tag is about hazardous material ? -Pieren 09:37, 17 May 2011 (BST)
- These are closely related to hazmat=*, so hazmat:ADR_category=*? There seems to be a mention of the tunnel categories from a year ago at Talk:Key:hazmat. Alv 06:37, 18 May 2011 (BST)
I am happy with that as well. I will change the proposal to hazmat:adr_tunnel_category - I hope most people will be happy with this. --Csmale 21:47, 24 May 2011 (BST)
Only tunnel ?
ADR restrictions could be applied on railways, waterways and any road, everywhere there's a potential hazard, not only tunnels. You can read this on ADR page on UNECE website. The tag may be changed to be compatible with all ways. --Dri60 18:55, 16 May 2011 (BST)
As far as transport infrastructure is concerned, only tunnels are classified on a defined scale. AFAIK there is no equivalent classification system for railways, waterways or other roads (if there is, please let me know!). The main part of the ADR regulations is about classifying the load, not about the requirements for the transport infrastructure. --Csmale 19:54, 16 May 2011 (BST)
- Well, in fact ADR apply only on roads, the mistake is that in France, the "TMD" decree, based on ADR recommendations, is applied on all sort of ways. Similar proposals can be created, there's European legislation for others transports (Part "RID" in the OTIF for trains, ADN for waterways, and probably others). --Dri60 13:35, 18 May 2011 (BST)
I am interested here in classifying the infrastructure, and not the goods or the vehicles. ADR has a classification system for certain parts of the road infrastructure (namely tunnels). If RID has a system for classifying (parts of) the rail infrastructure, so you can say something like "this section of track has RID classification X3", then that can be tagged as well if we like. --Csmale 21:45, 24 May 2011 (BST) | http://wiki.openstreetmap.org/wiki/Talk:Proposed_features/tunnel:adr_category | CC-MAIN-2017-13 | refinedweb | 451 | 61.97 |
Day in the Life of a Correctional Officer
by Amber Maccione
The Life of a Correctional Officer
According to the United States Department of Labor, becoming a correctional officer is a good idea. With only having to have your high school diploma or G.E.D. and little to no experience, it is considered an entry level job. Most entry level jobs start you out at minimum wage or a little higher. The average pay for a correctional officer is around $39,000 salary or $18.00 hourly (give or take depending on location and prior experience) (Bureau of Labor Statistics 2012). But there is also a downside to this well paying job that some may not realize. When you take on a job that’s main goal is to oversee individuals who have been arrested, are awaiting trial, or are already serving time (Bureau of Labor Statistics 2012), you are walking into a “hot zone”: a place that can be potentially dangerous because the people being detained do not want to be there and are there because of crimes they have committed. Most of the training that you receive before starting a job as a correctional officer is in self-defense (Luna 2010). Why? This job is one of the most stressful and hazardous jobs to hold because the people you manage are criminals (Bureau of Labor Statistics 2012). So what is it like to be a correctional officer?
A correctional officer’s job description is to “assist in the accomplishment of the mission of the prison by maintaining control and order within the prison” or jail (Seiter 2011 p. 390). They supervise the inmates within the walls of a prison or jail and also make sure that the security procedures are followed. Seiter describes their job as highly technical in the fact that the “security procedures require strict adherence to policy and attention to detail” and highly interactive as they have to be in constant communication with the inmates in making sure all things run smoothly with little to no incidents (Seiter 2011 p. 390).
Getting a job as a correctional officer usually does not require a degree. Most places will take you as long as you have a high school diploma or equivalent (Bureau of Labor Statistics 2012). All facilities that employ you have different types of training. One experienced correctional officer shared in her story that her first job in a juvenile facility consisted of thirty-six hours of classroom training with twenty-five of those hours being about “self-defense and use of chemicals to restrain inmates” (Luna 2010). After the training, she was assigned a position at the facility. Depending on where you are assigned determines what your day will look like. A basic day in the line of duty consists of routine. Routine is essential to keeping a secure facility as well as keeping all within safe. Seiter gives an example of what one correctional officer’s routine may look like: His job starts at seven a.m. where he reports for duty and reviews what the prior shift has already done. He then opens the unit’s doors (in which he is assigned) to allow the inmates to go to work. He supervises the inmates in his crew as they work. Then after the morning shift of work, he opens the unit’s doors once again for the inmates to return. By eleven a.m., he supervises the inmates as they go to the dining hall for lunch. By early afternoon, he opens the unit’s doors to allow the inmates to go to their afternoon shift of work. Around this same time, they will do a count and allow inmates not at work to go to the recreation yard. By three p.m., the correctional officer will end his shift by recording his activities and signing over his unit to another correctional officer (Seiter 2011 p. 392). Again, all correctional officers’ days may be different as far as what their activities entail, but they all have one thing in common – routine.
Looking at what your day consists of as a correctional officer makes the job seem rather simple and easy, but the facts show otherwise. Working as a correctional officer is stressful and dangerous because those you are overseeing and managing do not want to be locked up or even told what to do and when to do it. There are many dangers that come with the territory. Officer Luna was told when starting her job that she should prepare her family by telling them that there could come a day when she leaves for work and does not return (Luna 2010). This field of work has the highest rates of nonfatal on the job injuries (Bureau of Labor Statistics 2012), but it also has potential to do more than injure you. Some of the things (other than the fact that those you supervise do not want to be there) that make the job stressful and dangerous are 1) the demands and the fact that most places are understaffed, 2) excessive amounts of overtime and lack of ability to get time off, 3) threat of violence from inmate demands not being met (assaults, riots, etc.), 4) threat of disease (Seiter 2011 p. 393-394 & Luna 2010). Luna shares that during her first week on the job she was assaulted by four inmates when they hit her with a stair stepper. She also shared that during a Code Black, she was in a unit with only two other officers and twenty-five inmates. By the time help came, inmates and officers had already been injured from the riot (Luna 2010). Correctional officers can also be exposed to disease. Luna shares that when an inmate gets angry enough he can throw feces and urine at you (Luna 2010).
So You Want To Be A Correctional Officer
So with the reward of a well paying job, comes the downside of stress and potential danger. So how do you gain compliance of inmates to lower your stress and also make sure you go home unscathed? Seiter states that the disciplinary system of the facility is key. Every facility has policies and procedures in place to make the prison or jail safe and secure for all that are within its walls. Following these things and also providing the inmates with this information will help the facility run smoothly. Luna gives a second option in which Seiter agrees: respect (Luna 2010 & Seiter 2011 p. 395). Respect is two-fold. When you give respect, you tend to get respect back in return (Luna 2010). Combining these two things will help you gain inmate compliance. If an inmate knows that you are a correctional officer here to do your job professionally and treat him with respect as a human being than most of the time he will comply with what you are asking him to do. Inmates will try to push your buttons and manipulate you only to see if you are professional. If you choose to be professional and not fall prey to their antics, your job will become less at risk for danger and less stressful.
All in all, being a correctional officer can be a rewarding job in that you have decent pay, know what is expected of you each day, and are helping inmates through their time of stay within the facility that you work. Just as inmates are to follow rules, so are you. When both comply, it makes for a pleasant atmosphere in a not so pleasant place. If you have a good work ethic and are morally sound, a job as a correctional officer could be a great fit for you career wise.
References
Bureau of Labor Statistics. (2012). “Correctional Officers.” Occupational Outlook Handbook. United States Department of Labor. Retrieved from
Luna, C. (2010). “Life on the Inside: A Correctional Officer’s View of Life Behind Bars in Texas Prisons.” HubPages.com. Retrieved from
Seiter, R. (2011). Corrections: An introduction (3rd ed.). Saddle River, NJ: Pearson Education, Inc.
Popular | https://hubpages.com/business/Correctional-Officers | CC-MAIN-2019-04 | refinedweb | 1,347 | 60.95 |
one extreme, the folder might contain markdown instructions about how to setup a development environment, or a list of prerequisites to develop and run the software. There’s nothing automated about markdown files, but the developer starting this week doesn’t need to figure out the setup using trial and error..
"Cloud Computing Governance" sounds like a talk I’d want to attend after lunch when I need an afternoon nap, but ever since the CFO walked into my office waving Azure invoices in the air, the topic is on my mind.
It seems when you turn several teams of software developers loose in the cloud, you typically set the high-level priorities like so:
Missing from the list is the priority to "make the monthly cost as cheap as possible", but cost is easy to overlook when the focus is on security, quality, and scalability. After the CFO left, I reviewed what was happening across a dozen Azure subscriptions and I started to make some notes:
Yes, there’s 104 un-pooled Azure SQL instances, and 38 app services running on 30 app service plans.
There are countless people in the world who want to sell tools and consulting services to help a company reduce costs in the cloud. To me, outside consultants start with only 1 of the 3 areas of expertise needed to optimize cost. The three areas are:
In Venn diagram form:
Let’s dig into the details of where these three areas of knowledge come into play.
Let’s say your application needs data from dozens of large customers. How will the data move into Azure? An outside consultant can’t just say “Event Hubs” or “Data Factory” without knowing some details. Is the data size measured in GB or TB? How often does the data move? Where does the data live at the customer? What needs to happen with the data in the cloud? Will any of these answers change in a year?
Without a good understanding of the Azure offerings, a tech person often answers with the technology they already know. A SQL oriented developer, for example, will use Data Factory to pump data into an Azure SQL database. But, this isn’t the most cost effective answer if the data requires heavy duty processing after delivery, because Azure SQL instances are priced for line of business transactions that need atomicity, reliability, redundancy, high availability, and automatic backups, not hardcore compute and I/O.
But let’s say the answer is SQL Server. Now what?
Now a consultant needs to dig deeper to find out the best approach to SQL Server in the cloud. There are three broad approaches:
Option #1 is best for lift and shift solutions, but there is no need to take on the responsibility for clustering, upgrades, and backups if you can start with PaaS instead of IaaS. Option #2 is also designed for moving on-prem applications to the cloud, because a managed instance has better compatibility with an on-prem SQL Server, but without some of the IaaS and management hassles. For greenfield development, option #3 is the best option for most scenarios.
Once you’ve decided on option 3, there is another two levels of cost and performance options to consider. It’s not so much that Azure SQL is complicated, but Microsoft provides flexibility to cover different business scenarios. For any given Azure SQL instance, you can:
Option #1 is the best option when you manage a single database, or you have a database with unique performance characteristics. A pool is usually better from a cost to performance ratio when you have 3 or more databases.
After you’ve decided to pool, the next decision is to decide how you’ll specify the performance characteristic of the pool. Will you use DTUs? Or will you use vCPUs? DTUs are frustratingly vague, but we do know that 20 DTUs are twice as powerful as 10 DTUs. vCPUs are at least a bit familiar, because we equated CPUs with performance capability for decades.
One significant difference between the DTU model and the vCPU model is that only the vCPU model allows for reserved instances and the “hybrid benefit”. Both of these options can lead to huge cost savings, but both require some business knowledge.
The “hybrid benefit” is the ability to bring your own SQL Server license. The benefit is ideal for moving SQL databases from on-prem to the cloud, because you can make use of a license you already own. Or, perhaps your organization already has a number of free licenses from the Microsoft partner program, or discounted licenses from enterprise agreements.
Reserved instances will save you 21 to 33 percent if you commit to a certain level of provisioning for 1 to 3 years. If you customers sign one year contracts to use your service, a one year reserved instance is a quick cost savings with little risk.
If everything I’ve said so far makes it sound like you could benefit from a using a spread sheet to run hypothetical test, then yes, setting up a spreadsheet does help.
Once you have a plan, you have to enforce the plan and reevaluate the plan as time moves forward. But, logging into the portal and eyeballing resources only works for a small number of resources. If things go as planned, I’ll be blogging about an automated approach over the next few months.
I’ve updated my Cloud Patterns and Architecture course on Pluralsight.
The overall goal of this course is to show the technologies and techniques you can use to build scalable, resilient, and highly available applications in the cloud, specifically with Azure.
In addition to walking through sample architectures, demonstrating design patterns, and adding bits of theory on topics like the CAP theorem, here are some of the lower level demos in the course:
Setting up Azure Traffic Manager and using Traffic Manager profiles to route traffic to a geo-distributed web application.
Setting up Azure Service Bus to send and receive queued messages.
Creating an Azure Redis Cache and using the cache with an SDK, as well as configuring the cache to operate behind the ASPNET IDistributedCache interface.
Provisioning a Content Delivery Network (Azure CDN) and pushing static web site content into the CDN.
Importing a web API into Azure API Manager using OpenAPI and the ASPNET Swashbuckle package, then configuring an API to apply a throttling policy.
Creating, tweaking, running, and analyzing load tests using Azure DevOps and Visual Studio load testing tools.
And more! I hope you enjoy the course!
I’ve been using Azure DevOps since the early days when the service carried the name Visual Studio Online. I’ve used the service for both professional projects and personal projects, and I’ve enjoyed the service so much I’ve demonstrated and recommended the service on consulting gigs, at workshops, at user groups, and in Pluralsight courses.
ADO has sometimes been a hard sell. The previous monikers for the service tied the product to Windows, Visual Studio, and Microsoft, so getting a Node developer to sit down and see a continuous delivery pipeline for a pure JS project wasn’t always easy. People already in the Microsoft ecosystem would also resist given the baggage of its on-premises ancestor, Team Foundation Services. And by baggage, I mean heavy enterprise baggage overstuffed with XML. I’ve gotten a lot of work done with TFS over the years, but TFS is also the only Microsoft product I’ve upgraded by hiring an external expert. I did not want to learn the installation incantations for the unholy amalgamation of TFS, SQL Server, SSRS, and SharePoint. TFS is also the only source code provider I’ve seen crash a commercial-grade network router while fetching source code.
But, the past is gone, and no other service exemplifies the evolution of Microsoft quite as well as evolution of TFS to Azure DevOps. We’ve gone from a centralized behemoth with an enterprise focus to a modern looking and sleek cloud platform that aggressively supports small open source projects as well as larger organizations.
Here are the constituent services that form Azure DevOps.
Pipelines provide a platform for building, testing, packaging, and deploying applications. It’s a feature rich build system that is extensible and easy to use. I’d consider this the crown jewel of Azure DevOps. All the heavy lifting uses build machines that the service transparently provisions in the cloud. Here are three more fun facts:
Pipelines are not tied to source control in Azure. You can pull source from public and private repositories, including GitHub.
Build minutes for OSS projects are free and unlimited..
Boards are where a team can track issues, bugs, work items, and epics. There are Kanban boards, of course, and custom workflows. The service is well featured, particularly since it is free for 5 users and about $9,000 USD a year for 100 users (note that developers with MSDN subscriptions will have free access). There are other products that have many more bells and whistles, but they’ll also start license negotiations at $20,000 for 100 users.
Git source control with an unlimited number of private or public repositories.
Automated tests will typically execute in a Pipeline. The Test Plans service is more of a place for tests not executing in a pipeline, so this service covers manual tests, and exploratory tests, as well as load tests (which are automated, but fall here for some reason).
The load testing features are the only features I’m qualified to speak about since I’ve been using the testing tools in VS Enterprise for years. Unfortunately, the tools themselves remain pretty much unchanged over these years and feel dated. The test recorder requires Internet Explorer and a plugin. The “Browser Mix” feature will allow you to make HTTP requests using an IE9 UA string, but there is no mention of any browser released after IE9, and even having a browser mix feature in 2018 is questionable.
Behind the scenes, the load testing artifacts are relatively simple XML files, so.
Your own ultimate package repository for Maven, npm, and NuGet packages. Publish packages here for internal use at your organization.
The app store for DevOps contains some high quality extensions. There is also an extensive HTTP API throughout the DevOps service to integrate with other products and your own custom utilities. Between the API and the custom extensions, there is always a way to make something work in DevOps, all you need is the will.
My opinion: GitHub is community focused, Azure DevOps is focused on organizations. But, there is some crossover. If you have an OSS project, you’ll want to host on GitHub and build in Pipelines.
Look for yourself at the aggressive and transparent evolution of Azure DevOps over the years. My only worry today is Azure DevOps using the word "DevOps" in the name. DevOps requires a way of thinking and a culture. I hope organizations don't adopt DevOps tools in the same way they adopted Agile tools and then proclaimed themselves Agile.
In a previous post I mentioned that a
scripts directory can be a welcome addition to any source code repository. What goes into
scripts? Anything you can automate to make a developer’s life easier!
Here’s a script I’ve used to simplify adding an EF migration. All I need to do from the command line is
addmigration [migration_name].
pushd src\beaverleague.data dotnet ef migrations add %1 dotnet ef database update popd
I also have a
recreatedb script I can use to start fresh after pulling changes.
pushd src\beaverleague.web dotnet run dropdb migratedb seeddb stop popd
More on how the parameters above work in a future post.
The EF repo itself uses a tools folder instead of a scripts folder, but the idea is the same. Inside you’ll find scripts to clean up test environments by dropping and shrinking databases, like this one that uses a combination of
sqlcmd and
sqllocaldb command line tools, as well as a script to query for all the non-system databases in a DB instance.
@echo off sqlcmd -S "(localdb)\mssqllocaldb" -i "DropAllDatabases.sql" -o "DropAll.sql" sqlcmd -S "(localdb)\mssqllocaldb" -i "DropAll.sql" del "DropAll.sql" sqllocaldb stop mssqllocaldb sqllocaldb delete mssqllocaldb ShrinkLocalDBModel.cmd
For more examples and ideas, checkout the TypeScript repo with scripts for everything from running tests to automating GitHub issues with OctoKit. There’s the vscode repo with scripts to setup an environment. The repo to build the official .NET Docker images includes Powershell scripts to execute
docker pull with retries.
These are all examples where 5 or 6 lines of script code can not only save time for the entire team in the long run, but also codify a common operation.
I specifically want to call out special capabilities of the
dotnet CLI tool. We’ve always had the ability to build, publish, and package from the command line, but the new global tools feature gives us an npm-ishly easy path to installing new tools and use them from anywhere.
Here are some of the tools I use.
Nate McMaster maintains a more complete list of global tools.
Take advantage of the command line renaissance in .NET Core to speed up a repeatable development process.
How does
next know how to call the next piece of middleware in the HTTP processing pipeline? I’ve been asked this question more than once when helping to write middleware components for ASP.NET Core.
I thought it might be fun to answer the question by showing the code for an implementation of
IApplicationBuilder. Keep in mind the code is meant to demonstrate how to build a middleware pipeline. There is no error handling, no optimizations, no pipeline branching features, and no service provider.
We want an app builder with a
Use method just like a real application builder, that is a
Use method that takes a
Func<RequestDelegate, RequestDelegate>. This
Func<> represents a middleware component.
When we invoke the function we have to pass in a
next delegate that represents the next piece of middleware in the pipeline. What we get back when we invoke the function is a second function that we can use to process each individual HTTP request.
The code below looks just like the code in the Configure method of a web app, although the middleware doesn’t do any real work. Instead, the components write log statements into a fake HTTP context.
app.Use(next => { return async ctx => { ctx.AddLogItem("Enter middleware 1"); await next(ctx); ctx.AddLogItem("Exit middleware 1"); }; }); app.Use(next => { return async ctx => { ctx.AddLogItem("Enter middleware 2"); await next(ctx); ctx.AddLogItem("Exit middleware 2"); }; }); app.Use(next => { return async ctx => { ctx.AddLogItem("Enter middleware 3"); await next(ctx); ctx.AddLogItem("Exit middleware 3"); }; });
If we were to look at the log created during execution of the test, we should see log entries in this order:
Enter middleware 1 Enter middleware 2 Enter middleware 3 Exit middleware 3 Exit middleware 2 Exit middleware 1
In a unit test with the above code, I expect to be able to use the app builder to build a pipeline for processing requests represented by an
HttpContext.
var pipeline = app.Build(); var request = new TestHttpContext(); pipeline(request); var log = request.GetLogItem(); Assert.Equal(6, log.Count); Assert.Equal("Enter middleware 1", log[0]); Assert.Equal("Exit middleware 1", log[5]);
Each time there is a call to
app.Use, we are going to need to keep track of the middleware component the code is adding to the pipeline. We’ll use the following class to hold the component. The class will also hold the
next pointer, which we’ll have to compute later after all the calls to
Use are finished and we know which component comes next. We’ll also store the
Process delegate, which represents the HTTP message processing function returned by the component
Func (which we can’t invoke until we know what comes next).
public class MiddlewareComponentNode { public RequestDelegate Next; public RequestDelegate Process; public Func<RequestDelegate, RequestDelegate> Component; }
In the application builder class, we only need to store a list of the component being registered with each call to
Use. Later, when building the pipeline, the ability to look forwards and backwards from a given component will prove useful, so we’ll add the components to a linked list.
public void Use(Func<RequestDelegate, RequestDelegate> component) { var node = new MiddlewareComponentNode { Component = component }; Components.AddLast(node); } LinkedList<MiddlewareComponentNode> Components = new LinkedList<MiddlewareComponentNode>();
The real magic happens in
Build. We’ll start with the last component in the pipeline and loop until we reach the first component. For each component, we have to create the
next delegate.
next will either point to the processing function for the next middleware component, or for the last component, be a function we provide that has no logic, or maybe sets the response status to 404. Once we have the
next delegate, we can invoke the component function to create the processing function itself.
public RequestDelegate Build() { var node = Components.Last; while(node != null) { node.Value.Next = GetNextFunc(node); node.Value.Process = node.Value.Component(node.Value.Next); node = node.Previous; } return Components.First.Value.Process; } private RequestDelegate GetNextFunc(LinkedListNode<MiddlewareComponentNode> node) { if(node.Next == null) { // no more middleware components left in the list return ctx => { // consider a 404 status since no other middleware processed the request ctx.Response.StatusCode = 404; return Task.CompletedTask; }; } else { return node.Next.Value.Process; } }
This has been a "Build Your Own AppBuilder" excercise. "Build you own ________" exercises like this are a fun challenge and a good way to understand how a specific piece of software works behind the scene.
In addition to src and test folders, there are a few other top level folders I like to see in a repository for a .NET Core code base.
benchmarks – for performance sensitive projects. Benchmarks typically require a benchmarking framework and perhaps some custom applications. All of the benchmark related code can live inside this folder.
build – for build scripts and other build related files. Some build systems require build artifacts to live in the root of the repository, but supporting files can live here to avoid cluttering the root. More on build files in a future post.
docs – for markdown files, diagrams, and other documentation. There are a few possible audiences for this folder, depending on the project type. For OSS libraries, documentation could include contributor focused documentation, like build instructions and style guidelines. For business apps, the folder might target users with setup instructions.
samples – for code to demonstrate libraries and frameworks. My basic rule of thumb is that if the repo builds NuGet packages for other developers to consume, you’ll want a samples folder demonstrating some basic scenarios on how to use the package.
scripts – for scripts related to the project. These could be automation scripts for sample data, computer setup, cloud provisioning, or desired state configuration. More on scripts in a future post.
specs – for those projects building on published specs. Examples would be HL7 specifications for a health data parser, or the open language grammar for a parser.
tools – for utilities, possibly from a third part, that are required to build, run, or deploy the code.. When I was learning .NET Core, I found these other folders invaluable.
Coming up: more on the build and scripts folders. | https://odetocode.com/blogs/all?page=7 | CC-MAIN-2019-51 | refinedweb | 3,258 | 63.29 |
25 January 2013 06:27 [Source: ICIS news]
By Ong Sheau Ling
SINGAPORE (ICIS)--Spot benzene prices are Asia is likely to stay soft, as a result of increased supply and weaker demand from the downstream sectors, market players said on Friday.
Several ongoing scheduled shutdowns at the key downstream styrene monomer (SM) facilities across Asia have curtailed demand for benzene and consequently, regional sellers have to seek more material to head to the US – Asia’s largest benzene consumer, they added.
“[Benzene] is in surplus in the Asian side,” a major South Korean aromatics producer said.
The US market opened this week with a soft note, declining for three successive sessions of $0.08/gal or 1.6% before grounding to a halt on Thursday at $4.88-4.92/gal (€3.66-3.69/gal) FOB (free on board) US Gulf, according to ICIS.
Asian sellers said they faced some resistance from their US buyers, delaying February loading, in view of possible downside in prices.
“US has to buy, just that they are waiting for Asia prices to fall further,” a South Korean trader said.
On 25 January mid-day, spot benzene prices were discussed at $1,390-1,405/tonne FOB Korea for February loading, shedding $42.50/tonne or 3% from Monday’s close, ICIS data showed.
Apart from declining prices, market activity also decelerated, traders and brokers said.
“[From Asia to the US], February [loadings] is slower as compared to January,” a Singapore-based shipping broker said.
“It also depends on the vessel availability,” a Singapore-based trader said, adding that Asian supply condition may remain surplus until Asian cargoes resume heading to the US in a regular manner.
Besides the numerous turnarounds at SM plants, its downstream expandable polystyrene (EPS) and unsaturated polyester resins (UPR) sectors will be due to shut from mid-February during the Lunar New Year for at least one week to even a month, traders said.
China will be closed on 9-15 February on account of the Lunar New Year holiday.
“It is the traditional lull season for SM in China, with that benzene demand will be hit,” a Singapore-based trader said.
Although margins of SM producers are healthy, absence of demand down the chain does not justify the SM makers to stock-up benzene, traders said.
On 24 January’s close, spot SM deals were reported at $1,725-1,730/tonne CFR (cost and freight) China for March parcels, according to ICIS.
In other benzene downstream markets such as phenol, margins remained squeezed. The current spread between benzene and phenol will need to rise three times to reach a breakeven level, market players said.
“Benzene producers’ margins have been fantastic. They have the room to reduce offers,” a northeast Asian SM maker said.
The benzene-naphtha spread on 25 January mid-day was at $402/tonne, more than double the breakeven level for Asian integrated aromatics makers, industry players said.
“The market does look a little soft now,” another Singapore-based trader said, adding that from March to June, market will paint a rosy picture with a slew of scheduled maintenance at the BTX (benzene, toluene, xylenes) units in Asia (see table below) .
“It is just the breathing period now. The low prices will be short-lived,” another South Korean trader said.
Shutdown schedule of BTX units in first half of 2013?xml:namespace>
($1 = €0.75)( | http://www.icis.com/Articles/2013/01/25/9634834/Asia-benzene-poised-to-soften-on-more-supply-less-demand.html | CC-MAIN-2014-23 | refinedweb | 571 | 61.36 |
Thus loadInterface() is deprecated and will be removed from Zend.php, unless somone provides practical reasons to keep it. Documentation must also be updated to reflect this change.
Are we also removing loadClass(), then? Of course, loadClass() cannot load interface classes because it uses class_exists().
No. Zend::loadClass() serves a valid purpose by providing a mechanism for factory methods to load classes, but throw exceptions on error conditions.
Loading interfaces is different, since the class using the interfaces should simply use "require_once()" directly in the file containing the source code for the class.
Since ZF has a concept of namespaces, and Zend::loadClass understands that, it seems logical to maintain a similar loading system for interfaces.
Basically, if I call:
Zend::loadClass('Zend_Controller_Router');
it seems logical that I should also be able to call:
Zend::loadInterface('Zend_Controller_Router_Interface');
If you are abstracting the actual file and using a namespace for your classes, then wouldn't it make more sense to do the same for interfaces?
I just think that a common method for utilizing namespaces for classes and interfaces should remain.
The fact that Zend::loadInterface() knows how to translate the name into an actual file exactly like loadClass() seems more coherent.
barring the fact that Zend.php couldn't use that method, every other class in the ZF could use it to load needed interfaces and classes. Although currently the ZF classes seem to use require_once for interfaces instead. Is there a significant speed difference?
Well, why use loadClass()?
If you are abstracting the actual file and using a namespace for your classes, then wouldn't it make more sense to do the same for interfaces?
Well, why use loadClass()?
No. This question was answered in my response above on 22/Aug/06.
Zend::loadClass('Zend_Controller_Front');
Now, if I understand what you are saying, we should really just use:
require_once('Zend/Controller/Front.php');
And leave Zend::loadClass() to the factory methods?
Coding standards are always open for discussion. In fact we specifically moved them to the wiki to encourage improvement and discussion within the community (see numerous past emails on the topic in fw-general).
loadClass and the other load classes do a little more than just support factory methods. They convert names to paths and verify that the file and contents are what are being requested. None of them are needed as they are convenience methods.
I prefer the function over require_once simply because it matches loadClass and does additional error checking. If it didn't exist I would write it myself.
static public function loadClass($class, $dirs = null, $isInterface = false)
In Zend classes I think we have to use require_once (not loadClass or loadInterface), because loadClass for me is an external tool. So in project I use require_once only once when calling require_once 'Zend.php'; then I use only Zend::loadClass().
Anyway if some of developers are using loadInterface, why not to leave it? I thought framework developed to make a unified tool or a wraper to frequently used functions
And the main reason, why I post comment is my idea of improvement of Zend::loadClass(), described in ZF-410.
Some child classes are optional. The example is Zend_Config and Zend_Config_Array. | http://framework.zend.com/issues/browse/ZF-329 | crawl-002 | refinedweb | 534 | 56.76 |
Three tips for faster launchpadlib api clients
Three tips from Leonard’s lightning talk in Prague about writing faster Launchpadlib API clients:
1. Use the latest launchpadlib. It gets faster from one release to the next. (The versions in the current Ubuntu release should be fine; otherwise run from the branch or the latest tarball.)
2. Profile:
import httplib2 httplib2.debuglevel = 1
will show each http request and response, so that you can see what’s taking time.
3. Fetch objects only once:
Don’t do this:
if bug.person is not None: print bug.person.name
instead
p = bug.person if p is not None: print p.name
In the first case, the client may fetch the Person object twice. (We may fix this in future.)
Tags: API, clients, front-page, Performance, tip
July 14th, 2010 at 2:28 pm
Another trick is to use Uris instead of objects in method arguments, for example
In [6]: timeit zeitgeist.searchTasks(assignee=str(launchpad._root_uri) + “~thekorn”)
1 loops, best of 3: 337 ms per loop
In [7]: timeit zeitgeist.searchTasks(assignee=launchpad.people[“thekorn”])
1 loops, best of 3: 537 ms per loop
The api doc at [0] tells you how the uri of a certain object has to llok like.
[0]
July 14th, 2010 at 2:41 pm
For a read-only script of mine trawling bugs, I saw a roughly 5-times speed increase by wrapping my bug-task objects in this below – a very blunt caching mechanism:
[edited to fix formatting — mbp]
July 14th, 2010 at 2:43 pm
oh dear – indentation not preserved :(. the if … “Entry” only acts on the single succeeding line. I think everything else is relatively unambiguous
July 14th, 2010 at 9:40 pm
“May fix”
It should be the API’s responsibility to handle caching. Else you are coding around the core problem instead of fixing it. Passing references all around the place to try limit your http calls is silly. The API is supposed to be the interface to LP not just a dumb layer on top of http.
It should at the very least be an option that is enabled by default. Since most people that use the API will be small time fish and the bigger fish would simple know the API well enough to turn off the caching and handle it internally.
Just my 2cents.
July 15th, 2010 at 9:21 am
@drubin I agree we should have at least a sensible minimal level of caching, and we need the API to at least take the concept of caching into account. I can imagine over-aggressive caching also being confusing to clients.
July 20th, 2010 at 7:58 pm
Latest version of launchpadlib is rather vague – talking with Leonard about this he really meant the version of launchpadlib in Maverick which is still under active development.
July 23rd, 2010 at 7:15 pm
Working with Leonard I’ve included the performance improvement patches into a Lucid version of the package which can be found in my PPA –. This should also make its way into Lucid updates and you can follow bug 607947 regarding that. | http://blog.launchpad.net/api/three-tips-for-faster-launchpadlib-api-clients | CC-MAIN-2016-30 | refinedweb | 525 | 71.14 |
Algorithmic Trading Series: Hooking up to TD Ameritrade’s API
Welcome to the first installment of what will likely be a series of tutorials on building algorithmic trading bots to do a multitude of things for us automatically! Along the way, we’ll touch on APIs, cloud computing, stock and option trading strategies, and a little bit of data science to search for opportunities. It should go without saying that none of what is written about here constitutes as financial advice, it’s quite likely you’ll lose money listening to me ;)
Let’s get started.
Setting up an account with TD Ameritrade
For the purpose of this series, I’m going to be using TD Ameritrade as our broker for everything we cover. This is largely a personal preference (it’s who I use for retirement, etc.), but what you choose is up to you- with the notable exception that your broker should have an API that you can get data from and access your account to make trades from. I believe Robinhood has an API as well, but I haven’t explored its capabilities much at all.
To get started, open an account with TDA if you haven’t already. The account type doesn’t really matter, but Individual is probably your best bet if you want to follow along. You don’t have to fund your account right away if you simply want to give this whole thing a shot first. Once you’ve got a brokerage account, you’ll need to register for a developer account. This is a separate account, so you can use the same username for continuity.
Building your first app
In order to place orders on your account, you need to create an developer application that will allow you to do so. Think of this as vehicle in which you can access your account. We need to create a module that will let us programmatically interact with our account via API and this is how we’ll do it.
At the top left of the screen after you register, you’ll see “My Apps”, click on this and add an app. From here it’s pretty simple, give the app a name, a description, and then specify a callback URL. The callback URL is how you’ll receive authentication to access your account, for the purpose of this tutorial we can simply use localhost to do this. It’s best to use HTTPS protocol to do this so I’m using.
Once your app gets approved, you can go to My Apps and click on the app to view your Consumer/API Key. This key is important to keep personal (do not share it!), but we will need it to perform OAuth.
tda-api
There is a beautiful package of wrappers built by Alex Golec that will allow us to do much of what we’re going to want to in the near future (documentation here and source code here). As opposed to making a large number of HTTP requests to TD’s API, we can simply use this wrapper to make things a little bit easier and less ugly. This package will make OAuth a breeze as opposed to having to handle a set of auth keys and tokens. We’ll need to install the
tda-apipackage, and we’ll also want to have
ijsonon hand to parse the JSON responses we’ll get from our requests, as well as
seleniumto perform the OAuth workflow. To download the necessary packages, I’ll use
pipin Z shell:
% pip3 install tda-api% pip3 install ijson% pip3 install selenium
Chromedriver
Once we have the packages, we’ll also need to have Chromedriver downloaded. This will allow Python to programmatically open Google Chrome (tda-api is browser agnostic, so Chrome isn’t necessary but you need a driver of some sort). Take care in where you place the executable, we’ll need to put the path in our script.
OAuth
To get the keys to the car so we can access our account and place trades, we need to get a token that will allow us to verify who we are. For 99% of people, using the process that the
tda-apipackage has in place is exactly what we need. If you are wanting to go serverless with your trading, then this process will not be for you as we’ll be generating a token file that will not work in a serverless architecture. To make my life easier, I’m planning to instead use a VM instance. If your head is spinning at the last couple sentences, this process will work for you.
To get this thing cooking, we’ll go ahead and authenticate and then get some price history for $AAPL. To do this, we write up the following in a .py script.
# 1.
from tda import auth, client
import json
# 2.
token_path = ‘token’
# 3.
api_key = ‘YOUR_API_KEY@AMER.OAUTHAP’
# 4.
redirect_uri = ‘'#5.
try:
c = auth.client_from_token_file(token_path, api_key)
except FileNotFoundError:
from selenium import webdriver
# 6.
with webdriver.Chrome(executable_path=’/Users/trouze/Documents/td_bot/chromedriver’) as driver:
# 7.
c = auth.client_from_login_flow(
driver, api_key, redirect_uri, token_path)
# 8.
r = c.get_price_history(‘AAPL’,
period_type=client.Client.PriceHistory.PeriodType.YEAR,
period=client.Client.PriceHistory.Period.TWENTY_YEARS,
frequency_type=client.Client.PriceHistory.FrequencyType.DAILY,
frequency=client.Client.PriceHistory.Frequency.DAILY)
assert r.status_code == 200, r.raise_for_status()
print(json.dumps(r.json(), indent=4))
To break it down, we are doing the following:
1. Importing
tdaand
jsonpackages
2. Specifying the token path, it’s likely you’ll want to keep it in the same directory that you’re working in, so calling it
tokenwill suffice
3.
api_keyis the Consumer Key that is listed on your app. Leave the suffix
@AMER.OAUTHAP
4.
redirect_uriis the callback URL we specified when making our developer app, if you’re following along it should be
5. What happens next is the script will try to authenticate, because we don’t have a token yet, we will drop down to the
except: call, which will bring up our Chrome browser.
6. We need to tell
seleniumwhere to find the Chromedriver that we downloaded earlier, so enter the path after
executable_path=and make sure you put
chromedriverat the end of it so it can execute.
7. This is where the login flow wrapper will open Chrome and bring us to the TD Ameritrade authentication page, enter your Brokerage account username and password (not developer account!). Under the hood, this makes a request with your Consumer key that sends back an authorization token to our Callback URL, in which we capture through
selenium. The auth token gets written to our
tokenfile.
8. This part of the code uses our current authorized session to request price history on $AAPL
Copy the above code block and put it in a Python script and run it.
% python3 td_bot.py
This will run the flow, print the price history, and save the auth token in a file
token in the same directory.
Auth Token
TDA’s auth tokens last for 90 days, and the
tda-apipackage will automatically update when the 90 days is up through the same workflow. It should also be noted that the auth token is used to generate a session token, which only lasts for 30 minutes. So if you’re running this line by line and too much time passes, you’ll have to re-authenticate:
c = auth.client_from_token_file(token_path, api_key)
And again, I can’t stress enough, do not share any of the tokens/keys or put them online anywhere.
If you’ve made it this far, you now are set up to programmatically access your TD Ameritrade account via API request. Boom!
Check back soon, as I’ll be walking through how we can take this to the cloud where we’ll be able to schedule scripts to be ran during trading hours. To get updated automatically, subscribe and I’ll fire it out to you when it’s ready. | https://tylerrouze.medium.com/algorithmic-trading-series-hooking-up-to-td-ameritrades-api-53156b346d51 | CC-MAIN-2021-21 | refinedweb | 1,335 | 60.35 |
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
EXTENDED JSON
Simple extended version of JSON encoder for handling serialization of few other than standard python data types. It tries to use simplejson lib if found then fallback to stdlib json module. Raises an exception if no json module can be loaded.
Supports the following objects and types by default:
In addition if object have __json__ attribute or method encoder will use that for serialization
usage:
from ext_json import json
imported json have already extended encoder as default so no special calls are needed to execute json.dump or json.dumps
if you prefer to import specific encoder you can do:
from ext_json import simplejson # for simplejson <-- can be None from ext_json import stdlibjson # for json from stdlib | https://bitbucket.org/marcinkuzminski/ext-json/overview | CC-MAIN-2017-34 | refinedweb | 142 | 53.71 |
PDF/A doesn't specify an archival strategy, it only specifies a number of constraints that a PDF document must satisfy. There are currently two levels of conformance: PDF/A-1b and PDF/A-1a. The PDF library supports level 1b; 1a includes all of the constraints of 1b plus the requirement that all textual content must be tagged with structural information, which is not yet supported. When authoring PDF/A documents, you must ensure:
- all fonts used are embedded in the document using an embeddable font format
- all colour spaces used are device independent
- you do not include audio or video media
- you do not embed JavaScript, links to executables, or hyperlinks to external documents
- you do not use encryption of streams
- you specify standards-based (Dublin Core) metadata for the document
First, we need to use an embeddable colour profile. If you're working with PDF/A you should have an ICC profile available in a file, and you can use java.awt.color.ICC_Profile to load it in. Here I use a profile in the file SWOP.icm, this is a CYMK profile.
import org.faceless.pdf2.*; import java.awt.Color; import java.awt.color.*; ICC_Profile icc = ICC_Profile.getInstance("SWOP.icm"); ColorSpace cs = new ICC_ColorSpace(icc); OutputProfile profile = new OutputProfile(OutputProfile.PDFA1b_2005_Acrobat, "CGATS TR 001", null, "", null, icc);If we want to include text then we need to load in the font to use from a file. It must be an embeddable font format such as OpenType.
InputStream fin = new FileInputStream("HelveticaLTStd-Roman.otf"); PDFFont helvetica = new OpenTypeFont(fin, 2);
Now we can create a new PDF with this output profile and draw some stuff into it as usual, ensuring that we use only the embeddable fonts and the colour space we defined. Note that the colour components used to create the java.awt.Color object depend on the colour profile (I use CMYK black below).
PDF pdf = new PDF(); pdf.setOutputProfile(profile); PDFPage page = pdf.newPage("A4"); PDFStyle style = new PDFStyle(); style.setFont(helvetica, 24); style.setFillColor(new Color(cs, new float[] { 0, 0, 0, 1 }, 1)); page.setStyle(style); page.drawText("Hello, PDF/A-viewing world!", 100, page.getHeight() - 100);
We should add some metadata, the more the better to help those people opening your PDF/A time capsule hundreds of years in the future make sense of the contents.
pdf.setInfo("Author", "Joe Bloggs"); pdf.setInfo("Title", "My first PDF/A document"); pdf.setAction(Event.OPEN, PDFAction.gotoFit(page));
Finally, render the document to a stream:
pdf.render(out); | http://bfo.com/blog/2009/02/20/creating_pdf_a_documents_with_the_bfo_library/ | CC-MAIN-2017-04 | refinedweb | 425 | 57.87 |
> Why polling?
I suspect Salem doesn't have the support from the admins to get it implemented and he wants to show them that the board at large thinks it's necessary.
That's just a guess, though.
This is a discussion on Please restore the code tag checking script within the A Brief History of Cprogramming.com forums, part of the Community Boards category; > Why polling? I suspect Salem doesn't have the support from the admins to get it implemented and he wants ...
> Why polling?
I suspect Salem doesn't have the support from the admins to get it implemented and he wants to show them that the board at large thinks it's necessary.
That's just a guess, though.
-Govtcheez
govtcheez03@hotmail.com
>> Maybe I don't want to tag my code for some reason. If you don't like it, don't read it and don't post any answer.
echo Salem - I don't see what reason one could have for not using them ... makes no sense to me really. And if you do post code without tags, unless the topic interests me, I won't
>> We could all just change our sigs like quzah
Nice idea, but I don't know if it would work ... unless quzah posts at the start of every thread ...
This is why we neet that script back!
Last edited by twomers; 08-18-2006 at 02:57 PM.
For example I don't want to quote my one line
fstream myfile;
I don't know the script's behavior as I said. But if it wants to prevent me, I am not agree with it. It is my freedom to send my post in whatever format I want (even if I never send a bad formated post in my life). If moderators want to force members, the polling is meaningless, or at least it should be titled: "Force code tags or not?". But if this polling is to ask ideas, this is my idea.
Beside the auto tagger that is very useful, a script for painting keywords would be very nice.
If its true, why admins don't come to tell us their opinion? The board can activate the script for a while and after that poll for it.If its true, why admins don't come to tell us their opinion? The board can activate the script for a while and after that poll for it.I suspect Salem doesn't have the support from the admins to get it implemented and he wants to show them that the board at large thinks it's necessary.
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
I voted yes before I even read what they were.....
I don't regret it though.I don't regret it though.
>You've voted, right, joe. Voted yes, right?
Didn't you look at the extended poll results?
I was unaware of this. The forced code tags was irksome when trying to quote something like:I was unaware of this. The forced code tags was irksome when trying to quote something like:Also, if you really wanted to post braces, you could use the HTML character quoting & # thingy to get your braces into prose.
You would be forced to add code tags.You would be forced to add code tags.Code:if (num == 2) {
The problem with the code tag script was that it was stupid, and easily thwarted. People would just stick code tags in... NOT AROUND THEIR CODE... just in any old place, and it would still let their code through. Or, you could have two segments of code, with say a commentary between them, wrap one of them in code tags, and not the other, and the script wouldn't catch it.
Also, if I recall correctly, the script was stupid in that any time you used a { or a }, it assumed you were posting code, and required you to code tag wrap that. As a matter of fact, I believe that was the only thing it checked for. For example, the following wouldn't require code tags:
if( a == b )
c( );
else
d( );
Anyway, I'm for deleting threads which don't use code tags. Delete it, PM them why, and call it good enough.
Quzah.
Hope is the first step on the road to disappointment.
I voted yes because whenever I was notified about not having tags I felt
overwhelming shame and uncleanliness and immediately modified my post.
Perhaps just a warning before continuing would suffice, and a counter of the
number of times it was ignored by a person, maybe a limited number in a
timeframe - (so many per week || another amount per month) - if either is
broken your post is blocked?
I'm personally fed up with the number of poorly formatted posts lately, and the
necessity to request that the OP cleans it up. Also, is the page with the rules
still displayed when becoming a member these days? Perhaps a big flashing
annoying box that says use tags and ask definite questions that won't close
for half an hour might do the trick for new members - be a fun challenge to get
that past pop up blockers...
No No's:
fflush (stdin); gets (); void main ();
Goodies:
Example of fgets (); The FAQ, C/C++ Reference
My Gear:
OS - Windows XP
IDE - MS Visual C++ 2008 Express Edition
ASCII stupid question, get a stupid ANSI
I don't remember that script...must have been during some hiatus or something.
Not to stroke the fur the wrong way, but I'm going to say no. Why?
1) we do a pretty good job of ignoring people who don't use code tags
2) those who don't ignore usually mock the poster in a most entertain fashion /cough quzah /cough
So intead of code tags, we should just make sure quzah sticks around. If he's ok with that idea of course. Or maybe we can have a public service anouncment with the transforms.
"Always use code tags timmy, or you're going to get reamed. Now you know, and knowing is half the battle!"
No need to delete the posts, no need to mock the user. The script is a minor annoyance to established members who know what they are doing, but it often helps new members who don't.
Not everybody who doesn't know the rules is an idiot, and the code tag script is an excellent way to help those that aren't. Those that are will expose themselves anyway.
> For example I don't want to quote my one line
> fstream myfile;
The script never detected one-liners like that.
It used the heuristic that IF (and only IF) the post had braces that is was almost certainly code (good enough to bet on anyway).
Braces imply that the code has block structure (and therefore if the programmer has any clue, indentation), and thus it becomes highly desirable that the code is surrounded by code tags to preserve that indentation.
> The board can activate the script for a while and after that poll for it.
We did that last time, long before you showed up.
All I'm after is getting the functionality prior to the board upgrade restored, nothing more.
Wanna reverse your vote yet?
> Not to stroke the fur the wrong way, but I'm going to say no. Why?
So half the posts on the board become the ticking corpses of posts which got it wrong first time round. And when the creative flames die away and posts become ignored, the board will die - nobody posts on boards which have 0 replies to too many threads.
Yeah, "That'll work - NOT" my simple auto tagger, it finds code lines and marks them as "code" then it will add tags where appreciated :
1) Find all lines ending with ';' and mark them as "code". This line will be processed later. Now search backward to find a blank line and mark all lines below it as "code".
2) Find all lines beginning with '#' and mark them as "code".
3) Find ")*{" where * is space or nothing. Then search for "}" and mark all the lines between them as "code".
4) In case of ")*{" search backward for "(" and mark its line as "code"[EDIT] and its above line until reach a blank line.
5) Find all lines beginning with "//" and mark them as code.
6) Find all lines beginning with "/*" and find its next"*/" then mark all lines between them (including their lines) as code.
With this technique, this program will be tagged like this:
[Quote]
This is my program take a look at it.
Think we have a int array each member for each line. 0 is for no code, 1 is for code and -1 is for blank lines. My code is lines, the array will be like:Think we have a int array each member for each line. 0 is for no code, 1 is for code and -1 is for blank lines. My code is lines, the array will be like:Code://This program is for testing auto tagger #include<iostream> int a; int b; using namespace std; int main() { cin >> a; cout<<"On your mark, ready set lets go" <<"dance floor pro, I know you know…"; return 0; } cout << "This line is out of the braces "<<endl <<"but it will be marked as \"code\" too"<<endl;
In the next phase it will turn all -1 between 1s to 1. In the third phase it adds code tags and paint keywords for the sequences of 1s.In the next phase it will turn all -1 between 1s to 1. In the third phase it adds code tags and paint keywords for the sequences of 1s.Code:isCode[0] == 0 : isCode[10] == 1:Between{} isCode[1] == 1 :// Mark isCode[11] == 1 :Between{} isCode[2] == 1 :'#' Mark isCode[12] == 1:Between{} isCode[3] == 1 :';' Mark isCode[13] == 1:Between{} isCode[4] == 1 :';' Mark isCode[5] == -1 :Blank isCode[14] == 1 : } Mark isCode[6] == 1 : )*{ Found isCode[15] == -1 :Blank isCode[7] == 1 :)*{ Found isCode[16] == 1 :';' Mark backward search isCode[8] == 1 :Between{} isCode[17] == 1 :';' Mark isCode[9] == 1 :Between{} isCode[18] == -1 : Blank
There should be one blank line between code and no code if poster wants to begin code without brace.
For exampleThis line doesn't work:
Code:cout<<"classmates ar lazy" <<endl;
Last edited by siavoshkc; 08-19-2006 at 08:04 AM.
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
I think (as far as I can see) the main reason some of you are pushing for the code tag script is:
* To learn newbies in the art of using code tags
And the opposition is mostly centred on:
* Experienced members know what they're doing and don't want to have bots force their poorly-coded opinions on them
So why don't we force the tags on new members, pop-up a "reminder" for existing members and assume the seniors are better off without? You could use postcounts to differentiate.
As for me, well, I'd rather the forum software just inform me ("Hey, you seem to have forgotten code tags") and not force anything, or worse, do it by;}
>> So why don't we force the tags on new members, pop-up a "reminder" for existing members and assume the seniors are better off without? You could use postcounts to differentiate.
Let's not. Post counts should never mean anything, and it would be too simple to get rid of such a lousy barrier with a little time.
Not necessarily directed at anyone (but maybe everyone): I really do have trouble understanding the opposition in this discussion. A little JavaScript alert is pretty non-intrusive, and JavaScript can be disabled if you hate it. The experienced people here are not likely to see it that often anyway. The trouble in "Going Advanced" is also a non-issue, simply because the reply button was there if you needed to do something fancy. The auto-tagger was never a serious idea, coming from this thread, either.
But post counts imply that the poster is at least somewhat competent (forum wise, not C/C++/C#/Win/Linux programming wise)! I mean, if a new member wants to ask a question, they won't go to the GD where code isn't the main discussion, they go to whichever board seems right. Even if someone is competent at programming, that doesn't mean that they know about the tags, which in turn doesn't mean they will use them. Lets face it, who read the guidelines before posting their first thread?
The script could ignore stuff inside [noparse][/noparse] tags. That way if you wanted to post a curly brace (like "You forgot a } after the second if") outside code tags you could surround it with noparse tags.
[edit] If the script was enabled without any way to post curly braces, some people would have to change their signatures. This one comes to mind:
[/edit][/edit]
Originally Posted by crepincdotcomOriginally Posted by crepincdotcom
Last edited by dwks; 08-24-2006 at 04:21. | http://cboard.cprogramming.com/brief-history-cprogramming-com/81961-please-restore-code-tag-checking-script-5.html | CC-MAIN-2013-20 | refinedweb | 2,240 | 78.38 |
SKEY(3) NetBSD Library Functions Manual SKEY(3)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
skey, skeychallenge, skeylookup, skeygetnext, skeyverify, skeyzero, getskeyprompt, skey_set_algorithm, skey_get_algorithm, skey_haskey, skey_keyinfo, skey_passcheck, skey_authenticate -- one-time password (OTP) library
LIBRARY
S/key One-Time Password Library (libskey, -lskey)
SYNOPSIS
#include <skey.h> int skeychallenge(struct skey *mp, const char *name, char *ss, size_t sslen); int skeylookup(struct skey *mp, const char *name); int skeygetnext(struct skey *mp); int skeyverify(struct skey *mp, char *response); int skeyzero(struct skey *mp, char *response); int getskeyprompt(struct skey *mp, char *name, char *prompt); const char * skey_set_algorithm(const char *new); const char * skey_get_algorithm(void); int skey_haskey(const char *username); const char * skey_keyinfo(const char *username); int skey_passcheck(const char *username, char *passwd); int skey_authenticate(const char *username); void f(char *x); int keycrunch(char *result, const char *seed, const char *passwd); void rip(char *buf); char * readpass(char *buf, int n); char * readskey(char *buf, int n); int atob8(char *out, const char *in); int btoa8(char *out, const char *in); int htoi(int c); const char * skipspace(const char *cp); void backspace(char *buf); void sevenbit(char *buf); char * btoe(char *engout, const char *c); int etob(char *out, const char *e); char * put8(char *out, const char *s);
DESCRIPTION
The skey library provides routines for accessing NetBSD's one-time pass- word (OTP) authentication system. Most S/Key operations take a pointer to a struct skey, which should be considered as an opaque identifier.
FUNCTIONS
The following high-level functions are available: skeychallenge(mp, name, ss, sslen) Return a S/Key challenge for user name. If successful, the caller's skey structure mp is filled and 0 is returned. If unsuccessful (e.g. if name is unknown), -1 is returned. skeylookup(mp, name) Find an entry for user name in the one-time password database. Returns 0 if the entry is found and 1 if the entry is not found. If an error occurs accessing the database, -1 is returned. skeygetnext(mp) Get the next entry in the one-time password database. Returns 0 on success and the entry is stored in mp and 1 if no more entries are available. If an error occurs accessing the data- base, -1 is returned. skeyverify(mp, response) Verify response response to a S/Key challenge. Returns 0 if the verification is successful and 1 if the verification failed. If an error occurs accessing the database, -1 is returned. skeyzero(mp, response) Comment out user's entry in the S/Key database. Returns 0 on success and the database is updated, otherwise -1 is returned and the database remains unchanged. getskeyprompt(mp, name, prompt) Issue a S/Key challenge for user name. If successful, fill in the caller's skey structure mp and return 0. If unsuccessful (e.g. if name is unknown) -1 is returned. The following lower-level functions are available: skey_set_algorithm(new) Set hash algorithm type. Valid values for new are "md4", "md5" and "sha1". skey_get_algorithm(void) Get current hash type. skey_haskey(username) Returns 0 if the user username exists and 1 if the user doesn't exist. Returns -1 on file error. skey_keyinfo(username) Returns the current sequence number and seed for user username. skey_passcheck(username, passwd) Checks to see if answer is the correct one to the current chal- lenge. skey_authenticate(username) Used when calling program will allow input of the user's response to the challenge. Returns zero on success or -1 on failure. The following miscellaneous functions are available: f(x) One-way function to take 8 bytes pointed to by x and return 8 bytes in place. keycrunch(char *result, const char *seed, const char *passwd) Crunch a key. rip(buf) Strip trailing CR/LF characters from a line of text buf. readpass(buf, n) Read in secret passwd (turns off echo). readskey(buf, n) Read in an s/key OTP (does not turn off echo). atob8(out, in) Convert 8-byte hex-ascii string in to binary array out. Returns 0 on success, -1 on error. btoa8(out, in) Convert 8-byte binary array in to hex-ascii string out. Returns 0 on success, -1 on error. htoi(int c) Convert hex digit to binary integer. skipspace(cp) Skip leading spaces from the string cp. backspace(buf) Remove backspaced over characters from the string buf. sevenbit(buf) Ensure line buf is all seven bits. btoe(engout, c) Encode 8 bytes in c as a string of English words. Returns a pointer to a static buffer in engout. etob(out, e) Convert English to binary. Returns 0 if the word is not in the database, 1 if all good words and parity is valid, -1 if badly formed input (i.e. > 4 char word) and -2 if words are valid but parity is wrong. put8(out, s) Display 8 bytes s as a series of 16-bit hex digits.
FILES
/usr/lib/libskey.a static skey library /usr/lib/libskey.so dynamic skey library /usr/lib/libskey_p.a static skey library compiled for profiling
SEE ALSO
skey(1), skeyaudit(1), skeyinfo(1)
BUGS
The skey library functions are not re-entrant or thread-safe. The skey library defines many poorly named functions which pollute the name space. NetBSD 5.0 November 10, 2001 NetBSD 5.0 | https://man.netbsd.org/NetBSD-5.0/skey.3 | CC-MAIN-2022-40 | refinedweb | 897 | 66.13 |
PAGE 2
Feburary 2014 • Volume 1 • Number 7 Mitsi Brown Levert Blount III Consultants Gene R. Hill, Sr. Reginald Clark Contributing Writers K.G. McDonough Paige Francis Trina Morgan Sylvia Stelly Abby Ecker Joyce R. Kebodeaux Dawn Guillory Mary Ledet Mark Wayne All. Feburary 2014 • Volume 1 • Number 7 FEBRUARY 2014 • Volume 1 • Number 7
4 A Path to a Patent 6 LaFamilia: Valentine’s Day Around the World 9 How Will Health Care Reform Affect You? 10 Foreman-Reynaud Community Center 12 Music Makers 2 U 14 Junior League: Celebrating 80 Years 17 Valentine’s Day Tips 20 Lake Charles Business Report
4
6
9 10 12
20
brenda@thevoiceofsouthwestla.com tracy@thevoiceofsouthwestla.com PAGE 3
An Inventor’s Journey
The Path to a Patent by K.G. McDonough
Gene R, Hill, Sr., has lived a colorful career life. He started out as a cook in the Army. Since then, he’s worked off-shore, for a utility company, and in industrial plants. He’s been a welder, mechanic, machinist, construction worker, pipe fitter, and heavy equipment operator. He’s a multi-craftsman; a “jack of all trades and master of some,” as he likes to say. Add to that list “inventor.” In the year 2000, Hill contracted himself out as a mechanic with a local trucking company. Around that time, the government mandated that tractor-trailer rigs must have a device that manages communication between tractor and trailer. Seeing Hill’s capabilities, supervision ex-
pressed their need for a device that would comply with the mandate. This was the beginning of what Hill named the Swivel-Hill, an apparatus for supporting cables, hoses and the like between a tractor and trailer of a tractor-trailer rig. Seven Swivel-Hills were designed and placed on seven of their trucks. The trucking company owner immediately recognized the benefits of the apparatus and bought ten more Swivel-Hills with easy installation. How does one come to have the knack for ingenuity? Hill believes he was born with it – a gift from God. As a child, Hill made all his own toys. “I made my own kites, my own wagons, bows and arrows. I didn’t just become an inventor in 2000,” he says. “God was training me all along. He walked me in the way that I needed to go to become who I am today.” Hill had a rough childhood, basically growing up an orphan. His father died when Hill was seven; his mother when he was twelve. “I lived with my grandfather, aunts, uncles
and people in the community. I was always a pretty good kid, but I acted out some anger.” In school, Hill was the kind of kid educators often label as “difficult.” He preferred to gaze out the window rather than focus on the teacher and chalkboard. But Hill doesn’t see that as a negative thing. He says that by looking out the window, he learned how to apply the teachers’ lessons to the real world. As an adult, Hill has a soft spot in
How the Swivel-Hill Works This device works manually with the action of the 5th wheel on an 18-wheeler. Prior to the government mandate, the electrical and hydraulic lines would lay on the catwalk or platform between the tractor and trailer. The friction caused by the constant rubbing of the rubber hoses on the rough metal platform caused damage to the hoses, increasing the risk of accidents. The Swivel-Hill suspends the lines off the platform and protects them on turns. It significantly decreases incidents, accidents and hazardous waste spills, also improving highway and environmental safety. PAGE 4
Feburary 2014 • Volume 1 • Number 7
his heart for kids who struggle as he did. He says, “Teach a child how to get in touch with himself and bring what he has within him to society. Everyone has their own gifts.” Hill conducts a prison ministry at the Allen Correctional Center. He visits with the inmates once a week, counseling and giving them hope. He is also a mentor in the neighborhood for fatherless youth needing guidance and support. Hill also feels God put people in his life that fostered his creativity. In the mid-90s, Raymond Phillips, who invented the first cordless telephone in 1956, came to Lake Charles. He was also a preacher. Hill met Phillips at a church service. “He inspired me, and I said a silent prayer, ‘Lord, I would love to be an inventor.” After Hill designed the Swivel-Hill, his wife Brenda urged him to apply for a patent for the appara-
Feburary 2014 • Volume 1 • Number 7
tus. Hill agreed, and put into motion the patent process, which ultimately took three years. A minister in Texas, John Whitley, helped Hill find a patent attorney who helped him get started. But in the meantime, Hill needed to earn a living. Whitley asked, “Gene, what can you do?” Of all the skills Hill possessed, Hill said, “I can bake cookies. I make the best cookies in the world!” Hill developed recipes for various cookies and the famous hilka-doodle, a snicker doodle with a different twist, became a favored trade secret. This is how he became known as the ‘Kukee Man.” In 2003, the long-awaited patent approval letter finally arrived in the mail. But patent approval was only the beginning. Hill still had to market his apparatus. He visited Donna Little at the McNeesse State University Small Business Development Center and Adrian Wallace, SWLA
Microenterprise Development Director and received the needed help. He called trucking companies and truck manufacturers. While focused on the safety value of the Swivel Hill, he did a test market to gather necessary data with the Louisiana Department of Transportation, (LA DOTD) District 07. LA DOTD District 07 recommends the “Swivel-Hill” safety apparatus. Things seemed to be moving along fairly well . . . until the 2005 hurricane season. Hurricanes Katrina, Rita and Wilma set back Hill’s marketing ventures considerably. It was a dark and difficult time for the Hills. They had storm damage to their own home. They were discouraged. Louisiana was in recovery mode. No one had time to think about a simple apparatus that could improve safety on trucks. But Hill never gave up. He contacted U. S. Department of Trans-
portation, Federal Motor Carrier Safety Administration in Washington, D.C. to provide them with information about the Swivel-Hill. Hill hopes insurance companies, officials, lobbyists and legislating bodies will consider the benefits and safety of the Swivel-Hill. So far, his safety apparatus is still not widely in use. He continues his quest to establish his invention in the trucking industry. And he says he has a notebook full of other ideas, just waiting to be developed. “I ask God to give me an understanding of whatever I might be working with. God gave me the idea for the Swivel-Hill. It’s not what you see; it’s what you desire because witty inventions come out of the mind of God and He puts it before you. Out of a need, I made something beneficial.”
PAGE 5
Love
“El Dia del Amor y la Amistad”
by Sylvia Stelly
When I think about love I can only think of God’s love. Because it is through God’s love that we can love one another. No matter your race, creed or nationality. John 5:12 – Love one another, as I have loved you. It doesn’t say to love because you’re the same skin color or we look the same. This is something we all need to keep in mind when we see someone of a different culture, nationality or speaking a different language. Love is a universal language. There shouldn’t be any limits. God’s love is far above mere human love. – it never fails. True love is not based on outer appearances. It goes deeper and it is a matter of the heart. God’s love does not draw lines. It comes with OPEN eyes,
PAGE 6
OPEN arms and an OPEN HEART. If I can could move mountains, but didn’t love others, I would be nothing. If I gave everything I have to the poor and even sacrificed my body, I could boast about it; but if I didn’t love others, I would have gained nothing. Love is patient, love, love and the greatest of these is LOVE. 1 Corinthians 13:1-13 “. Here are some cultural fun facts of how Latinos celebrate Valentine’s Day around the World: Cuba: It is often said that romance and passion runs in the veins of the Cubans and every person there have his or her own love story to tell. The festival has been a grand affair for the natives since a long time, as reflected in the endless parties and balls organized on the day. However, one is hardly surprised by this fact, as the country has always been associated
with passionate love and soul-consuming romance. Gift giving and receiving is an essential component of Valentine’s Day festival in Cuba and lavish gifts are showered on loved ones. Although this is mostly a celebration of romantic love between two people, friends, family and acquaintance also take part in it, through get-togethers and parties. Preparing special meals is a vital part of these celebrations and the whole house is adorned with beautiful decors and ornaments.. Feburary 2014 • Volume 1 • Number 7
in Colombia, men still serenade woman. It is a beautiful tradition. Puerto Rico: This day.!
fessing their love. How adorable is that?? For Venezuelans and Colombians this is a big holiday. Colombia is also the number one exporter of flowers on this day. Bolivia: “Día de Amor” is celebrated on September 21st with an exchange of cookies, candies, and flowers..
Colombia: Valentine’s day is usually celebrated on the third Saturday of September, this day is filled with secret admirers giving gifts and pro-
Chileans, Argentineans, Bolivians and Ecuadorians celebrate on February 14 “El Dia de los Enamorados”, and in Ecuador like
WIRELESS
• NO Phone Lines • NO Contracts • Local Service
BUSINESS INTERNET! 337-310-1554 Feburary 2014 • Volume 1 • Number 7
True Latin Culture Traditions for Valentine’s/ Valentine’s Day Latino Style:.
icant appreciated, more so knowing that enjoying chocolate is an ancient tradition in Latin America. So as we celebrate Valentine’s Day whether the traditional style or with a LATIN twist let us remember to celebrate with the love of GOD not merely today but EVERYDAY!!
Giving native orchids to your loved one is a tradition in Colombia and Peru. For many these flowers are more signif-
• Great Rates • Fast Install • High-Speed
Locally Owned & Operated
Part of the Louisiana Radio Communications Group PAGE 7
All About the Tractor Trailer Support Aparatus Department of Transportation, National Highway Traffic Safety Administration (U.S. Code of Federal Regulations Title 49 Part 571 Section 106) gives labeling and performance requirements for motor vehicle brake hose, brake hose assemblies, and brake hose end fittings. Southwest Louisiana (SWLA) is experiencing an historic economic boom in the oil and gas industry. Will the Swivel-Hill experience an historic economic boom in the trucking\transportation industry for SWLA?
The Swivel-Hill
by Mary Ledet A tractor which is driven by an engine typically provides electrical power, air and\or hydraulic fluids for operation of various components of the tractor and the trailer. These are normally required to provide electrical power and\or fluid communication between the tractor and the trailer The Swivel-Hill is a tractor-trailer apparatus for supporting cable, hose and the like which provides power and\or fluid communication between a tractor and trailer of a tractor-trailer rig. This total hose management assembly is heavy duty and moves as the tractor and trailer pivot relative to each other, keeping them supported in a manner as to prevent rubbing\ chafing and reduce brake system failures from pressure vacuum loss due to hose or hose assembly rupture. In 2005, a test market in Westlake and Lake Charles, La revealed these benefits of the Swivel Hill: 1) reduces wear\tear and improves the life of hoses. 2) secures hoses when running bob-tailed 3) holds the drive line when it is dropped 4) acts as a hoist to lift and store tarp; preventing back injury to operator PAGE 8
this may be done. Trucking companies equip their rigs with the necessary apparatus to keep these hoses secure, and provide maintenance. Typically the trailer hoses are held up by springs, which allow for movement during travel. These It’s not something you think about springs wear out and must be remuch--unless you’re a truck driver. placed. The truck hoses are now usually the coiled type, which are The Department of Transportation safer than the older straight ones. has standards to which these hoses These coiled hoses are expensive and cables must be managed and and must be replaced frequently. protected against abrasion, crimping, and debris. If they are not For owner-operators, handy gadgets properly cared for, citations will be such as a spring-loaded apparatus given to the driver, costing him or called a pogo-stick, which attachher money and racking up DOT es to the truck and holds the hos“points” of which a driver may have es secure, is sometimes used when only 100 before the CDL is revoked the springs have worn out. Another clever invention called E-Z Claw permanently. can be used to keep the truck hosIf a hose should come disconnect- es from friction against the catwalk ed during a trip, a serious problem and also hold the trailer hoses at the --no brakes or lights--could occur. optimum distance from the underSo it is the driver’s responsibility carriage of the trailer. to inspect the rig before, during, and after trips to make sure that So next time you’re driving I-10, all safety measures are being kept. glance over at that rig you’re passPreventive maintenance is the key ing. Don’t expect to see any danBy Trina Morgan to maintaining safety and avoiding gling, or worse, dragging, hoses or If you glance over at a tractor-trail- citations. cables, because the DOT is keeping er rig as you pass it on the highway, a close eye on these rigs to help keep you can see the hoses beneath the There are a number of ways that the highway safe. 5) prevents hoses from breaking in hard turns 6) allows hoses to swing around and escape damage 7) weighs less than 41 pounds 8) withstands most climate weather conditions 9) transfers easily when new rigs are purchased 10) installs easily and requires little maintenance 11) has a life expectancy of 12-15 years 12) available in various colors to match individual preferences. Operators reported that this aparatus is very useful in keeping hoses and electrical lines up and off the lowboy platform. It also works really well when backing up and eliminates many safety concerns. When used properly, it can be cost-saving and eliminate excessive replacement of hoses and electrical lines that are damaged when not properly tied back. “For these reasons LA DOTD District 07 recommends the use of the “Swivel-Hill”. Visit swivelhill.com for more details.
trailer and on the back of the truck itself that carry electrical and braking systems to the rig. These hoses are in need of constant attention to keep them from dangling or crimping as the truck travels.
Hose & Cable Management
Feburary 2014 • Volume 1 • Number 7
Obamacare, the Affordable Care Act, the Patient Protection Act . . .
wherever they qualify,” he explains. “But the only place you can get the premium tax credit is by purchasing insurance through the federal exchange system.” According to Fontenot, people whose household incomes are between 100-400%
What happens if a person neglects to obtain health insurance?
costs. It cannot cost the employee more than 9.5% of the cost of a single person’s policy in that insurance If someone is required to purchase plan. It cannot cost the employee health insurance and has not done more than 9.5% of the family’s total so by March 31, 2014, he/she will income. Tax professionals such as receive a penalty on their 2014 tax Mr. Fontenot can help clients deter-
by K.G. McDonough
We hear about healthcare reform in the news, but what exactly does it mean for citizens and how will it affect them? Last year, the government passed these new tax laws in an effort to make healthcare insurance more accessible and affordable for the masses. By March 31, 2014, most Americans will be required by law to have health insurance. Many have health insurance through their employers, but if they do not, or if the insurance provided by an employer does not meet certain criteria, then individuals and families must purchase their own health insurance. Ron Fontenot, a certified public accountant with ComPro Tax on Broad St., has become an expert on the subject of healthcare reform. He estimates approximately fifty percent of the U.S. population can benefit from this new legislation. “They can buy health insurance in the private exchange systems or the federal marketplace exchange system; Feburary 2014 • Volume 1 • Number 7
of the federal poverty level qualify for a premium tax credit that is applied directly to the purchase of health insurance in the form of a government subsidy. Poverty level is determined by income and number of dependents. For example, for a family of four, 100-400% of the poverty level equals a range of $23,550 to $94,200. “This premium tax credit works like earned income credit, on a sliding scale based on income and family size,” says Fontenot. “The less money you earn, the more premium tax credit you receive.” Persons who earn greater than 400% of the poverty level and who do not have employer subsidized healthcare must purchase their own healthcare and they will not receive the premium tax credit. Those who earn less than 100% of the poverty level are not required to file an income tax return. They may choose to purchase health insurance but are not required by law to do so.
mine if their employer-based health insurance complies with the reform criteria. Fontenot admits these new laws can be confusing to the general public. He highly recommends tax payers find a qualified tax professional to help them navigate the maze of healthcare reform and its tax implications. “It’s so important at this point in time,” he says. “If they try to do it on their own, they might miss some information or Who benefits the most? “Lower income earners, in the choose a wrong policy. We can give 11,000-30,000 per year range, are them the information they need to the primary beneficiaries in this make wise decisions.” plan,” says Fontenot. “The reforms make their insurance more afford- For more information, able.” Those hit hardest are people Call Ron who have an adequate income, ap- Fontenot proximately $35,000 per year and at up, but do not have qualifying health insurance through their employer. ComPro To qualify under these new laws, Tax, employers’ healthcare must meet (337) certain conditions. It must cover at 436-1614 least 60% of an employee’s medical return (filed in 2015). The penalty in 2014 is $95 per adult and $47.50 per child, and the fee is capped at $285 or 1 percent of household income. Each year the penalty increases exponentially; in 2016, the fine rises to $695 per adult and will be capped at $2,085 or 2.5 percent of income. Eventually, it will become more cost effective to purchase insurance than pay the tax.
PAGE 9
Foreman-Reynaud Community Center A Beacon in the Heart of North Lake Charles
We have been providing recreational services and programs since 1946. The Community Center, originally founded in 1946 as a “blacks only” extension of the Kirby Street YMCA, was located on Enterprise Boulevard and I-10 in the building locals knew as Walkers Recreational Center. In 1973, the YMCA moved into its present location and received its independent charter from the national board of the YMCA. The new building was named in honor of Edmond Burnice Foreman and Ralph Clifton Reynaud, two educational, civic and religious leaders who dedicated their lives to the community in which they lived. In 2001, the Foreman-Reynaud YMCA gave up its charter and, in cooperation with the City of Lake Charles, became the Foreman-Reynaud Community Center. True to its humble beginnings, the Foreman-Reynaud Community Center remains dedicated to improving the quality of life for the community, especially the economically disadvantaged, through a wide range of programs. The Foreman-Reynaud Community Center is a 501(c)(3) non-profit organization. We provide recreational and educational opportunities to the community in a safe, wholesome environment. Some of the programs include: After School Tutorial/Homework Help; 8 week Summer Camp; Youth Achievers; Computer Classes; Water Aerobics; Swimming Lessons; Boy Scouts; The Lighthouse Club; a social club for older adults; and free showers for the homeless (Monday – Saturday 11:00 am – 11:30 am.) We offer an updated fitness center, including exercise equipment and an indoor pool, showers and locker area. We also have a recreation PAGE 10
area for games and activities and will soon be offering health and nutrition classes. We also provide tutoring and mentoring programs as well as summer camps for children. Our newly renovated event center is perfect for parties, weddings and other special occasions. Our mission is to improve the quality of life for all members of the Southwest Louisiana Community. Our programs and services are aimed at enhancing the growth and development as well as the spiritual, social, cultural and educational needs of our citizens.
Helping to Shape the Leaders of Tomorrow Afterschool Homework/Tutoring Program
Children and youth enrolled in this program are assisted with homework and are tutored in their academic areas of difficulty. Our certified staff, “foster grandparents” who have an education background and McNeese State University interns are here to help with schoolwork. Participants are required to bring their report cards to evaluate and asses each individual’s progress. The goal of this program is to help kids develop competencies necessary to be successful in school. The Afterschool Homework/Tutoring Program is for ages 4-18, and is offered Monday-Thursday,
from 3-5 p.m. For more information, call (337) 436-2509.
Summer Youth Day Camp Our Summer Day Camp offers a safe environment for ages 3-12 in Southwest Louisiana from June-August each year. The program offers an opportunity for children to build friendships, learn to work as a group and develop their individual talents and gifts. They learn about health/nutrition, swimming/water safety, math, reading, language arts and much more, all within a fun and creative environment. We work on building self-confidence so our children have an easier transition back into the school year. The camp is Monday-Friday, from 7:30 a.m.-
5 p.m. beginning in June. For more information, call (337)436-2509.
Youth Achievers
Our Youth Achievers Program gives young people an avenue to dedicate their time, talents and resources to positively impact their communities, schools and futures. Meet ever other Saturdays 11:00 am - 2:00 am Youth Ages: 12-18
Meet Our Staff
Stephanie Chretien Executive Director, Michelle Jackson Secretary, Sharonda Broussard Summer Camp Program Director Sharonda Broussard Youth Achievers Program Assistant, Milton Alvarez Maintenance Supervisor, Sheila Washington Evening Receptionist Jule Taylor Evening Maintenance, DeAndre Taylor Life Guard Allyson Clark Life Guard, Mary Cline Bookkeeper/Youth Acheivers Program Director
Feburary 2014 • Volume 1 • Number 7
Empowering youth with the skills and self-awareness to help them succeed in school, life, and their community. In the Youth Achievers, youth focus on academic enrichment, healthy lifestyles, social skills and leadership development. The overall goal of our Youth Achievers Program is to help our youth set and pursue high educational and career goals. Our program gives special attention to African-American and at-risk students. Through academic support, career exploration and mentoring, the Youth Achievers Program will help raise the students’ academic standards, develop a positive sense of self, build character, explore diverse college and career options and meet and interact with professionals who serve as the role models to inspire them to greater heights. The Youth Achievers Program staff takes pride in ensuring that these youth, especially those whose experiences have made it difficult for them to succeed, are connected with their special abilities/ gifts and given hope for a promising and fulfilling future. Youth Achiever Pledge As a young achiever, I pledge my honesty, my will, dedication, hard work and want for success to all that has to be accomplished in my organization, social activities, environment and society as a whole.
Senior Light House Club
Our Senior Light House Club is a social club for adults ages 55 and older. Members participate in socials, workshops, zydeco aerobics, various events held at the center and more. This is a great opportunity to socialize and form those strong bonds that make life richer. Yearly Free Tax Preparation: January – April 2014 Monday – Friday 5pm – 7pm Saturday 10am – 2pm Feburary 2014 • Volume 1 • Number 7
Top Left – Melanie Jackso n, Marc Pettaway, Botto m Left – Gertie Charles, Daphne Higginbotham, Katie Williams, Terry Mu rray. Not pictured – Dorot hy Miller, Catherine Norman, Sherly n Jefferson
Computer Classes: Adult Beginners Computer Class
Introductory computer classes are offered to adult patrons who are introduced to basic computer concepts and technology orientation to commonly used software within Microsoft Windows. This is a lab structured six weeks class. The orientation to computers is ideal for those who have had little exposure to computers. The class overview covers understanding parts and components of the computer and terminology including: desktop, menus, mouse, scrolling, clicking, keying (typing), saving, and basic Internet skills. General use of Microsoft Office Word and Excel will be introduced. Class is a 1 hour sessions twice a week Tuesday and Thursday from 12:30pm to 1:30pm. This group pictured above completed the six week session ending December 10, 2013 and received their certificates of completion.
Swimming – Olympian teaches swim safety – Cullen Jones
You’ve seen him in the pool and on the podium. And now, Olympic Gold medalist, Cullen Jones, is swimming in Lake Charles at the Foreman-Reynaud Community
Center to teach water safety in the Make A Splash tour. Olympic Gold Medalist and NBC broadcaster, Rowdy Gaines, says, “Here we have an African American male, the first one to break a world record ever in history...and he’s an Olympic Gold medalist. It’s just sort of a natural tie in to be able to do what we wanted to start years ago. We felt like Cullen would be a great representative. He’s so well spoken, so likable, and he’s such a great ambassador of the sport.”
first step towards getting kids water safe. And that being right up my alley, and me almost drowning at the age of five, they knew that I would understand exactly what these kids are going through, so I signed on immediately.” Approximately ten people drown every day in the United States. Of those ten, two are under the age of 14. This makes drowning the second leading cause of death for kids under 14. So what’s the solution? Attending a formal swim lesson can reduce drowning risks by 88%. To prove that water safety can be fun, four kids were able to learn the basics of water safety from the champ himself. Gaines says, “I think it’s more important to the parent than it is even to the kids because a lot of what we have found, the studies we have found, one of the reasons children don’’t know how to swim is because of their parents.” Before the lesson, two of the kids had never put their face under water. With the help of an Olympian by the end they were jumping in the deep end without hesitation.
are to serve mmunity Center prep ndraiser Co ud na ey -R an m re Youth Achievers of Fo d guests at the 2nd Annual Scholarship Fu their supporters an onderland” themed “A Winter’s W
Cullen says that joining the initiative was an easy decision. Jones says, “A friend actually showed me some of the drowning rates and told me about the Make A Splash initiative really kind of putting their money where their mouth was and really trying to take the
For more information call Foreman-Reynaud Community Center
(337)436–2500
PAGE 11
Board Members from left to right with youn g musician, John: Em Judy Davidson, Patri ma Guillory, John, Ev cia Prudhomme, Hube a LeBlanc, next row: r “Mickey” Smith, Jr., next row: Robin Ande rson & Tiffany Jones.
Kendrick is loving his new trumpet!
Board Members, front to back: Tiffany Jones, Greg LeBlanc, Huber “Mickey” Smith, Jr., Emma Guillory & Dr. Michael Buckles.
Ezra received a full-size violin!
Hattie asked, “Can I hug my violin?” Kendrick exclaimed, “I am playing higher notes with my new trumpet!” John said, “I can’t let go of it” about his new violin. Such are the responses of students in southwest Louisiana upon receiving refurbished musical instruments from MusicMakers2U (MM2U). Their “new” instruments were provided through the generosity of donors who no longer have a use for them. The MM2U Foundation was established in August 2013 as a non-profit organization created to provide students with the gift of music. The premise behind MM2U is that many school students have a desire to play a musical instrument but no means to obtain one. At the same time, many instruments have been silenced as they sit on closet shelves or in attics collecting dust. By pairing donated instruments with students desiring to play them, MM2U restores sound to the instrument and a voice to the student. MM2U is made aware of students desiring to play
PAGE 12
through their educational instructors who are integral players in the program’s success. Once MM2U accepts an instrument, it is professionally cleaned, refurbished and repaired before being assigned to a student. Since MM2U’s short inception, 30 instruments have been donated and 10 pairings completed – all prior to publicly announcing MM2U’s formation. Dr. Jeffrey J. Lemke, coordinator of instrumental music education at McNeese State University, states, “By helping improve academic achievement, build self-esteem, teach critical social skills, and engender creativity and innovation, MM2U helps to ignite the spark of creativity that lies within all children and inspires a love of learning.” An added benefit for students participating in an MM2U is the parental involvement that comes with the pairing. Students accepting an MM2U instrument also agree to accept the responsibility of taking care of their instrument. The ‘cost” for the student in accepting the gift is the understanding that they now have an obligation to care for
and practice on the instrument, to participate in school activities and to have the maturity necessary to return the instrument if their musical interest ever wanes. For MM2U to grow contributions are being requested for instrument donations. Financial support is also needed to clean and refurbish the instruments. The group is currently working to find instruments to fill the following requests: two euphoniums and a trumpet for students at Washington Marion High School; a ¾ cello, ¾ string bass and a viola for the after school Colt String Orchestra at S.J. Welsh Middle School; and two violas and an oboe for students in the Bulber Youth Orchestra. The foundation would be happy to receive these items as used instruments or to receive donations to purchase them. For further information, contact Eva LeBlanc, MM2U President, by calling 337244-9314, by emailing musicmakers2U@gmail.com or by writing MM2U, P.O. Box 7964, Lake Charles, LA 70606. Feburary 2014 • Volume 1 • Number 7
ONE: Bring your marriage license
upon arriving at your reception…. This could be a favorite recipe book for cocktails or a picture of the bride and groom in a matted frame, or “An important part of making it simply an autograph book. Also, ‘official!’ Check with the jurisdic- don’t forget the pens!” tion where your ceremony will take FIVE: place about any deadlines for applyInvitation suite ing for your marriage license well in advance of your wedding date and Brides should remember to pack at also whether a blood test or special least one full invitation suite and any documentation is required to com- other stationery details (rehearsplete your application. al dinner invites, shower invites,
Airport security will not let you get on the plane with expired identification, so be sure you have taken care of this detail one month before your wedding.” After the Wedding
months after your big day. Set aside some time each day to dedicate to writing these notes so that you don’t get overwhelmed...Also, don’t forget the important people in your life, including your parents, famEIGHT: Thank-you Notes ily members, and bridal party that were there with you through the Your thank-you notes to your guests planning from the beginning. should be sent out no later than two
save-the-dates) that were mailed out during the engagement to bring with them in the bridal prep suite Be sure you remember to feed the the day of the wedding so that your people that are working nonstop to photographer can shoot the invimake your day flawless! Don’t for- tations to include in your wedding get to include the number of ven- photo album. dors you’ll have so that the caterer SIX: can prepare simple meals for them, separate from your guests. Cake knife &
TWO: Vendor meals
THREE: Favors
toasting flutes
When packing up your items to be placed at the reception, be sure to They are a fantastic detail that each remember to pack your cake knife of your guests will appreciate! So and toasting flutes (and keep the don’t make your favors an after- original packaging to avoid breakthought — think about what you’ll age) so that this detail will not be present your guests as a ‘thank-you’ overlooked. for coming at least two months in advance of your wedding date.
FOUR: Guestbook & pens Include something for your guests to leave their well-wishes for you Feburary 2014 • Volume 1 • Number 7
SEVEN: Passport & identification
Be sure your passport and driver’s license are up to date and packed safely in your carry-on luggage : PAGE 13
JENNINGS MARDI GRAS CELEBRATIONS & SQUEEZEBOX SHOOTOUT
It will soon be Mardi Gras in Jennings, Louisiana, and that means there will be plenty of good times rolling Saturday, March 1, as the city’s 22nd Annual Mardi Gras Parade and Festival takes over downtown with an accordion championship, giant colorful floats, live music, lots of beads, great food, craft vendors and other family fun. Each year, the parade and the Main Street after-party street dance has grown tremendously and is now recognized as a Mardi Gras season highlight. There’s the feeling of the big city but small enough for everyone to take part in the fun. This year t-jam DJ Service will be playing music in Founders Park until the Parade begins rolling at 4:30 p.m. Immediately after the parade,
the live band SECOND TYME AROUND will perform until 7:30 p.m. Several years ago the Cajun Squeezebox Accordion Championship was added. The competition, in its 9th year, begins at 11:30 a.m. with Cajun diatonic nine and ten button accordion players of all ages converging on the Historic Strand Theatre at 432 North Main Street to compete for Trophies, Bragging Rights, and over $3,000 in prize money. There is no entry fee for the contest, but accordionists must register in order to compete. There are four divisions: Youth, Junior, Adult, and Professional.
JUNIOR LEAGUE OF LAKE CHARLES, INC. The Junior League of Lake Charles, Inc. has a legacy of serving, strengthening and sustaining the community. During the last five years alone, the JLLC volunteers have performed over 120,000 hours of community service and funded over $600,000 in community programs, educational grants, scholarships and volunteer training. Since its inception, the women of the JLLC—who range in age from 23 to 94—have had hearts of giving and have been catalysts for lasting community change. Some of the legacies left to the community by the League are: Arts & Humanities Council, Calcasieu Community Clinic, Children’s Museum, Family & Youth Counseling Agency, Imperial Calcasieu Museum, Lake PAGE 14
Celebrates 80 Years
CONTACT INFO: If you or michelle@cityofjennings.com someone you know would be interested in entering the contest. • 337-821-5532
Charles Symphony and Literacy Council of SWLA.
The SWLA Economic Development Alliance recently recognized the League for its generosity and investment in a program that helps develop a stronger workforce and future leaders. The JLLC is donating time, support and $80,000 in order to bring The Leader in Me to Maplewood Elementary. This partnership honors the League’s 80th year of promoting voluntarism, developing the potential of women and improving the community through the effective action and leadership of trained volunteers. They also collaborate with Dolby and Oak Park Elementary. Join them on April 10, 2014 at
Central School for the closing reception of their juried exhibit, The HeART of Giving. Local students are asked to submit “heART work” featuring original artistic interpre-
tations exploring “What volunteerism means to me.” Submissions are due February 21st and details are online at. Feburary 2014 • Volume 1 • Number 7
INTELLECTUAL PROPERTY 101: the mind. In broad terms, these creations include legal rights in new ide as, inventions, and discoveries. There are four basic types of intellectual property: by Nadine Dunbar Gills, Esq. Attorney At Law Nadine@gillslawfirm.com (337) 513-4820
Intellectual property is a complex area of federal law which establishes legal rights to protect creations of
COPYRIGHTS-which include writings, music, art and software, among other things. TRADEMARKS-These are distinctive words, images or sounds that identify a brand, such as Nike. TRADE SECRETS-These are valuable pieces of information, such as a recipe, process or tech-
How to Establish Your Legal Rights In New Ideas, Inventions, And Discoveries nique, which provides a business advantage. Popular examples include the Popeye’s Famous Fried Chicken secret recipe and the Coca-Cola formula PATENTS-A patent gives an inventor the exclusive right to make, use, or sell an invention. In order to protect your creation, you will want to make it official by having your work registered with the United States Patent and Trademark Office. By doing so, you will improve the strength of your position as an owner and gain legal authority to prevent anyone else from using your creation without your permission.
For more information on registration and establishing rights to your intellectual property, visit the United States Patent and Trademark Office website at or contact an attorney who specializes in Intellectual Property law.
Call for Submissions by the Junior League of Lake Charles, Inc.
The HeART of Giving
Theme: Create original “heARTwork”in any medium 2-D or 3-D exploring the idea “What volunteerism and/or a heart of giving means to me.” Works featuring original artistic interpretations of a heart as part of the work are encouraged. Eligibility: Students in the 5-parish area grades K-high school attending public, private or homeschool programs
Deadline: Deliver submissions to Art Associates Gallery (in Cen-
2014
tral School) Wed., 2/19 through Fri., 2/21 for jury selection.
Exhibit Dates: March 10-April 13, 2014 at Art Associates Gallery, 809 Kirby St., Central School Suite 208, Lake Charles
cultur al season
Banners.org
Recognition/Closing Reception: April 10, 2013 from 6-7:30 pm
Learn more at, follow us on Facebook, or best of all, become a League volunteer! Feburary 2014 • Volume 1 • Number 7
Banners.org
PAGE 15
by Abby Ecker Valentine’s Day is for expressing love and appreciation to our significant others. For some, this means a family pet. One way to show your beloved pet affection is to devote time. A walk or jog, a trip to your local doggy park or a simple game of sit and play
with your pet’s favorite toy are just a few ideas of spending time with your pet to show them affection. If you like to buy gifts, local pet stores have stocked their shelves with plush, squeaky hearts and heart shaped dog, cat and bird treats waiting to be pur-
chased for your loyal loved ones. There are also fabulous websites to shop online for unique pet gifts. You can create a custom made gift basket for your pet at organicpetboutique.com. Just remember, what your little friend craves most is you.
While looking for Valentine’s Day gifts, remember your local animal shelters. According to the American Society for the Prevention of Cruelty to Animals (ASPCA) only eighty-six percent of pets given as gifts are fortunate enough to stay with their new families. One pet finding website is AdoptAPet.com. It has selection tools to help you locate a pet. Cyndi Gwatney, foster parent, works with six local animal rescue organizations. She has been successful in finding homes for over six hundred pets in the last five years. She provides these tips for potential adoptive parents: “Know the needs of the breed you are committing to. Obtain as much information as you can such as the animal’s response to children and other animals. Know if the animal is a “working” breed that will only be content if performing his duties. Know how much exercise the pet will need. All baby animals are cute but they will grow. It is essential to know the expense and needs of your chosen pet as it ages. Visit Cyndi’s Facebook page: Cyndi’s Adoptive Dogs.
“Adopting a pet is a lifetime commitment”.
PICK UP YOUR COPY! LAKE CHARLES
Stine Lumber Brown’s Grocery Harequin Steakhouse Gatti’s Pizza Happy Donuts Don’s Car Wash All Area Hospitals Imperial Health PAGE 16
MOSS BLUFF
Fox’s Pizza Market Basket Harry’s
SULPHUR
Misse’s Grocery Joe’s Pasta Dairy Barn Post Office
Stine Lumber Pitt Grill
KINDER
Food Mart Feather Fuel Allen Parish Hospital
JENNINGS
Easy Mart Java Joltz
Feburary 2014 • Volume 1 • Number 7
Tips for Singles on Valentine’s Day Do Something for Someone Else
Make it a Friends Night By Dawn Guillory Valentine’s Day is a day set aside for love, and many singles desire to love and be loved. We can enjoy Valentine’s Day by focusing outward to family and friends or inward to ourselves. As a child, I learned to focus
outward from my mother. She had a Valentine, but she increased the day’s emphasis to include us, her children. I remember the first Valentine’s treat was just a pretty cupcake, and I still remember how special I felt getting this treat, and other treats years after. Increase your day’s
activities to include a visit to a nursing home, hospital or animal shelter and bring the gift of love. It seems that we over extend ourselves in everything on a daily basis. Turn our focus inward and love our self by making it a day of self-care. Start by being grateful and counting
our blessings one by one. Relax and meditate in a quiet place. Do something for self, even consider having a party. So often in our single quest to find a soul mate, we miss how fearfully and wonderfully made we are.
Relax & Do What You Love
Pamper Yourself
Gifts for a “Challenged Person” Shouldn’t be Challenging by Mark Wayne Allen Valentines Day is, arguably, the biggest of romantic holidays, but for challenged persons, it can be cumbersome. Back when I was dating, I was often asked, “What kinds of gifts do you like receiving?” Well, since I’m in a power chair, I don’t think I want roller skates, a basketball, or a football (unless it’s autographed by Drew Brees, hint hint). A few years back, my sweet mother-in-law once told me that she was running out of ideas for gift giving. She was always looking to buy me things that I could physicalFeburary 2014 • Volume 1 • Number 7
ly use; she was really creative about it too. My reply to her was, “Hey, I’m a guy; I like tools.” If you don’t know what to get a challenged person, ask them, or at least get them something that they are interested in. Often times, whether they can physically use it or not is a moot point. For example, I have others use the tools that I receive while I watch and supervise. People are the same in all areas. We all like flowers, candy, and other stuff. Relationships with challenged people have their obstacles: all relationships do. The simple act of getting comfortable enough with the person to ask questions and to be close is a challenge in itself. All relationships have this in common. The problem becomes more
difficult when you have a walker, crutches, or especially a power chair in the way. My feet and legs stick out like the flu at a doctor’s convention and the arms of the chair are built-in barriers to closeness. To achieve that special closeness with a challenged person requires telling your significant other anything that concerns you including wants, needs, how, where, and when. Plaster them into a chair if you have to and say, ‘We need to talk.’ If they’re going out the door, get in their way. Never leave anything unsaid. If you can’t talk, write your feelings down. Write them a letter, like I have done on many occasions. I don’t speak so well sometimes either. The main idea is letting them know how you feel, but be prepared,
the good, the bad, and the ugly, is going to come back at you. It’s okay though; that’s what good communication is all about: understanding each other.
Mark Wayne Allen has attended La. Tech in computers and has a B.S in business from LSU He is the author of the book Star Siege. markwayneallen.com facebook.com/authormwa #authormwa PAGE 17
Carl E. Gaines is Retiring but not Leaving Home On the first Sunday of July 1970 Carl E. Gaines, known as Bro. Gaines, began holding services in St. Mary Drive Recreation Center with three families in attendance. Ninety days later they moved to a warehouse on Mill Street and now, today, 2318 Mill Street Church of Christ, (MSCC) has over 150 families. He says “Some of the children born here when the church first began are now the grandparents bringing their little ones to worship.” He doesn’t tell his age but says to those who ask, “I’ve turned 45.” He just doesn’t say when that was. He feels it was God’s will, not C. E. Gaines, to come to Lake Charles, Louisiana and preach. After two years of “friendly persuasion” he and his wife agreed to move their family to Southwest Louisiana. “Alright I’ll go but only for four years.” He laughs as he admits that 43 years later he is still here. When they came here their son and three daughters were all in school. “This was only a short time after integration and stories about the south did not entice African Americans to come here to live,” he said. “Also, stories about Louisiana culture, hoodoo, voodoo, snakes and alligators added to my fears and terrors, and then exposing all this to my young family.” A.B. Franklin, State Representative District 34, and Luvertha August, City Councilwoman District B, presented he and his wife with a plaque for long years of dedication to community service and his retirement, which occurred December 31, 2013 Meeting the pastor with his ready smile and sense of humor that comes PAGE 18
out in conversation is inspiring. His love of life and people immediately puts others at ease. Born before the days of integration he admits that he lived through some hard and rough times but refuses to dwell on them. He chooses to use his experiences to describe an interesting past which has guided him to where he is today. Bro. Gaines comes from a family of 11 children. He began his ministry in 1953, and met his bride, Eva Worthy in 1954. They were married two years later on the campus of Southwestern Christian College (SWCC) in Terrell, Texas, where he received
Christ throughout Oklahoma and Arizona before coming to Louisiana. He received an MSW in Social Work from Louisiana State University, and acquired a Specialty in Geriatrics, all while serving as minister at MSCC. “There will always be ups, downs and pitfalls; because no one can stop the inevitable,” he said, “But when
tative District 34, and en es pr Re e at St , in kl A.B. Fran uncilwoman District B Co ty Ci , st gu Au ha rt ve Lu ue and his wife with a plaq presenting Bro. Gaines cation to community for long years of dedi ent. service and his retirem an AA in Religious Studies. In 1960 he served in the United States Air Force where he worked in personnel. He left the military, enrolled at the University of Arizona and graduated with a BS in Public Administration. He continued to serve in churches of
you find a tall mountain you must pray for strength to be able to climb it.” Bro. Gaines is not one to boast about his accomplishments but while engaged in conversation it is evident that he practices what he preaches. Many programs have been put into
By Joyce R. Kebodaux
place because of his belief that when one steps out in faith, God provides the means to make things happen. He began the Gulf Coast Lectureship meeting, annually, along the Gulf Coast to build church unity and strengthen it; Men’s Seminar meeting, throughout Louisiana and Arkansas, to teach bible principles to men and boys, Louisiana Youth Conference, meeting in universities throughout Louisiana, to inspire spiritual and academic development and inspired the development of the Marriage Couples Banquet for Valentine’s, to preserve the sanctity of marriage and Ladies Retreats meeting, annually, for sisterhood networking. One program especially close to his heart is bringing student preachers, during spring break, from SWCC to MSCC to learn church functions. These future ministers door knock, teach bible classes, live with church families and tour the area to learn about the culture and geography of places where they may one day be assigned. Courtney Jones, to be installed as the new minister at MSCC, February 2, 2014, is one of the students who started coming in 2004. “He is a good man and the congregation already knows him,” Bro. Gaines said. When asked “How important is the wife in a minister’s life?” he an-
Feburary 2014 • Volume 1 • Number 7
swered without hesitation. “Without Eva I would be dead in the woods. For fifty seven years, she has made a home for our family and for me to do what I do.” Their home is also a gathering place for visiting clergy and officials in the church. ”At the time of this interview she was making preparations to host a gathering for the Ladies Fellowship in their home on Eleventh Street. Br. Gaines is happy with the life of service he has chosen and his plans are to remain in Lake Charles. Now he will have more time to spend with his son, David and his family, and daughters, Beverly Cole, Deborah and Karla Gaines and their children. His eyes light up when he speaks of his family especially his eleven grandchildren. He expects to catch up on his fishing and do some writing. He says, “I hope to have more time to work with the programs I began and help make a difference in the lives of many.”
SWLA FAMILY BOOK FESTIVAL Sponsored by the Bayou Writers Group
Saturday • February 22, 2014 at Central School
809 Kirby St., Lake Charles • 9am-1pm • Free Admission! If you are looking for a good time that involves books, this festival is for you! READINGS, BOOKS, WRITERS—Meet your favorite local author. Every member of your family will have a blast! Plan to be there from the start!
. 433-3611 Feburary 2014 • Volume 1 • Number 7
FFBLA.COM PAGE 19
Louisiana AARP Advocates a Better Human Services Transportation System turn. Older adults who don’t drive still spend money at the mall, grocery stores, and on entertainment. Enabling a handicapped person to live independently rather than in a long term care facility saves the state $3500 per month. In Maryland, they make a $1000 investment in each qualified person by modifying their home and providing transportation, saving the state an average of $2500-$3000 per person.
Eight million Americans do not drive. The majority of these persons are elderly, disabled, or under-privileged. They are the consumers of the Human Services Transportation (HST) Agency. But the system is flawed. The Healthy Community Coalition in Lake Charles recently hosted its monthly meeting and welcomed Jason Tudor, AARP Louisiana Director of Outreach, to address this issue. “One of AARP’s primary concerns is viable communities where people of all ages can live, work, and play for as long as they want,” says Tudor. “Two key pieces required to do that are good affordable accessible housing. And good affordable transportation options. HST helps people who can’t drive have an option to get around in their community. It could be as simple as a voucher for a taxi ride, or as involved as someone who catches a bus at a stop with a wheelchair ramp.”
PAGE 20
Paratransit, the short white buses that say Louisiana Transit on the side are an example of HST. Currently, transportation services are cumbersome. They don’t work together well. There’s no coordination. They each have multiple funding sources that are difficult to keep track of. The AARP advocates a simpler system. “We want a ‘one click one call’ center for
people who need rides,” says Tudor. A 211 center is an example. The HST and communities around the state are working toward better coordination in an effort to save millions of dollars. Tudor cited some success stories. In Florida, they found that for every dollar they spent on transportation, they received $8.75 in re-
According to Lake Charles’ mayor Randy Roach, the primary transportation system provided by the city is traditional bus service. Calcasieu Parish provides the majority of Paratransit. “We have talked about creating a regional transit authority,” says Roach. “An initial plan has been developed. We built a new transit building on Ryan St. with the idea that this building would serve as the office for a regional transit system in Calcasieu Parish. Both the city and parish transportation
Feburary 2014 • Volume 1 • Number 7
agencies are currently in that same building, in an effort to begin coordinating the services. But I think we can do more.” Roach adds that funding is the biggest hurdle. How can you help? Get involved with the Imperial Calcasieu Planning Commission (IMCAL). Call them and find out when their HST coordination meetings take place and attend them. Tudor asks, “How can we save millions of dollars, add millions of dollars back into the economy, keep people out of nursing homes, and provide a high quality of life for our residents? Coordinating transportation is the answer to that.”
Healthy Communities, Healthy Louisiana Last fall, the Region 5 REACH (Regional Education Agencies Concerning Health) Cancer Coalition and the Tobacco Subcommittee transitioned into a single coalition, now called the Healthy Community Coalition (HCC). According to HCC coordinator Patricia Bettis, the coalition encompasses all aspects of wellness: obesity, physical education, chronic diseases, stop smoking efforts, to name a few. “Our
goal is to find out what [health issues are] prevalent in our region and this Coalition will talk about what it is we want to take
on as an objective and hopefully those objectives will turn into something more sustainable, including policy changes, system changes, and environmental changes.” The HCC partners with the Department of Health and Hospitals and the Office of Public Health to combat obesity and other health concerns. “We get a lot more accomplished when we partner with each other,” adds Bettis.
Seeing Humanity with Estella Scott by Sherry Perkins I knock. A young man answers the door. “I’m here to see Mrs. Scott,” I say. From inside the house, a soft voice squeaks, “Come on in, honey.” I step inside and a feeling of warmth envelopes me. An elderly lady appears from another room and walks up to me. “Hello, Baby,” she says as if we are long-lost friends, not strangers meeting for the first time. She puts out her hand. “I’m Estella Scott.” I take her hand and reply, “I’m Sherry.” Mrs. Estella Scott is a true humFeburary 2014 • Volume 1 • Number 7
ble servant for the community of DeRidder, the whole community. For 10 years, she worked for the Tax and Water Department of DeRidder. “I saw problems in the community. I saw a need.” When a position on the City Council became vacant, she ran. “I didn’t want to do it at first. But people supported me. For 20 years no one beat me.” From 1986 – 2006, Mrs. Scott served with distinction on the City Council. Not only did she serve on the City Council, she was also Director of Headstart for 25 years, sat on the Board of Trustees for the West Louisiana Health Services, Beauregard Memorial Hospital, from 1994 – 2002, and was the first African-American woman to be appointed by (then) Governor Kathleen Blanco in 2004 to serve on the Sabine River Authority Board.
Governor Bobby Jindal reappointed Mrs. Scott, where she continues to make decisions for the largest manmade lake in the South. Mrs. Scott has received many awards and accomplishments. Some include: The National Association of Women named her Woman of the Year; she was named Newcomers Hospitality Club Woman of the Year in 2001 and 2005; and in 1995 she was given the Outstanding Community Service Award for Upholding the Ideals of Negro Women. I ask, “Since the death of Dr. King, what are your comments on race relations?” “His dying was not in vain and his legacy shall go on. When you learn better, you do better. Throughout my life, I’ve learned through trial and error.” A humble spirit glows from within her as she recalls taking her children to the funeral of Med-
gar Evers in Mississippi. “Anything I think will enhance them, we do it.” For 15 years, Mrs. Scott even transported Senior Citizens from DeRidder to Jasper, Texas, to see Christmas lights. “Oh, they enjoyed it so much. When insurance issues arose, we had to stop.” She praises God for His blessings. “I can do all things through Christ who strengthens me.” In a comment about DeRidder’s economic development, she says, “We’ve come a long way. DeRidder is on the move. I’m a people person and a community servant to all my people.” When she says, “…servant to all my people,” she doesn’t just mean African-Americans. This lady doesn’t see race or color; she only sees humanity. One visit with her and you will agree.
PAGE 21
Sulphur’s Team Hope Needs You! Huntington’s Disease Society of America
is pleased to announce its FIRST annual Team Hope Walk for HD at The Grove at Heritage Square in Sulphur on Saturday, March 22nd. Support from the community is needed to help make this event a success! Support includes: • Corporate and individual sponsorships • In-kind goods • Volunteers • Corporate and individual teams To learn more about Huntington’s disease , please visit and the local webpage at Contact Dolly Ardoin, Team Hope Walk Committee Chair at hdsa.thwsulphur@gmail.com.
Sassy Oil & Vinegar
HEALTH FAIR Feb. 8th 1pm-4pm
Mill Street Church of Christ 2318 Mill St • Lake Charles For more information contact Liz Fuselier 337-540-1408 sassyoilandvinegar.com PAGE 22
Feburary 2014 • Volume 1 • Number 7
The Biblical Boss by Paige Francis
“He whose walk is blameless is kept safe, but he whose ways are perverse will suddenly fall.” - Proverbs 28:18 “Better a poor man whose walk is blameless, than a rich man whose ways are perverse.” - Proverbs 28:6
Wealth should not be the biggest motivating factor in business. When money becomes the focus of a businessman or woman, it can easily consume every part of their being. Looking back, you can probably recall someone you know that once began their business. They were focused, excited and exuberant. They were passionate and purposeful day
Feburary 2014 • Volume 1 • Number 7
in and day out. As their success grew, did you find a change in the air about them? This happens so easily, especially when experiencing a quick growth in business. But as the Bible so clearly explains, one must tread lightly in the field of wealth. There must be a balance in the desire to attain wealth and the desire to stay spiritually and mentally grounded. Because fortune is one of life’s biggest snares, when it slips away from us we can be tempted to do unhealthy or
unrighteous things to attain it once more. Hurting colleagues, lacking in loyalty to those who are loyal to you, making bad business deals to benefit yourself, all are ways in which the desire for more can motivate you to do things that you normally would not do. Therefore, as success approaches be sure to check yourself on a regular basis, making sure that you are doing the right thing at all times. In the event that you chose to do wrong, be aware that it will not end favorably.
PAGE 23
Hello. 24 73615_WCH_Hello_10x11_25c.indd 1
Feburary 2014 • Volume 1 • Number 7 1/21/14 3:54 PM | https://issuu.com/tnonette64/docs/feb_issue | CC-MAIN-2017-47 | refinedweb | 10,439 | 62.48 |
View Complete Post
I
Hi All
I tried many ways , but have non can successfully alter the combo box Text after selected an item from drop down, and I want to make sure this is just not possible.
This is what I need, if after I selected an item - "1 apple" from the drop down, i want the combo box shows text, "1". I tried write code in different eventhandlers, overrider Text property, clear items . non of those way can achieve this.
public class AccountComboBox : ComboBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
if (this.SelectedItem != null)
{
base.Text = SelectedItem.ToString().Remove(this.SelectedItem.ToString().IndexOf(" "));
}
I need to create one custom text box control which should be bind with data
base.
I am referring following link...
I used DataBoundControl to create my control but i am
not able to do it properly.
public class SimpleTextBoxControl : DataBoundControl { private TextBox nameTextBox; public string DataTextField { get { object o = ViewState["DataTextField"]; return ((o == null) ? string.Empty : (string)o); } set { &n
Hi guys,
I have noticed a weird behavior on databinding some radiobuttons to an enum property.
Scenario:
- an enum dependency property on a Window (eg: property Test of type Visibility);
- three radiobuttons to display and select the value of the property, one for every enum value (eg: Visible, Hidden and Collapsed)
- a converter that converts and converts back the value of the property to the radiobutton's IsChecked property
The weird behavior is that when I click on a radiobutton the value of the property changes, but if I assign via code a new value directly to the property, the radiobuttons get disconnected from the property, resulting in not changing anymore the value of
Test property when a radiobutton is clicked.
I created a test project in which you can select, using the radio buttons, the value of the Test property, and if you click the 'Test' button, the value is assigned to the Test property by code.
In the second part of the window there is the same thing with the SelectedIndex property of a ListBox, bound to a TestIndex property, this time without a converter.
If you launch the project, and first of all click on the Test button, the value of the property changes, but now, if you change the selection on the radiobuttons, the property never changes again if you click 'Visible' or 'Hidden'
hi,
{
Web Part Custom Property Text Values Showing Up on Page | http://www.dotnetspark.com/links/13283-how-to-get-and-set-radiobutton-value-without.aspx | CC-MAIN-2016-44 | refinedweb | 408 | 53.24 |
From: "Sean Brandt" <sean@fuzzymagic.com>
> On Tuesday, February 25, 2003, at 11:45 AM, James Strachan wrote:
>
> > [snip]
>
> > XMLOutput uses aggregation to work with any SAX ContentHandler or
> > LexicalHandler so no need to derive.
> >
> > XMLParser is a ContentHandler and LexicalHandler. So you could do
> > something
> > like this in pseudo code
> >
> > public class EvalTag extends TagSupport {
> > private String var;
> >
> > public void doTag(XMLOutput output) throws JellyTagException {
> > XMLParser parser = new XMLParser();
> > XMLOutput newOutput = new XMLOutput( parser );
> >
> > // invoke body, redirecting SAX events into the Jelly parser
> > invokeBody( newOutput );
> > Script script = parser.getScript();
> >
> > if (var != null) {
> > context.setVariable(var, script);
> > }
> > else {
> > // lets just execute the new script
> > script.run(context, output);
> > }
> > }
> > }
> >
> Pretty much exactly what I'd done with my previous message,
Agreed.
> though I'm
> still having an issue with variables set in the body's script not being
> visible to the parent script.
One thing I missed off is the context should be passed into the XMLParser.
So
XMLParser parser = new XMLParser();
parser.setContext(context);
...
should do the trick?
BTW have you also got a JDOM tag library? If so do you fancy submitting it
for inclusion in the Jelly project?
James
-------
__________________________________________________
Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts | http://mail-archives.apache.org/mod_mbox/commons-user/200302.mbox/%3C015501c2dcf8$d7c112b0$9865fea9@spiritsoft.com%3E | CC-MAIN-2014-23 | refinedweb | 213 | 58.08 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.