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
In part 1, I started walking you through making a console using uGUI, Unity’s built-in GUI framework. I’m showing you how to implement a simple input parser. Let’s continue where we left off here in Part 2. We’re going to program the behavior of the console. I split this into a ConsoleController, which handles parsing and executing commands, and a view component that handles the communication between the ConsoleController and uGUI. This makes the parser code cleaner, and easier to switch to a different GUI system in the future if needed. First, make a new script called ConsoleController. Completely delete its contents and replace them with the following class: /// /// Handles parsing and execution of console commands, as well as collecting log output. /// Copyright (c) 2014-2015 Eliot Lash ///using UnityEngine; using System; using System.Collections.Generic; using System.Text; public delegate void CommandHandler(string[] args); public class ConsoleController { #region Event declarations // Used to communicate with ConsoleView public delegate void LogChangedHandler(string[] log); public event LogChangedHandler logChanged; public delegate void VisibilityChangedHandler(bool visible); public event VisibilityChangedHandler visibilityChanged; #endregion /// /// Object to hold information about each command ///class CommandRegistration { public string command { get; private set; } public CommandHandler handler { get; private set; } public string help { get; private set; } public CommandRegistration(string command, CommandHandler handler, string help) { this.command = command; this.handler = handler; this.help = help; } } /// /// How many log lines should be retained? /// Note that strings submitted to appendLogLine with embedded newlines willconst int scrollbackSize = 20; Queue be counted as a single line. /// scrollback = new Queue (scrollbackSize); List commandHistory = new List (); Dictionary commands = new Dictionary CommandRegistration>(); public string[] log { get; private set; } //Copy of scrollback as an array for easier use by ConsoleView const string repeatCmdName = "!!"; //Name of the repeat command, constant since it needs to skip these if they are in the command history public ConsoleController() { //When adding commands, you must add a call below to registerCommand() with its name, implementation method, and help text. registerCommand("babble", babble, "Example command that demonstrates how to parse arguments. babble [word] [# of times to repeat]"); registerCommand("echo", echo, "echoes arguments back as array (for testing argument parser)"); registerCommand("help", help, "Print this help."); registerCommand("hide", hide, "Hide the console."); registerCommand(repeatCmdName, repeatCommand, "Repeat last command."); registerCommand("reload", reload, "Reload game."); registerCommand("resetprefs", resetPrefs, "Reset & saves PlayerPrefs."); } void registerCommand(string command, CommandHandler handler, string help) { commands.Add(command, new CommandRegistration(command, handler, help)); } public void appendLogLine(string line) { Debug.Log(line); if (scrollback.Count >= ConsoleController.scrollbackSize) { scrollback.Dequeue(); } scrollback.Enqueue(line); log = scrollback.ToArray(); if (logChanged != null) { logChanged(log); } } public void runCommandString(string commandString) { appendLogLine("$ " + commandString); string[] commandSplit = parseArguments(commandString); string[] args = new string[0]; if (commandSplit.Length commandString)); return; } else if (commandSplit.Length >= 2) { int numArgs = commandSplit.Length - 1; args = new string[numArgs]; Array.Copy(commandSplit, 1, args, 0, numArgs); } runCommand(commandSplit[0].ToLower(), args); commandHistory.Add(commandString); } public void runCommand(string command, string[] args) { CommandRegistration reg = null; if (!commands.TryGetValue(command, out reg)) { appendLogLine(string.Format("Unknown command '{0}', type 'help' for list.", command)); } else { if (reg.handler == null) { appendLogLine(string.Format("Unable to process command '{0}', handler was null.", command)); } else { reg.handler(args); } } } static string[] parseArguments(string commandString) { LinkedList parmChars = new LinkedList (commandString.ToCharArray()); bool inQuote = false; var node = parmChars.First; while (node != null) { var next = node.Next; if (node.Value == '"') { inQuote = !inQuote; parmChars.Remove(node); } if (!inQuote && node.Value == ' ') { node.Value = ' n'; } node = next; } char[] parmCharsArr = new char[parmChars.Count]; parmChars.CopyTo(parmCharsArr, 0); return (new string(parmCharsArr)).Split(new char[] {' n'} , StringSplitOptions.RemoveEmptyEntries); } #region Command handlers //Implement new commands in this region of the file. /// /// A test command to demonstrate argument checking/parsing. /// Will repeat the given word a specified number of times. ///void babble(string[] args) { if (args.Length = 0; --cmdIdx) { string cmd = commandHistory[cmdIdx]; if (String.Equals(repeatCmdName, cmd)) { continue; } runCommandString(cmd); break; } } void reload(string[] args) { Application.LoadLevel(Application.loadedLevel); } void resetPrefs(string[] args) { PlayerPrefs.DeleteAll(); PlayerPrefs.Save(); } #endregion } I’ve tried to comment where appropriate, but I’ll give you a basic rundown of this class. It maintains a registry of methods that are mapped to string command names, as well as associated help text. This allows the “help” command to print out all the available commands along with extra info on each one. It keeps track of the output scrollback as well as the history of user-entered commands (this is to aid implementation of bash-style command history paging, which is left as an exercise to the reader. Although I have implemented a simple command, ‘!!’ which repeats the most recent command.) When the view receives command input, it passes it to runCommandString() which calls parseArguments() to perform some rudimentary string parsing using a space as a delimiter. It then calls runCommand() which tries to look up the corresponding method in the command registration dictionary, and if it finds it, calling it with the remaining arguments. Commands can call appendLogLine() to write to the in-game console log, and of course execute arbitrary code. Moving on, we will implement the view. Attach a new script to the ConsoleView object (the parent of ConsoleViewContainer) and call it ConsoleView. Replace its contents with the following: /// /// Marshals events and data between ConsoleController and uGUI. /// Copyright (c) 2014-2015 Eliot Lash ///using UnityEngine; using UnityEngine.UI; using System.Text; using System.Collections; public class ConsoleView : MonoBehaviour { ConsoleController console = new ConsoleController(); bool didShow = false; public GameObject viewContainer; //Container for console view, should be a child of this GameObject public Text logTextArea; public InputField inputField; void Start() { if (console != null) { console.visibilityChanged += onVisibilityChanged; console.logChanged += onLogChanged; } updateLogStr(console.log); } ~ConsoleView() { console.visibilityChanged -= onVisibilityChanged; console.logChanged -= onLogChanged; } void Update() { //Toggle visibility when tilde key pressed if (Input.GetKeyUp("`")) { toggleVisibility(); } //Toggle visibility when 5 fingers touch. if (Input.touches.Length == 5) { if (!didShow) { toggleVisibility(); didShow = true; } } else { didShow = false; } } void toggleVisibility() { setVisibility(!viewContainer.activeSelf); } void setVisibility(bool visible) { viewContainer.SetActive(visible); } void onVisibilityChanged(bool visible) { setVisibility(visible); } void onLogChanged(string[] newLog) { updateLogStr(newLog); } void updateLogStr(string[] newLog) { if (newLog == null) { logTextArea.text = ""; } else { logTextArea.text = string.Join(" n", newLog); } } /// /// Event that should be called by anything wanting to submit thepublic void runCommand() { console.runCommandString(inputField.text); inputField.text = ""; } } current input to the console. /// The ConsoleView script manages the GUI and forwards events to the ConsoleController. It also watches the ConsoleController and updates the GUI when necessary. Back in the inspector, select ConsoleView. We’re going to hook up the Console View component properties. Drag ConsoleViewContainer into the “View Container” property. Do the same for LogText into “Log Text Area” and InputField into “Input Field.” i Now we’ve just got a bit more hooking up to do. Select InputField, and in the Input Field component, find the “End Edit” event list. Click the plus button and drag ConsoleView in to the new row. In the function list, select ConsoleView > runCommand (). Finally, select EnterBtn and find the “On Click” event list in the Button component. Click the plus button and drag ConsoleView in to the new row. In the function list, select ConsoleView > onCommand (). Now we’re ready to test! Save your scene and run the game. The console should be visible. Type “help” into the input field: Now press the enter/return key. You should see the help text print out like so: Try out another test command, “echo foo bar baz”. It will show you how it splits the command arguments into a string array, printed out as a comma separated list: Also make sure the fallback “Ent” button is working to submit the input. Lastly, check if the console toggle key works: press the backtick/tilde key (located right above the left tab key.) It looks like this: The console should disappear. Press it again and it should reappear. On a mobile device, tapping five fingers at once will toggle the console instead. If you want to use a different means of toggling the console, you can edit this in ConsoleView.Update(). If anything is not working as expected, please go back over the instructions again and try to see if you’ve missed anything. Lastly, we don’t want the console to show when the game first starts. Stop the game and find ConsoleViewContainer in the hierarchy, then disable it by unchecking the box next to its name in the inspector. Now, save and run the game again. The console should be hidden until you press the backtick key. And that’s it! You now have an in-game, interactive console. It’s an extremely versatile debugging tool that’s easy to extend. Use it to implement cheat codes, enable or disable experimental features, obtain diagnostic output, or whatever else you can think of! When you want to create a new console command, just write a new method in ConsoleController “Command handlers” region and add a registerCommand() line for it in the constructor. Use the commands I’ve included as examples. If you want to have other scripts be able to log to the console, you can make the ConsoleController into a service as I described in my article “One-liner Singletons in Unity”. Make the ConsoleController set itself as a service in its constructor, Then have the other script get the ConsoleController instance and call appendLogLine() with its message. I hope having an in-game console will be as useful for you as it has been for me. Lastly, don’t forget to disable or delete the ConsoleView before shipping production builds unless you want your players to have access to all of your debug cheats! About the author Eliot Lash is an independent game developer and consultant with several mobile titles in the works. In the past, he has worked on Tiny Death Star and the Tap Tap Revenge series. You can find him at eliotlash.com. this HTML website completly broke all the generics in your code btw… The code in this example is hilariously broken.
https://hub.packtpub.com/making-game-console-unity-part-2/
CC-MAIN-2019-18
refinedweb
1,652
51.04
Beaulieu 5008S Multispeed Here you can find all about Beaulieu 5008S Multispeed like manual and other informations. For example: review. Beaulieu 5008S Multispeed manual (user guide) is ready to download for free. On the bottom of page users can write a review. If you own a Beaulieu 5008S Multispeed please write about it to help other people. [ Report abuse or wrong photo | Share your Beaulieu 5008S Multispeed photo ] Manual Preview of first few manual pages (at low quality). Check before download. Click to enlarge. Beaulieu 5008S Multispeed User reviews and opinions No opinions have been provided. Be the first and add a new opinion/review. Documents Midnight Engineering November-December, 1990 RESOURCE BIN number thirteen Perils and pitfalls of patents and patenting. ur usual reminder here that the Resource Bin is now a two-way column. You can get tech help, consultant referrals and off-the-wall networking on nearly any electronic, tinaja questing, personal publishing, money machine, or computer topic by calling me at (602) 428-4073 weekdays 8-5 MST. Ive got a free pair of insider secret resources brochures waiting for you when you call or write. This month, I thought wed take a slightly different tack. Instead of my showing you lots of great places to get stuff, I will be showing you the one resource that you should studiously avoid at all costs. Because it is certain to waste your time, energy, money, and sanity. The term mark first came from the carnival midway. Any time a scam operator (the rube in carneyspeak) had significantly lightened a prospects wallet, he would give him a friendly exiting pat on the back. Along with a supporting "Gee Fella, thats too bad." Unmentioned and unbeknownest to the lightenee was the fact that the rube had secretly dipped his hand in a hidden stash of powdered chalk just before the pat on the back. And thus marking a large "X" on the lightenee, clearly identifying him as worthy of special treatment by the next rube on down the line. Eventually, every non-rube who so much as entered the carnival midway area became known as a mark. And were contemptuously treated as such. These days, we no longer have too many marks left. So, you substitute the term inventor instead. Any time an "inventor" context crops up, you are assured of an uneven playing field very much comparable to a carnival midway or a casino floor. A scene which is intended primarily to (A) liberate as much money as possible from the mark, and (B) to keep the status quo exactly where it is. The foremost reason to studiously avoid any "inventor" context is the totally absurd popular mythology which now surrounds patents and inventing. Nearly all of which is dead wrong. To prove this to yourself, just mention the word "patent" at any party and then observe the ludicrous disinformation heaped upon you. Then challenge them to name one individual anywhere, ever, whom they personally know that, in a small scale context, has shown a net positive cash flow from their patent involvement. A cash flow that was worth the time and effort involved. No, the windshield wiper guy has not collected yet. The Sears wrench dude has wasted his entire lifetime by tilting at windmills. To me, Hyatt looks like a rube. Tesla died a pauper. The patent system drove Armstrong to suicide. And Edison was a ripoff artist who made most of his bag by simple theft, using the most ruthless gaggle of renegade patent attorneys ever assembled anywhere. So much for urban lore. Now, patents might or might not retain at least a marginal utility in a Fortune 500 context. Our concern here September-October, 1994 Midnight Engineering 29.2 Tech Musings June, 1997 he folks at IBM have added a new patent repository to the web. With a free searchable master file for all patents in all fields newer than 1971. Plus a $3 per patent hard copy fax service. You can access this site from the Patent Avoidance Library Shelf page of my Or reach it directly at This new service certainly is fast, convenient, and scads of fun to play with. Text and complete figures are included. As are "forward looking" cross references. The site is not yet in Adobe Acrobat, so the figures remain somewhat grubby looking. And I feel their search engine seems to be a tad on the weak side. But do note that not one patent in 200 ever shows any net positive cash flow. Less than one patent in 1000 is ever "new" enough or "non-obvious" enough that it cannot get busted with a thorough enough search for prior art in obscure enough places. Thus, any patent repository might overwhelmingly end up providing a mind-numbing stash of incompetent failures and total losers. An amazing number of patents just plain do not work. Your effort is infinitely better spent studying the trade journals and all of the web sites where the winners consistently appear. Ferinstance, I was two for two on my first visit here. I looked into two patents and now have a pair of superb new candidates for my patent horror story collection. I first searched on "ac phase control" to find out where it would end up leading me. The first patent from 1992 looked vaguely familiar. Sure enough, I had published the exact same waveforms back in the September 1969 Popular Electronics. On page 30. While studiously ignoring obvious high profile public domain prior art, they did, of course, manage to make their design far more complex and way more expensive than necessary. The second patentocity was more recent. And even sadder. They started with a 1938 construction project you % Consulting services available on concepts shown. % Two-way recordable comm is **REQUIRED** for these utilities. % Routines excerpted from FINDRMS.PS on. /scaleamp sqrt mul def /startang 0 def /stopang 180 def /endang 180 def /res 0.1 def % use a 117 volt ac cycle % set limits % % % step resolution in degrees % Assume a ONE OHM load. Make a normalized array holding the desired % waveform values. This routine optimizes for ac phase control. % Any values array normalized to peak = 1 can be substituted. /makewaveform {/waveform mark 0 res endang {/ang exch store ang startang gt ang stopang lt and {ang sin} {0} ifelse} for] def } def % do the rms and average calculations on the waveform array. /findrms1 { 0 waveform {add } forall waveform length div /normaverage exch store 0 waveform {dup mul add} forall waveform length div sqrt /normrms exch store normrms normaverage dup 0 eq {pop 0.000001} if div /normratio exch store} def % report the results. /crlf true def % IBM or sanity? /return {(r) print crlf {(n) print} if} def /reportrms {return return (The average normalized waveform value is ) print normaverage 20 string cvs print return return (The rms normalized waveform value is ) print normrms 20 string cvs print (.) print return (The ratio of rms to average is ) print normratio 20 string cvs print (.) print return return (The average scaled waveform value is ) print normaverage scaleamp mul 20 string cvs print (.) print return return (The rms scaled waveform value is ) print normrms scaleamp mul 20 string cvs print (.) print return return return} def /findrms {findrms1 reportrms} def % convenience linker % ========== % % demo - remove or alter before reuse. ========== (A) Plot the rms voltage versus phase angle for a triac that conducts only a portion of each ac half cycle % % % % % 0.1 degree accuracy start at turnon angle go to the end of half cycle stop at one half ac cycle use a 117 volt ac cycle /res 0.1 def /startang 0 def /stopang 180 def /endang 180 def /scaleamp sqrt mul def 180 { /startang exch store (The phase angle is ) print startang 20 string cvs print ( degrees.) print return makewaveform findrms} for flush % should return these edited results. %% %% %% %% %% %% The phase angle is 0 degrees. The rms voltage is 117.0. The ratio of rms to average is 1.11072. The phase angle is 10 degrees. The rms voltage is 116.936. The ratio of rms to average is 1.11852. << more stuff here >> %% %% %% %% %% %% The phase angle is 170 degrees. The rms voltage is 3.94639. The ratio of rms to average is 4.88476. The phase angle is 180 degrees. The rms voltage is 0.0. The ratio of rms to average is undefined. Modeling materials Your local hobby shop probably has smaller quantities of most building stock. I have found it better to go to the actual sources for wider variety and far better prices. For aluminum, brass, and other metal sheets, rods, and tubes, try K & S Engineering. For styrene sheet stock and similar plastic items, use Evergreen Scale Models. And for "lumber" precisely cut in all of the train gauge and scale dollhouse sizes, Northeastern Scale Models is it. For the larger pieces of flat display, exhibit and modeling materials, your best source is Fomeboards. These folks are strong in foam core plastics and similar base materials for architectural mockups, fancier point-of-purchase signs, trade show panels, and such. Several highly unusual decorative sheeting materials are now sold by Coburn. These can include prismatics, holographics, foils, glow-in-the-darks, metallics, and lots of other stunningly attractive display materials. One of my favorite sources for the traditional art supplies is Dick Blick, while the Polyline people are big on cases, labels, and packages for audio cassettes and VCR video cases. I use Polyline cases for my Introduction to PostScript videos. They also stock hard-to-find VHS spine labels. LASERWRITER SECRETS The name is short for Educational Lumber Company. These folks are into exotic hardwoods in a very big way. Especially the weird, the beautiful, or the unusual. Nothing like a piece of wenge or cocobolo to liven up a small electronic enclosure. A free catalog is offered. The reprints from all Dons Midnight Engineering columns. Includes the case against patents, book on demand publishing, toner secrets, paradigm stalking, insider research, lots more. $18.50 Outwater Plastics This outfit believes they are in the display fixtures business. They have a wildly mind-boggling assortment of low cost and potentially quite useful hardware for you electronic hackers. Plus all sorts of ways of hanging and showing things. They even now offer Grecian urns for writing odes on. Once again, a fat and free catalog is offered. This one is a real page turner, chock full of "use me" stuff. Stuff that simply cannot be ignored. Model Railroader Box 1111 Placentia, CA 92670 (714) 632-7721 An all-ads mail order shopper specifically for hardware hackers, ham radio operators, CB folks, computer users, and satellite pirates. Their low-price ads are attractive for most shoestring technical startups. PaperPlus 1027 North 7th Street Milwaukee, WI 53233 (414) 272-2060 Besides unusual tools and techniques, this hobby magazine has far and away the finest technical writing and technical illustration of any publication anywhere ever. Use it as a style and layout manual, and hope to someday be able to communicate that well. Should be required reading for any tech writer. Motion Magazine 300 Oceangate #800 Long Beach, CA 90802 (800) 272-7377 If youve ever tried buying paper from an old line source, you know the hassles. Instead, try these walk-in paper supermarkets now in most states. Especially useful for book-on-demand publishers. Also stocks certificates, bumper sticker stock, acetates and polyesters. Box 6430 Orange, CA 92613 (714) 974-0200 Free trade journal that covers steppers, servo motors, linear actuators, the power control semiconductors, and general robotics stuff. Pricey products but full of good technical ideas and resources. Mouser Electronics 2472 Eastman Avenue Ventura, CA 93003 (805) 658-0933 Used to be called Power Conversion and Intelligent Motion. Another free trade journal for the robotics crowd. Covers steppers, servos, motors, linear actuators, and their electronic control components. Player Piano Company 11433 Woodside Avenue Santee, CA 92071 (800) 346-6873 Electronic distributor with low minimums, low pricing, and extensive stock. Very hacker friendly. Carries semiconductors, ics, relays, resistors, capacitors, inductors, hardware, and all the usual goodies. Largely imports. Northeastern Scale Models 704 East Douglas Wichita, KS 67202 (316) 263-3241 Well, just because it is there, I guess. Unusual source for very unusual tools, materials, and techniques. Has hobby robotics potential, especially for low pressure pneumatics. Printers Shopper PO Drawer 1056 Chula Vista, CA 92012 (800) 854-2911 Not really a shopper, but a monthly mail-order catalog for a major printing equipment tools, materials, inks, and supplies house. Many hundreds of items listed. Their prices are usually better than buying locally. toner to the pc board. Or else a laser printer modified to print directly onto 1/16th inch copper clad. Ive found that a few seconds of pre-etch helps bunches, as does preheating the board so it does not act as a giant heat sink. A post-transfer bake also helps. Trying to use an ordinary iron is an outright joke. I currently use a Kapton film from Dupont that Ive coated with a high temperature mold release from Miller-Stephenson. A commercial toner transfer product called Meadowlake works for some people some of the time. Fake Kroy Color machines and toners are found at Lazer Products. Two other toner sources are Black Lightning and Don Thompson. Two fine trade journals on printed circuits are Circuits Manufacturing and Electronic Packaging and Production, while your best hacker source for pc boards and etchants is Kepro. A low price, low end printed circuit layout package is included in my PostScript Show and Tell from Synergetics. EMERGING TECHNOLOGIES NAMES AND NUMBERS Adobe PostScript 1585 Charleston Road Mountain View, CA 94039 (415) 961-4400 Black Lightning RR 1-87 Depot Road Hartland, VT 05048 (800) BLACK99 C & H Sales Box 5356 Pasadena, CA 91107 (800) 325-9465 Carter Carburetor 9666 Olive Road St. Louis, MO 63132 (314) 997-7400 Clippard Minimatic 7390 Colerain Road Cincinatti, OH 45239 (513) 521-4261 Dialog Information Service 3460 Hillview Avenue Palo Alto, CA 94304 (415) 858-2700 DTM Systems 1611 Headway Circle, B2 Austin, TX 78754 (512) 339-2922 Dupont Kapton 1007 Market Street Wilmington, DE 19898 (302) 774-1000 Edmund Scientific 101 East Gloucester Pike Barrington, NJ 08007 (609) 573-6250 Exair 1250 Century Circle North Cincinnati, OH 45246 (513) 671-3322 Flow International 21440 68th Avenue South Kent, WA 98032 (206) 872-4900 Haskell 100 East Graham Place Burbank, CA 91502 (818) 843-4000 Hygenic Manufacturing 1245 Home Avenue Akron, OH 44310 (216) 633-8460 Jerryco 601 Linden Place Evanston, IL 60202 (312) 475-8440 Kepro 630 Axminister Drive Fenton, MO 63026 (314) 343-1630 Kroy Sign Systems 14555 North Hayden Road Scottsdale, AZ 85260 (800) 521-4997 Lazer Products 12741 East Caley #130 Englewood, CO 80155 (303) 792-5277 MasterCAM 2101 Jericho Turnpike New Hyde Park, NY 11040 (516) 328-3970 Meadowlake 25 Blanchard Drive Northport, NY 11768 (516) 757-3385 Meredith Instrument 6401 North 59th Avenue Glendale, AZ 85301 (602) 934-9387 Miller-Stephenson George Washington Hwy Danbury, CT 06810 (203) 743-4447 MWK Industries 1440 S. College Blvd #3B Anaheim, CA 92806 (800) 356-7714 Phillips 2001 W Blue Heron Blvd Riveria Beach, FL 33404 (407) 881-3200 Player Piano Co 704 East Douglas Wichita, KS 67202 (316) 263-3241 Roland Digital 7200 Dominion Circle Los Angeles, CA 90040 (213) 685-5141 SGS-Thompson 1000 East Bell Road Phoenix, AZ 85022 (602) 867-6259 Sharp Sharp Plaza Mahwah, NJ 07430 (201) 529-8757 Sprague 70 Pembroke Road Concord, NH 03301 (603) 224-1961 Synergetics Box 809 Thatcher, AZ 85552 (602) 428-4073 Technical Insights PO Box 1304 Fort Lee, NJ 07024 (201) 568-4744 Don Thompson 23072 Lake Center #100 El Toro, CA 92630 (714) 855-3838 3-D Systems 26081 Avenue Hall Valencia, CA 91355 (805) 295-5600 Toshiba 1220 Midas Way Sunnyvale, CA 94086 (800) 321-1718 Value Plastics 3350 Eastbrook Drive Fort Collins, CO 80525 (303) 233-8306 Vortec 10125 Carver Road Cincinnati, OH 45242 (800) 441-7475 Whole Earth Review 27 Gate Five Road Sausalito, CA 94964 (415) 332-1716 Emerging Opportunities III t sure is rewarding for me to see you other Midnight Engineers picking up on and successfully going with some of our previous emerging opportunities. All in your own small scale home-based Money Machines. Several examples here include John Rees who offers a great video on converting car alternators into power stepper motors. And Martin Carbone whose new desktop finishing products include a pair of very low cost scoring machines for boxmaking and bookbinding. Or Frank Miller who has bunches of useful direct toner printed circuit products. Or Kevin Bennet with his easy to do "raised print" laser thermography. That uses nothing but a small desk lamp. Or Stan Griffiths and his fine new book on recycling Tektronix classic oscilloscopes. Or Kirk McLoren who has a new Micro Cogeneration book that shows you how homemade power can actually end up cheaper than utility power. Lets return to the scene of the crime. Heres what I see as the current crop of emerging opportunities. Along with several GEnie PSRT filenames you could go to for more details. Stuff that suddenly has become cheap enough and real enough, yet remains fuzzy enough and undeveloped enough for superb Midnight Engineering potential All you really have here is an air core transformer. With the core being the distance between your chest and your wrist or handlebars. Plain old near field inductive coupling is all you require for effective comm. But wait. What do we really have here? We have a tiny, lightweight, sealed and waterproof transmitter. With a one year or longer life from its internal lithium cell. That can handle a data rate of zero to 200 Hertz or so. At a retail list price of $22, far less in quantity. Providing a signal that is handily received by a coil and an op-amp or two. Largely unidirectional, except for deep axis nulls. Two leading brands of these devices are Polar and Vetta. More details on their internal workings in HACK68.PS. By the way, a dental X-ray is a dandy way to reverse engineer sealed modules of this type. One big new use I see for short haul telemetry ISOPOD ENERGY REPORTER Short Haul Telemetry Micropower radio and infrared transmitters have gotten super small and very cheap. To the point where they can be used for all sorts of data comm over ranges of, say, four to six feet. There are a lot of new possibilities here. I like to call the sum total of these devices short haul telemetry. Ferinstance, there are all kinds of new uses for ordinary TV remote controls. There are antishoplifting tags. And implanted animal monitors. And schemes to get data on or off a rotating shaft. Inventory controls. Security systems. Intelligent data tags. New wireless mice and modems. Car locks. 3-D position sensors. Attitude detectors. A brand new trade journal that addresses these devices is Wireless Design and Development. One low cost and grossly underutilized short haul system is called an EKG heart monitor. This is normally used to optimize aerobic excercise sessions. You have a strap that wraps around your chest. The strap picks up your electrical heartbeats and converts them to transmitted 36 cycle bursts of 5 kHz rf energy. These low frequency waves are then picked up using a nearby wristwatch or bicycle mounted computer display. The big advantage is that they perform reliably during strenuous exercise. Cheap finger or ear-clip infrared units do not. Look Ma, no wires. May-June, 1997 Midnight Engineering 44.-21 December, 1995 just got a helpline call from an "inventor" trying to "protect" a "new" auto headlight idea. To stop "Detroit" from stealing it. Ive never heard of "Detroit" ever paying any outsider for any untested, undeveloped, or unproven idea. Instead, "Detroit" buys parts from suppliers and bolts them together to make cars. They are in the process of outsourcing much of their product engineering. They are significantly reducing their number of suppliers. And holding them to the tightest of razor thin margins. Uh, strike one. Illumination engineering is one of the very few things that Fortune 500 companies happen to do very well. A multi-skill project team approach is usually required, combined with ray tracing computers, arcane production engineering, and outstanding access to the worlds research base. So, those big boys clearly have an unbeatable home turf advantage here. For strike two. Your really big issue on all future headlights is efficiency. Because of downsizing in general and electric or hybrid cars in particular. Anything less than 100 Lumens per Watt wont hack it. You can bet that tomorrows headlights will most definitely not be based on a heated filament. I got the impression the caller was not a member of the SAE. Nor the IESNA. Nor did he seem to be at all into trade journals or online literacy. He seemed to feel that car headlamp efficiency was "not important." And apparently did not have the slightest idea how woefully inefficient his new design was. For a self-inflicted swing and a miss for strike three. Superb avaition history book A new RGB to NTSC encoder Lamps and lighting efficiency Emerging ultra-fast computers Product development concepts But be sure to remember the key insider secret rule for all successful new product development: They must come to you. And never vice versa. Do note that you are not selling an idea. Ideas are worth ten cents a bale in ten bale lots. You are instead now offering a proven, in-demand, and a ready to manufacture product. here you have already completed most of the high risk steps. More on becoming a purveyor of risk reduction in RISKDOWN.PDF on And much more in general on idea development in my Blatant Opportunist and my Case Against Patents packages. Or one that long ago fell off the shelf because of inherent problems. Step two is to ask yourself "Who is it that (A) likes bright headlights, and (B) has their own wallet in their own back pocket? Well, out here on my sand dune, the answer is glaringly obvious: 4WD desert off-roaders. To these folks, a "map" light is 50,000 candelpower. And a "running" light can vaporize troublesome boulders at 75 paces. On low beam. So, firstoff, you would have a few four wheelers critique your design. If it is any good, you then let the local 4WD club beta test it. Once you have your tested and proven product well received, you sell a few at regional meets. Then you publish it in all the offroad mags. Next you seek out one or more of those off road lighting outfits. K.C. Manufacturing is but one of the name brand biggies out here. Competitors include Dick Cepek, Hella, Explorer, and Piaa corp. have been the traditional method of doing panels for limited and small volume production. Because of the front end expense and time cutting a screen, these work best for a dozen or more identical panels. Three good sources for silk screen materials and supplies include Dick Blick, Advance Process, and Southern Sign Supply. And, of course, your leading source for all printed circuit materials and supplies is Kepro. While youll still find traditional electronic decals offered by some old-line sources, these simply arent worth the time and effort. These are basically a sucker bet guaranteed to give second-rate results that range from unprofessional to attrocious. For totally superb panel artwork, consider linking PostScript to those old annodized aluminum dialplate systems offered by MetalPhoto or Fotofoil. These are somewhat pricey but are ideal for rugged and durable one-up or small quantity panels. They are also useful for museum signs and electronic relay rack panels. Picture an aluminum sheet which has only partially gone through the annodizing process, leaving a brightly colored but a very open and spongy surface. A photo emulsion is then applied. You later expose the emulsion through your custom PostScript artwork. A contact printer or an enlarger can be used. Followed up by a traditional darkroom slopping-in-the-slush. After developing, you can boil the panel in a magic glop that reseals the surface, closing a sapphire (literally!) hard surface and locking your image inside the panel. The results are quite durable. It takes a highly dedicated vandal to harm a Metalphoto panel. While the lettering and images are normally black, a wide range of bright colors are offered. Also the "plain old gray" of traditional annodizing. You might use a reverse technique to give you a black panel having colored or gray lettering. Again, this is utterly trivial with PostScript. There is also a slightly cheaper self-stick vinyl based system. This one used to be called ScotchCal, but has been renamed Dynamark. Picture a white self-stick vinyl with a colored photoglop on it. You contact print the vinyl using strong sunlight or some other u-v source, again through your PostScript artwork. Where present, the light hardens the photoglop against chemical attack. You then use a Webril wipe or other nonwoven pad to apply a chemical that removes the color from all areas which were not photohardened. The result is white over a color or vice versa, depending on whether youve used normal or reverse artwork. A clear epoxy overcoat gives you reasonable scratch resistance. You can then peel and stick your vinyl over your aluminum or other panel. Once again, if you are very careful, the vinyl can also be used as a punching and drilling guide. Kits are readily available, both in single and assorted colors. Very thin aluminum versions are also offered. There is also a non-stick product called Scotch Color Key offered to the printing industry. This gives you a mylar film having color selectively photoapplied to it. Many dozens of colors are offered. There are lots of prototyping opportunities here. info and other ads for materials with robotics potential. As do pubs from the SAE library, formerly the Society of Automotive Engineers. For lots of sensor and transducer info, check into Sensors magazine, and Measurement & Control. For the motion control info, your best trade journals include PCIM, Motion, Motion Control, and MotorTechniques. There are a number of vocational education magazines that may get into robotic topics. Typical examples include both School Shop and Industrial Education. There are a dozen more. And dont forget Model Railroader. Their ads do offer a great selection of unusual tools and materials. These folks have been in the robotic business for years. They just do not seem to want to admit it. Robotic opportunities OK, so what can be done in hobby robotics today? With the possibility of a reasonable cash return for your time and effort? I see several areas where original thought might come up with several long term robotic solutions. low pressure pneumatics We saw Magazines and trade journals There are a dozen or so robotics magazines. The SRS Encoder is a new labor-of-love newsletter, published by the Seattle Robotics Society, a leading amateur robotics group. There is also a Robotics Experimenter magazine. The rest are industry trade journals or scholarly publications. Ive tried to list most of them in our Names & Numbers sidebar. I was unable to review all of these by column deadline time, so do let me know which ones you find useful. Electronics Now runs an occasional robotic project or tutorial. Many trade journals focus on some other field, but may happen to have great robotics info in them. The two best mechanical trade journals are Machine Design and Design News. The largest industrial supply throwaway mags are New Equipment Digest and Industrial Product Bulletin. Appliance, the Appliance New Product Digest, and the Appliance Manufacturer trade journals sometimes have motor back in Resource Bin #7 and in my Resource Bin Reprints available from Synergetics how you could buy a low pressure 3-way air valve for only a quarter each. Low pressure air has yet to take off but its got outstanding robotics potential. Aquarium pumps can be used as compressors, and your actuators can be nothing but a balloon, bellows, or some rolling diaphram. You can get much more force much more linearly than you could ever hope to with a solenoid or another electronic solution. Sensor Trade Journals As I may have mentioned a time or two before, those free trade journals are the best way to get informed in a big hurry on almost any subject. Start with Ulrichs Periodicals Dictionary on your librarys reference shelf. This gem lists some 150,000 trade journals and other magazines. At any rate, your horses mouth trade journal is Sensors. From Carl Helmers of early Byte magazine fame. Also try Measurement & Control. You can also go to industry specific mags for all sorts of useful stuff. Say Pollution Equipment News for typical environmental sensors, Powder & Bulk Sensors and Sensing This month, I thought wed take a look at sensors and sensing. A sensor is any device that converts some other physical attribute into an electrical or electronic signal. Sensors of one sort or another are involved in just about any electronic project. And they sure are one hot topic on our helpline and on PSRT. Usually, there will be two stages involved in any sensor problem. First, youll have to do your actual sensing. This gets done using a transducer of some type. The result is often a very small signal, possibly a few tens of millivolts. Noise is always a problem in any sensing situation. And extreme caution is required to take care of this very weak signal. Next, you will typically have to do some signal conditioning to convert the sensed signal into something useful. Such as a higher current, a pulse train, or a digital word. Signal conditioning tricks include shielding, differential mode sensing, isolation, offsetting, amplifying, temp NEXT MONTH: Don looks at high frequency techniques and hackable resources. Solids for level controls, or American Laboratory for chemical sensors. Or even Weight Engineering for coverage on strain gauges. One Stop Shopping Your highest profile source for just about any sensor is Omega. These folks offer scads of impressive free catalogs on temperature, level, flow, pH, strain, pressure, data acquisition, and bunches more. Pricey, though. One shirtsleeves source for nearly any industrial sensing instrument or tool is Abbeon Cal. February 1995 / Nuts & Volts Magazine Devices sells a TMP01 programmable controller. Range of both devices is -55 to +125 C. One obvious use is as a hot tub controller. Pressure Silicon pressure sensors are rapidly becoming low cost commodities. These are basically a "drumhead" etched into bulk silicon. Strain sensors are implanted on the drumhead. As the pressure changes, the drumhead flexes, causing a resistance change. There are two main pressure sensor types. The absolute sensor compares pressure against a perfect vacuum. A differential sensor instead compares a pressure difference thats between two ports. If one of those ports is left open to your ambient air, then you have a variant called a gauge sensor. Temperature compensation and a lot of amplification are often needed when sensing pressure. Some sensors are offered both as raw chips or with signal conditioning and temperature compensation built in. Your two most obvious sources for the pressure sensors are Motorola and Microswitch. But the real action comes down from Sensym, I.C. Sensors, and Novasensor. Sensym has a Solid State Pressure Sensors handbook. This one includes a great slide chart. An oddball use for pressure sensors is in low pressure tire alarm systems. Fleet Specialties is one source. Theres also some purely resistive approaches to pressure sensing. One source is Interlink Electronics. With mice and music apps. For ultra cheap, you can sometimes get by using nothing but the black anti-static foam that chips arrive in. But repeatability and reliability can be big problems here. At the high end, Force Imaging sells subminiature and quite thin sensors that work from 1 to 20,000 PSI. A modification to a pressure sensor will let it measure acceleration. The motion of a mass is sensed. The rate of change of motion of the mass is the mass velocity. The rate of change of the velocity is the acceleration. Except for airbag sensors, these devices are still very expensive. One source is Silicon Designs. around ten percent. Thus, simply to break even, your venture has got to generate more than $100 per year and do so forever. But your tools and materials wont last forever. If they last for ten years, then your venture must generate more than $270 per year to amortize your initial expense and the time value of money over the effective life. With a five year lifetime, your venture must generate more than $329 per year. Just to break even! If your total cost is less than the returns, then you have an economic loss. The total costs must include all parts, labor, and your time value of money. Plus great heaping bunches of intangibles. Not to mention taxes and inflation. Paying cash does not make much difference. Since theres other things you might be doing with the money that gives better returns. Sadly, any "hacker economy" that Winegard CA-6060 Yagi, fixed roof mount Radio Shack 15-1117 coax inline 10 db amplifier Solid earth ground! Lightning / static block 75 coax roof drop Line splitter / two set coupler Denon TU-650-RD FM RBDS tuner Existing cable system Other stereo reveiver Some Details Say you want to start a technical venture. You first borrow a thousand dollars for your tools and materials. Today, the actual time value of money of those dollars will be somewhere Fig. 1 MY TEST SETUP for ultra-fringe FM and RBDS. Wavelets Update Theres sure been a lot of interest in wavelets recently. These can be a super performing replacement for the older Fourier analysis techniques that relate time and frequency. Important usage areas include everything from video compression schemes to human vision to seismography. Advanced math is required. The field is maturing and there are now dozens of books available. Ive listed several of the more popular of them in our resource sidebar. The best tutorial paper is probably by Rioul and Vetterli in IEEE Signal Processing Magazine, vol 8, #4, Oct 1991 pp 14-38. Also check that Dec 1993 issue of their IEEE Transactions on Signal Processing. Note that these are two different pubs. Yes, we have wavelet shareware up on Code: 0,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,0 Shorthand Code: 0x2,1x1,0x1,8x1,0x1,1x1,0x3,-1x1,0x1,-1x8,0x1,-1x1,0x1 The fundamental peak amplitude is 1.0545 times the "1" amplitude. Fundamental: (1.0000) 2nd Harmonic: 0 3rd Harmonic: 0 4th Harmonic: 0 5th Harmonic: 0 6th Harmonic: 0 7th Harmonic: 0.1184 8th Harmonic: 0 9th Harmonic: 0 10th Harmonic: 0 11th Harmonic: 0.2230 12th Harmonic: 0 13th Harmonic: 14th Harmonic: 15th Harmonic: 16th Harmonic: 17th Harmonic: 18th Harmonic: 19th Harmonic: 20th Harmonic: 0.0.0.1301 0 Fig. 3 AN "EVEN MORE MAGIC" power sinewave waveform of 210 bits. the filter only makes a difference on a few stations. But what a difference. Does it make sense to add a lower quality booster at the antenna ahead of an ultra hot receiver? A modest 10 db boost at your antenna gives your antenna a fixed impedance to work into and makes up for both line and distribution losses. The slightly higher signal level is enough to override the "no stereo on weak signal" feature. Which lets you switch by yourself rather than using the factory preset. Naturally, mono is cleaner for marginal signals. But any preamp also adds to your cross mod and can cause overloading. Which was only observable at half a channel away from a nearby station. If you use a preamp, be sure to use an inline coax version which is totally shielded. Providing you with only the bare minimum gain needed. Does a fixed antenna make sense? Fixed is cheaper and more rugged. And theres not too much east of me because of this slight rise that some folks call the Continental Divide. But Bee does not get her classic Tucson KUAT very well. Despite its strong reception on the car radio in the driveway. Some sniffing around with an unboosted cheap fringe-butnot-ultra Radio Shack 15-1636 FM antenna led to a big surprise. A large number of FM stations appear to now use vertical or circular polarizations. Their apparent aim is to improve nearby auto reception at the cost of distant coverage. For KUAT, flipping the antenna to the vertical dramatically improved the reception in Thatcher. The ultimate solution is antenna height. Which conquers all. At the top of the two mile high mountain in my front yard, I can take a $4 pocket FM receiver and tune it to 93.3. By pointing the whip antenna in one of three directions, I can get KDKB in Phoenix, KKOB in Alburquerque or a WAVELET BOOK RESOURCES C.K. Chui, An Introduction to Wavelets, Academic Press, 1992. C.K. Chui, Wavelets, World Scientific Pub, 1992. C.K. Chui, Wavelets: A Tutorial in Theory & Applications, Academic Press, 1992. C.K. Chui, L. Montefusco & L. Puccio, Wavelets, Theory, Algorithms, & Applications, Academic Press, 1994. J.M. Combes, Wavelets, Spr-Verlag, 1989. I. Daubechies, Ten Lectures on Wavelets, Soc Indus-Appl Math, 1992. G. David, Wavelets & Singular Integrals on Curves & Surfaces, Spr-Verlag, 1992. M. Farge, Wavelets, Fractals & Fourier Transforms, 1993. E. Foufoula-Georgiou, P. Kumar, Wavelets in Geophysics, Academic Press, 1994. Frazier, Wavelets, Mathematics & Applications, CRC Press, 1993. Jawerth, Practical Guide to Wavelets, CRC Press, 1994. G. Kaiser, A Friendly Guide to Wavelets, Birkhauser, 1993. T.H. Koornwinder, Wavelets: An Elementary Treatment of Theory & Application, World Scientific Pub, 1993. W. Light, Advances in Numerical Analysis, V2, OUP, 1992. Y. Meyer, Wavelets: Algorithms & Applications, Soc Indus-Appl Math, 1993. Y. Meyer, Wavelets, Cambridge University Press, 1993. Y. Meyer, Wavelets & Applications, Spr-Verlag, 1992. R.L. Motard & B Joseph, Wavelet Applications in Chemical Engineering, Kluwer Ac, 94. D.E. Newland, An Introduction to Random Vibrations, Spectral & Wavelet Analysis, Halsted Press, 1993. Ruskai, Wavelets & Their Applications, Jones & Bartlett, 1992. L.L. Schumaker & G. Webb, Recent Advances in Wavelet Analysis, Acad. Pr., 1993. G.G. Walter, Wavelets & Other Orthogonal Systems with Applications, CRC Press, 94. G. Wornell, Wavelet-Based Signal Processing with Fractals, P-H, 1994. R.K. Young, Wavelet Theory & Its Applications, Kluwer Ac, 1992. Invicta XL-3600 Kxtg7432 RCR 127 AG-1980 Dslr-A500L MFC-5890CN GR-642tvpf WR 360 SRU 5040 KAC-721 FT920 Maker 90069 2300DL M7500 XLF 200 GX-1001 Banshee-2000 13-RE ZTB220 III DVD P-400 Aspire 5100 NW-E003F MM1402 Control Plus GXV3000 Printer JBL LX44 Avant IN24EP System FAX-LAB 200 ML3471ND-ETS PM-1201 FLS572C HT-CN300H C-180 Motorola T805 Aspire-1620 B7620 UPS 10 RR-QR170 PMP518M BH6R1-1 3D-100 Photosmart 2573 BR 600 AEG-electrolux K19E DF6260-ML 1 RAS18CH1 14PV225 Legacy Kddv7300J-KD-dv7300 ML-1710 WFM-90 Interface CQ-C7303N PD-F100 DVP3005K LX8000SA DV 8200 SDM-P234 KM300 Play NOW Uniden 1260 Series PLC-SW20AR NW-S718F Hero Panasonic G51 DSC-HX5v B Clipper 380 C SCH-I600 KDC-316S C-350 AS150 TU-MHD600 VSX-D409 Hunting 2 AVR-486 ICD-BP150 PS42A410c1 AFE325 32A456c2D VGN-SZ5xn C AVL 109 M6 D6 PRO9500 PM-G720 VGN-NR32m S Control UX-W71CL BO5021K Reference 30 Review GN45-032 AT2635 DI
http://www.ps2netdrivers.net/manual/beaulieu.5008s.multispeed/
crawl-003
refinedweb
6,642
65.62
![endif]--> Arduino <![endif]--> Buy Download Products Arduino AtHeart Certified Learning Getting started Examples Playground Reference Support Forum Advanced Search | Arduino Forum :: Members :: nitrolx Show Posts Pages: [ 1 ] 2 3 1 Using Arduino / Motors, Mechanics, and Power / Re: Cummins Fuel Control on: September 23, 2013, 07:19:25 pm Apologies for bringing this back from the dead, but has there been any progress on this project? 2 Using Arduino / Project Guidance / 2nd Arduino to handle some tasks - Serial communication? on: April 08, 2013, 06:28:02 pm. 3 Using Arduino / Project Guidance / Re: Reflective surface, alternatives to mirrors? on: March 15, 2013, 05:21:10 am old/blank CDs/DVDs?? never tried it but they are designed to reflect a laser when they're read so??? cheap and plentiful and pretty well undamageable? 4 Using Arduino / Project Guidance / Re: Adjustable Duty Cycle PWM signal at low Hz on: March 14, 2013, 07:40:17 pm Quote from: PeterH on March 14, 2013, 07:24:02 pm At that sort of frequency, you could just use the techniques demonstrated in 'blink without delay' to switch the outputs at the desired times. I thought that. . and I think I can work out how to get, say a 10Hz squarewave (working out the ms periods of a 10Hz signal etc) but it would always only be at a 50% duty cycle (on for half the period, off for half the period). I need to work out how to change the duty cycle. . 5 Using Arduino / Project Guidance / Adjustable Duty Cycle PWM signal at low Hz on: March 14, 2013, 07:17:21 pm Hi all, just working on a project and was wondering if anyone knew of a library or had some working code to manually creat a PWM-style output signal but at low frequencies. I need to pulse solenoids to control flow, but the onboard PWM is way too fast for the solenoids to react. I need to create a signal around the 10Hz - 20Hz range with an adjustable duty cycle. Ideally I want to be able to ramp the flow up and down over a time period. . eg start at 25% flow and then after 2 seconds the flow has linearly ramped ot 100%. The frequency needs to be adjustable to suit different style solenoids but would only be a setting it wouldn't need to be dynamic like the duty cycle. I've had a search and seen ideas where the internal timers are changed to slow down the onboard PWM frequency, but this also affects millis() and other timing functions which are in use in the project. Cheers for any help. 6 Using Arduino / Project Guidance / Re: Scoop Lights Based on Throttle Position on: July 30, 2012, 03:37:12 am Quote from: dxw00d on July 30, 2012, 03:02:04 am Quote More than anything, we're hoping it'll have a psychological effect on people so when they look in the rearview mirror Well, I know what I think when I see stuff like that in the mirror. LOL! It certainly would have a 'psychological effect on people' but I don't think it's the one you're looking for. (And generally, anything that needs a glowing light in the hood scoop that changes with rpm to 'give them a hint as to how fast he's accelerating' is going to spend most of its time in the rear view mirror!!) 7 Using Arduino / Project Guidance / Re: Reading frequency on: July 28, 2012, 06:28:47 pm Here is some example code using the above library to calculate 2 different frequencies (and convert to RPM). Using floating point and a fractional frequency. This is just the frequency parts pulled out of a bigger sketch so this is untested stand alone. Code: #include <FreqPeriodCounter.h> // PIN ASSIGNMENTS const byte counter1Pin = 2; const byte counter1Interrupt = 0; const byte counter2Pin = 3; const byte counter2Interrupt = 1; // RPM CALCULATIONS int rpm1; float hz1; int rpm2; float hz2; FreqPeriodCounter counter1(counter1Pin, micros, 0); FreqPeriodCounter counter2(counter2Pin, micros, 0); void setup() { attachInterrupt(counter1Interrupt, counter1ISR, RISING); attachInterrupt(counter2Interrupt, counter2ISR, RISING); } void loop() { if(counter1.ready()) { hz1 = (1000000.0/counter1.period); // period in ms rpm1 = (hz1 * 60); } if(counter2.ready()) { hz2 = (1000000.0/counter2.period); rpm2 = (hz2 * 60); } } void counter1ISR() { counter1.poll(); } void counter2ISR() { counter2.poll(); } 8 Using Arduino / Project Guidance / Re: Reading frequency on: July 28, 2012, 06:03:27 pm I have found this library; quite helpful for projects like this. You can use 2 inputs (using the 2 interrupt pins) with the code implemented either using the interrupts or polling the counter in the loop. Works well, you can have it measure Hz directly from the library (in whole numbers) if you're measuring a relatively high frequency, or using a floating point variable and calculate the frequency from the period of pulses if you need a fractional Hz result (if you need to detect small changes in low frequencies). My project measures the RPM of 2 different shafts, which are relatively low, so I use the fractional option. Uses a bit more memory that way due to the floating point calculation so if you're reading higher frequencies, the built in counter.hertz() function is better. Cheers, Ryan. 9 Using Arduino / Sensors / Re: U-Tube Manometer Level Sensor on: July 27, 2012, 09:21:16 pm Can you replace the tube manometer entirely with an electronic differential pressure meter? That would open up your interfacing options. 10 Using Arduino / Project Guidance / Re: Car rev limiter on: July 27, 2012, 08:26:53 pm)? 11 Using Arduino / Programming Questions / Re: Smoothing RPM data on: July 21, 2012, 06:11:13 pm Quote from: dc42 on July 21, 2012, 09:49:32 am I would do 2 things: 1. Use a Hall sensor instead of a reed switch to detect the magnets. Contact bounce in the reed switch is likely to cause jitter. There may be less need for smoothing if you eliminate this jitter. Hall sensors cost very little these days. 2. One way of smoothing the output is to measure the time for several rotations instead of just one. You could have the ISR record the times of e.g. the last 8 pulses instead of just the last one, like this (warning: untested code!): Code: const int nReadings = 8; volatile unsigned long times[nReadings ]; volatile unsigned char lastReading = 0; void DSIsr() { unsigned long DSnow = micros(); if (DSnow - times[lastReading] > 100) { lastReading = (lastReading + 1) % nReadings ; times[lastReading] = DSnow; } } ... unsigned long refreshcurrentMillis = millis(); if(refreshcurrentMillis - refreshpreviousMillis > refresh) { refreshpreviousMillis = refreshcurrentMillis; noInterrupts(); unsigned int lr = lastReading; unsigned long interval = times[lr] - times[(lr + 1) % nReadings]; interrupts(); unsigned long DSrpm = ((nReadings - 1) * 60000000UL)/interval; lcd.setCursor(0, 1); lcd.print(DSrpm); lcd.print(" "); lcd.print("RPM "); } I've done the calculation in unsigned long instead of float for better speed, but you can use float if you want to display fractional RPM. Thanks for that! Fractional RPM isn't needed, not sure why I used float in my code actually, I think it's code I used from another project that displayed a fractional RPM. The whole length of the event I'm logging will only be 9 seconds (hopefully a bit less) and the shaft will accelerate from 0 RPM to about 7000 in that 9 seconds. I'm looking for the most accurate RPM calculation I can get to analyse the acceleration rate of the shaft over the 9 seconds. The shaft will have 4 magnets at 90 degree intervals, so there will be 4 'pulses' per revolution. Will your method give a less accurate or less 'responsive' result then the original calculations, or will the difference be negligible? 12 Using Arduino / Programming Questions / Smoothing RPM data on: July 21, 2012, 05:25:51 am Hi all, I'm working on a project which logs the RPM of a shaft; shaft has magnets on it and I'm using a reed switch which pulls an input to ground when a magnet is near. The code is using an interrupt and measuring the period to work out RPM. This works fine. However I'd like to include some 'smoothing' or noise reduction in the data. My ISR for the rpm calc is as follows; Code: void DSIsr() { unsigned long DSnow = micros(); unsigned long DSinterval = DSnow - DSlastPulseTime; if (DSinterval > 100) { DSrpm = 60000000.0/(DSinterval * DSpulsesPerRev); DSlastPulseTime = DSnow; } } I then log the result of DSrpm (to SD card eventually but currently just to the Serial output) at an adjustable refresh rate using; Code: unsigned long refreshcurrentMillis = millis(); if(refreshcurrentMillis - refreshpreviousMillis > refresh) { refreshpreviousMillis = refreshcurrentMillis; lcd.setCursor(0, 1); lcd.print(DSrpm); lcd.print(" "); lcd.print("RPM "); // Serial.println(DSrpm); } 'refresh' is 50ms at the moment. I would like a way to 'average' the rpm results, say over 5 or 10 samples, to smooth the data that I'm getting. I tried a similar method I've used to smooth analog inputs; Code: rawvalue = 0; for (int i=0; i< count; i++) rawvalue += analogRead(A1); rawvalue = rawvalue / count; but that doesn't seem to work using an ISR-derived value, as each time the ISR is triggered, DSrpm is re-calculated. Is there anyway I can use a similar idea to 'average' a few samples of DSrpm and smooth the data?? Cheers, Ryan. 13 Using Arduino / Project Guidance / Re: Homebrew 2-stroke ignition? on: July 02, 2012, 06:23:57 am Quote from: cyclegadget on July 01, 2012, 09:46:07 pm To. Nearly every high performance/drag racing style engine runs an MSD crank trigger ignition. 4 magnets located around a trigger wheel on the balancer at 90 degree intervals corresponding to each 4 TDC positions (V8). A pickup fires the ignition each time a magnet flies past. These engines turn 10,000 rpm plus and make thousands of horsepower. The trick I can see here is having the pickup trigger advanced some amount before you actually want the ignition to fire and work a delay into the controller. This allows you time for processing. (I've got no idea how much timing a 2 stroke engine runs but to use my drag engine as an example, we run (depending on gear, fuel, weather and other tune up factors) somewhere around 38 degrees BTDC ignition timing. The pickup is actually adjusted to be somewhere around 40 - 42 degrees. The processing in the ignition controller then fires at 38 (as seen if you check the timing with a timing light). You can then work a 'retard' curve into your controller, referencing RPM or boost/MAP or any other factor you care to use. Remember, the controller can only retard the timing from your base setting. It can't predict into the future to fire before the trigger, it can only trigger after the trigger, so your pickup must be set at the maximum amount of advance you want anywhere in the curve, then retard back from that value in your curve. In my case we pull 1 degree out when it shifts from low to top gear, and can ramp a few degrees out on launch if traction is marginal, or plot an entire curve for each gear based on RPM or time. The maths/interfacing for an Arduino to do this and whether it can actually do the job; I have no idea. But I do know it works with only 1 reference per cylinder TDC event in some pretty high performance applications, so it may well be possible. Have fun with it! 14 Using Arduino / Project Guidance / Re: Automatic engine/generator control on: June 19, 2012, 05:19:50 am Interesting project idea! How are you controlling engine speed of the generator unit? Also, you'll probably find you'll get oil pressure > 5psi just on the starter, especially when the oil is cold. Might need a higher set point, or use an engine RPM signal or the output of the alternator/generator to signal 'engine started' or 'engine running' to the controller. Have fun and I look forward to seeing this project progress! Ryan. 15 Using Arduino / Programming Questions / Re: Read a 2-variable 'MAP' on: February 20, 2012, 05:44:42 am Quote from: PaulS on February 20, 2012, 05:37:46 am Yes. It's trivial, even. Just define a 2D array, called map. The value of interest then is map[A-1][B-1]. Thanks for the quick reply! I'll have to hunt up an example of how to use Arrays. Is it possible to interpolate values between the finite values defined? Probably just for the inputs, the outputs can remain discrete and defined in the 'map'.(array?). so, if input A is between 2 & 3, (rather than exactly 1 or 2), what is the output? Pages: [ 1 ] 2 3 | SMF © 2013, Simple Machines Newsletter ©2014 Arduino
http://forum.arduino.cc/index.php?action=profile;u=64253;sa=showPosts
CC-MAIN-2014-35
refinedweb
2,146
60.14
Douglas Crockford Mentioned 178 Describes the reliable features of JavaScript, covering such topics as syntax, objects, functions, arrays, regular expressions, inheritance, and methods. I ==? The identity ( ===) operator behaves identically to the; I don't fully get what Node.js is all about. Maybe it's because I am mainly a web based business application developer. What is it and what is the use of it? My understanding so far is that: Are my understandings correct? If yes, then what are the benefits of evented I/O, is it just more for the concurrency stuff? Also, is the direction of Node.js to become a framework like, JavaScript based (V8 based) programming model? I use Node.js at work, and find it to be very powerful. Forced to choose one word to describe Node.js, I'd say "interesting" (which is not a purely positive adjective). The community is vibrant and growing. JavaScript, despite its oddities can be a great language to code in. And you will daily rethink your own understanding of "best practice" and the patterns of well-structured code. There's an enormous energy of ideas flowing into Node.js right now, and working in it exposes you to all this thinking - great mental weightlifting. Node.js in production is definitely possible, but far from the "turn-key" deployment seemingly promised by the documentation. With Node.js v0.6.x, "cluster" has been integrated into the platform, providing one of the essential building blocks, but my "production.js" script is still ~150 lines of logic to handle stuff like creating the log directory, recycling dead workers, etc. For a "serious" production service, you also need to be prepared to throttle incoming connections and do all the stuff that Apache does for PHP. To be fair, Ruby on Rails has this exact problem. It is solved via two complementary mechanisms: 1) Putting Ruby on Rails/Node.js behind a dedicated webserver (written in C and tested to hell and back) like Nginx (or Apache / Lighttd). The webserver can efficiently serve static content, access logging, rewrite URLs, terminate SSL, enforce access rules, and manage multiple sub-services. For requests that hit the actual node service, the webserver proxies the request through. 2) Using a framework like Unicorn that will manage the worker processes, recycle them periodically, etc. I've yet to find a Node.js serving framework that seems fully baked; it may exist, but I haven't found it yet and still use ~150 lines in my hand-rolled "production.js". Reading frameworks like Express makes it seem like the standard practice is to just serve everything through one jack-of-all-trades Node.js service ... "app.use(express.static(__dirname + '/public'))". For lower-load services and development, that's probably fine. But as soon as you try to put big time load on your service and have it run 24/7, you'll quickly discover the motivations that push big sites to have well baked, hardened C-code like Nginx fronting their site and handling all of the static content requests (...until you set up a CDN, like Amazon CloudFront)). For a somewhat humorous and unabashedly negative take on this, see this guy. Node.js is also finding more and more non-service uses. Even if you are using something else to serve web content, you might still use Node.js as a build tool, using npm modules to organize your code, Browserify to stitch it into a single asset, and uglify-js to minify it for deployment. For dealing with the web, JavaScript is a perfect impedance match and frequently that makes it the easiest route of attack. For example, if you want to grovel through a bunch of JSON response payloads, you should use my underscore-CLI module, the utility-belt of structured data. For another perspective on JavaScript and Node.js, check out From Java to Node.js, a blog post on a Java developer's impressions and experiences learning Node.js. Modules When considering node, keep in mind that your choice of JavaScript libraries will DEFINE your experience. Most people use at least two, an asynchronous pattern helper (Step, Futures, Async), and a JavaScript sugar module (Underscore.js). Helper / JavaScript Sugar: Asynchronous Pattern Modules: Or to read all about the asynchronous libraries, see this panel-interview with the authors. Web Framework: Testing: Also, check out the official list of recommended Node.js modules. However, GitHub's Node Modules Wiki is much more complete and a good resource. To understand Node, it's helpful to consider a few of the key design choices: Node.js is EVENT BASED and ASYNCHRONOUS / NON-BLOCKING. Events, like an incoming HTTP connection will fire off a JavaScript function that does a little bit of work and kicks off other asynchronous tasks like connecting to a database or pulling content from another server. Once these tasks have been kicked off, the event function finishes and Node.js goes back to sleep. As soon as something else happens, like the database connection being established or the external server responding with content, the callback functions fire, and more JavaScript code executes, potentially kicking off even more asynchronous tasks (like a database query). In this way, Node.js will happily interleave activities for multiple parallel workflows, running whatever activities are unblocked at any point in time. This is why Node.js does such a great job managing thousands of simultaneous connections. Why not just use one process/thread per connection like everyone else? In Node.js, a new connection is just a very small heap allocation. Spinning up a new process takes significantly more memory, a megabyte on some platforms. But the real cost is the overhead associated with context-switching. When you have 10^6 kernel threads, the kernel has to do a lot of work figuring out who should execute next. A bunch of work has gone into building an O(1) scheduler for Linux, but in the end, it's just way way more efficient to have a single event-driven process than 10^6 processes competing for CPU time. Also, under overload conditions, the multi-process model behaves very poorly, starving critical administration and management services, especially SSHD (meaning you can't even log into the box to figure out how screwed it really is). Node.js is SINGLE THREADED and LOCK FREE. Node.js, as a very deliberate design choice only has a single thread per process. Because of this, it's fundamentally impossible for multiple threads to access data simultaneously. Thus, no locks are needed. Threads are hard. Really really hard. If you don't believe that, you haven't done enough threaded programming. Getting locking right is hard and results in bugs that are really hard to track down. Eliminating locks and multi-threading makes one of the nastiest classes of bugs just go away. This might be the single biggest advantage of node. But how do I take advantage of my 16 core box? Two ways: Node.js lets you do some really powerful things without breaking a sweat. Suppose you have a Node.js program that does a variety of tasks, listens on a TCP port for commands, encodes some images, whatever. With five lines of code, you can add in an HTTP based web management portal that shows the current status of active tasks. This is EASY to do: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(myJavascriptObject.getSomeStatusInfo()); }).listen(1337, "127.0.0.1"); Now you can hit a URL and check the status of your running process. Add a few buttons, and you have a "management portal". If you have a running Perl / Python / Ruby script, just "throwing in a management portal" isn't exactly simple. But isn't JavaScript slow / bad / evil / spawn-of-the-devil? JavaScript has some weird oddities, but with "the good parts" there's a very powerful language there, and in any case, JavaScript is THE language on the client (browser). JavaScript is here to stay; other languages are targeting it as an IL, and world class talent is competing to produce the most advanced JavaScript engines. Because of JavaScript's role in the browser, an enormous amount of engineering effort is being thrown at making JavaScript blazing fast. V8 is the latest and greatest javascript engine, at least for this month. It blows away the other scripting languages in both efficiency AND stability (looking at you, Ruby). And it's only going to get better with huge teams working on the problem at Microsoft, Google, and Mozilla, competing to build the best JavaScript engine (It's no longer a JavaScript "interpreter" as all the modern engines do tons of JIT compiling under the hood with interpretation only as a fallback for execute-once code). Yeah, we all wish we could fix a few of the odder JavaScript language choices, but it's really not that bad. And the language is so darn flexible that you really aren't coding JavaScript, you are coding Step or jQuery -- more than any other language, in JavaScript, the libraries define the experience. To build web applications, you pretty much have to know JavaScript anyway, so coding with it on the server has a sort of skill-set synergy. It has made me not dread writing client code. Besides, if you REALLY hate JavaScript, you can use syntactic sugar like CoffeeScript. Or anything else that creates JavaScript code, like Google Web Toolkit (GWT). Speaking of JavaScript, what's a "closure"? - Pretty much a fancy way of saying that you retain lexically scoped variables across call chains. ;) Like this: var myData = "foo"; database.connect( 'user:pass', function myCallback( result ) { database.query("SELECT * from Foo where id = " + myData); } ); // Note that doSomethingElse() executes _BEFORE_ "database.query" which is inside a callback doSomethingElse(); See how you can just use "myData" without doing anything awkward like stashing it into an object? And unlike in Java, the "myData" variable doesn't have to be read-only. This powerful language feature makes asynchronous-programming much less verbose and less painful. Writing asynchronous code is always going to be more complex than writing a simple single-threaded script, but with Node.js, it's not that much harder and you get a lot of benefits in addition to the efficiency and scalability to thousands of concurrent connections... Is there a set of things that every JavaScript programmer should know to be able to say "I know JavaScript"? Understanding the stuff written in Crockford's Javascript: The Good Parts is a pretty good assumption that a person is a decent JS programmer. You can pretty much know how to use a good library like JQuery and still not know the hidden parts of Javascript. Another note is Debugging tools on various browsers. A JS programmer should know how to debug his code in different browsers. Oh! And knowing JSLint will totally hurt your feelings!! What "Hidden Features" of JavaScript do you think every programmer should know? After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript. Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is. I could quote most of Douglas Crockford's excellent book JavaScript: The Good Parts. But I'll take just one for you, always use === and !== instead of == and != alert('' == '0'); //false alert(0 == ''); // true alert(0 =='0'); // true == is not transitive. If you use === it would give false for all of these statements as expected. In JavaScript, every object is at the same time an instance and a class. To do inheritance, you can use any object instance as a prototype. In Python, C++, etc.. there are classes, and instances, as separate concepts. In order to do inheritance, you have to use the base class to create a new class, which can then be used to produce derived instances. Why did JavaScript go in this direction (prototype-based object orientation)? what are the advantages (and disadvantages) of prototype-based OO with respect to traditional, class-based OO? You should check out a great book on JavaScript by Douglas Crockford. It provides a very good explanation of some of the design decisions taken by JavaScript creators. One of the important design aspect of JavaScript is its prototypal inheritance system. Objects are first class citizens in JavaScript, so much that regular functions are also implemented as objects ('Function' object to be precise). In my opinion when it was originally designed to run inside a browser, it was meant to be used to create lots of singleton objects. In browser DOM, you find that window, document etc all singleton objects. Also JavaScript is loosely typed dynamic language (as opposed to say Python which is strongly typed, dynamic language), as a result a concept of object extension was implemented through the use of 'prototype' property. So I think there are some pros for protytype-based OO as implemented in JavaScript: Here are some of the cons of prototypal OO: Is it possible to call the base method from a prototype method in JavaScript if it's been overridden? MyClass = function(name){ this.name = name; this.do = function() { //do somthing } }; MyClass.prototype.do = function() { if (this.name === 'something') { //do something new } else { //CALL BASE METHOD } }; I'm afraid your example does not work the way you think. This part: this.do = function(){ /*do something*/ }; overwrites the definition of MyClass.prototype.do = function(){ /*do something else*/ }; Since the newly created object already has a "do" property, it does not look up the prototypal chain. The classical form of inheritance in Javascript is awkard, and hard to grasp. I would suggest using Douglas Crockfords simple inheritance pattern instead. Like this: function my_class(name) { return { name: name, do: function () { /* do something */ } }; } function my_child(name) { var me = my_class(name); var base_do = me.do; me.do = function () { if (this.name === 'something'){ //do something new } else { base_do.call(me); } } return me; } var o = my_child("something"); o.do(); // does something new var u = my_child("something else"); u.do(); // uses base function In my opinion a much clearer way of handling objects, constructors and inheritance in javascript. You can read more in Crockfords Javascript: The good parts. At the moment, the only fully supported language, and the de-facto standard for DOM tree manipulation in the browser is JavaScript. It looks like it has deep design issues that make it a minefield of bugs and security holes for the novice. Do you know of any existent or planned initiative to introduce a better (redesigned) language of any kind (not only javascript) for DOM tree manipulation and HTTP requests in next generation browsers? If yes, what is the roadmap for its integration into, say, Firefox, and if no, for what reasons (apart of interoperability) should be JavaScript the only supported language on the browser platform? I already used jQuery and I also read "javascript: the good parts". Indeed the suggestions are good, but what I am not able to understand is: why only javascript? On the server-side (your-favourite-os platform), we can manipulate a DOM tree with every language, even fortran. Why does the client side (the browser platform) support only javascript? If you're thinking that JavaScript has deep issues, I recommend Doug Crockford's book, JavaScript: The Good Parts. (Or Google for "Crockford JavaScript" to find several video presentations he's done.) Crockford sketches out a safe subset and set of practices, and specifically lists some parts of the language to avoid. I'm unaware of plans to replace JavaScript as the de facto means of manipulating the DOM. So best learn to use it safely and well. Is it a good idea to learn JavaScript before learning a JavaScript framework library such as jQuery, Prototype, etc.? Sometimes I find myself struggling because I feel I don't know JavaScript as well as I should. There are really two seperate aspects to JavaScript within the Browser. First, the JavaScript Language, and second the HTML DOM that allows you to manipulate the page using the JavaScript Language. That said, then YES you should spend time learning the JavaScript Language. I recommend picking up a copy of "JavaScript: The Good Parts" by Douglas Crockford. Now as to the second part, the HTML DOM. You really don't need to focus too much on learning the ins and outs of the HTML DOM if you are going to use a framework like jQuery. Just do things the "jQuery way" and then pick up as much HTML DOM as is necessary along the way. I'm new to JavaScript and just discovered toFixed() and toPrecision() to round numbers. However, I can't figure out what the difference between the two is. What is the difference between number.toFixed() and number.toPrecision()? I believe that the former gives you a fixed number of decimal places, whereas the latter gives you a fixed number of significant digits. Math.PI.toFixed(2); // "3.14" Math.PI.toPrecision(2); // "3.1" Furthermore, toPrecision will yield scientific notation if there are more integer digits in the number than the specified precision. (Math.PI * 10).toPrecision(2); // "31" (Math.PI * 100).toPrecision(2); // "3.1e+2" EDIT: Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford. I am going offline for a few days, and would like to bring the JavaScript documentation with me on my laptop :) Does anyone know of a place where I can get downloadable reference documentation for JavaScript, preferably for Firefox? I have checked the Mozilla site, but have only been able to find an online version. How about finding a copy of both (or either one of) JavaScript: The Definitive Guide by David Flanagan and JavaScript: The Good Parts ? This is a question for general discussion. Are there any good, comprehensive resources for useful JavaScript design patterns. I am trying to avoid references that attempt to coerce JavaScript into, say, Java by imposing patterns more suited to another language. Let's let JS be JS and shape our patterns around the strengths. Please any discussion would be valued by more than just me, I suspect. Peter Michaux has some decent articles Also see Crockford's articles (and his book) A new book on the subject by Stoyan Stefanov: Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries JavaScript is a lightweight and powerful language, but it's often misunderstood and hard to learn (especially about its object oriented programming). What are the good materials (blogs, screencasts and books) to learn JavaScript OOP? The topics can be anything, but let's not include browsers, AJAX and libraries for now. Also how did you learn the functional programming, closure, object, inheritance and design patterns in JavaScript? Personally I would like to see more code examples because some of the books I mentioned above keep the example minimal. (EDIT: As this post is now community effort, please help maintain and develop the following list of resources!) Books Videos On Stack Overflow Others You can see great code examples of Javascript in mainstream libraries like jQuery. I've learned a lot just reading it's source code. There's nothing better than reading sources that are working in millions of websites and are concerned about best practices. In the same vein as The Good Parts, Douglas Crockford's website has many good articles on JavaScript and OOP, such as Prototypal Inheritance, Classical Inheritance in JavaScript, etc. My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue. But I'm finding Javascript/jQuery surprisingly difficult to get right. Very frustrating. Why? It seems to violate a number of traditional programming principles (e.g. variable scope) Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs): $("a").click(function(event) { event.preventDefault(); $('<div/>') .append('default ' + event.type + ' prevented') .appendTo('#log'); }); What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API? There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?) Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?) Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility. It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials. What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me? Are there any resources that explain Javascript's quirks/gotchas? Thanks! Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C. Link provided to Amazon; I snagged mine from O'Reilly. Have you ever restricted yourself to using a subset of language features, and more importantly, why? I'm curious to find out who choose to use only certain language features and avoid others in order to win big in areas such as, but not limited to, memory usage, execution speed or plain old readability and maintainability. And by doing so did it yield the expected results or did it perhaps just hamper some other aspect of producing software. Are there any cautionary tales or wild success stories out there worth sharing regarding this subject? Douglas Crockford's book Javascript: The Good Parts is a prime example of this. He lists 'features' in javascript that should be avoided and provides alternatives that use the 'good parts' of the language. A few of the bad parts are: eval slower, harder to read, dangerously insecure == confusing and ambiguous with differently typed operands with unpredictable results A while ago, when I was learning Javascript, I studied Javascript: the good parts, and I particularly enjoyed the chapters on the bad and the ugly parts. Of course, I did not agree with everything, as summing up the design defects of a programming language is to a certain extent subjective - although, for instance, I guess everyone would agree that the keyword with was a mistake in Javascript. Nevertheless, I find it useful to read such reviews: even if one does not agree, there is a lot to learn. Is there a blog entry or some book describing design mistakes for Python? For instance I guess some people would count the lack of tail call optimization a mistake; there may be other issues (or non-issues) which are worth learning about. You asked for a link or other source, but there really isn't one. The information is spread over many different places. What really constitutes a design mistake, and do you count just syntactic and semantic issues in the language definition, or do you include pragmatic things like platform and standard library issues and specific implementation issues? You could say that Python's dynamism is a design mistake from a performance perspective, because it makes it hard to make a straightforward efficient implementation, and it makes it hard (I didn't say completely impossible) to make an IDE with code completion, refactoring, and other nice things. At the same time, you could argue for the pros of dynamic languages. Maybe one approach to start thinking about this is to look at the language changes from Python 2.x to 3.x. Some people would of course argue that map() and filter() return iterators instead of lists, range() behaves like xrange() used to, and dict methods like dict.keys() return views instead of lists. Then there are some changes related to integers, and one of the big changes is binary/string data handling. It's now text and data, and text is always Unicode. There are several syntactic changes, but they are more about consistency than revamping the whole language. From this perspective, it appears that Python has been pretty well designed on the language (syntax and sematics) level since at least 2.x. You can always argue about indentation-based block syntax, but we all know that doesn't lead anywhere... ;-) Another approach is to look at what alternative Python implementations are trying to address. Most of them address performance in some way, some address platform issues, and some add or make changes to the language itself to more efficiently solve certain kinds of tasks. Unladen swallow wants to make Python significantly faster by optimizing the runtime byte-compilation and execution stages. Stackless adds functionality for efficient, heavily threaded applications by adding constructs like microthreads and tasklets, channels to allow bidirectional tasklet communication, scheduling to run tasklets cooperatively or preemptively, and serialisation to suspend and resume tasklet execution. Jython allows using Python on the Java platform and IronPython on the .Net platform. Cython is a Python dialect which allows calling C functions and declaring C types, allowing the compiler to generate efficient C code from Cython code. Shed Skin brings implicit static typing into Python and generates C++ for standalone programs or extension modules. PyPy implements Python in a subset of Python, and changes some implementation details like adding garbage collection instead of reference counting. The purpose is to allow Python language and implementation development to become more efficient due to the higher-level language. Py V8 bridges Python and JavaScript through the V8 JavaScript engine – you could say it's solving a platform issue. Psyco is a special kind of JIT that dynamically generates special versions of the running code for the data that is currently being handled, which can give speedups for your Python code without having to write optimised C modules. Of these, something can be said about the current state of Python by looking at PEP-3146 which outlines how Unladen Swallow would be merged into CPython. This PEP is accepted and is thus the Python developers' judgement of what is the most feasible direction to take at the moment. Note it addresses performance, not the language per se. So really I would say that Python's main design problems are in the performance domain – but these are basically the same challenges that any dynamic language has to face, and the Python family of languages and implementations are trying to address the issues. As for outright design mistakes like the ones listed in Javascript: the good parts, I think the meaning of "mistake" needs to be more explicitly defined, but you may want to check out the following for thoughts and opinions: At work, we place braces on the next line, but at home, I do the opposite. Which one do you prefer? (K&R vs OTBS) function something() { // ... } function something() { // ... } A lot of JavaScript libraries seem to use the OTBS (one true brace style). I'd like to follow them for consistence among other JavaScript projects, but doesn't K&R style look more readable? Note: We know the problem with return and braces in JavaScript, that will always be an exception. However, that is only a single case. Douglas Crockford gives a reason for choosing the K&R style1: I always use the K&R style, putting the {at the end of a line instead of the front, because it avoids a horrible design blunder in JavaScript's returnstatement. The blunder he is referring to is how JavaScript handles the return statement differently in the following two scenarios: return { 'status': 'ok' }; ... and: return { 'status': 'ok' }; The first one will return an object with a status property, while the latter will return undefined because of semicolon insertion. 1 Douglas Crockford: JavaScript: The Good Parts: Style (page 96) - ISBN: 978-0596517748. What it a good starting point for learning javascript? I'm a well versed C and Java programmer and I have some decent experience in C++, so I'm looking for a few suggestions: alert()'s? Thanks I think that there are a lot of good answers here with a lot of good suggestions, however, I also disagree with most of the answers that say "start learning with jQuery." I'm passionately against learning a framework for a language before learning the language in which the framework is implemented. You're automatically creating a level of abstraction for yourself. Knowing the language prior to learning jQuery or any other framework will help enhance your ability to understand what the framework is doing, how to write better code, and how to implement a feature into the framework that you wish was there but isn't. With that said, here's a set of resources that I have found to be extremely helpful in learning JavaScript (some of them have already been mentioned): Websites Books Videos Frameworks IDEs Yes, there are more websites, books, and videos that can help you get started, but for someone that has a programming background, I can't imagine that picking up JavaScript would be utterly difficult. Additionally, there are other frameworks available, but jQuery and Prototype are the ones with which I'm most familiar and have found them to be really useful.. What's the best and most efficient book to learn JavaScript? I think I've read them all. Here's the dark sheep. This one came out of left field. I was surprised at how good it is. JavaScript: The Missing Manual The other books are great. But for actually learning the language, I think this one wins hands down. JavaScript: The Good Parts Learning Javascript: after the basics, every Javascript developer must read this: Douglas Crockford: JavaScript: The Good Parts ppk on JavaScript was really great. His website is also filled with tons of useful information including lots on browser incompatibilities. I've been reading Douglas Crockford's JavaScript: The Good Parts, and I came across this weird example that doesn't make sense to me: '' == '0' // false 0 == '' // true 0 == '0' // true false == undefined // false false == null // false null == undefined // true The author also goes on to mention "to never use == and !=. Instead, always use === and !==". However, he doesn't explain why the above behavior is exhibited? So my question is, why are the above results as they are? Isn't transitivity considered in JavaScript? '' == ? Having trouble understanding why JSLint is surprised by my use of this in the following code: function testConstr (x) { 'use strict'; this.joker = "Whyyy sooo seriousss?"; this.x = x; } For both property assignments, JSLint says: Unexpected 'this'. How do I correct my code? So in other words, JSLint doesn't automatically expect me to use a constructor pattern? You know, I think you're right. Your question bugged me, and I signed up for Crockford's JSLint discussion group and asked. He replied, but ignored the solution I'm going to present, below, which I think means that it's okay, the same way JSLint doesn't complain if something passes muster. (I'm still waiting for an updated Good Parts, though.) That caveat aside, here's what I'd suggest doing for OO JavaScript that passes Beta JSLint (as of today, anyhow). I'm going to rewrite an example from MDN's page, "Introduction to Object Oriented Programming," which itself uses this liberally. this Here's the original, unlinted MDN example from the section linked, above:" That follows the conventions we know and love. this It's pretty easy to figure out how to make "constructors" that don't follow that pattern, but we lose use of prototype, if I'm not missing something, and have to include all of the object's methods in our constructor that we want all of our Peeps to share. /*jslint white:true, devel:true */ var Peep = function(firstName) { "use strict"; var peep = {}; peep.firstName = firstName; peep.innerSayHello = function() { console.log("Hello, I'm " + peep.firstName + "."); }; return peep; }; var peep1 = new Peep("Bob"); var peep2 = new Peep("Doug"); peep1.innerSayHello(); peep2.innerSayHello(); So there's a lintable alternative. That does, other than the return peep; and the inner definition of methods, make JavaScript act like many OO-first languages you might encounter. It's not wrong, at least. Not having access to prototype isn't horrible; it's really bad news to change prototype somewhere that's not right beside the constructor, as your code would go to spaghetti. "Some Persons have sayGoodbye() and some don't, depending on if we'd amended the prototype at the point of their construction." That's awful. So this alternative convention has its advantages. You can still, of course, add functions to a single instantiation of Peep later, but I'm not sure how you'd access firstName without using this, so perhaps he wants us to stop munging objects after construction. person1.sayGoodbye = function (other) { console.log("Goodbye, " + other + "."); }; (I mean, we could also still monkey-patch Peep to change it mid-process, but that's horrible, stupid programming. Usually.) this) And inheritance is easy enough, I think. var PeepWithGoodbye = function (firstName) { "use strict"; var peepWithGoodbye = new Peep(firstName); peepWithGoodbye.innerSayGoodbye = function (otherPeep) { if (undefined === otherPeep) { otherPeep = { firstName: "you" }; } console.log("This is " + firstName + " saying goodbye to " + otherPeep.firstName + "."); }; return peepWithGoodbye; }; var pwg1 = new PeepWithGoodbye("Fred"); pwg1.innerSayHello(); // Hello, I'm Fred. pwg1.innerSayGoodbye(peep1); // This is Fred saying goodbye to Bob. pwg1.innerSayGoodbye(); // This is Fred saying goodbye to you. EDIT: See also this answer where the asker later found Crockford's suggested means of creating OO javascript. I'm trying to convince that guy to delete that Q&A and move the A here. If he doesn't, I'll probably add his stuff and community wiki it here. I'm a self learner in javascript and I'm currently following the lessons in the book named "Beginning javascript 3rd edition" by Paul Wilton. So far I've advanced myself towards chapter 4: Javascript - An object based language, and I did follow and solve the exercises provided inside the book. I tried to write a calculator myself, and by modifying and changing the code, every time I learn something new to enhance it. How can I become good in javascript coding? Is there any special approach? Is there any concept or things I should learn first? What kind of study/career path should I follow for javascript? Anything I should be aware of? I really have the courage to continue learning javascript, I just need some guidance. I don't mind any expert opinion given, or pointing out any mistakes regarding this question, as I know that through my mistakes, I always learn something. I think that Object-Oriented JavaScript by Stoyan Stefanov is an amazing book, but that could just be me. var myJSON = { "list1" : [ "1", "2" ], "list2" : [ "a", "b" ], "list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ], "not_a_list" : "11" }; How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with: var myJSON = {}; First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object". With that pedantry out of the way, I think that you're asking how to set object and array properties. // make an empty object var myObject = {}; // set the "list1" property to an array of strings myObject.list1 = ['1', '2']; // you can also access properties by string myObject['list2'] = []; // accessing arrays is the same, but the keys are numbers myObject.list2[0] = 'a'; myObject['list2'][1] = 'b'; myObject.list3 = []; // instead of placing properties at specific indices, you // can push them on to the end myObject.list3.push({}); // or unshift them on to the beginning myObject.list3.unshift({}); myObject.list3[0]['key1'] = 'value1'; myObject.list3[1]['key2'] = 'value2'; myObject.not_a_list = '11'; That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts. The following code illustrates an object literal being assigned, but with no semicolon afterwards: var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); This appears to be legal, and doesn't issue a warning (at least in FireFox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it. Javascript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur. var foo = 'bar' // Valid, foo now contains 'bar' var bas = { prop: 'yay!' } // Valid, bas now contains object with property 'prop' containing 'yay!' var zeb = switch (zeb) { ... // Invalid, because the lines following 'var zeb =' aren't an assignable value Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object: return { prop: 'yay!' } // The object literal gets returned as expected and all is well return { prop: 'nay!' } // Oops! return by itself is a perfectly valid statement, so a semicolon // is inserted and undefined is unexpectedly returned, rather than the object // literal. Note that no error occurred. Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style. I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "Javascript: The Good Parts". I highly recommend it. I am developing my first ASP.NET MVC application and I beleive that Script# can help me a lot. But it cannot find the resource necessary to support my development. I could not find The codeplex site; There is only one manual, which is very good, but it is not enough; I could find very few tutorials; I know that Script# was used to develop ASP.NET MVC scripts and that the source of MVC distributes the library. But it seems that it is used only internally in Microsoft. Where can I find other resources??? Do you really think that Script# will be continued and new versions will be deployed and it should be used by third-party projetcs ??? Thanks in advance Don't be afraid of Javascript, it's a beautiful and powerful language. And with frameworks like jQuery, Prototype and Dojo, DOM manipulation and AJAX are greatly simplified and cross-browser issues are mostly history. About Script#, I agree with this answer by mcintyre321. Last release over a year ago + closed source = no go for me. UPDATE Jan/2010: there have been new Script# releases since the original writing of this answer. It's still closed-source but the author mentions open sourcing it after 1.0 UPDATE May 2011: Script# is now open source. over the last couple of years I've seen jquery grow leaps and bounds. And every time I look at some jquery code I feel there is something I am missing which I need to learn. I've given their documentation a try, and it seems to be ok for basic stuff. Can you guys suggest a good jquery book that might help? I'm looking for something that doesnt go much in depth into the theory part of jquery but actually does and shows examples of how to do all the cool stuff. Back in the days when I was in school, I never cared for JS, CSS, HTML ...but now that after 3 years after school I see myself doing a lot of server side web development. I want to learn these technologies. Learn the language first: Javascript The Definitive Guide, 5th Edition Learn jQuery: jQuery in Action I agree with Mark Hurd below. Learn Javascript first. The first book that gave me "aha- this is amazing" is DOM Scripting: Web Design with JavaScript and the Document Object Model Once you get the basics of that, what jQuery does will come more naturally to you and it will seem easy. and his book ppk on JavaScript These books are all (co) authored by John Resig who also wrote jQuery itself. For JS in general, I've also heard very good things about this: JavaScript: The Good Parts by Douglas Crockford who works for Yahoo!. Crockford and Resig both have free and comprehensive videos at the YUI theater. These three are good for a broad overview of general JS: I have been programming in PHP and C# for a long time, but I have done very little Javascript. For server side programming I use MVC, which is very nice and my code is neatly organized. Now, for Javascript, when I write code, I usually screw things up. It becomes something like spaghetti code. I don't know how to organize my code. Can anyone please help me with any resource, book, or anything which might help with writing neat and organized Javascript code? Thanks in advance. JavaScript: The Good Parts Plus any Crockford videos from YUI Theater. You mention that you have been programming in PHP and C# for a long time. Take your code organization experience and apply it to your javascript. Couple of frameworks Google's Closure tools - If Google uses it to organize Gmail and Google Docs, then it should work for most large applications. Also, Yahoo! YUI is good too - And backbone.js (not as "big" as Google or Yahoo) - Decent Book For me, writing javascript unit test helps me stay organized - Test-Driven JavaScript Development I think the following code will make the question clear. // My class var Class = function() { console.log("Constructor"); }; Class.prototype = { method: function() { console.log("Method");} } // Creating an instance with new var object1 = new Class(); object1.method(); console.log("New returned", object1); // How to write a factory which can't use the new keyword? function factory(clazz) { // Assume this function can't see "Class", but only sees its parameter "clazz". return clazz.call(); // Calls the constructor, but no new object is created return clazz.new(); // Doesn't work because there is new() method }; var object2 = factory(Class); object2.method(); console.log("Factory returned", object2); Because JavaScript doesn't have classes, let me reword your question: How to create a new object based on an existing object without using the new keyword? Here is a method that doesn't use "new". It's not strictly a "new instance of" but it's the only way I could think of that doesn't use "new" (and doesn't use any ECMAScript 5 features). //a very basic version that doesn't use 'new' function factory(clazz) { var o = {}; for (var prop in clazz) { o[prop] = clazz[prop]; } return o; }; //test var clazz = { prop1: "hello clazz" }; var testObj1 = factory(clazz); console.log(testObj1.prop1); //"hello clazz" You could get fancy and set the prototype, but then you get into cross-browser issues and I'm trying to keep this simple. Also you may want to use "hasOwnProperty" to filter which properties you add to the new object. There are other ways that use "new" but sort of hide it. Here is one that borrows from the Object.create function in JavaScript: The Good Parts by Douglas Crockford: //Another version the does use 'new' but in a limited sense function factory(clazz) { var F = function() {}; F.prototype = clazz; return new F(); }; //Test var orig = { prop1: "hello orig" }; var testObj2 = factory(orig); console.log(testObj2.prop1); //"hello orig" EcmaScript 5 has the Object.create method which will do this much better but is only supported in newer browsers (e.g., IE9, FF4), but you can use a polyfill (something that fills in the cracks), such as ES5 Shim, to get an implementation for older browsers. (See John Resig's article on new ES5 features including Object.create). In ES5 you can do it like this: //using Object.create - doesn't use "new" var baseObj = { prop1: "hello base" }; var testObj3 = Object.create(baseObj); console.log(testObj3.prop1); I hope that helps Rails is a very great backend framework keeping everything clean and structured. I guess that you all have thought about doing the same for the frontend. Do you use one of thes MVC javascript frameworks for the frontend with Rails? In case you do, do you feel satisfied with it? How did you code before and how has it changed? Isn't Sproutcore more suitable for Rails cause it uses js+css+html which Rails also does. In Cappuccino you don't use either of these. Share your thoughts and experience cause I'm all green to this field and don't know which one I should use with Rails. I just know I better have a MVC framework on the frontend to get DRY-structure and best practices. When looking at MVC frameworks at work, we considered SproutCore and Cappuccino. They both draw an enormous amount of inspiration from Apple's Cocoa framework and Objective C. We chose to use SproutCore because: We didn't choose Cappuccino because: (Keep in mind, I don't have a great deal of experience in Cappuccino and Objective J, so if I make broad and naïve claims, tell me!) You need to look more at what you want as a frontend framework rather than what "works best" with Rails. Both frameworks are good. We chose SproutCore because it fit our needs that we had for our application more, and fit our ideology. From experience from wading through SproutCore's source, I can say that it's fairly independent of the server implementation that you're using. We use Prosody, a BOSH server written in Lua. You want to use Rails. SproutCore offers this out of the box: As for your DRY requirement- that's all up to you! You can leverage the framework to make your code independent and DRY, or have tight dependencies and repeat. Either framework is good, it just depends on your needs. Don't be nervous- dive in and get to know the communities and what's going on in each of them! We don't bite... too much. I'm reading Douglas Crockfords Javascript: The Good Parts, I just finished the regular expressions chapter. In this chapter he calls JavaScript's \b, positive lookahead (?=) and negative lookahead (?!) "not a good part" He explains the reason for \b being not good (it uses \w for word boundary finding, and \w fails for any language that uses unicode characters), and that looks like a very good reason to me. Unfortunately, the reason for positive and negative lookahead being not good is left out, and I cannot come up with one. Mastering Regular Expressions showed me the power that comes with lookahead (and of course explains the issues it brings with it), but I can't really think of anything that would qualify it as "not a good part". Can anyone explain why JavaScript (positive|negative) lookahead or (positive|negative) lookahead in general should be considered "not good"? It seems I'm not the only one with this question: one and two. Maybe it's because of Internet Explorer's perpetually buggy implementation of lookaheads. For anyone authoring a book about JavaScript, any feature that doesn't work in IE might as well not exist. I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this: var level = 1; var hex = level.toString(16); So I run this in my browser's console to see what I get.... var level = 1; level.toString(16); Hey, it returns " 1"... Fabuloso! Wunderbar! Then to be cheeky, I try this to see what I get... 1.toString(16); And I get SyntaxError: Unexpected token ILLEGAL What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome. Related: Stack Overflow question Why don't number literals have access to Number methods?. It's just a language grammar limitation. Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens: 1. toString ( ) And that's an illegal sequence of tokens. It's object method, instead of object . method. In the working versions in @Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing: 1.0.toString() or 1..toString() since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal. I am curious as what else the new keyword does in the background apart from changing what the this scope refers too. For example if we compare using the new keyword to make a function set properties and methods on an object to just making a function return a new object, is there anything extra that the new object does? And which is preferred if I don't wish to create multiple objects from the function constructor var foo2 = function () { var temp = "test"; return { getLol: function () { return temp; }, setLol: function(value) { temp = value; } }; }(); var foo = new function () { var temp = "test"; this.getLol = function () { return temp; } this.setLol = function(value) { temp = value; } }(); The firebug profiler tells me using the new keyword is slightly faster (2ms instead of 3ms), on large objects is new still significantly faster? [Edit] Another matter is on really large object constructors is having a return at the bottom of the function (It will have a large amount of local functions) or having a few this.bar = ... at the top of the function more readable? What is considered a good convention? var MAIN = newfunction() { this.bar = ... // Lots of code }(); var MAIN2 = function() { // Lots of code return { bar: ... } }(); Quoting Douglas Crockford from the Good Parts book (page 47), to answer the title of this question: If the newoperator were a method instead of an operator, it could be implemented like this: Function.method('new', function () { // Create a new object that inherits from the // constructor's prototype. var that = Object.create(this.prototype); // Invoke the constructor, binding -this- to // the new object. var other = this.apply(that, arguments); // If its return value isn't an object, // substitute the new object. return (typeof other === 'object' && other) || that; }); The Function.method method is implemented as follows. This adds an instance method to a class (Source): Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; Further reading: Object.create() Function.apply() From someone with few experience in JS, what do you recommend for learning Node.js? I read a lot in the forum about event driven, non-blocking , async, callbacks, etc but I don't know what's that! Where can I learn the basics in order to understand all that terms and in the future, node.js? Thanks! «Javascript: The Good Parts» is one of the best books ever for learning the ins and outs of the language and not just DOM stuff. I am a .NET webdev using ASP.NET, C# etc... I "learned" javascript in college 5+ years ago and can do basic jobs with it. But I wonder if it is useful to become proficient in it. Why should I learn Javascript? Is it more advantageous then learning JQuery or a different library? Yes, absolutely you should learn JavaScript if you are doing web development. I highly recommend JavaScript: The Good Parts, by Doug Crockford. And, JQuery is a great framework to use (this site uses it) -- it kind of depends on what you are trying to do -- YUI and ExtJS are also very nice. I recommend Jeremy Keith's books: DOM Scripting and Bulletproof Ajax. After you become more fluent in JS I would recommend a JS library(I use jQuery, but that is not important). JS is important to learn. You cannot use a framework without the proper understanding of how it works. That is doing things backwards. I am trying to do this, I'm a full time front-end dev and am aware that I am yet to achieve this. When I am referring to OOP skills I am referring to understanding and being familiar with concepts like inheritance, polymorphism, encapsulation, abstraction. I am aware that it may be more likely to achieve what I'm after by focusing on another language in my spare time. This is the plan, but I'd be really intrigued to hear if anybody has managed to achieve this purely through JavaScript and how you did it. It'd be even better to hear from strong OOP developers from who use different programming languages to know if they have worked with developers who have managed to achieve this. Just in case people are wondering where I went from this - I've taken a closer look at what prototypal inheritance means and how to use it better. I've decided to spend more time properly learning ruby (could be any language that is class based) in my spare time. I've decided to experiment (nonchalantly) with different languages so that I can gain not the intricacies/exact syntax of them, but more of an overview of how they approach OOP. I've started with Self, Scheme is next on my list. Thanks a lot for the really helpful answers. There's no reason you can't develop strong object-oriented skills via Javascript - but Javascript is a prototype-based object-oriented language, which is quite different from other mainstream object-oriented languages (C++, Java, etc.), which are class-based. You should familiarize yourself with both models as soon as you can (once you've mastered the basics of javascript), so you can learn from discussions about class-based models without too much friction. Finally, in case you aren't already familiar with Douglas Crockford, I highly recommend visiting his site, reading his article JavaScript: The World's Most Misunderstood Programming Language, then reading his book Javascript: the Good Parts. Possible Duplicate: Why avoid increment (“++”) and decrement (“--”) operators in JavaScript? I've heard in a few places that it is not recommended to use ++ & -- in javascript, and we should be using += 1 or -= 1 instead. Can anyone clarify why for me? The only time I saw these operators discouraged was in Douglas Crockford's JavaScript: The Good Parts book. Quoting from the "Bad Parts" Appendix: The increment and decrement operators make it possible to write in an extremely terse style. In languages such as C, they make it possible to write one-liners that could do string copies: for (p = src, q = dest; !*p; p++, q++) *q = *p; They also encourage a programming style that, as it turns out, is reckless. Most of the buffer overrun bugs that created terrible security vulnerabilities were due to code like this. In my own practice, I observed that when I used ++and --,my code tended to be too tight, too cryptic. So, as a matter of discipline, I don't use them anymore. I think that as a result, my coding style has become clearer. In addition, quoting from the JSLint documentation (the code quality tool which he has written): The ++(increment) and --(decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators. He really doesn't fancy these operators... But come on! I think we can still use the ++ and -- operators without writing cryptic code. I use them, and I like them. Everyone uses them. Note that although JSLint has the option to disallow these operators, this option is not enabled by default. Before asking my question, let me give a disclaimer. I know what var does, I know about block scope, and I know about variable hoisting. I'm not looking for answers on those topics. I'm simply wondering if there is a functional, memory, or performance cost to using a variable declaration on the same variable more than once within a function. Here is an example: function foo() { var i = 0; while (i++ < 10) { var j = i * i; } } The previous could just have easily been written with the j variabled declared at the top: function foo() { var i = 0, j; while (i++ < 10) { j = i * i; } } I'm wondering if there is any actual difference between these two methods. In other words, does the var keyword do anything other than establish scope? Reasons I've heard to prefer the second method: I consider these reasons to be good but primarily stylistic. Are there other reasons that have more to do with functionality, memory allocation, performance, etc.? In JavaScript - The Good Parts Douglas Crockford suggests that by using the second method and declaring your variables at the top of their scope you will more easily avoid scope bugs. These are often caused by for loops, and can be extremely difficult to track down, as no errors will be raised. For example; function() { for ( var i = 0; i < 10; i++ ) { // do something 10 times for ( var i = 0; i < 5; i++ ) { // do something 5 times } } } When the variables are hoisted we end up with only one i. And thus the second loop overwrites the value, giving us an endless loop. You can also get some bizarre results when dealing with function hoisting. Take this example: (function() { var condition = true; if(condition) { function f() { console.log('A'); }; } else { function f() { console.log('B'); }; } f(); // will print 'B' })(); This is because function bodies are hoisted and the second function overwrites the first. Because searching for bugs like this is hard and regardless of any performance issues (I rarely care about a couple of microseconds), I always declare my variables at the top of the scope. I'm working on a project and I'm really trying to write object-oriented JavaScript code. I have just started reading Douglas Crockford's JavaScript: The Good Parts and I'm quickly beginning to realize that writing Java-esque OOP in JavaScript will be a difficult task. Thus far, I've written something like the following... // index.html $(document).ready(function() { $().SetUpElements(); }); // this is in a different js file $.fn.SetUpElements = function() { // do stuff here $().UpdateElement(); }; // this is in yet another different js file $.fn.UpdateElement = function() { // do stuff here var element = new Element(id, name); // continue doing work }; function Element(id, name) { var id = id; var name = name; // other stuff }; ... the idea being that I want objects/functions to be refactored and decoupled as much as possible; I want to reuse as much code as I can. I've spread a lot of my code across different .js files with the intention of grouping specific relevant code together, much like if you would write different classes in Java. As I've been learning more about jQuery, I realized that the notation $.fn.foo = function() { ... }; is actually adding this foo function to the prototype of all jQuery objects. Is this something I should be doing? Am I misusing jQuery somehow? I would appreciate suggestions on how to improve my approach to OOP in JavaScript and I would love to see references to sources/tutorials/articles/etc... that discuss this topic. Please feel free to provide feedback even if an answer has been selected. I am looking for your advice... this is why I posted :) ** Note: I'm not developing a jQuery plugin. I'm developing a web app and heavily making use of jQuery. I would say the first way you're creating methods is a misuse of jQuery. The jQuery.fn.foo syntax is generally reserved for functions that act upon a DOM element but you're using them as static functions, by using an empty jQuery object. If you want to create static functions under the jQuery namespace, you can do: jQuery.foo = function(){}; then call it via: jQuery.foo(); instead of: jQuery.fn.foo = function(){}; which allows you to do: jQuery('#someElementId').foo(); In terms of OOP. there are many different approaches (module pattern, prototype, factory...). The way I generally approach it, is create a Class as a static function, then invoking it with the keyword new (function($){ var undefined; $.ClassName = function(options){ var self = this; var cfg = $.extend(true, {}, this.defaults, options); // ******************** // start:private // ******************** function _init(){ }; // ******************** // start:public // ******************** this.methodName = function(){ }; _init(); }; $.ClassName.prototype.defaults = {}; })(jQuery); In terms of reusing functionality, there's a threshold after which decoupling is more detrimental than anything. Make sure you keep the right balance of modularity and organization. I am currently developing apps for the iPhone and iPad with Objective-C. I found some code related to using JavaScript in the iPhone. Web Apps Web Apps are highly optimized special websites that are accessed from any device but still look and feel like a full-fledged application. An early example would be GMail. Here is an old blog post by jQuery's John Resig on early web app development. 1. Can we create apps more easily and accurately with the help of Javascript? This is a bit mis-leading as the intents may be different. The goal of web apps to hit the widest possible audience with minimal effort, however, you are restricted to non-native functions. Native functions include use of the device hardware such as camera, gps, touching other apps, notifications etc. There are several libraries that provide a wrapper around your web app to expose these underlying calls but then you must do that for each device. Libraries include: Phonegap, Titanium. 2. Does Apple approve apps created at least partially with JavaScript? Most certainly! They even have a special section. With most webapps it is just a bookmarklet the user drags to their home screen for quick access. If you want to do the true app in the store you will need a wrapper library as mentioned before to package your app together. 3. How should one begin learning JavaScript? Out of scope for this question, but Douglas Crockford is one of the better teachers, he has a multi-part video series as well as a book to get you learning the "good parts". 4. Are there any tutorials that can help me to understand and learn JavaScript, particularly for iPhone/iPad programming? Honestly, it would best to learn javascript first, as it is a prototypical object based puzzle then worry about how to utilize the various frameworks for best mobile performance. Adding 5. What are some javascript mobile frameworks? These are just the most common but I would browse each of them a bit as jQuery, dojo and sencha have different approaches on how javascript should be used. I am trying to understand the internals of how jquery framework is written and finding it hard to understand the code. Does anyone have any suggestions regarding a good way to get started. Thanks for all the useful input. Editing the topic since I had limited space for adding individual comments. I have written a lot of basic javascript code. I know basic DOM, have used event handlers, know CSS basics. I have read about many of the topics you have mentioned and I am familiar with it although not an expert and have not coded some of the advanced topics like closures. Here are the books I have used so far Head first javascript - good in the beginning as a starter. Books my friends have recommended and I use regularly are Javascript - The Definitive Guide, Javascript - The good parts (I read this a while ago and it was hard for me at the time). My friend just recommended Secrets of Javascript Ninja - John Resig. Seems like a good one. I ordered the Javascript Design patterns book you recommend last week I have read the you pointed me to. I will checkout some of the other resources you pointed me to. Let me think a little more regarding if I want to do a little more reading before I post specific questions I have on jquery. Thanks Susan To comprehend the actual source would require some degree of Javascript knowledge - If you don't already know what's going on then you basically need to learn more Javascript. Key things to learn: When learning, use Firebug so you can evaluate your expressions interactively and immediately see what's going on An excellent free resource for learning that I would recommend: If you're a beginner to DOM Scripting/Javascript: If you're intermediate level: If you're past intermediate level and want to be an expert: Other technical references: If you have specific questions about a certain code snippet just ask here. Another resource that I can recommend for more advanced questions would be the jQuery mailing list or irc://irc.freenode.net/jquery where jresig hangs out himself and comes by and answers questions. There are other guru ops who reside there like ajpiano/paulirish/nlogax. I have the following code: // Creates a timer to check for elements popping into the dom timer = setInterval(function () { for (p in pixelTypes) { checkElems(pixelTypes[p]); } }, 10); // Add Document finished callback. $(document).ready(function () { // Document is loaded, so stop trying to find new pixels clearInterval(timer); }); In Firefox, it works great, but in IE6, I get a "Object Expected" error on the $(document).ready line. I can't figure out what would cause IE6 to not recognize it, jquery is fully loaded by this point. Is this a known issue? Just a few pointers for anyone that's interested: $(document).ready(function() {...}); and $(function() {...}); means exactly the same thing. The latter is a shorthand for the former. If you develop for a large site, using multiple Javascript libraries, or you develop plugins meant to be compatible with other peoples work, you can not trust the dollar sign ($) to be associated with the jQuery object. Use the following notation to be on the safe side: (function($) { [your code here] })(jQuery); This passes jQuery into a self-executing function, and associates $ with the jQuery object inside this function. Then it does not matter what the $ represents outside of your function. To get back to your question, have you checked whether the timer variable is assigned when you get the error? I believe the browser will see the $(document).ready(function() {...}); all as one line, so if you have some kind of debugger that tells you that's the offending line, it might be the timer variable... Last thing: In Javascript, it is not correct to place open curly braces on a new line. This can cause really bad errors due to Javascripts semicolon-insertion. For further info, read Douglas Crockford's Javascript: The good parts: Anyway, really hope I didn't upset anyone. Hope you solve the problem! EDIT: I'm not sure if this is what robertz meant by fully qualified, but as far as I know, when a URL is fully qualified it means no parts are missing, ie. it's an absolute URL starting with http:// or https:// (or some other protocol). Please correct me if I'm wrong! I'm using the Raphael JS library, and I'm trying to figure out how to make a point appear on screen, then disappear. I use a for loop to create the points, and then I make them fade in. Is there a way that they can also fade out, and I can remove them? I'm quite new to Javascript, so I don't know the best strategy for dealing with this. I could not see how to to this in the Raphael documentation. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>blink point</title> <script src="js/raphael.js"></script> <!--<script src=""></script>--> <script type="text/javascript"> window.onload = function () { //Point Array pointList = new Array (); // Create Canvas var r = Raphael(10, 50, 600, 600); // Make a 'group' of points for( i=0; i<20; i++){ //Create Point pointList[i] = r.circle(10*i, 10*i,5); pointList[i].attr({stroke: "none", fill: "#999", opacity: 0}); //Fade in pointList[i].animate({opacity: 1}, 1000 ); } // Remove points, starting with the first for( i=0; i<20; i++){ //Try fading them out //pointList[i].animate({opacity: 0}, 1000 ); } }; </script> </head> <body> <div id="holder"></div> </body> </html> I also was not able to get the online link to the Raphael library to work, so it might be necessary to download the library. To clarify - Raphael's animate() will start happening as soon as you make the function call and will keep happening while the rest of your JavaScript is executed. I've modified Eldar's example code to demonstrate this. See: Note that the yellow circles are drawn at the same time as the grey ones even though the call to animate() them occurs later in the code. Hitting a callback function upon the completion of an asynchronous code path is a common pattern in JavaScript and it is essential to understand it in order to be productive with JS. In Eldar's example, an anonymous function is attached to the first animate()'s callback handler. Upon completion of the initial fade-in animate(), the function gets called, and performs a fade-out. I recommend Douglas Crockford's JavaScript: The Good Parts (which is, somewhat amusingly, the slimmest programming book I've ever read) and running through JavaScript Koans. Doing that should set you on the right track. I am beginner to webprogramming & Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions. I found "pagetutor.com" which has practical javascript exercises, but it's paid! Please suggest any paid sites too which is really worth for practical learning. you could try. it's a very basic intro to the language. Also I would recommend JavaScript: The Definitive Guide very nice book, describes the language in details. Also Douglas Crockford's JavaScript: The Good Parts And probably some good blogs: for exercise I would recommend jsFiddle I learned that from books. Basics: W3schools javaScript For advanced I suggest these books: Advanced JavaScript(TM), Third Edition Pro JavaScript Techniques Professional JavaScript for Web Developers (Wrox Programmer to Programmer) Books are cheap :) Also I bought W3Schools books about HTML, JavaScript and CSS and I like it :) Now that frameworks like GWT, Morfik etc exist which compile Java client side code into major JavaScript dialects, is it still worth learning JavaScript? Yes, ...and I speak with experience: I've never learned javascript and only used parts of it, when I encountered it in google searches for questions. Now that I'm building a Web application, I notice that not all abstractions away from javascript have the desired functionality, and I need to go into javascript to solve it. I notice that I miss the fundamental knowledge I have with other languages, just like I miss the 'javascript programming language' book (I'm not sure it exists but I have similar copies for C, C++ and Java). So today I ordered Javascript:The good parts and I will learn it... OK, so I'm trying to learn JavaScript properly so that I can write good, clean client-side code, but whenever I think I'm making progress, something stops me dead in my tracks! I want to know: What is the different between JavaScript, ECMAScript and JScript? Which should I focus on learning? If these are versioned, which version should I be supporting? Are there any really good references (web / books etc) that are a must have/read? How do I ensure that what I write will be compliant with all major browsers (IE, FF, Safari, Chrome, Opera etc.) ? MOST IMPORTANTLY...Is there a reference of the core objects (Array, Number etc) so I know what is implemented already and what I need to do myself? Thanks.. Depends on you, but I think most commonly used for web dev is JavaScript JavaScript was formalized in the ECMAScript language standard and is primarily used in the form of client-side JavaScript I would recommend this book By learning more and more about the language itself and writing tests ECMAScript is the language, JavaScript and JScript are dialects I would, personally, look at and learn JavaScript. It depends on what browsers you want to support, easily googled. MDN is a pretty good web source. JavaScript: The Good Parts and JavaScript: The Definitive Guide are both very good books, the first short and concise the latter very detailed. JavaScript libraries like jQuery is very good for this reason. It all comes down to learning all the quirks of the browsers. Google is your friend. I know that there are several ways to define a function in JavaScript. Two of the most common ones are: (1) function add (a, b) { return a + b; } (2) var add = function (a, b) { return a + b; } I am comfortable with the idea of a function as an object that can be passed around just like any other variable. So I understand perfectly what (2) is doing. It's creating a function and assigning to add (let's say this is in the global scope, so add is a global variable) the said function. But then what is happening if I use (1) instead? I already know that it makes a difference in execution order: if I use (1) then I can refer to add() before the point in the code where add() is defined, but if I use (2) then I have to assign my function to add before I can start referring to add(). Is (1) just a shortcut for (2), albeit one that happens to behave like other C-style languages in allowing us to define a function "below" the point at which it's used? Or is it internally a different type of function? Which is more "in the spirit" of JavaScript (if that isn't too vague a term)? Would you restrict yourself to one or the other, and if so which one? It looks like you are already aware of the main characteristics of function declarations1 (1) and function expressions (2). Also note that in (1) there is still a local variable called add containing a function value, just like in (2): function hello () { alert('Hello World'); } console.log(typeof hello); // prints "function" setTimeout(hello, 1000); // you can still pass functions around as arguments, // even when using function declarations. One other point worth mentioning is that function declarations (1) shouldn't be used to define functions conditionally (such as in if statements), because as you have mentioned, they are automatically moved to the top of the containing scope by the JavaScript interpreter2. This is normally referred to as hoisting. As for which approach is more in the spirit of JavaScript, I prefer using function expressions (2). For a more authoritative opinion, Douglas Crockford lists function declarations (1) in the "Bad Parts" chapter in his popular The Good Parts book2. 1 Also known as function statements (See @Tim Down's comments below). 2 Actually some browsers are able to handle function declarations in if statements (Again refer to comments below). 3 JavaScript: The Good Parts - Appendix B: Page 113. I realize that title may require explanation. The language I first learned was C, and it shows in all my programs... even those not written in C. For example, when I first learned F# I wrote my F# programs like C programs. It wasn't until someone explained the pipe operator and mapping with anonymous functions that I started to understand the F#-ese, how to write F# like a F# programmer and not a C programmer. Now I've written a little javascript, mostly basic stuff using jquery, but I was hoping there was a good resource where I could learn to write javascript programs like a javascript programmer. Douglas Crockford's - Code Conventions for the JavaScript Programming Language would be a good place to start. I learned a lot of useful information in regards to code convention through his video tutorials, which I suggest viewing. I posted the link to the first video out of the four in the series. Also, as suggested by Ben, (which is a book I would also highly recommend) is Douglas Crockford's book JavaScript: The Good Parts If you want to find good explanations on jQuery, check out the creator, lead developer and fellow StackOverflower John Resig's website/personal blog. Who can explain why result are [20, 20, 10, 10] in this code: var x = 10; var foo = { x: 20, bar: function () { var x = 30; return this.x; } }; console.log( foo.bar(), (foo.bar)(), (foo.bar = foo.bar)(), (foo.bar, foo.bar)() ); Links to specification are welcomed Can't point you at specification, but i can highly recommend reading Douglas Crockford's "Javascript: The good parts". This book will help you understand most of the weird but great features of JavaScript. As of your question: thiskeyword in barfunction is bound to fooobject In javascript you can assign variables from right to left multiple times z = 3; x = (y = z); console.log(x); //3 functions are variables as anything else. So you are assigning the function foo.bar to foo.bar, but the parenthesis causes the assigned function to be returned, and then executed. (foo.bar = foo.bar)(); //is the same as var f = (foo.bar = foo.bar); f(); //and this also the same as: var f= foo.bar; f(); The function returned from parenthesis is not bound to anything, so this will refer to global object, in case of browsers - to the window object. 4.. The clause (foo.bar, foo.bar)() is just alike: a = (3, 4); //last value is returned, first just parsed. //a contains 4 var f = (foo.bar, foo.bar); //f contains body of foo.bar function, f() // is executed in the context of `global` object, eg. `window`. Please read about binding of functions in JavaScript. The browser based app is said to be done using Canvas 2D or Web GL. I tried to view source using chrome by using "Inspect Element" button, but my chrome crashes each time. I am just trying to find out how one can begin to develop such awesome games. Looking for pointers to online resources,books, and specific tips for beginners. If you want a book, Foundation HTML5 Canvas: For Games and Entertainment just came out. It is fairly basic but will be useful to you if you are completely new to JavaScript and Canvas. A faster-paced introduction would be the Mozilla Canvas tutorial, which is very clear. To get a grasp on going from drawing things to being able to interact with them, I'd suggest my own tutorials on the matter, here. For a general book on Javascript (regardless of your prior experience), it is probably worth reading Javascript: The Good Parts As for general advice, I give you the words wonder if someone could be kind enough to explain the function.prototype thingie (thingie!!??) in OO javascript. I come from a server side programming background, and may be I am not grasping the whole concept of prototypes, Given the following snippets of code: var animate=function(){}; animate.angular=function(){/*does something here*/}; animate.circular=function(){/*does something here*/}; And var animate=function(){}; animate.prototype.angular=function(){/*does something here*/}; animate.prototype.circular=function(){/*does something here*/}; as far as I can tell, both the latter functions are callable via animate.angular(/*args*/) and animate.circular(/*args*/) so, I guess my question is, what are the merits of defining the functions in the second way? and how or why are they different? Hope I made sense... EDIT: Thankyou all for the enlightening answers, It's very hard to judge an answer here as being "Correct", so I'm gonna mark the one I feel made the most contribution... You all have certainly given me more food for thought... Javascript is a weird language ... very powerful but not all that strongly structured compared with other languages... The prototype is how JavaScript lets you save memory if you're going to be creating multiple instances of a class... So if you're using JS in an OOP way you should define your functions as part of the prototype. Also, there are ways to simulate inheritance using the prototype. I highly recommend the book "Javascript, the Good Parts" for lots of great explanation about this. So I've been reading through Javascript - The Good Parts and one thing that Crockford points out is the use weakness of global variables in Javascript, in such a way that if your product is expanded in some manner, and it relies on a 'global' variable it could be inadvertently set. That's all good and fine and I understand the pros/cons of protecting variables, in other manners such as closures as well. However, I was doing some thinking, and wrapping code in a function like so: (function () { var x = 'meh'; })(); (function () { alert(typeof x); // undefined })(); gives it variable scope, which thereby prevents cross contamination of variables. I'm not sure if there's a blatant downside to this approach though and wondered if the community had any input, or if I'm just overthinking things and ignoring the main point. That's a perfectly legal way of doing things -- the variables inside of your function (as long as they are prefaced by var) are local to the function. It's called the module pattern, and it's very well accepted. What is a good javascript (book or site) that is not just focused on syntax but does a good job explaining how javascript works behind the scenes? Thanks! crockford does a good job of explaining JS. check out the articles on his website and his new book: Both scenario, the typeof the variable will be "undefined". But undeclared variable will raise a exception. Is there a easy way to handle this? You should never be attempting to access undeclared vars if you're writing clean JS. To avoid such pitfalls (among many others) start LINTing your JS with or . A good read to help you understand the LINT tools and reasoning behind their findings is Crockford's Book, JavaScript: The Good Parts ( ). Currently, I am using Javascript - The Definitive Guide for learning Javascript from scratch. Having learnt Java, PERL and other programming languages, I am in a habit of solving small exercises to check/better understand what I have been learning as well. In case of Javascript, I found the book to be severely lacking in exercises. Infact, I did not find exercises in the only other book [ Beginning Javascript ] I have either. Is there any source that I can refer to for exercises in Javascript? I would suggest reading everything Douglas Crockford has to say about JavaScript, reading The Good Parts, writing as many programs as possible and running them all through JSLint with "the Good Parts" and rewriting them until it stops complaining, and reading the source of jQuery. It also wouldn't hurt to read Dmitry A. Soshnikos' rendition of the ECMA-262 spec. (It's very specific and goes into minute detail but it also covers every possible aspect of the language) It would probably be good to mention that you don't need to follow Crockford's conventions to the letter if you don't want to (though I would recommend writing for ES5 strict) but limiting yourself to them while you learn the language is definitely the way to go. Once you get a good grasp on the syntax, Crockford has a page that compares javascript with Scheme and takes you through a short book The Little Schemer. The article is appropriately named The Little JavaScripter. After reading the book, I was changed. Or perhaps transformed. Or altered. In a good way. There are very few books that deeply change the way that you think. This is one of those books. He's gone through the chapters and translated the functions into javascript. As an exercise, you could do the same and compare your solutions. I am reading Douglas Crockford's book "Javascript: The Good Parts". He is talking about scope and saying that JS doesn't have block scope: In many modern languages, it is recommended that variables be declared as late as possible, at the first point of use. That turns out to be bad advice for Javascript because it lacks block scope. So instead, it is best to declare all of the variables used in a function at the top of the function body. However, I couldn't think of a good example why this statement makes sense and it would be really nice to see some examples which verify this statement. Declaring variables at the top helps you avoid situations like this: function outer() { var i = 50; function inner() { alert(i); var i= 30; } inner(); } outer(); Many people would expect the alert to show 50, and they would be surprised to see undefined. That's because the i variable is declared within the inner function, but it isn't initialized until after the alert. So it has full function scope, even though it's declared after its initial use. I am really a big fan of javascript. It is really a great prototype based OOP language. Now I want to learn some other prototype based language. Really really interested in some design guideline i.e How can I manage the code without classes etc. Which language should I choose ? Some resource in design patterns for prototype based language ? The best guidelines that I have read to take advantage of JavaScript's prototypical nature were in the book JavaScript the Good Parts and you can apply these guidelines to other languages also. I changed the way I code in Python after reading this book. If you want to learn a language similar to JavaScript, try ActionScript first. Both are based on the same standard. It will be easy and rewarding. I'm a relatively newbie to object oriented programming in JavaScript, and I'm unsure of the "best" way to define and use objects in JavaScript. I've seen the "canonical" way to define objects and instantiate a new instance, as shown below. function myObjectType(property1, propterty2) { this.property1 = property1, this.property2 = property2 } // now create a new instance var myNewvariable = new myObjectType('value for property1', 'value for property2'); But I've seen other ways to create new instances of objects in this manner: var anotherVariable = new someObjectType({ property1: "Some value for this named property", property2: "This is the value for property 2" }); I like how that second way appears - the code is self documenting. But my questions are: Which way is "better"? Can I use that second way to instantiate a variable of an object type that has been defined using the "classical"way of defining the object type with that implicit constructor? If I want to create an array of these objects, are there any other considerations? Thanks in advance. Best way to create javascript objects is quit using new (at least if you subscribe to the crockford camp) myObjectType = function(props) { // anything defined on props will be private due to the closure props.privateVar = "private"; // anything defined on obj will be public obj = {}; obj.testing = new function() { alert(props.privateVar); }; return obj; }; instance = myObjectType({prop1: "prop"}); // if we want inheritance, it just means starting with the base type instead of // a new object subType = function(props) { obj = myObjectType(props); obj.subTypeProperty = "hello."; return obj; }; Page 52 of Javascript: The Good Parts, I highly recommend it :-) I'm interesting in improving my javascript code to be properly OOP.... currently I tend to do something like this: jQuery(document).ready(function () { Page.form = (function () { return { //generate a new PDF generatePDF: function () { }, //Update the list of PDFs available for download updatePDFDownloads: function () { }, /* * Field specific functionality */ field: (function () { return { //show the edit prompt edit: function (id, name) { }, //refresh the value of a field with the latest from the database refresh: function (id) { } }; }()) }; }()); }); In the end it's just mainly organized functions I suppose... what's a good resource where I can learn to program javascript in an OOP manner, or what suggestions would you have for improving my current style of programming? It seems like I should do a sort of model prototype and have my form object inherit from that prototype. (I'm using jQuery instead of $ because of conflicts with prototypeJS) Some good sources for Object-Oriented JavaScript and JavaScript in general... I hope this helps. Hristo I've been instantiating subclasses in javascript using object = new class () but I notice some people instantiate using object.prototype = new class () Question: What's the difference? To me it seems like the latter is respecting the inheritance chain more because if class () has a bunch of " this.variable = x" statements, and object is something you want to inherit from it rather than an instance of class, you are accurately assigning those variables to object's prototype rather than to the object itself as in the former case. So in effect it's like this? object = new class () |vs.| subclass.prototype = new superclass () However, functionally in the program both are the same? Side question: Also I'm a bit unclear as to what the new operator actually does. It seems to me to do something like just create an empty object and assign it's proto property? The code samples in your question reflect a couple of misunderstanding. Let's address them first: Quoting Douglas Crockford in Chapter 5, Inheritance, of JavaScript: The Good Parts: Instead of having objects inherit directly from other objects, an unnecessary level of indirection is inserted such that objects are produced by constructor functions. (...) When a function is invoked with the constructor invocation pattern using the new prefix, this modifies the way in which the function is executed. Douglas Crockford then explains how the new operator could be implemented as a JavaScript function. This function makes use of several other functions defined in the book, so I rewrote it in a (somewhat) simpler form below: function createNew(constructor) { // a function to explain the new operator: // var object = createNew(constructor); // is equivalent to // var object = new constructor(); // // param: constructor, a function // return: a new instance of the "constructor" kind of objects // step 1. create a new empty object instance // linked to the prototype of provided constructor var hiddenLink = function(){}; hiddenLink.prototype = constructor.prototype; var instance = new hiddenLink(); // cheap trick here: using new to implement new // step 2. apply the constructor the new instance and get the result var result = constructor.apply(object); // make this a reference to instance within constructor // step 3. check the result, and choose whether to return it or the created instance if (typeof result === 'object') { return object; } else { return instance; } } In simple English, if you call new constructor(), where constructor is a function, the operator creates a new object with a link to inherit properties from the constructor, applies the constructor function to it, and returns either the value returned by the constructor, or the new object in case the constructor returned something else which is not an object. At any time, before or after creating new instances using a custom constructor, you may modify the prototype (object) on the constructor (function): function constructor(){} // the most simple constructor function: does nothing var before = new constructor(); var different = new constructor(); different.answer = "So long, and thanks for all the fish"; constructor.prototype = {}; // set an empty object to the prototype property constructor.prototype.answer = 42; // create a new property on prototype object constructor.prototype.answer = Math.PI; // replace an existing property var after = new constructor(); Through the hidden link added to all objects created using this constructor (see "cheap trick" in createNew), the properties of the prototype object can be accessed on all these instances, unless overridden by properties defined on the objects directly. before.answer === Math.PI; // true after.answer === Math.PI; // true different.answer === "So long, and thanks for all the fish"; // true Using this newly acquired knowledge, how would you create a new "class" of objects that inherit all the properties of arrays, together with a new method empty() to remove all elements? First, there are no classes in Javascript, so in order to create a new "class", I have to define a new constructor function. Let's call it CustomArray, with a capital C to follow the convention that constructor functions should start with a capital. function CustomArray(){} I can now create custom instances: var myArray = new CustomArray(); Second, I want instances created with CustomArray to inherit Array properties: myArray.prototype = new Array(); // WRONG EXAMPLE: we must set CustomArray.prototype CustomArray.prototype = Array; // WRONG EXAMPLE: prototype expects an object, Array is a function CustomArray.prototype = new Array(); // OK, BUT: the simpler form [] should be used instead CustomArray.prototype = []; Third, I want all instances created with CustomArray to have the empty() method: function empty(){ // empty this array by setting its length to 0 // function to be called in the context (this) of an array this.length = 0; } CustomArray.prototype.empty = empty; // set the function named empty to the property "empty" of the prototype Finally, I can rewrite the whole example in a more concise way: function CustomArray(){} CustomArray.prototype = []; CustomArray.prototype.empty = function(){ this.length = 0; } I can now create a custom array, set a couple of values and empty it: var myArray = new CustomArray(); myArray[0] = "abc"; myArray[1] = "def"; myArray[2] = "ghi"; myArray.empty(); The issue is: the above code does not work as expected. Why? Because unlike in regular arrays, setting values in our custom array does not automagically increase the length property of the array. Likewise, calling empty() only sets the length property of our custom array to 0, it does not delete all the values within. Besides, we could not use the array literal syntax to initialize our custom array: var myArray = ["abc","def","ghi"]; // this creates a regular array All in all, it is important to understand how Javascript inheritance works, but you may often find it less useful than expected and there are simpler ways to achieve the same result, for example by using builder functions instead of constructors. We can solve the problem by using a builder function customizeArray to extend regular arrays: function customizeArray(array){ array.empty = function(){ this.length = 0; }; } var myArray = ["abc","def","ghi"]; customizeArray(myArray); myArray.empty(); This code works as expected because myArray is a regular array in this case, extended with a new method named empty. The main advantage and drawback of this approach in comparison with using prototypes is that it modifies only the selected instance, and if you were working with lots of similar objects at the same time, setting this extra property would use more memory than setting a single shared property on a common prototype. To avoid that, you may be tempted to modify the Array prototype directly: Array.prototype.empty = function(){ this.length = 0; }; var myArray = ["abc","def","ghi"]; myArray.empty(); It works, but I would advise against it: you are attaching a custom property to every array instance, including all those created by those fancy libraries, plugins, frameworks, advertising and analytics scripts, all the code on your page. Needless to say that it may break something in a place where you cannot fix it. Edit: Interesting post on kangax's blog as a follow-up: "How ECMAScript 5 still does not allow to subclass an array" This is what I got so far, and it's not working at all :( all the variables are null in my player class and update never gets called. I mean a programming class, not a css class. I.E. not (.movingdiv{color: #ff0000;}) <!DOCTYPE html> <html lang="en"> <head> <title>Class Test</title> <meta charset="utf-8" /> <style> body { text-align: center; background-color: #ffffff;} #box { position: absolute; left: 610px; top: 80px; height: 50px; width: 50px; background-color: #ff0000; color: #000000;} </style> <script type="text/javascript"> document.onkeydown=function(event){keyDown(event)}; document.onkeyup=function(event){keyUp(event)}; var box = 0; function Player () { var speed = 5; var x = 50; var y = 50; } function update() { box.style.left = this.x + "px"; box.style.top = this.y + "px"; box.X: "+ this.x + "<br /> Y: " + this.y + "</h6>"; } var player = new Player(); var keys = new Array(256); var i = 0; for (i = 0;i <= 256; i++){ keys[i] = false; } function keyDown(event){ keys[event.keyCode] = true; } function keyUp(event){ keys[event.keyCode] = false; } function update(){ if(keys[37]) player.x -= player.speed; if(keys[39]) player.x += player.speed; player.update(); } setInterval(update, 1000/60); </script> </head> <body> <div id="box" ></div> <script type="text/javascript"> box = document.getElementById('box'); box.X: "+ player.x + "<br /> Y: " + player.y + "</h6>"; </script> </body> </html> Edit: alright, I think I messed up here. The first time I tried to make a class I seem to have messed up. After retrying I seem to be able to now using the "1 Using a function" in Meders post. the real problem seems to be that javascript doesn't know what to do when it gets to this line in my real code: box.style.background-position = "" + -(this.frame * this.width) + "px " + -(this.state * this.height) + "px"; It also seems to choke anytime I put box.style.background-color So the question I need answered now is how do I set a value to style variables in javascript that have a "-" in the name. I'll post a test in a second You're using Player like a constructor, but it is not set up like one. Rather than using var inside the constructor function, like var speed = 5; you need to use this.speed=5; Then it wil return an instance of Player. As it is, you're just setting some variables and returning nothing in particular. Now, as far as learning JS object creation and inheritance, I suggest checking out Douglas Crockford's resources. As you may know, it's not intended to be class-based like Java, PHP, Python and so on. JavaScript has prototypal inheritance based on cloning objects that already exist. Crockford discusses doing class-based inheritance in JS in this older article. The problem is, you're not using JS to it's best trying to do that. This treatise may be interesting where he explains one way of cloning objects. That is the Object.beget method, which is good, but has limits as well. The best way is the 'functional' method. Sorry for the PowerPoint links, but you should read this: and this: is one version of a video where Crockford discusses the ins and outs of JS. is another of the same. I really recommend getting the book JavaScript: The Good Parts for a thorough run down of pragmatic advanced JavaScript. Beginner in JS :) needs an explanation of code piece from Crockford's book, section 4.15: var memoizer = function (memo, fundamental) { var shell = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = fundamental(shell, n); memo[n] = result; } return result; }; return shell; }; var fibonacci = memoizer([0, 1], function (shell, n) { return shell(n - 1) + shell(n - 2); }); Question: How do we calculate fibonacci(15), and if it is simple fibonacci(15) call, then how it works in detail? Thanks for help. As the comments to your question suggest, you should walk through the code in a debugger to get a good understanding of what's going if you can't follow the explanation in the book. But I'll give you a brief overview of what's happening: What's being demonstrated is 'memoisation' which is a common optimisation technique used in functional programming. A function is said to be pure if the result depends only on the arguments passed into it. So, if a function is pure you can cache the result based on the arguments - this technique is called memoisation. You would do this if a function is expensive to calculate and is called multiple times. The classical example used to demonstrate this (as here) is generating Fibonacci numbers. I'm not going to go through how those are worked out, but basically as you go to higher and higher numbers you repeat yourself more and more as each number is calculated from the preceeding two numbers. By memoising each intermediate result you only have to calculate them once hence making the algorithm much faster (much, much faster as you go higher up the sequence). As far as this code is concerned the memoizer takes two parameters - 'memo' which is the cache. In this case it's going in with the first two values already filled in the '[0,1]' - these are the first two Fibonacci numbers. The second parameter is the function to which the memoisation will be applied. In this case a recursive Fibonacci function: function (shell, n) { return shell(n - 1) + shell(n - 2); } i.e. the result is the sum of the previous two numbers in the sequence. The memoizer first of checks to see if it already has a cached result. If it does it returns that immediately. If not it calculates the result and stores it in the cache. Without doing this it'd be repeating itself again and again and rapidly gets impossibly slow once to get to the higher numbers in the sequence. Can anyone show me some complex JSON structure and tutorials where i can excel more on this JSON topic using javascript. So far i am able to understand JSON, its basic structure and how to parse and alert out properties. I can search in google or other search engines, but i want links from you expert guys who can lead me to right direction than a BOT which displays result. JSONobject, JSON.parseand JSON.stringify If you have some knowledge of other languages, you could look at some JSON processors' implementations and get to know what makes them better or worse than their competitors, read their code, etc... For instance, for Java: For other languages: see json.org (at the bottom of the page) for tons of links. Look online for webservices exposing JSON-enabled endpoints to play with them. Head over to ProgrammableWeb for that, or use any search engine. For experimenting, use either: Actually you could very much just use your javascript console to experiment without any end-point and test whether you manage to create objects. know let is to declare block scope local variables, but why doesn't it support redeclaration and hoisting like var does? What's the design purpose of this limitation? (function(){ 'use strict'; alert(a); // undefined var a; })(); (function(){ 'use strict'; alert(a); // error let a; })(); (function(){ 'use strict'; var a; var a; alert(a); // undefined })(); (function(){ 'use strict'; let a; let a; // error alert(a); })(); The idea is to create a tool that's more unambiguous and more strict than the original var. As a human, the following is valid JavaScript but nearly impossible to understand: alert(a); // Where does a come from? Why does this not throw? /* 1000 lines later, or even in an entirely different file */ var a; Moreover, imagine code with 5 var declarations for the same variable on the same scope, some in if statements, some in fors. Which is the first? What value will end up being created? The idea was to fix some of the bad parts of var. I'm reading some tutorials now about jQuery.. function creating,plugin creation etc. but these tutorials are missing some basic explanations like they mention things like function prototype, anonymous functions, umm putting (jQuery) after the }); .. and stuff like that .. is there a tutorial/website/book that explain these I'm not sure how to call them "terms" from beginner level to advance. I'm mean I have a knowledge of some jquery syntax but not enough to understand this, can anyone recommend useful resource? Google doesn't help much, I googled "advance features of jquery" don't really get me the things I wanna know. EDIT Also if someone can share his/her story steps on how to become comfortable with javascript, how to overcome this "terminology" or whatever is called For JavaScript, there is: Javascript The Good Parts For jQuery, I'd suggest: The jQuery CookBook I'd also suggest some podcasts and screencasts: I would consider myself to be reasonably competent with JavaScript and familiar with many of the different ways of achieving the same thing. But today I came across some function syntax which I hadn't seen before: function document.body.onload() { alert('loaded'); } If I were to write such code I would have done it like this: document.body.onload = function() { alert('loaded'); } Ignoring the fact that this is not the best way to handle the onload event, is this actually valid JavaScript? It appears to causes syntax errors in FireFox (and JSLint), so I am guessing that it is Internet Explorer only syntax? If it is IE only then I would like to remove it but I am concerned that it might have some quirky side effect. No, it's not valid. the function X() {} variant requires that the name of the function only contains letters, digits, '$' and '_'. If you want to check other syntax, you can get the standard here, but the syntax diagrams in the back of JavaScript: The Good Parts are much easier to digest. I would like to develop some apps for the JVM using a concise, dynamic language. The most popular choices for this seem to be Jython, JRuby, Groovy, and maybe Clojure. Rhino appears to be fast and very stable, but I see no books on Rhino development and little discussion. Why is there apparently little use of JavaScript for other than embedded scripting? Edit: I found this question informative on the viability of Rhino-based development. I've used Rhino as a part of a production-grade VoiceXML interpreter written in Java and running on the JVM. It works extremely well for this purpose. If I were reimplementing this interpreter from scratch, I would have leaned towards doing even more of my development in JavaScript. So it's definitely an option. You'll need to explore how mature the surrounding libraries are for your application area (you can always write logic that calls out from JavaScript to Java libraries, but that might be too laborious). But I also agree with @Peter Recore: do give the other JVM languages a second look. I'm impressed with the object-functional Scala language: its performance is nearly as good as Java, and it has a lot of expressive power. Update: Good books to read on JavaScript are: JavaScript: The Definitive Guide and JavaScript: The Good Parts. The only Rhino-specific stuff you'll need is here. Using the tiny Diggit/Blog feature of StackOverflow described here: I would like to post the following Google tech talk video I have just saw and that I found quite interesting. I have always had problems understanding javascript "nature". Here, the JavaScript good parts are described by Douglas Crockford I hope you find this link useful. Now the question part: What are your complaints about javascript? Do you use an IDE for javascript editting? Do you think this video helps to understand the "good parts"? Javascript the Good Parts is a pretty decent book too. For Javascript Firefox+Firebug and Notepad++ are my IDE. jQuery (and assorted plugins) is my Framework. My biggest complaint about Javascript is IE6 Possible Duplicate: Is it a good idea to learn JavaScript before learning jQuery? I have been trying to teach myself Javascript recently, and I have gotten a lot of comments from people telling me that I should just teach myself jQuery. I see uses to both - and obviously understanding Javascript lets you understand what is going on in jQuery to a greater extent. But jQuery seems easier, more intuitive and quicker to get to production level code (always useful when you're in a business environment). Learning a framework (jQuery) without learning the language (javascript) it is based on is not the best way to go about it. If I was starting out fresh and wanted to get productive quickly I would read Douglas Crockfords Javascript the good parts first. This books gives a good background on using the good parts of javascript and is the basis for many of the design ideas used in jQuery. Then I would get started with jQuery. Iam trying to get better in javascript coding. Away from 1000 lines of code in one file. But iam not sure if this is the "right" way: RequireJS to load files when needed inside "boot.js": require([ "library/jquery.form/jquery.form", "app/eventManager", "app/myapp" ], function() { $(function() { MyApp.init(); }); }); MyApp.js var MyApp = { init: function() { MyApp.mainController(); }, // this is our controller, only load stuff needed.. mainController: function() { //controller = set from php/zendframework switch (controller) { case 'admin': MyApp.initAdmin(); break; default: break; } }, // action for admin controller initAdmin: function() { //lazy load require(["app/admin/admin"], function(){ MyApp.admin.init(); }); }}; MyApp.admin.js MyApp.admin = { init : function() { if (permisson != 'admin') { console.log('Permission denied.'); return false; } MyApp.admin.dashboard.init(); } }; MyApp.admin.dashboard = { init: function() { MyApp.admin.dashboard.connectEventHandlers(); MyApp.admin.dashboard.connectEvents(); MyApp.admin.dashboard.getUserList('#admin-user-list'); }, connectEvents: function () { EventManager.subscribe("doClearCache", function() { MyApp.admin.dashboard.doClearCache(url); }); EventManager.subscribe("doDeleteUser", function() { MyApp.admin.dashboard.doDeleteUser(url); }); }, What other "styles" are common? or this a goodway to structure code? THere a lot of examples in the net, but i was not able to find "real life" code.. And one of biggest "problems" when does i need ".prototype" ? I defer to Douglass Crockford on all matters pertaining to JavaScript best practices. Here is his homepage:. Here is a great book on what to do and what not to do in JavaScript. Here is his amazing tool which can automatically tell you if you are employing any worst practices. As to the prototype question, you use prototype when you want to employ prototypal inheritance, or create a "static" class function which will be present for all instances of that class without consuming memory for each instance. I do not like saving files, switching to a web-browser and refreshing and seeing if it worked. That is why I am asking. When I must touch PHP I use Eclipse, and I can create unit tests and make sure it works properly, I don't write a bit, test then write a bit and test. So I expect to "develop" Javascript the same way, write a chunk, make sure it works, but I'm not sure how I can test actions triggered by a button say. I've searched for "Javascript development" and other terms, I get the expected slews of crap on ... well hello world Javascript snippits really. Can someone point me in the right direction? I currently use Eclipse (Eclipse CDT, PyDev, Eclipse PHP, so forth) and I can debug. I could make do without the step-by-step debugging for Javascript, but I'd really like unit tests. The other problem I have is the difficulty finding out what went wrong, Even PHP can give you a call trace, I'm stuck with Firefox's annoying-to-access error thing in the web-developer settings. There must be a better way, but I'm struggling to find it. Step one; static analysis: Step two; testing: Automatic tests in Eclipse for JavaScript Step three: JavaScript The Good Parts I have learned basic JS knowledge, and read "Javascript definitive guide" book, but best way to improve is learning by doing, so any opensource project for practice, or any good suggestion for improving JS? As an example of an open source project you could look into I would recommend to check the dojo sources. It's easier to grasp the advanced concepts there than e.g. in JQuery since there is a much wider code base for many different aspects. There is a lot to go through in the dojox packages. The code is also nicely documented, and recently they added nice online documentation, too, something that was missing for a long time. I learned a lot by peeking into dojo's internals, so I can only recommend it. You should pay attention to their way of coding object-orientedly and how it differs from what plain JS offers you. In addition to great code you can learn the concepts of code minification there, which is a big deal for the dojo project. There's also material on unit testing with Javascript code, something that is often overlooked but as important as back-end unit tests imo. By reading "Javascript - The definitive guide" you now know a good bit about the language itself and its usage for browser-based applications. But with the recent popularity gain of Javascript it has also found its application on the server side. E.g. node.js is a very interesting project you could look into. The concept of "Closures" is something you could look up, then find examples in existing code and finally use them in your own. "Ajax" is another buzzword and concept you should be familiar with, it lets you do all the nice things in your browser that some years ago were only possible in desktop applications. Modern web applications make heavy use of Javascript, but since standard Javascript and its prototypical inheritance are a bit clumsy to use, frameworks were written that simplify common tasks. You should familiarize with one or more of them to get an understanding of what they simplify compared to plain Javascript - this way you will automatically learn the drawbacks and shortcomings of pure Javascript. A good example is the with keyword. It's there, but nobody uses it. If your time just allows you to delve into one of these frameworks then my recommendation would be jQuery - it's the most widely used Javascript framework out there. Some Frameworks Read blogs and technical articles on the web, skim through Javascript questions here at Stackoverflow to keep up to date and learn about interesting corner cases. Some book recommendations I looked it up and this pattern is Hofstadter Female sequence. The equations are: M(n) = n-F(M(n-1)) F(n) = n-M(F(n-1)) but I'm not sure how to put that into code. So far I have: while () { _p++ _r++ if (_p % 2 === 0) { _r = _p - 1; } } Any help? Similar to GaborSch's answer, you could use Doug Crockford's memoizer function, which can be found in Chapter 4 of Javascript: The Good Parts. Using memoization took the calculation time for the first 150 terms of the male and female Hofstadter sequences down to 256 ms as compared to almost 8 seconds without memoization. var memoizer = function (memo, formula) { var recur = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = formula(recur, n); memo[n] = result; } return result; }; return recur; }; var maleHofstadter = memoizer([0], function (recur, n) { return n - femaleHofstadter(recur(n-1)); }); var femaleHofstadter = memoizer([1], function (recur, n) { return n - maleHofstadter(recur(n-1)); }); var N = 150; var f = []; var m = []; for (var i = 0; i <= N; ++i) { f.push(femaleHofstadter(i)); m.push(maleHofstadter(i)); } console.log('F: ' + f.join(',')); console.log('M: ' + m.join(',')); I was wondering how one would go about making "classes" similar to those in Python in Javascript. Take the Python classes and functions listed here: class one: def foo(bar): # some code The function "foo" would be called with one.foo(bar). What would the JS equivalent be? I suspect it would be something like this: var one = { foo: function(bar) { // JavaScript } }; Thanks. Have a look at this link. There a different ways to do OO programming in Javascript. The details are too much to be explained here. If you are serious about Javascript programming, you should read this book. If you want to do real heavy OO programming, I would recommend to have a look at Coffee Script. Ok so as I understand my code, I created a promoSlides object, I a private function called init and in the return of a js closure (which I am not too familiar with) I returned init so I can use it outside globally kind of. When I run the file I get promoSlides is undefined, says error console of FF. I am not sure where I went wrong. I am new to this so probably something is wrong. Oh and slides was defined in my original doc but I took it out for simplicity sake var Slider = (function (name) {return name;}(Slider || {})); Slider.promoSlides = ( function() { var slides; var init = function(s) { slides = s; sortSlides(); startTimer(); addListeners(); }; return { init : function a(s) { init(s); } }; })(); $(document).ready(function(){ Slider.promoSlides.init(slides); }); Semicolon insertion strikes again! return { init : function a(s) { init(s); } }; needs to be return { init : function a(s) { init(s); } }; This is a result of a "feature" in JavaScript that looks at your line with just return on it, and says: "oh, you forgot your semicolon, I'll add it for you." It changes return to return; so your function now returns undefined, and then you have some naked JSON sitting below it, which is the source of your error. Douglas Crockford actually describes this as one of the "awful parts" of JavaScript. So the moral of the story is: always put your opening brace on the same line when you're coding in JavaScript. function wrapper() { var $R = {}; $R.expandFont = function (direction, max_time) { // wtf? $R jslint error var self = this, el_prim = self[0], $R = {}; alert(direction + max_time + el_prim + $R); }; } This snippet gives error: line 573 character 13 '$R' is already defined. I think it is clear that it has not been previously defined. $R was defined in the outer scope, but this should not be relevant. I should be able to define a local variable with the same name as JavaScript ( the language ) is function scoped. Yes, I know it is not block-scoped, but it is function scoped. It is basic scoping rules. What gives? Is this a jslint bug? I think that your understand yourself, that if you rename $R in outer or in inner scope of the function the JSLint "error" will be fixed. I decided to write my answer only because I think there are misunderstanding about the goal of JSLint. It's not just a tool which helps you to find errors from the point of view of JavaScript language. You can consider the tool as AddOn to the book JavaScript: The Good Parts. Douglas Crockford tried to show which constructions of the language could be misunderstood by people which read the code. Some from the potential misunderstandings he declared as "warnings", another as "errors". Some from the "warnings" or "errors" can be suppressed by comments like /*jslint ... */ another not (like declaration of var inside of for-loop header). The choice which potential misunderstandings should be interpret as a "warning" and which one as an "error" is very subjective and represents only the personal meaning of Douglas Crockford. I'm not always agree with recommendations of Douglas Crockford, but the warning ("error"): '$R' is already defined I would personally find also as critical because of difficulties to read such code. I would recommend you to rename one from $R variables too. I want to emphasize one more time that the goal of such changes not fixing of an JavaScript error, but improving of readability of your program for other people. By the way I would recommend you to use variables with all capital letters only on the top level ( $R looks so, independent from the first $ letter). See the last sentence of the JSLint recommendation about the naming convention. Why in javascript if you reference objects method to some variable it loses that objects context. Can't find any link with explanation what happens under the hood. Except this one which states: ‘this’ refers to the object which ‘owns’ the method which doesn't seam to be true. var Class = function() { this.property = 1 } Class.prototype.method = function() { return this.property; } var obj = new Class(); console.log(obj.method() === 1); var refToMethod = obj.method; // why refToMethod 'this' is window console.log(refToMethod() !== 1) // why this is true? var property = 1; console.log(refToMethod() === 1) From Douglas Crockford's book JavaScript: The Good Parts The Method Invocation Pattern When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object. If an invocation expression contains a refinement (that is, a . dot expression or[subscript] expression), it is invoked as a method In your example method invocation pattern is console.log(obj.method() === 1); and this in this case is bound to the object "Class" and it works as you expected. The Function Invocation Pattern When a function is not the property of an object, then it is invoked as a function: var sum = add(3, 4); // sum is 7 In your case var refToMethod = obj.method; // why refToMethod 'this' is window console.log(refToMethod() !== 1) // why this is true? refToMethod is bound to the global object "window" in this case You can find more information about this at JavaScript “this” keyword. as a developer with OOP background(c#, Java) OOP JavaScript is wild horse for me. I am trying learn nuts and bolts of language and then jump on libraries (Am I wrong?); so, I checked dozen of books/tutorials about objects, functions...etc..learned several ways to create objects but syntax used in almost every JS library confuses me. namely var Person = Backbone.extend.Model({ //pretty complex staff }) what is Model behind the scenes? object? function? Welcome to stackoverflow, I strongly advise you to have a look at Douglas Crockford's Website and there are also insightfull videos in YUI Theater - start with the ones of Douglas. He's the one who discovered JavaScript has good parts. I also found John Resig's Secrets of the JavaScript Ninja very helpfull for grocking the language (John is the creator of the omnipresent jQuery Library). I would further advise you to look at some libraries (and their code - that's how I learned it - just start with jQuery). There are a ton of other libraries out there but one step at a time :-). Now to your question: The Backbone.Model is a constructor function, normally you would use it like in Java new Backbone.Model({ configOption: true, ... }). But juicy as JavaScript is it allows you to do crazy things under the hood. For example you can implement your own OOP Class implementation or you can program in a functional style like you would do in Scheme or Lisp. What you see here is Backbone's own subtyping wrapper in action (virtually any decent JS library provides some way to do this). The code is actually doing something along the lines of this: // Creating a sub type of the Backbone.Model *class* - it's not really // a class like in Java or C# but rather a (constructor) function. var Person = Backbone.Model.extend({ defaults: { hasTheOneRing: true }, initialize: function (hasTheOneRing) { // Note that Backbone is implementing getters/setters // under the hood so you can listen for change events later this.set('hasTheOneRing', hasTheOneRing); } // More configuration ... }); // Person now is a constructor function that creates instances // of it's *class* when you create an object with it var frodo = new Person(true), sam = new Person(); // Note that you can supply as many arguments as you wish // Frodo has the ring console.log(frodo.get('hasTheOneRing')); // Sam doesn't have the ring (well not all the time) console.log(sam.get('hasTheOneRing')); // In plain old JavaScript the sub typing mechanism works a little bit like this: // A constructor function is just a function function Person() { // JS doesn't have the notion of *super* or *base* but you // can emulate the behavior as many libraries do in the wild Backbone.Model.call(this); } // The prototype of a person is based on that of a Backbone.Model Person.prototype = Object.create(Backbone.Model.prototype); // Object.create has not been there since the beginning. After // Douglas Crockford discovered the good parts this function // has been adapted into the standard portfolio of every modern browser // what it does is essentially just: function create(object) { // There's actually more going on in here but you get the idea function F() {} F.prototype = object; return new F(); } // So this means almost the same Person.prototype = new Backbone.Model(); My way of getting to love JS was to read library code - and Backbone is open source so have a read and be amazed by the awesomeness g. I think the fact that JS is just plain text send over the wire had a big influence on the language getting that strong in the ecosystem, even Microsoft couldn't stop it. Give the language a try, when it clicks you'll most likely actually begin to like it :-). Happy coding! Being a web developer I have noticed that anything I create works absolutely great in all browsers, but always always always has a speed issue in Internet Explorer. Please note I am referring to speed, as I always take care that it displays and works across all browsers. Is there anywhere, or does anyone have, good programming tips for internet explorer? I mean how to do things, so as that it's more or less optimized for internet explorer. I mean my latest example is that I return JSON data from DB (via AJAX) and then I build the page with the results. The response from the server is minimal, and it loads instantaneoulsy in aaaaall browser, but takes 5-10 seconds in internet explorer depending on OS and ie version. I am lost for words, and I was just wondering if there's anything I can do. Examples: -theo Javascript performance in IE is currently the worst among all of the popular browsers. The suggestion to use IE as your baseline for performance is well grounded. I'll add that using an accepted js/ajax library (jQuery, YUI, etc.) will ensure a lot of browser-specific optimizations have been done and heavily tested for you. If you are doing a lot of custom js in your web application and are just looking for some best practices, I can recommend a few websites: jspatterns.com, IE + JavaScript Performance Recommendations. This is a good chance to plug Douglas Crockford's Javascript: The Good Parts for general js zen. Hey everyone I just purchased the book JavaScript demystified to read and learn JavaScript but I just noticed that it was published in 2005 and it references netscape browsers and other "pratices" I believe are out dated like using the language attribute in the script tag and also not ending each line with a semicolon My main question is has javascript changed so much since this book was published that reading this book not teach me what I need to know or could it still be a good reference? Yes, the language has changed way too much in the past 6 years. All those changes I'm talking about here come along with ECMAscript edition 5 which is now pretty much available in any browser. If that is not covered in the book (I doubt it) its only good for the basic Javascript syntax. However, there are "oldish" books which also do not cover ES5 but still are great to understand the language. I don't know the book in question, but still a hot candidate is "Javascript - the good parts" by Douglas Crockford. Again, the basic Javascript syntax has not changed all that much, but there are TONS of new native methods / techniques which really are the future of this language. I am a C/C++ programmer with more than 10 years of experience. I also know python and perl, but I've never used this languages for a web development. Now for some reasons I want to move into the web development realm and as part of that transition I have to learn css, javascript, (x)html etc. So I need an advice for a good sources of information for such topics. For a while I don't want to read lengthy tutorials, I want something quick and dirty, something to start with. Since you are an experienced programmer, a good place to start with javascript might be Javascript: The Good Parts by Douglas Crockford. It is a brief but thorough tour of, well, the best parts of javascript (and pretty much all you'll need for quite a while). Your approach to CSS and HTML will have to be very different. I suggest trying to make a static site or two, checking reference material if you get stuck. Pick a site that you like, and try recreating the basic layout in HTML. Got the layout? Try making it look pretty. Repeat. I am beginner in javascript. my usage for javascript is for server side applications. e.g. Node.JS but wherever i see any tutorial/example for javascript it always starts with html tags, script tags, invoking browser window functions etc. e.g. <!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayDate() { document.getElementById("demo").innerHTML=Date(); } </script> </head> <body> <h1>My First Web Page</h1> <p id="demo">This is a paragraph.</p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html> Where can i find a javascript tutorial which only teaches the language, not the webpage/browser usage of it. I want to know language aspects like regexp in JS functional prgramming in JS any good javascript design patterns (if there are any) program structure in JS in general Thanks a lot. Vimal If you're new to Javascript, you should start with the book Javascript: The Good Parts by Douglas Crockford: That will give a great and concise introduction to the language. If you're starting with node, it might also be a good idea to check out Express JS which has a pretty good guide, and you get to work with a higher level API: Note that you'll also miss out on some of the great low level action, using Express :) i am just finished college and worked with the java language for the past few years. i want to change, what do you guys think is the most usefull web development language to use? what would you guys recommend for me to learn rite so guys u have all explained a different language, lets say i would like to create a file sharing web service, if i was to develop in one language for the client side, how could i use a different language server side? how could i get them to interact? Javascript - You need to work on the client side. I suggest the book Javascript The Good Parts. Javascript is also an interesting language due to its prototypical nature. If you want to do Javascript on the server side, look at node.js, which is interesting due to code reuse possibilities. Python - Multi-faceted language with great web toolkits. Not as expressive as other languages (doesn't match the DSL capability of Ruby), but clean and expandable. Look at Pylons, Django, CherryPy. Perl - Perl web applications work great, even if the language isn't "cool". Mason, Template Toolkit are contenders. Ruby - Rails is a great RAD framework. There are questionable practices galore (monkey patching), but they don't ruin the platform from a usability point of view (maintainability on the other hand...). If you don't want rails, there are minimal Ruby web frameworks as well. PHP - Tragedy of the commons. It works, its installed everywhere, but the language and runtime is terrible. Factor - Be non traditional, use concatenative languages! Smalltalk - Seaside is fun to use. Common LISP - UnCommonWeb is a great continuation style web framework. Erlang - This language is fantastic for its integral hot reloading and high availability features. You can also use the built in database (Mnesia) or CouchDB. Scala/Groovy/Clojure - More JVM languages to try, to stay true to the Java platform. The most interesting language in that grouping is Clojure. C/C++ - Why not, it works, and can be fast. Bourne Shell - Perl with less features. C#/VB.Net/Other CLR language - An easy jump from Java in terms of model. Good RAD support in in ASP.NET MVC. Using all of ASP.NET restricts you to Windows only (Mono is good, but not 100%). Drinking vendor kool-aid is always fun. ColdFusion - When just Java and all of the inherent flexibility is not enough, throw in some bizarre database table to website middleware. It works just as well as the ColdFusion reactor on my desk. I found one interesting project on github which deals with pdf rendering in the browser. I tried to read the code because I'm interested in this topic but I realized that my javascript knowledge is poor (insuficient). There are constructs like: var Obj = (function() { function constructor(type, value) { this.type = type; this.value = value; } constructor.prototype = { }; var types = [ "Bool", "Int", "Real", "String", "Name", "Null", "Array", "Dict", "Stream", "Ref", "Cmd", "Error", "EOF", "None" ]; for (var i = 0; i < types.length; ++i) { var typeName = types[i]; constructor[typeName] = i; constructor.prototype["is" + typeName] = (function (value) { return this.type == i && (typeof value == "undefined" || value == this.value); }); } constructor.prototype.lookup = function(key) { function lookup(key) { if (!(this.value.contains(key))) return Obj.nullObj; return this.value.get(key); } } Object.freeze(constructor.trueObj = new constructor(constructor.Bool, true)); Object.freeze(constructor.falseObj = new constructor(constructor.Bool, false)); Object.freeze(constructor.nullObj = new constructor(constructor.Null)); Object.freeze(constructor.errorObj = new constructor(constructor.Error)); Object.freeze(constructor.prototype); Object.freeze(constructor); return constructor; })(); You can see more of them in the link above. Could you please advise me some resources which to study to be able to understand the code in the project with ease and even better to contribute later to the project? Douglas Crockford's book JavaScript: The Good Parts is a great place to gain an appreciation of the power in JavaScript, while steering you away from the ugly (or downright dangerous) parts. His website also has a collection of interesting articles about the language. I recommend both. I have some experience in ASP.Net and can work my way around it without much trouble, however there are a lot of gaps in my knowledge of asp.net and .net in general. I know the basics of c# and asp.net so I can accomplish most things. But I don't know anything at all about LINQ, Entity Framework, ADO.NET, delegates, ASP.NET Ajax, ASP.NET MVC, Providers, the different api's provided with asp.net (such as membership), the default controls that come with asp.net as well as the normal patterns used to create rich, stable and high performance asp.net sites. The list goes on and on.... I have really been wanting to upgrade my skills now and become a well rounded .net developer before I get left too far behind in the curve. I also have been meaning to look into ASP.NET MVC partially because I`d like to extend an open source project. The problem is every time I get down to learning I get too overwhelmed. I dont know where to start, whats relevant, whats not. I basically need to figure out in what order should I be approaching all these different things and tackling them? Should I get down with one of those monstrous asp.net 3.5 books (such as asp.net unleashed...1500pages) and read it from start to finish? And then pick up some book on ASP.NET MVC? Do I need to actually read such books from start to finish or are there topics I can safely skip? Sorry if the question is badly worded but I think my problem should be evident. I feel .net is evolving very fast and I am getting left behind more and more. Aside from that I really want to be a good asp.net developer because web development is somewhat of a passion of mine. Books I currently have in my possession... Building a Web 2.0 Portal with ASP.NET 3.5 Pro ASP.NET 3.5 in C# 2008 Javascript: The Good Parts Pro C# 2008 and the .NET 3.5 Platform To echo what others have said, you have to write code. However, don't stop moving forward when you hit a wall. If you're stuck on "the best way to do X" (best practices) either look it up if it's simple enough, or pull it off to the best of your knowledge THEN look it up and either go back and refactor it, or the next time you come across it implement it with the new techniques you've picked up. As for what to learn and the order to do so, I suggest focusing on what you feel you really want to pick up OR what you think is going to be the most relevant and applicable to your job. Granted, you might not work somewhere that is constantly using the latest technology, in which case you'll need to learn things on the side through some mini-projects. There's a lot out there, so narrow it down. Another suggestion would be to start a simple project and decide to implement parts of it using a particular technology. So, for example, you might pick LINQ to SQL or the Entity Framework for your data access side. Then pick AJAX or jQuery to verify a form using simple validation. Store some data in XML and read it using LINQ to XML. LINQ to Objects opportunities are many with in memory collections, string parsing, etc. In other words think small and implement some items with a particular technology and you'll touch upon many things. From there you can begin to expand your scope and may decide to explore a particular technology further and do more with it. I agree with David Basarab's recommendation for the free ASP.NET MVC ebook. In addition, be sure to check out the site. There are many videos and the StoreFront series is a well known example to follow along with. I'm a beginner w/ Javascript. I'm looking at the following code that someone else wrote: function MeetingPage() { MeetingPage.colors = new Object(); } ... var meeting = new MeetingPage(); From what I've seen, I believe that the MeetingPage function creates an object that later someone holds onto in meeting. What is the MeetingPage.colors? Is the MeetingPage prefix some kind of global? Is it a "this" pointer of some kind? Any suggestions would be appreciated. This talk was really helpful when I got into different object patterns in javascript. Example code is included in the second link (the video introduces it). Of course, you should also definitely read HTH I must apologize if this is a duplicate question, but I can't seem to find one close enough to what I'm asking. I'll happily close this one if someone can point me to the duplicate. Just for some background. I'm a developer that started in the .NET space with WinForms. While I did do some WebForms work, most of that work was spent very much in the classic Postback style of WebForms development and firmly routed in that particular abstraction. I very quickly found myself in the XAML world (primarily Silverlight). All of that is to say that all of my web development work has been primarily in a particular abstraction, with little or no "Close to the Metal" type work. I have very briefly looked at the Microsoft ASP.NET MVC stuff and found it very interesting, but it had to be put on the "back burner", while I focused on the things I worked with day-to-day. I finally find myself in a place where I have enough time and determination to work with technologies (like MVC) that allow me to reach outside of those pre-made abstractions. The challenge is, that with all the time spent there, I don't know what I don't know. So, to the true question. Can anyone recommend some good resources as a starting point for learning the technologies involved. I understand that I'll nee to brush up more on good HTML markup, JQuery, maybe an MVC framework or two. But also, where do I go to learn, what I as as a developer should understand about the HTTP Protocol, headers, etc...? Where can I go to learn what other base level technologies I should understand (as in what they even are) if I want to work in this more granular fashion? I cut my teeth in a Microsoft-centric space, and while working from that perspective may speed things up for me, I don't feel like using JUST those tools is a requirement by any stretch. I truly hope that the question makes sense and is able to properly explain what I'm asking for. I have had difficulty articulating what I'm trying to understand. I very much feel that there are holes in my knowledge, that I'd like to fill. I'm just not certain I understand what and where those holes are. Thanks in advance for your anticipated support. Cheers, Steve You are definitely on the right track... but a couple points.. Don't work with jQuery until you learn the javascript language, it has many nuances that can easily trip up experienced classical programmers like yourself. I recommend Javscript: The Good Parts. Not to mention to stay true to you're commitment to learn "Close to the metal" Web Development... Understanding that the HTTP model is stateless is BIG... ASP.NET WinForms tries to give the developer a state-full experience, which is going directly against the grain of the web. Request > Response... no persistent state is retained. With the rise of RESTful web services really learning the HTTP model is a big help going forward. MVC is essentially the industry standard and Microsoft has finally came on board. MVC3 is good and is leaps and bounds an improvement over WinForms, but still has that bloated feel. I would recommend PHP's Codeigniter as a good starting point... they don't do a lot of magic for you and you really learn a lot while using it. The PHP syntax is a bit verbose for my taste, but it should be fairly similar for you coming from a C based lang background. I actually found myself in the exact opposite recently, going from a more "close to the metal" approach to (through work) moving to the ASP.NET Winforms model... really frustrating experience... <script type="text/javascript"> function CustomAlert() { this"; } this.ok = function () { } } function HighScore( arg ) { CustomAlert().render(); } </script> Why is it telling me that CustomAlert is undefined? I also attempted to assign CustomAlert() to a var but then the console tells me that the var is now undefined. Why is it telling me that CustomAlert is undefined? I also attempted to assign CustomAlert() to a var but then the consol tells me that the var is now undefined?? Because you should create an object of this var customerAlert = new CustomAlert(); and then call the render method of it. Or in one statement: function HighScore( arg ) { new CustomAlert().render(); } This is called the Constructor Invocation Pattern. Actually in JavaScript functions can be invoked with one of the following ways: Method Invocation pattern This method of invocation is used when the function is stored as a property of an object. Hence we call this function a method, like in other object oriented languages. When we call the function this is bound to the that object. For instance: var app = {"; } ok : function () { } }; In this case we would call the render method as below: app.render(); Function Invocation Pattern This is the case where the function is not the property of an object. In this case the function is bound to the global object -which usually is the window object in web applications-. var"; }; Then we just call it as below: render(); Constructor Invocation Pattern This is the case where we invoke a function with the new prefix. In this case a new object will be created. It is a good way to create object with the same properties. These functions are called constructors and by convention their names starts with a capital letter. Apply Invocation Pattern The apply method give us the opportunity to construt an array of arguments that will be used for the invocation of the function. Furthermore, it give us the ability to choose the value of this. For more information on the above, please refer to JavaScript: The Good Parts The variable value is not correctly set inside getJSON function. The variable $videoId displays 396 and 397 as expected in the first Alert. But in the second alert, the value 397 is displayed twice. Am I missing anything here? I could not find any other post here discussing this kind of issue. If so please point me over there. Below is the jQuery code. $( "div .ow_video_list_item").each(function(){ $videoId = $(this).children("a").attr("href").split("/")[5]; alert($videoId); ==> First Alert $.getJSON("video/get-embed/" + $videoId + "/", function (data) { $.each(data, function (key, code) { alert($videoId); ==> Second Alert }); }); }); Below is the HTML code: <div class="ow_video_list_item ow_small"> <a href="">Video 1</a> </div> <div class="ow_video_list_item ow_small"> <a href="">Video 2</a> </div> A couple things. <a href="" data-Video 1</a> That way you can access that video id easily with $(element).data('videoId'). There are other strategies for this, like using classes. If $videoLink is NOT supposed to be $videoId in your code sample, then $videoId is defined somewhere outside of the scope of that function. There are lots of resources out there about scope/closures in JS. If you are doing a decent amount of JS dev work I would suggest Javascript: The good parts. Going back to assuming $videoLink is actually $videoId in your code sample. You are assigning it's value inside of that .each loop BUT that variable itself isn't "closed" inside of that function. It's either global, or defined somewhere else outside the scope of that each loop. throw a var in front of the $videoLink = statement to keep that var contained. Another potential issue is that you are calling an async call to the server, but depending on a variable outside of the scope of that async call. Most of the time these calls will be milliseconds, but a good way to understand what is going on is to mentally step through the code and pretend that each server call will take 1 minute. In your example the outer loop runs through once, gets the id of 396 then fires off an AJAX request, then loops again and does the same thing for id 397. The server hasn't responded in the time it took for the 2nd ajax request to fire off. So you have 2 ajax requests hanging out now. A minute later they come back and oh look, your $variableLink variable has the value of 397 because it was defined outside of the ajax callback function. Solutions to this? There are a few. You can use some data you get back from the server for what you need or you can keep an array/hash of potential videos being accessed from the server. There are other ways to do it, but without knowing the exact use-case of what you are trying to do beyond tracking that variable it's hard to say. But this should give you a good starting point for it. This is from Crockford's JavaScript: The Good Parts var is_array = function (value) { return Object.prototype.toString.apply(value) === '[object Array]'; }; Would this code have worked just as well if he had used a simple equality compare == instead of the identity compare ===? My understanding of identity is that it allows you to check if a value is really set to something specific, and not just something equivalent. For example: x == true Will evaluate to true if x is 1, or true, but x === true will only be true if x is true. Is it ever possible for the is_array function above to work with either == or ===, but not the other? In this particular case == and === will work identically. There would be no real difference in this case because both sides of the quality test are already strings so the extra type conversion that == could do won't come into play here. Since there's never any type conversion here, then == and === will generate the same result. In my own personal opinion, I tend to use === unless I explicitly want to allow type conversion as I think there is less likelihood of getting surprised by some result. Possible Duplicate: What is tail-recursion? What is tail recursion optimization? In JavaScript: The Good Parts, Crockford says, "Some languages offer the tail recursion optimization. This means that if a function returns the result of invoking itself recursively, then the invocation is replaced with a loop, which can significantly speed things up." Possible Duplicate: JavaScript Variable Scope I am (obviously) pretty new to Javascript, and I've seen several different points on other threads about the usage of Global and Local variables, but I'm trying to lock down some basic points on the subject in one place. What is the difference between the following, declared outside (or used inside) of a function? var thing = 1; thing = 1; I understand that using var declares the variable in it's current scope. So leaving out var makes it global. What are some pitfalls that can show up? Could someone give a simple example of where variables might step on each other in this case? Thanks in advance. Unlike many C-style languages, JavaScript supports block syntax but does not support block scope, so the following may not run as you would expect: var foo = 'bar'; { var foo = 'baz'; } console.log(foo); // 'baz' This is also evident in other JavaScript constructs that support blocks like if: var foo = 'bar'; if (true) { var foo = 'baz'; } console.log(foo); // 'baz' Moreover, as Bergi pointed out, your i counters for fors will override each other because a for will not create a new scope. Crockford considers JavaScript's lack of block scope an "Awful Part" of the language. Instead, JavaScript has lexical scoping, so only functions will create a new scope: var foo = 'bar'; (function() { var foo = 'baz'; console.log(foo); // 'baz' }()); console.log(foo); // 'bar' Every function in JavaScript has access to the variables in the function that contains it; inner has access to outer, but not vice versa. In the case of the above example, the IIFE (immediately-invoked function expression) has access to the foo = 'bar'; defined in the global scope, but instead we choose to override foo with a local var declaration and set it equal to 'baz'. Bonus Point: Shog9 found that with can simulate block scope with an object literal like so: var foo = 'bar'; with ({foo: 'baz'}) { console.log(foo); // 'baz' } console.log(foo); // 'bar' Crockford discourages with due to its ambiguity, but if you really desire block scope, I see no harm in the with workaround. Can someone suggest good learning materials or websites to learn JavaScript and jQuery? Am pretty new to this and want to learn right from basics. Thanks in advance, Geetha My recommended reading list JavaScript JavaScript - the Definitive Guide Pro JavaScript Techniques JavaScript - the Good Parts Object Oriented JavaScript Secrets of the JavaScript Ninja jQuery I also recommend JSBin for testing and trying out ideas The following sites are also useful JavaScript Mozilla JavaScript Reference jQuery How do you manage Javascript content on a larger website? I'm especially struggling with various $(document).ready()'s and the fact that I need to juggle all those id ($('#id')) strings. I thought of combining the necessary $(document).ready() with each "module" that uses them but this results in visible speed degradation as I don't have my javascript at the bottom of each page anymore. What is a good way to manage Javascript of a fairly large site efficiently and keep it easy to maintain? If you are looking for a good resource on writing good and clean JS, you might want to look at Douglas Crockford's book JavaScript: The Good Parts as it contains many useful resources including tips on how to structure code well. When I write apps which have a lot of JS, I typically create a single object (so as not to clutter the global namespace) and then divide it into sub objects which contain various bits of application data and behavior. A small example: var PandaApp = {}; PandaApp.setup = {}; PandaApp.setup.init = function init() { // do something neat }; PandaApp.utils = {}; PandaApp.utils.showMessage = function showMessage(msg) { // do some jQuery goodness or something }; That way I have exactly one global object with all of my data in it and everything is neatly-namespaced in a manner of my choosing. I am creating a custom object to be used in some internal applications where I work. I researched some ways to go about doing this - and this is what I came out with. function ISGrader(text) { this.text = text; this.printInfo = function(){ alert("Object working " + text); } this.putGrade = function(score) { alert(score); } } I believe this shows constructor-type functionality, as well as some simple starter methods that I will build on. Is the above good practice or is there another way that is more standard? While not really an answer, I recommend Douglas Crockford's book JavaScript: The Good Parts as it does a good job of introducing you to the "good parts" of the language and discusses the pros and cons of the different ways to create objects in JavaScript. You can also review this resource if you're just looking for an explanation of member visibility in JavaScript objects: i am new of javascript, i have been told by someone, he said "speak strictly, javascript doesn't have multidimensional Array and associative array ". but in a book, i saw the following var my_cars=Array(); my_cars["cool"]="Mustang"; $a=Array(Array(0,1),2); so the opinion form he is wrong? am i right? JavaScript has arrays of whom their elements can be other arrays. However, JavaScript has Objects with properties, not associative arrays. []is much better than Array(). Also, why not instantiate an Arrayobject explicitly then rely on Arrayreturning a new object? coolon the Array. $asigil? Why no newoperator again? I just decide to learn backbone.js. I am a between junior and intermediate level front-end developer. my current job is dealing with html, css and jQuery. My boss asked me to learn this backbone.js and want to know how long it gonna take me to learn. so can anyone who experienced before tell me how long it gonna take? thank you If you don't know javascript, it will take awhile. I know this because I didn't really understand javascript when I got started with it. By know javascript, I mean being able to understand and fully explain: If you don't know all that, get and read Crockford's Javascript: the Good Parts If you do know all that, then you need to understand how to use Backbone properly otherwise it won't make any sense. When using Backbone, you really shouldn't have any non-backbone javascript outside of a sparse initialization of your base Views...also learning how to use the built in event binding is essential. This is a pretty good guide, as (obviously) are all the sources here So I would say it could take a few days to a week or longer to fully comprehend whats going on, and much longer to get to the point of being very skilled with it. I'm spending a lot of time to learn how OOP is implemented in Javascript as in ECMA 262 of 1999: now I want to know if someone think that the new JS 2.0 will arrive soon and I'am studying uselessly because with this new version will be the OOP implemented in a classical way (Java etc.) and will be interfaces, generics and other classical languages features... So do I must stop and wait...........????? Thanks I would highly recommend you learn JavaScript as it is. Whatever changes may come, you'll still be forced to deal with the historic usages sooner or later, and probably very often if you are a web developer. I would also recommend Crockford's JavaScript: The Good Parts, as it covers all modes of inheritance and strips away the bad stuff you shouldn't use. I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery? I see that jquery 1.4 has been released. Does this change anything w.r.t answers? Well python is a language and jQuery is a framework, so I'll give you one for javascript and then you can move to jQuery: This book should be a required read for front end devs: JavaScript: The Good Parts by Douglas Crockford Then: This one is a pretty awesome dive into all the different aspects of programming real world applications with jQuery, whereas "Dive into Python" and "JS The Good Parts" are more like poignant language overviews. I've been learning Js recently from "JavaScript the Good Parts", and according to my understanding Object.propertyName yields same result as Object["propertyName"](Please correct me if I'm not right and describe the difference of the two). I'm trying to augment the Function.prototype to make a method available to all functions as below: Function.prototype.method = function (name, func) { this.prototype[name]= func; }; And it's working fine.However, when I'm replacing the this.prototype[name] with this.prototype.name, it'll fail functioning as expected! This is how I'm testing it: Number.method("myRoundFunction", function () { return Math[this < 0 ? "ceil" : "floor"](this); }); console.log((-10 / 3).myRoundFunction()); This shows the expected value (-3) when using this.prototype[name], but (-3.3333333333333335).myRoundFunction is not a function on changing it to this.prototype.name Could someone possibly clarify why this is happening? Thanks in advance for any help. What's happening is that name is a variable, and cannot be used directly with dot notation. To better illustrate the issue, let's say you pass a value of "newMethod" for name. Now when you do: this.prototype[name] = func; ...it is equivalent to writing: this.prototype["newMethod"] = func; But when you do: this.prototype.name = func; ...you are assigning to the name property of the object, and not to the newMethod property. The variable that you passed under the parameter name is not referenced at all in the above statement. The syntax that would preform the assignment you expect is: this.prototype.newMethod = func; But you cannot express that using dot notation and the name variable (except perhaps by cheating and using string concatenation and eval()). In such a case you have to use the array-subscript notation instead. I've been reading through JavaScript: The Good Parts and I'm currently on "Chapter 5: Inheritance." From what I understand, using functional inheritance is preferred because it allows privacy for the properties and variables of an object while still allowing them to be called using methods outside of the object. However, it does seem like there is an advantage for prototypal inheritance because you can create a prototype object fairly easily (which makes understanding what the object is, to me, a little more concrete). When should I choose one over the other? Should I always use functional inheritance whenever possible? Or are there "better" guidelines that I can follow to make that determination? I've seen very little code that uses functional techniques as the primary form of inheritance. The vast majority I've seen uses prototypal inheritance. It's fast and easy to implement, and seems most natural to JavaScript. That's not to say that functional inheritance should never be used, but I think you'll find prototypal more than sufficient for most applications. Let's not also forget that you can still use some functional techniques within your prototypal inheritance, like giving each object it's own version of a function that closes over a variable in the constructor. So it doesn't need to entirely be one or the other. Most important is to understand the concepts of prototypes and functions/closures. This alone will give you what you need to know in order to make appropriate decisions. I was wondering whether it would be ok to name the variable name for a promise just like the argument passed to a callback: var dbItems = db.find(); dbItems.then(function(dbItems) { // Do some stuff with dbItems here... }); I think that would be syntactically correct, but are there any arguments (like possible confusion or readability) against using this from the perspective of code style? var dbItems = db.find(); dbItems.then(function(dbItems) { // Do some stuff with dbItems here... }); Is the same thing as writing: var dbItems = db.find(); dbItems.then(function(xxxxx) { var dbItems = xxxxx; // Do some stuff with dbItems here... }); which means that inside the anonymous function, dbItems is a completely different thing, and you do not have access to the "outer" dbItems variable. I don't usually recommend purchases on this site, but I feel that you could have very good use for this book. Maybe is tutorial's, article's, book's or something other to how design Game Engine(-Library, Framework) Architecture in JavaScript(HTML5 Canvas or DOM)? I am searching in Google but don't find. And have one more question: Why one framework's use Anonymous functions in this style(1) and other in this style(2)? 1: var Engine = (function() { var version = '0.0.1'; return { version : version } })(); 2: (function(window) { window.Engine = { version : '0.0.1' }; })(window); Or something like. Which is better? Neither of those are better, they are functionally pretty similar. The second one is guaranteed to attach Engine to window and the first one will only do so if it is executed in the top-level. The second one is used by jQuery and is arguably more common. If you are very new to Canvas, there is the book Foundation HTML5 Canvas: For Games and Entertainment. It is a pretty average book, and only really useful if you are very new to this stuff. It might help you get started though. Designing a good game-engine is a pretty broad and platform-agnostic topic though. If I were you I would seek out articles on designing engines in particular, moreso based on the type of engine you want to make (FPS? Point and click game? Side scrolling game?) How you design it will depend on the type of game a lot more than it will depend on than the language and platform involved. So what I'd really suggest is that you read JavaScript: The Good Parts by Crockford to get an idea of how JavaScript is different from other langauges. Then search the net for more general articles on game engine development, considering the type of game engine over the language. { out = rogueArray[13]; for (var arrayItem in vanWilder) { I'm a noob, so I need help :P This is what I am told on JSLint: Error: Problem at line 52 character 18: Move 'var' declarations to the top of the function. for (var arrayItem in vanWilder) Problem at line 52 character 18: Stopping. (30% scanned). Implied global: requestOne 19,22,25,27, XMLHttpRequest 19, document 29, out 51 Unused variable: evilVariable 25 "onreadystatechange", redBull 25 "onreadystatechange", wildGoose 25 "onreadystatechange", monkeyWrench 25 "onreadystatechange" How would I fix this? If not the second error, the first one at least! Problem at line 52 character 18: Move 'var' declarations to the top of the function. Because JavaScript doesn't have block scope, and variable definitions are hoisted, Crockford recommends you place all variable definitions at the top of the scope. Implied global: requestOne 19,22,25,27, XMLHttpRequest 19, document 29, out 51 Because out doesn't have the var keyword to the left, it will be attached to window, essentially making it a global. Unused variable: evilVariable 25 "onreadystatechange", redBull 25 "onreadystatechange", wildGoose 25 "onreadystatechange", monkeyWrench 25 "onreadystatechange" You must have defined a variable evilVariable somewhere and not used it. Remember, Douglas Crockford is a smart man and his JavaScript book is excellent, but take his word and JSLint as one man's recommendations and not the gospel. :) Regarding this question: What is the purpose of NodeJS module.exports and how do you use it? I'm a Javascript beginner. In the referenced question... mymodule.js code var myFunc = function() { ... }; exports.myFunc = myFunc; main js file var m = require('./mymodule.js'); m.myFunc(); Is mymodule essentially a class file defining objects? Node.js allows code to be separated into different modules. This modules are just javascript files that can expose functions or objects using the exports object. There are no Classes in JavaScript but you can use patterns to emulate that behaviour. There is a question about implementing OOP patterns in JavaScript: what pattern to use when creating javascript class? As a beginner there are very good books for JavaScript: They are short and will give you a very good insight of the JavaScript Language. This isn't as progressive as it sounds. Im not taking the whole "Oh I know Java, that must mean I can write in JavaScript too!" attitude. I have some education on Java under my belt, but now find myself having to do some PHP web development (which I have little experience in) using Java Script to handle some of the logic. But before going out and buying 2 or 3 books on JavaScript and diving right into it, I figure I might ask those that might have gone through the same experience. It appears that JavaScript lives and acts in its own environmnet which makes want to take the approach taking in JavaScript and PHP as a bundled package in my learning endeavors. JavaScript is similar just enough to Java that I will tend to make some dangerous assumptions. Should I treat JavaScript and PHP as one item, or should I still take this step by step and learn one at a time? What are some pitfalls that I might run Into? What are the main differences between the languages? Is there any litterature that has helped? Thanks Everybody. I learned Java script coming from Java myself. I had a bit of trouble with it until I worked with NodeJS a little bit. Learning JS by itself when I wasn`t warring with html and css at the same time made the experience much less painful and made it take less then a couple days. I would really recommend these two books Don`t be turned off by the fact the first book is related to a frame work. The first 250 pages are a fantastic JS basics crash course. Of course you are super comfortable with objects and you can find that in Javascript if you really wanted to and never even learn about prototyping and closures. Take the time though to read into these things there are a lot of timing problems that you really can`t solve any other way with respects to asynchronous actions and animation locks. Research functional programming. The hardest thing about the transition is javascripts wonky syntax at first you will hate it but it does finally catch a rhythm. Which reminds me use Lint a lot that will help you catch your syntax issues early. UPDATE: Perhaps this wasn't clear from my original post, but I'm mainly interested in knowing a best practice for how to structure javascript code while building a solution, not simply learning how to use APIs (though that is certainly important). I need to add functionality to a web site and our team has decided to approach the solution using a web service that receives a call from a JSON-formatted AJAX request from within the web site. The web service has been created and works great. Now I have been tasked with writing the javascript/html side of the solution. If I were solving this problem in C#, I would create separate classes for formatting the request, handling the AJAX request/response, parsing the response, and finally inserting the response somehow into the DOM. I would build properties and methods appropriately into each class, doing my best to separate functionality and structure where appropriate. However, I have to solve this problem in javascript. Firstly, how could I approach my solution in javascript in the way I would approach it from C# as described above? Or more importantly, what's a better way to approach structuring code in javascript? Any advice or links to helpful material on the web would be greatly appreciated. NOTE: Though perhaps not immediately relevant to this question, it may be worth noting that we will be using jQuery in our solution. This is just the sort of thing people use jQuery for. It has Ajax and DOM manipulation covered, so the learning jQuery site and the jQuery docs should help you hack something together. In general, JavaScript is tough to work with because it looks just like a typical Algol-family language, but misbehaves in subtle ways. (For instance, JavaScript does not have block scope.) If you want to invest some time, the basic book to get is Javascript: The Good Parts. The author has some interesting articles at his website. Your design, btw, is perfectly fine, and JS is object-oriented, so you could certainly implement it. JS just does inheritance and encapsulation differently (prototypes and closures, respectively) than mainstream OO languages. This is all covered in adequate detail in the book cited above. As someone who will be working extensively with JavaScript and JQuery, I hear the community is strong so I figured I would ask what a beginner should been keen in understanding when developing mobile applications. Like any other language, I wish someone would have walked in the first day of class when programming with C and said to me, "if you don't learn everything about malloc() and free() today, you will fail!" Or when I was writing with Java and heard that private and static are essential for every function and variable too late. See what I mean about learning the most important so I don't get frustrated with the details later. My current attempt at figuring this question out is reading a book, but like most books, they don't expect you to ask what is the high-level re-occurring concepts. I have used CSS and HTML and have not used scripts or Jquery as much when developing websites. Read "JavaScript the Good Parts" by Douglas Crockford This will give you what you need for JavaScript. I don't know "the best" source for jQuery, but start here: I'd like to implement bit.ly URL shortening service in my application and from biy.ly's API docs I read It uses JSON to short a link... Unfortunately, I never used JSON and I don't know where to start. Can anyone explain me how to implement bit.ly URL shortening service in my application? Thanks, Matteo JSON is just a (Javascript) way to encode you're data in name value pairs in an http POST request. So you just need to use a good encoder/decoder API for you're iphone application. See also this tutorial: tutorial: Json over http on the Iphone Want to know more about how JSON works, this book has an excelent chapter on it: JavaScript: The Good Parts Can any one here suggest a good Dojo and JSON book or a site for tutorials please for a graduate student. Many Thanks! I wouldn't really recommend reading a book since you can get very close to the same content online if you know how to look for it, but if you insist, the definitive guide books are always very helpful (you'll need to purchase two off them though to get info about dojo and json): Javascript: The Definitive Guide will teach you everything you need to know (and more) about JSON, and will prepare you for using frameworks like Dojo, Mootools, jQuery... etc. I own David Flanagan's Most Excellent "Javascript: The Definitive Guide" and I agree - it's a must-have for any Javascript developer. ... however ... The one framework Flanagan covers is jQuery (not Javascript). I'd recommend the on-line IBM Redbooks for Dojo and JSON: Etc. etc And, even more than Flanagan ("The Rhino Book"), I'd very strongly recommend Douglas Crockford's "Javascript: The Good Parts" as a must-have for every Javascript developer: Douglas Crockford makes reference to Simplified JavaScript in this article about Top Down Operator Precedence. Unfortunately he only makes references to it in this article. The best explanation I found here. But I still don't have a clue what it actually is. What is Simplified JavaScript? This is probably a reference to Crockford's book Javascript: The Good Parts. In this book, he describes which features of Javascript he feels are "good", as well as those that are "bad" and shouldn't be used. First what i mean by patterns.. Basically in Js there are multiple ways to do something but some ways of doing things offer greater benefits in terms of portability, performance, modularity, and extension. One of the patterns i like most are of jquery. But when writing my own code i feel urge to just keep on writing function after function...and i don't want to create an object just for the sake of organization. There should be a reason like reusability for object to be created. I want to learn patterns that make more use of closures, prototype, objects and chaining. So i can write better code. I know keeping code simple is best but when things are wide spread keeping code less intrusive and reusable is maybe more important. I watched this Google talk a few weeks ago and was inspired to read Crockford's entire book, "JavaScript: The Good Parts". Watch the talk and I think you'll find it's exactly what you're looking for, full of best practices for using closures & prototype. It's a little old and just covers core JavaScript, nothing about JQuery, ect. but if that's what you're looking for, this is your book. I am about to move to a job where I will be doing front end web development (mainly CSS and jQuery). What are good resources (books, websites, blogs etc.) for learning more about those technologies in particular and anything front-end web development related (good technologies to know, user interface ideas etc.) in general? Thank you! ETA: Just to give some idea of where I'm holding, I have about 1.5 years of experience in web development. So I already have a pretty good grasp of CSS and know the basics of jQuery. I also know a fair amount about user interface design. i assume you will also be doing HTML since this is at the core of FE dev. HTML, seems simple and is easy to ignore as a technology, but you should not turn your nose up to it. Writing terse, clean and semantic HTML is a skill and requires lots of learning and practice just as CSS and JS. Right, now onto things you actually requested :) For jQuery i would definitely consider learning as much as you can about JavaScript proper. Whilst you can write jQuery without knowing all that much about JavaScript, you need to understand JavaScript to make the most of jQuery and write better code. And of course to know when you can get away with using plain ol' JS. hope that helps in your quest into front-end development! I am new in Javascript but I did a lot of C#, VB.NET and Java programming that those languages are fully object-oriented. It seems Javascript cannot support all OO features. I am looking for a Javascript object-oriented syntax reference. What should it include is Read Javascript, the Good Parts by Douglas Crockford, and you will get what you are looking for. Books Videos On Stack Overflow Others I am new to JavaScript and am trying to learn how to upload images on my screen and then swap it. The way I manage it is using the following code: for(i = 0; i <= 5; i++) {"); } However, I want to learn how to use an object orriented way to do it and work with objects, but I found it very difficult to make it work. How to use OO? Using OO, I want to use an array of 3*3 size and swap the images on mouse click. OOP with JavaScript is a bit different. Like you, I'm relatively new to this topic so I have been trying to teach myself over the past couple of months. I would recommend reading over some of the articles posted by the other users as well as some of these: You didn't really specify what exactly you wanted to do with OOP in terms of code, so I can't really provide specific code, but I highly recommend reading these articles and others that you find on the web to get a general idea of what JavaScript is like, how it works with the DOM, and how it is related to OOP. I hope this helps. Hristo I am working on a small JavaScript application that will users to click on buttons on the page and pass it through to thier basket. The problem I have with doing this is I am unsure as to handle multiple buttons within the same function. I do not want to have to write out different functions for each button. I am trying to do it OOP and have this so far: var shop = {}; shop.items = []; shop.Item = function(item, description, price) { this.item = item; this.description = description; this.price = price; }; shop.print = function() { var itemCon = document.getElementById('items'),'; for(prop in this.items[i]) { html += '<p><span class="title">' + prop + '</span>: ' + this.items[i][prop] + '</p>'; }; html += '<button id="' + this.items[i].item + '">Add to Basket</button>' html += '</div>'; }; itemCon.innerHTML += html; }; shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20"); shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20"); shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20"); shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20"); var basket = {}; basket.items = []; basket.Item = function(item, description, price) { this.item = item; this.description = description; this.price = price; }; basket.add = function(data) { this.items[items.length] = new Item(data.item, data.description, data.price); }; basket.costCalculate = function() { var cost = 0, html = "Total: " + cost; for(var i = 0; i < this.items.length; i++) { cost += items[i].price; }; return html; }; basket.print = function() { var output; for(var i = 0; i < this.items.length; i++) { for(prop in this.items[i]) { console.log(prop + ": " + this.items[i][prop]); }; }; }; function init() { shop.print() }; window.onload = init; How would I determine what item has been clicked in order to run basket.add(data). How would I also pass through the data to that function for each item. Also how would one go about implementing closure? I understand that it is inner functions having access to the variables of the outer functions, is what I am doing working with closure so far? Okay, you've made a pretty good start but here are a couple suggestions: It's probably a good idea to only have one instance of each Item. By that I mean it looks like you create a bunch of Items for to populate your shop's inventory, so for example: var coat = new Item("Coat", "Warm", 20); shop.items.push(coat); Now when you click on your UI element, you ideally want this same instance of coat to go into your basket as well, so: // User clicks on UI element, which triggers the following to execute: basket.add( someItemIdentifier ); So now if you ever decide to increase all your prices by $10, you can simply do: shop.increasePricesBy = function(amount) { for(var i = 0; i < shop.items.length; i++) { shop.items[i].price += amount; } // execute some function to update existing baskets' totals }; I hope this makes sense for why there should be one instance of each item that multiple collections refer to. This begs the question how you can tie the customer's interaction to adding the correct item. One solution could be to use arbitrary IDs to track items. For example: // Create new item with some randomly generated ID var coat = new Item({ id: "93523452-34523452", name: "Coat", description: "Warm", price: 20 }); shop.items = {}; // Use a hash so it's easier to find items shop.items[coat.id] = coat; And your UI element could be some div like so: <div class="add-product-button" data- Add your click handler: // Pure JS solution - untested var clickTargets = document.getElementsByClassName("add-product-button"); for(var i = 0; i < clickTargets.length; i++) { var clickTarget = clickTargets[i]; clickTarget.onClick = function() { var itemID = clickTarget.getAttribute("data-id"); var item = shop.items[itemID]; basket.add(item); }; } // Equivalent jQuery code $(".add-product-button").click(function() { var id = $(this).attr('data-id'); var item = shop.items[id]; basket.add(item); }); While your basket implements add something like: basket.add = function(items) { this.items.push(item); }; And your costCalculate method gets a whole lot easier: basket.costCalculate = function() { var cost = 0; for(var i = 0; i < this.items.length; i++) { cost += this.item[i].price; } return cost; }; Instead of doing this: shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20"); You can instead do: shop.items.push(new shop.Item("Coat", "Warm", "20"); Probably a good idea to use a number instead of a string to represent the price. In your shop.print loop, you probably don't want to hard code <div id="item"> because that will result in multiple divs with the same id. Finally, I'm not going to try to answer your closure question here because I think that's been answered better than I can already so I'll just link you to some great resources that helped me understand it: Let me know if you have any questions, I'm totally down to discuss them. I have a Struts + Jsp + Java application and I have .js files for javascripting my jsp files. I need to use some (same) constants both in Java and Javascript files. I have defined the constants in my java classes. I also need to have those constants in my javascript files. Is there a way such that I can use my Java constants in my javascript? What is a good practice? Right now, I am defining them twice, once in Java classes and then in Javascript files. At the top of the JSP that includes the .js file, emit a javascript block that declares the javascript constants. For example: <script type="text/javascript> var myConstant1 = <%= MY_CONSTANT1 %>; var myConstant2 = <%= MY_CONSTANT2 %>; </script> This is a very simplistic answer - note that you probably shouldn't really be creating a bunch of global variables in JavaScript - you should create one object that wraps all of your constants (see), but this demonstrates the general concept. I have a medium size legacy php application with almost no javascript integration. I've recently been learning javascript (yes actually learning it) using Douglas Crockfords excellent book and taken YUI as my library of choice. I've tried out a few things and got a few things working but now I want to integrate the various components etc into my application properly, my question is how to go about doing this for ease of maintenance and code reuse. Currently the application consists of I have the following ideas about how to integrate my javascript into the pages. Does this make any sense? Does anyone have a good suggestion for this? Update: One extra bit of info is that its an internal application, so its not so important to restrict everything to a single file. Two other options: Or you can have a hybrid of these: one JS file that contains the vast majority of your code and an extra file if needed for particular pages or templates. None of the approaches mentioned are wrong (though I'd skip the inline JS one as much as possible); which one is best will depend on your precise situation and your personal preferences. I have just started writing my own JavaScript Framework (just for the learning experience), and have prefixed some private members with a _, like such: var _isFireBugEnabled = function () { return (window.console && window.console.firebug); }; When I ran my code against Crockford's JSLint (as always), with Recommended Options on, I was told about not using a _ as an identifier. My question is, Why does JSLint warn me as regards not using a _ as an identifier? Are there some side effects or implications I am missing here? PS. As far as I could scan just now, this is not documented in the book The reason is that Douglas Crockford hates about 78% of Javascript*. Many people think he's a bit strict, and in fact many libraries do use leading underscores in production code. I don't see much wrong with it. There are no side effects. Additionally, the '$', not the underscore, was the symbol set aside for "system" code by the ECMA spec. from ECMA 262, section 7.6: This standard specifies one departure from the grammar given in the Unicode standard: The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code. *Note: I'm being facetious. He really only hates about half, and he typically has good reason. I'd disagree with Crockford here, but he's usually very right. I have started to use jQuery.. I am struggling to understand how the organise the code and how to use it properly. At the moment I am using code similar to: $(document).ready(function(){ alert('all of the jquery goodness here'); $('#div1').click(function(){ /* some manipulation stuff here */ }) }) Is there a better way of having loads of click handlers after the dom has loaded ? Also is there some links to where I can get information regarding code layout in jquery ? I've been looking around source code but cannot find anything useful.. Thanks guys [Edit] Another quick question whilst I remember - Is it bad practice to use something similar to: function clickedevent(){ $('').toggle or other random jquery function } Look into the Module Pattern to write more Object-Oriented javascript. While on that topic, an excellent read is Douglas Crawford's 'Javascript: The Good Parts'. Here is an example of the module pattern with jQuery: window.MyCoolModule= (function(){ var doCoolStuff = function(){ alert("badumpumbishh") } var otherCoolStuff = function(){ alert("someone..moved their..mouse.. all over me"); } var superSecretPrivateFunction = function(){ // come at me bro } return{ somePublicFunction: function(){ //hello, i can be called by other people }, init: function(){ $("#div1") .bind("click", doCoolStuff) .bind("mouseover", otherCoolStuff) $("#div2") .bind("click", superSecretPrivateFunction) } } }()) $(function(){ MyCoolModule.init() }) Some points to note: Everything under "return" is public (it can be called by other objects) and everything above that is private (cannot be accessed outside this object) I lump all my bindings into one block of code '.bind("click", doCoolStuff)', so at a glance you can see all the DOM elements your module is listening to. I give the event handlers descriptive names rather than defining them inline '.bind("click", function(){}'. User 'bind("click", ...)' rather than '.click', even though they do the same thing. This is because jQuery also has a 'unbind' method which is useful, and I like having the mirrored reciprocal naming. But the bigger reason is that you can namespace functions. i.e you can do 'bind("click.customNamespace, ...)'. A reason to do this is that you can later do '.trigger("click.customNamespace") and it'll trigger only those namespaced events as opposed to all click events. You could do the $.ready check inside of init instead of outside - matter of coding style. I have this code i am working on but every time i call init method I keep getting an error this.addElement is not a function is it because i can't call methods from event handlers ? function editor () { this.init = function () { $("#area").bind('click' , this.click_event ); } this.addElement = function () { console.log("adding element"); } this.click_event = function(event) { this.addElement(); console.log("click event in x : "+event.data); } } function editor () { var that = this; this.init = function () { $("#area").bind('click' , this.click_event ); } this.addElement = function () { console.log("adding element"); } this.click_event = function(event) { that.addElement(); console.log("click event in x : "+event.data); } } You should read this book, JavaScript: the Good Parts and visit the Crockenator's web site here, crockford.com You can also read about the JavaScript "this" issue here, I have tried: <!--...--> <script type="text/javascript"> var myVar = "some string"; </script> <!--...--> <input name="&{myVar};" ... /> <!--...--> But using FireFox, the name is set to the literal string: "&{myVar};" instead of the value of myVar... UDPATE: I see this called JavaScript Entities and hasn't been supported for a long time - but there must be way if one can include JavaScript directly in events (I realize attributes are not events, so JavaScript probably isn't evaluated).. ?! It would be a lot nicer than hardcoding the value as it used elsewehere a lot.. Here's what you need to do. Start by never reading javascript tutorials from a Java site again. Different monsters entirely, plus the tutorials on the site you're referencing are horrible. Second, get a copy of Javascript the Good Parts, This book is perhaps the most useful book ever written (in my opinion) about the language itself. It doesn't say anything about dealing with DOM API's. I encourage you to learn the language itself before getting too deep into javascript libraries like jQuery. It'll do you a load of good sooner rather than later. Once you're at least somewhat familiar with the proper ways to use javascript as a language, start investing your time into one library or another. jQuery is probably the most used, well loved, and kindest library out there. It will make dealing with cross-browser crap SO much easier for you. I know you should avoid it, thus although annoying I always protect myself against it. But what exactly causes extensions to a prototype to show up when using "for in"? Sometimes it is (or seems to be) safe to use "for in" and other times it isn't. I'm talking about for example: Array.prototype.last = function(){ return this[this.length-1]; } Showing up as: for(var k in someArray){ console.log("%o %o", k, someArray[k]); // eventually outputs "last 'function(){ return this[this.length-1]; }' } This behavior is by design. for in loops over all enumerable properties, including those inherited from the prototype. I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a computation on each cell. function DOUBLE(input) { if (input.map) { // Test whether input is an array. return input.map(DOUBLE); // Recurse over array if so. } else { return input * 2; } } Things I don't understand: inputin this function? typeoftells me it is a number, but shouldn't it be an array? It is after all a range of values (e.g. A2:B). .mapthing after the inputvariable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are. return input.map(DOUBLE)mean "do whatever you find in the corresponding elsestatement over the whole array"? Why is it structured like so? Any insights (or pointers to the right sources) much appreciated. This code is an example of using introspection to conditionally execute the code. if (input.map) will return truthy if input is an Array (and has a map function) and will return falsy in all other cases. This code is therefore testing to see whether input is an Array and if not, it is treating it as a number, otherwise it is treating it as an Array. You can see the definition of the map function on MDN Best book to learn about JavaScript is "JavaScript the Good Parts" I'm fairly new to JavaScript. Can anyone share some good advice on getting started? I have a little experience in ActionScript 3 and have taken a few Java classes toward my CS degree but my background is of a designer transitioning into development. My goal is to become a well rounded front-end developer and I'd like to move beyond the simple slideshow animations and rollover effects. Any guidance/wisdom will be much appreciated! I'll recommend some reading materials: Beginner: JavaScript: The Definitive Guide Intermediate: JavaScript Patterns Advanced: JavaScript: The Good Parts The best way to learn is practice. Write a simple application. When you are done, rewrite it so you learn what you did wrong last time. Perhaps, rewrite it again. Then, take on a new project. Repeat :). I'm trying to learn JavaScript, but seem to be going around in circles regarding primitives, objects, functions, etc. I can code fairly well in Python, so the JavaScript part is now mostly about syntax and idioms. I am overwhelmed by the choices and I'm not sure how to choose: Prototype, jQuery, Dojo, Node.js, Backbone.js, etc. What would be good JavaScript framework/s to pick up after mastering the basics? At the risk of betraying my JavaScript naivete, I'd like one (or a combination of) framework wherein I can do asynchronous requests, data visualization, and UI implementation. I wouldn't be right to not first say to make sure you understand JavaScript itself first. It's a rather unique language with both good parts and bad parts. If you take the time to understand closure, prototypal inheritance, this keyword, constructor functions, etc, you will thank yourself. JavaScript, The Good Parts is an excellent place to start. Anyways... For basic DOM manipulation, event handling, ajax, etc jQuery is the clear winner. In the past, Prototype/Scriptaculous was a common alternative. For more advanced browser-based applications, Backbone.js, Angular.js, and Ember.js are the winners. Dojo, Mootools, ExtJS, and Knockout.js are some alternatives to Angular and friends... all with varying strengths and focuses. There are countless libraries for charting. HighCharts is a popular one. For more advanced visualizations, check out D3.js and Raphael. Node.js is different beast. It's a server-side, network IO platform. It's competitors are things like Python's Twisted and Ruby's EventMachine. Of course this topic has been covered in great length here: I need to know how I can use a class in angularjs. A simple class like this: function Person(name,age){ this.name=name; this.age=age; this.getAge(){ return age; }; //etcetera } I am learning angular but I can't find an answer to this. I want to create Person instances and use the name, age etc. in the view. Please a simple solution because I am from a C# OOP background and don't know js frameworks. But I want to use the MVC pattern. Thanks! AngularJS is a framework that is written in and used through JavaScript. Although JavaScript has many object oriented features, it handles inheritance quite differently. This used to be confusing to me too until I read the excellent: JavaScript: The Good Parts by Douglas Crockford. I suggest you read this, it's quite a brief book and points out differences in approach in a very clear and concise manner. I've always been dabbling in javascript, but never really got hugely into writing a lot of javascript until last year or so. One thing I noticed is that my javascript started to grow so complex, that parts of it were more complex than the server's application code (minus all the framework code of course, such as Spring or Hibernate). This caused me to realize that if you want to write a complex javascript application, in the same way you've been writing complex web applications on the server, you have to start thinking about best practices, architecture, how you structure your files, how you test your code, what abstractions do you use to create smaller, more reusable components, what is the best way to pass parameters and send messages, should i pass parameters or object literals, and just best practices all around. None of this provided or encouraged by Javascript itself, and everyone seems to have its own way of going about everything. And of course, because Javascript offers such very poor api out of the box, I often spend a countless amount of time researching what the best tools for the job are. Facilities like importing files and dependencies, or even a basic collection library, are things NOT handled by the language. Let's not forget that IDE support, even in something like Idea 10.5, is actually pretty bad and nowhere near as rich as say Java due to its dynamic nature and the lack of these hard-bindings for packages and imports. Outside of jquery, which I really like and feel comfortable with, I still haven't made any decisions as to the "right" way to do things either. This is odd to me. Everyone seems to have their own coding idioms too - they either write in a pure functional style, or they try and create a whole classical programming model and then use that. People's coding standards and idioms vary from library to library and person to person. All of this makes knowing what the "right" thing to do an incredible task. Even worse, there doesn't seem to be books on this sort of thing. It's like nobody has bothered to tackle it - which is totally contrary to what we have in the Java space, or many other spaces for that matter. What is the right/successful path to having a refined way to successfully write nice-looking and robust javascript for complex web applications? I feel like my knowledge of Javascript expanded and became more complete after reading Douglas Crockford's Javascript: The Good Parts. He really clarifies the most difficult and important parts of the language. Reading it made clear the different types of inheritance: neoclassical, functional, prototypal. And the different ways to invoke a function: constructor invocation, apply invocation, function invocation, and method invocation. I would start there. I want to learn how to write the Javascript/CSS/HTML side of my applications but I want to skip the CSS kludges, bad Javascript, and non-semanitic HTML of the past and jump directly to HTML 5, CSS 3, clean Javascript libraries. I've been reading Mark Pilgrim's Dive In HTML 5 which I think is awesome and now I'd like the equivilent books (or blog posts) for Javascript and CSS. Any suggestions? Douglas Crockford's JavaScript: The Good Parts is a classic. These are my recommendations exactly in the same order. The first 3 books are very light reads & are sufficient enough to get started with client side programming. However, learning JQuery will make your Javascript development much easier. It is similar to learning to use regular expressions (but JQuery offers more than regex). Learning Web Design: A Beginner's Guide to (X)HTML, StyleSheets, and Web Graphics Bulletproof Web Design: Improving flexibility and protecting against worst-case scenarios with XHTML and CSS (2nd Edition) DOM Scripting: Web Design with JavaScript and the Document Object Model Javascript is an incredible language and libraries like jQuery make it almost too easy to use. What should the original designers of Javascript have included in the language, or what should we be pressuring them into adding to future versions? Things I'd like to see:- I am no expert on Javascript, so maybe these already exist, but what else should be there? Are there any killer features of other programming languages that you would love to see? Read Javascript: The Good Parts from the author of JSLint, Douglas Crockford. It's really impressive, and covers the bad parts too. The 'K&R', 'Red Book', 'Camel' of JavaScript and CSS? When you see a site like or, what reading material do the developers likely have on their shelves? For JavaScript it's probably JavaScript: The Good Parts and/or JavaScript: The Definitive Guide. I don't know if there's an equivalent book for CSS yet. Which is better, learn the basics of JavaScript, and then jQuery Or master JavaScript and then learn jQuery Now I know the basics well But I did not write many exercises of javascript thanks sorry about My bad English It depends on what you want to do with javascript. If you want to go deeper into the javascript, want to experiment with it, then become a master in javascript. In that case I will suggest you to read this excellent book by Douglas Crockford. Becoming a master of something never hurts. But if you want to become a developer and want to only build websites with javascript, then learn the core basics and move on to learning jquery. Again, whatever you do, you should have a clear understanding about the basics of javascript. You should, at least, read this excellent article and understand how objects in javascripts work, what are prototypes, what datatypes are there. There are also many other resources on javascript on MDN and Opera Developers Network. Google also has some excellent resources on javascript. Possible Duplicate: Javascript === vs == : Does it matter which “equal” operator I use? when i checked my code with JSLINT, it was full of errors...it works perfectly even in Ie6 but for some reason because i'm not an elegant coder i got more than 100 errors... so i'd like to learn how to code better, error free... but when i used some suggestions JSLINT gave me like was to replace == with ===, well i did, and nothing was working... so my question is: do we have to follow literally all the JSLINT suggestions? JSLint tests a professional subset of Javascript, created by Douglas Crockford. Essentially, he seeks to carve only the "good parts" out of the JavaScript language, to make life for programmers easier and code more legible and predictable. So, the short answer is NO. You do not have to follow the instructions. Perfectly valid JavaScript code will, and does, fail JSLint all the time. But the long answer is that your life will be significantly easier in the long run if you do. Take === vs. ==, for example. The difference is testing for EQUALITY versus testing for IDENTITY. Or, as Crockford says in his book, JavaScript: The Good Parts: JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands, if you're using === instead of ==, your code will almost always perform as you expect it to, a small price to pay for typing an extra character. But if you use == and the operands are not of the same type -- a string and an integer, for instance, JavaScript will first translate those values to the same type, and then compare them. And they might not do what you want or what you expected. And since, in JavaScript, you're often dealing with elements brought in from the DOM, which come in as strings, you run into string conversion issues all the time. As Crockford writes, here are some of the issues you could run into: '' == '0' => false 0 == '' => true 0 == '0' => true false == 'false' => false false == '0' => true Screwy, eh? JavaScript: The Good Parts is a great book, super thin, and if you've been working with JavaScript for a while, it will change the way you code for the better. So will JSLint, if you bow your head like a good marine. So. Long answer? No. You don't have to do everything JSLint tells you. But you should. After working for on JAVA for a long time now i feel like also learn some other language just for a change. This time i want to spend some time learning and reading one of the dynamic languages. Which is the most appropriate one that covers most of the features offered by dynamic languages and the syntax which probably is fun and also one that is closer to the syntax used by most of the dynamic languages. BR, Keshav Javascript is by far the most useful of dynamic languages for real-world practical work - not only is it irreplaceable for "client-side" work on the user's browser, but Node.js is rapidly making it very interesting for server-side work, too. Sure, it has many issues, but a book such as Crockford's Javascript: the good parts will help you avoid many of them. JS's syntax of course is quite different from that of dynamic languages such as Python or Ruby, which try to avoid braces and semicolons (which you'd better not avoid in JS: it tries to guess on your behalf but too often it guesses wrong!-). There is really no "syntax used by most of the dynamic languages" given these huge syntax differences (which grow if you throw into the mix Scheme, Erlang, Perl, PHP, Tcl, ...), so that part of your specs is moot. Second most useful today is probably Python -- as Allison Randall (program chair of OSCON and a well-known Perl guru) put it, Python has surprisingly become something of a "default language" in many fields. For example, the SEC is considering a regulation to mandate publication of algorithms used in stock trading, and their initially proposed language for such a publication is "of course" Python. As this post explains,. This is what Allison meant by "default language", I think: not necessarily the one you'll choose to implement a given task (e.g. the above post's author would prefer using Perl), but a language everybody's supposed to be able to read in order to understand an algorithm that is published or otherwise presented -- as Bruce Eckel (deservedly-best-selling author of books on C++ and Java) puts it here, Python is executable pseudocode. You can look at the "executable" part as a bonus (it does guarantee lack of ambiguity, which non-executable pseudocode might lack;-) even though large systems such as reddit and youtube have been implemented in it. At the other extreme, if you're not necessarily looking for immediately useful knowledge, but for mind-broadening, Scheme or Erlang might suit you best (but the syntax in each case is quite different from most other languages, be warned;-). However, in that case, I'd suggest Mozart, to go with the masterpiece that is Van Roy's and Haridi's Concepts, Techniques, and Models of Computer Programming (that book is plenty motivation to learn Mozart, just like SICP is to learn Scheme -- indeed, I've described CTMCP as "SICP for the 21st century"!-). HI I am learning javascript since last few days, I read it as scripting language. I like to know how it differs from other scriptings. Where does it run ?I mean where exactly my code gets compiled or error is caught? I like to know even any good online tutorial for learning javascript. Some Basic: Some Advanced: Discussed On Stackoverflow: Buy: Still have some problems, Stackoverflow is always here for you I am an experienced programmer, and I have a few little ideas that I think would work really well as PHP based web applications. I have no problem with learning PHP, mySQL, etc, but I do have a problem with the design of a webpage in itself. I am used to interface design ala Interface Builder and Swing, where there are some clearly defined classes with clearly defined behaviors etc. To me, web design is the wild west where I have to write my entire user interface, complete with little effects and stuff, on my own. I'm not afraid of this by any means, I just need some advice on where to start. I've like to learn some proper HTML for starters, since everything I know how to do is static and ugly, and I'd like to learn Javascript to be able to make my pages more elegant as time goes by. In short, I'd like it if someone gave me a few books or suggestions on how to make the programming that I know and love more visible and accessible to internet users. Here are a couple of books that I'd recommend for learning a couple of these: Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day JavaScript: The Good Parts HTML & XHTML Pocket Reference CSS Mastery is my go-to book for any css/html problems I may have. It works in detail through common elements you may have to create, such as: forms, tables, general layouts etc and suggests solutions based upon standards compliant CSS/HTML. For JavaScript check out JavaScript with DOM Scripting and AJAX. Note: As soon as you're comfortable with JavaScript it's worth looking at jQuery or one of the other many JavaScript libraries that take away the headache of cross-browser compatibility. am trying to create a copy of object a, without having to manually enter its property's into object b. In this code, b simply refers to a. I want to create a new version of a, so that when I add a property to b, it is not visible through a. var a = new Object(); // create an empty object var b = a; // now b refers to the same object b.test = 1; // add a new property to b alert(a.test); // => 1: the new property is also visible through a a === b; // => true: a and b refer to the same object In your example, "a" is just a function object and you are just creating additional pointers. Just create a new instance of them var a1 = new a(); var b1 = new a(); a1.test = 1; b1.test = 2; a1 != b1 The advantage to using a function as a Class is the utilize object.prototype, inheritance and instance checking. If you want just a data store then just change it to a generic object var a = {}; var b = {}; a.test = 1; b.test = 2; "JavaScript the Good Parts" is an absolute must I am trying to remove a class and add a class to divs using jQuery but it doesn't seem to be working. My html is like this: <div id="foo"> <div class="row"> <div class="col-sm-4"> <h4>one</h4> </div> <div class="col-sm-4"> <h4>two</h4> </div> </div> </div> I would like to remove the class col-sm-4 and instead add class col-sm-6 This is what I've done: $("#foo").find(".col-sm-4").addClass(".col-sm-6").removeClass(".col-sm-4"); I've ensured that I am getting elements back by find alert($("#foo").find(".col-sm-4").length); //2 Even though I'm not getting any errors, there is no change in my elements. 1) ".col-sm-6" is an example of a JQuery selector - Which, from the JQuery site is: "Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document." The methods addClass and removeClass are functions that except a class name to add or subtract to the element's class attribute. You wrote it like a JQuery selector. You are using the concept of selectors correctly when you reference your object with the JQuery selector $("#foo div.col-sm-4"). 2) You say: "Even though I'm not getting any errors, there is no change in my elements." - This is a great observation. You should know that much of JavaScript fails silently. Between 1 and 2 of this answer, I highly recommend the book JavaScript: The Good Parts. I got a minor brain-teaser thats keep bothering me. I'm unable to control the numbers of decimals written by my scripts. HTML <script type="text/JavaScript"> <!-- document.write($tekn_2_2/$tekn_2_1) //--> </script> JS $tekn_2_1 = "28" $tekn_2_2 = "7600" I want this to return the value '271' instead of '271.42857142857144'. I apologize, I'm aware that this should be a small case, but I can get anything to work. Edit: Originally I had voted for toFixed but was not aware that this function also rounds. It looks like a simple floor is all that you need. Math.floor($tekn_2_2/$tekn_2_1) == 271 Edit: +1 for Javascript: The Good Parts it goes over basic operations such as this. In a short but very informative manner. I have a variable called "result", var result; that result value is equal to following value, please presume that is just a string :) ---------result value ----------- for (;;);{ "send":1, "payload":{ "config":{ "website":"", "title":"welcome to site", "website-module":1313508674538, "manufatureid":"id.249530475080015", "tableid":"id.272772962740259", "adminid":100002741928612, "offline":null, "adminemail":"admin@website.com", "adminame":"George", "tags":"web:design:template", "source":"source:design:web", "sitelog":[], "errorlog":0, "RespondActionlog":0, "map":null }, "imgupload":"" }, "criticalerror":[0], "report":true } ---------result value------------ From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript. How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript. You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid. You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice. I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it. var button; var form = $('.register_ajax'); $('#vote_up, #vote_down').on("click",function(e) { e.preventDefault(); button = $(this).attr("id"); }); and this other send the form data through AJAX using the info already obtained from the button using the script above. form.bind('submit',function () { $.ajax({ url: form.attr('action'), type: form.attr('method'), cache: false, dataType: 'json', data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) , beforeSend: function() { //$("#validation-errors").hide().empty(); }, success: function(data) { if(data.message == 0){ $("#fave").attr('src','interactions/favorite.png'); $("#favorite").attr('value',1); console.log(data.errors); } if(data.message == 1) { $("#fave").attr('src','interactions/favorite_active.png'); $("#favorite").attr('value',0); } if(data.message == "plus") { $("#vote_up").attr('class','options options-hover'); $("#vote_down").attr('class','options'); console.log(data.message); } if(data.message == "sub") { $("#vote_down").attr('class','options options-hover'); $("#vote_up").attr('class','options'); console.log("sub"); } }, error: function(xhr, textStatus, thrownError) { console.log(data.message); } }); return false; }); The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated. 1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function. 2nd edit: I found the solution, I posted below. You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at. I'm confused where should I use prototype to declare a method ? What I read is, if I create a method that is declared by prototype, all instances are using same reference so is it static or something different ? Because I can reach instance properties in a prototype method ? But in c#, you cannot reach class variables(not static) in static methods? An Example: function Calculator() { if(this === window){ return new Calculator(); } this.Bar = "Instance Variable"; } Calculator.prototype.SaySomething = function(thing){ return thing + " " + Bar; } Calculator().SaySomething("Test"); // Test Instance Variable I would suggest you read JS The Good Parts by Douglas Crockford. It will give you a better understanding of JS's prototypal object model. I'm reading Crockford's book on Javascript and trying its inheritance method "Beget", but I'm puzzled by the result. Could you explain why the following code returns "Values: blue_small / blue_big"? I would expect it to return "Values: blue_small / red_big". if (typeof Object.beget !== 'function') { Object.beget = function (o) { var F = function () {}; F.prototype = o; return new F(); }; } function calculate(){ var object1 = { color: "red", size: "small" }; var object2 = Object.beget(object1); object2.size = "big"; object1.color = "blue"; return "Values: "+object1.color +"_" + object1.size +" \/ " + object2.color+"_" + object2.size || "unknown"; } In Javascript, when the value of a property is not set on an instance, getting the value refers to the prototype chain. In this example, the object2 is created and object1 is its prototype. But the value of the color property is never set on object2 in an explicit way. This means that reading the value refers to the prototype which is object1 and since the value there is set to blue, you have the result. Your confusion probably stems from the fact that you would expect creating new object to create a copy that includes all properties. In fact however, the newly created object has no properties set in an explicit way. Whenever you get a value of a property, prototype chain is referred.. In Java/C/C++ (and, with the exception of Python, every other language I can think of) whitespace is ignored. I've just spent several hours trying to work out why I was getting an error on a return statement. The answer was whitespace. So here are the two code snippets that I thought were functionally equivalent. return { a:b, c:d}; return { a:b, c:d }; But I now understand that the first one works but the second one throws an error on the c:d line. Can someone explain why these are not syntactically equivalent? The problem here is that JavaScript has a "feature" called automatic semi-colon insertion. So, your second snippet was actually being executed like this (note the semi-colon after the return): return; { a:b, c:d }; Basically, you were returning undefined, rather than the object literal. JavaScript has so called "bad parts" and you ran in to one of them. I would highly recommend reading this book regarding the subject. See this article for more information about automatic semi-colon insertion. If you still wanted to format your code similarly to what you originally had, this might be the closest that wouldn't bite you: return { a:b, c:d }; It seems that many of the JavaScript questions are answered by the simple use of pushing a library, without taking into account the person asking the question. I think libraries are great myself, but sometimes I think that we're too quick to throw a library down someone's throat. Imagine a person asks a question and it's apparent that they barely know JavaScript. They're just using code they found and piecing it together with other code, and really have no firm foundation to work on. To add a library on top of that flimsy foundation seems like a disaster waiting to happen. With that in mind, what JavaScript / programming / web browser concepts do you think are necessary to understand before a library/framework is introduced to a person? Should a framework / library be part of the learning process? I don't think someone has to grasp absolutely everything to use a library, I just think some people would be better served with a "Library X might help solve your problems, but before you do that, you might want to read up on the following concepts", rather than just a "use library x" answer. They should read this And check out some of the links here I've taken courses, studied, and even developed a little by myself, but so far, i've only worked with Microsoft technologies, and until now I have no problems with it. I recently got a job in a Microsoft gold partner company for development in C#, VB.net and asp.net. I'd like tips on how to diversify, learning technologies other than those from Microsoft. Not necessarely for finding another job, I think my job just fits me for my current interests. I think that by learning by myself other languages, frameworks, databases.. I may become a better programmer as a whole and (maybe) at the end of it all having more options of job opportunities, choosing what i'm going to be working with. What should I start with? how should I do it? Ideally, one should know at least one example from each of the major "paradigms": I want to create an array by extracting the dates of some other array and then comma separate the values into a string. array.push({date:created_at,username:user}); for (i in array) { var combined=new array(); combined = array[i].date; } console.log(combined); I am new to javascript and hard to follow in arrays.Thanks !! Can anyone also recommend me a good book for javascript? Try this var originalArray = [{date:"2012-01-01", username: "first"}, {date:"2012-01-02", username: "second"}]; // First step: Get a dateArray with only the dates var dateArray = []; for (var i in originalArray) { dateArray.push(originalArray[i].date); } // Or if you prefer to cut a few lines // dateArray = originalArray.map(function(x) { return x.date; } ); // Second step: Get it as a comma separated string var datesString = dateArray.join(","); console.log(dateArray); // ["2012-01-01","2012-01-02"] console.log(datesString); // 2012-01-01,2012-01-02 One of the more popular books is "Javascript The Good Parts" by Douglas Crockford I want to learn JavaScript nicely and become very good at it. I want to form a systematic learning plan before I start reading the books. Don't want to end up wasting my time reading the wrong books. I want to learn from books that will teach me enough to be able to learn all the things that are commonly used in today's websites. For example, if you look at this website His page source doesn't show the full content of the web page. How does he do all those animated transition effects? How do I learn all that stuff? Please help me. I want to learn all that stuff. Which book should I start reading? Another example is the Stack Exchange websites. For instance, the Writers website itself. When you hover over the Questions link on the top or any of such links, it displays a yellow background highlight. How do they do that? Where do I learn all these tricks? I see two options: a) Look up the web on an ad hoc basis when you need to learn some trick. But I don't like this technique. OR b) Systematically learn and read some books. I will read all the books if I have to. Please tell me what technologies other than JavaScript are at use to do these things. And if it is just JavaScript, what books will teach me the level of JavaScript that Google employees and FogCreek and StackExchange employees use. And if it is just JavaScript, what books will teach me the level of JavaScript that Google employees and FogCreek and StackExchange employees use. This is the easiest to answer: none. Yes, get started with Danny Goodman's tome or JavaScript: The Good Parts if you have some programming experience and want a quick intro, but both will only get you started. I mean, I'm sure they had some textbooks they read in college, but it's kind of like asking what books made pro athletes so good, or what book you read to get good at guitar. It's maybe 10% textual material and 90% constant practice -- finding new problems to solve and figuring out how to solve them. EDIT I don't intend to imply that avoiding books is admirable, merely that experience is the best teacher, and that a theoretical understanding is only a means to an end: practical understanding. Books are absolutely necessary here; I'm mostly disputing the connection between books and the kind of expertise that lands you a high-flying job. For a perhaps more relevant example, imagine language learners. You can study the textbooks all you'd like, but absent experience you'll stutter like a first-year student. (Even if, for example, you can recite correctly the grammatical differences of some construction better than a native speaker.) So no, don't just copypasta and come to SO when things break. But do start early in your reading, and the mistakes you make (rather than some script you copied) are often the best teachers. I was going over Javascript the good parts and I came across this example, where the author was trying to explain how to be able to call a superclass: Object.method('superior', function (name) { var that = this, method = that[name]; return function ( ) { return method.apply(that, arguments); }; }); an example of using this code: super_get_name = that.superior('get_name'); however chrome wouldn't recognize method on Object. I tried doing the same thing using defineProperty but that didn't work either.. any help? update: does this method cause any known conflicts with jQuery? As soon as i put the following at the first js file in my page: I get this error in line 2062 in jquery-1.11.0.js: Uncaught TypeError: Object function (name) { var that = this, method = that[name]; return function ( ) { return method.apply(that, arguments); }; } has no method 'exec' this is the effected code: // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } any idea what's going on? Javascript do not have structures. So can i create a GLOBAL object like struct abc in javascript . Struct abc contains some variables & array of another structure struct xyz. struct xyz { var age; var name; }; struct abc { var start; var end; var length; struct xyz xyz_array[100]; }; If structures is not possible in javascript how can i save data in this format ? ============================= Edit some solution i found ================= Javascript: How to create an array of object literals in a loop ============================================= var details = { Start: 0, End: 0, length: 0 }; var arr = []; var len = 100; for (var i = 0; i < len; i++) { arr.push({ direction: "out", message : "" }); } ===================================== Array inside a Javascript Object? var details = { Start: 0, End: 0, length: 0 info_text : [] }; var len = 100; for (var i = 0; i < len; i++) { details.info_text.push({ direction: "out", message : "" }); } ========================================= Cited from JavaScript: The Good Parts The simple types of JavaScript are numbers, strings, booleans (trueandfalse),null, and undefined. All other values are objects. Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects. So you can use object, example : function xyz(age, name){ this.age = age; this.name = name; } var abc = { start : null, end : null, length: null xyz_array: [] } abc.xyz_array.push( new xyz(33, 'johnDoe') ); abc.xyz_array.push( new xyz(32, 'jeanDoe') ); console.log(abc); Just came across JSLint so decided to pass my JS through it but got lots of errors but not sure if they're bad. I have tried a few things I found online to get rid of them but can't seem to make the budge. JS code $( document ).ready"); $('div.icon').click(function () { $('input#search').focus(); }); function search() { var query_value = $('input#search').val(); $('b#search-string').html(query_value); if (query_value !== '') { $.ajax({ type: "POST", url: "../_Scripts/search.php", data: { query: query_value }, cache: false, success: function (html) { $("#results").html(html); } }); } return false; } $("input#search").on("keyup", function (e) { clearTimeout($.data(this, 'timer')); var search_string = $(this).val(); if (search_string == '') { $("#results").fadeOut(); $('h4#results-text').fadeOut(); } else { $("#results").fadeIn(); $('h4#results-text').fadeIn(); $(this).data('timer', setTimeout(search, 100)); }; }); $('#pmForm').on('submit', function (e) { e.preventDefault(); $('input[type=submit]', this).attr('disabled', 'disabled'); var pmSubject = $("#pmSubject", this).val(); var pmTextArea = $("#pmTextArea", this).val(); var Please type a subject.').show().fadeOut(6000); return false; } else if (!pmTextArea) { $('input[type=submit]', this).removeAttr('disabled'); $("#jqueryReply").html('<img src="../_Images/round_error.png" alt="Error" width="31" height="30" /> Please type in your message.').show().fadeOut(6000); return false; } else { $("#pmFormProcessGif").show(); $.post(url, $('#pmForm').serialize(), function (data) { $("#jqueryReply").html(data).show().fadeOut(10000); $("#pmTextArea").val(''); $("#pmSubject").val(''); $('input[type=submit]', this).removeAttr('disabled'); $("#pmFormProcessGif").hide(); }); } }); $('#newblog').on('submit', function (e) { e.preventDefault(); $('input[type=submit]', this).attr('disabled', 'disabled'); var blogTitle = $("#blogtitle").val(); var blogText = CKEDITOR.instances['blogbody'].getData(); var Please type a Title.').show().fadeOut(6000); return false; } else if (!blogText) { $('input[type=submit]', this).removeAttr('disabled'); $("#jqueryReply").html('<img src="../_Images/round_error.png" alt="Error" width="31" height="30" /> Please type in your Blog.').show().fadeOut(6000); return false; } else { $("#blogFormProcessGif").show(); for (instance in CKEDITOR.instances) { CKEDITOR.instances['blogbody'].updateElement(); } $.post(url, $('#newblog').serialize(), function (data) { $("#jqueryReply").html(data).show().fadeOut(10000); $("#blogtitle").val(''); CKEDITOR.instances['blogbody'].setData(''); $("#blogFormProcessGif").hide(); location.reload(); }); } }); function _(x) { return document.getElementById(x); }; function report(id, uid) { var url = "../_Scripts/report.php"; $.post(url, { blogid: id, userid: uid }, function (data) { alert(data); }); }; function toggleElement(x) { var x = _(x); if (x.style.display == 'block') { x.style.ul').hasClass('active')) { $(this).children('ul').removeClass('active').children('li').slideUp(); $(this).children('img').attr("src", "../_Images/arrow.gif"); e.stopPropagation(); } else { $(this).children('ul').addClass('active').children('li').slideDown(); $(this).children('img').attr("src", "../_Images/arrow-down.gif"); e.stopPropagation(); } }); Errors: '$' was used before it was defined. $( document ).ready(function() { line 1 character 4Unexpected space between '(' and 'document'. $( document ).ready(function() { line 1 character 13Unexpected space between 'document' and ')'. $( document ).ready(function() { line 1 character 29Expected exactly one space between 'function' and '('. $( document ).ready(function() { line 2 character 1Missing 'use strict' statement. !function (d, s, id) { line 3 character 5Expected 'var' at column 9, not column 5. var js, fjs = d.getElementsByTagName(s)[0], line 4 character 9Expected 'p' at column 13, not column 9. p = /^http:/.test(d.location) ? 'http' : 'https'; line 5 character 5Expected 'if' at column 9, not column 5. if (!d.getElementById(id)) { line 6 character 9Expected 'js' at column 13, not column 9. js = d.createElement(s); line 7 character 9Expected 'js' at column 13, not column 9. js.id = id; line 8 character 9Expected 'js' at column 13, not column 9. js.src = p + "://platform.twitter.com/widgets.js"; line 9 character 9Expected 'fjs' at column 13, not column 9. fjs.parentNode.insertBefore(js, fjs); line 10 character 5Expected '}' at column 9, not column 5. } line 11 character 1Expected '}' at column 5, not column 1. }(document, "script", "twitter-wjs"); line 11 character 3Wrap an immediate function invocation in parentheses to assist the reader in understanding that the expression is the result of a function, and not the function itself. }(document, "script", "twitter-wjs"); line 12 character 1Expected '$' at column 5, not column 1. $('div.icon').click(function () { line 13 character 5Expected '$' at column 9, not column 5. $('input#search').focus(); line 14 character 1Expected '}' at column 5, not column 1. }); line 15 character 1Expected 'function' at column 5, not column 1. function search() { line 16 character 5Expected 'var' at column 9, not column 5. var query_value = $('input#search').val(); line 16 character 23'$' was used before it was defined. var query_value = $('input#search').val(); line 17 character 5Expected '$' at column 9, not column 5. $('b#search-string').html(query_value); line 18 character 5Expected 'if' at column 9, not column 5. if (query_value !== '') { line 19 character 9Expected '$' at column 13, not column 9. $.ajax({ line 20 character 13Expected 'type' at column 17, not column 13. type: "POST", line 21 character 13Expected 'url' at column 17, not column 13. url: "../_Scripts/search.php", line 22 character 13Expected 'data' at column 17, not column 13. data: { line 23 character 17Expected 'query' at column 21, not column 17. query: query_value line 24 character 13Expected '}' at column 17, not column 13. }, line 25 character 13Expected 'cache' at column 17, not column 13. cache: false, line 26 character 13Expected 'success' at column 17, not column 13. success: function (html) { line 27 character 17Expected '$' at column 21, not column 17. $("#results").html(html); line 28 character 13Expected '}' at column 17, not column 13. } line 29 character 9Expected '}' at column 13, not column 9. }); line 30 character 5Expected '}' at column 9, not column 5. } line 31 character 5Expected 'return' at column 9, not column 5. return false; line 32 character 1Expected '}' at column 5, not column 1. } line 33 character 1Expected '$' at column 5, not column 1. $("input#search").on("keyup", function (e) { line 34 character 5Expected 'clearTimeout' at column 9, not column 5. clearTimeout($.data(this, 'timer')); line 34 character 18'$' was used before it was defined. clearTimeout($.data(this, 'timer')); line 35 character 5Expected 'var' at column 9, not column 5. var search_string = $(this).val(); line 35 character 25'$' was used before it was defined. var search_string = $(this).val(); line 36 character 5Expected 'if' at column 9, not column 5. if (search_string == '') { line 36 character 23Expected '===' and instead saw '=='. if (search_string == '') { line 37 character 9Expected '$' at column 13, not column 9. $("#results").fadeOut(); line 38 character 9Expected '$' at column 13, not column 9. $('h4#results-text').fadeOut(); line 39 character 5Expected '}' at column 9, not column 5. } else { line 40 character 9Expected '$' at column 13, not column 9. $("#results").fadeIn(); line 41 character 9Expected '$' at column 13, not column 9. $('h4#results-text').fadeIn(); line 42 character 9Expected '$' at column 13, not column 9. $(this).data('timer', setTimeout(search, 100)); line 42 character 9Too many errors. (23% scanned). Can anyone shed some light on these errors and tell me if they're going to affect me in the future? At the moment, the code runs fine. Thanks JSLint checks for code syntax, including whitespace, not just code errors. Errors such as Expected '===' and instead saw '=='. are very serious because of the nature of JavaScript. In JavaScript, == means compare value whereas === means compare value and type. Here are a few examples: 1 == '1' // Evaluates to true because it doesn't check for type 1 === '1' // Evaluates to false because it does check for type (they are // different types) It is therefore always best to use === and not ==. The whitespace errors/warnings such as Unexpected space between '(' and 'document'. and Expected '}' at column 9, not column 5. are not as serious and will probably not cause any problems with the actual performance of your code, they will, however, help improve the readability and clarity of your code. I recommend using the JSLint formatting/whitespace rules, but if you have your own valid JavaScript code formatting style, don't worry too much about it. JSLint is a standard, not the standard, for writing JavaSript code. That said, JSLint is a very good standard. If you don't care about whitespace, JSHint is a good alternative to JSLint. JSHint is a fork of JSLint but is not as strict in places where it doesn't matter as much, namely whitespace. As suggested in the comments above, I recommend concentrating on learning how to write good, clean, readable JavaScript code. For the most part, if your code is well written and readable, JSLint/JSHint won't find many errors. For more information about making good JavaScript code I recommend checking out JavaScript: The Good Parts by Douglas Crockford, the inventor of JSLint. My Manager wants to learn HTML and JS, and he has no idea of programming. Can you give me any good references from where he can learn? Do yourself a huge favor: do not use w3schools. A lot of its content has obviously not been updated in around 10 years, and a large portion of the javascript code on it is absolutely attrocious and should not be considered best practice even in a parallel universe. For more details on this, see - which also suggests some alternative resources. That said, I've personally found Mozilla Developer Network to be a very well-written resource, though I'll admit it may not necessarily cater to the greenest of audiences. For JavaScript as a language, I'd highly recommend picking up Douglas Crockford's book JavaScript: The Good Parts, as it discusses the language while specifically trying to emphasize the good parts of the language while steering you clear of the bad. It's important to remember that while JavaScript looks like Java, its similarities pretty much end there. EDIT: for JavaScript you may be better off starting with a resource like Eloquent JavaScript as Rebecca pointed out in her answer (for which she gets a +1 from me, and for which I kick myself for forgetting about). I might also point you towards Rebecca Murphey's jqfundamentals - particularly the first chapter, which also briefly goes through some JavaScript basics, though admittedly it does so quickly and thus shouldn't be your only read. But it's also well-written and should be hopefully easy to understand. (For consumable formats, look here:) Ok I trying to learn javascript for my first language but I'm having trouble with the logic/structure of "programming". I know almost everything in javascrupt I can write statements/loops/arrays/objects/ect... but I can't wrap my head around how to use it or put it into action and I can't find what I looking for on the web. So I guess my question is how do you structure a program in javascript? does it go like: variables go here functions go here arrays go here ect... I just dont get it.. If you must start with javascript as a programming language, then a good reference for having good structure and habits for your javascript code would be Douglas Crockford's Javascript: The Good Parts. There are a lot of gotchas in javascript, and Crockford is meticulous about style and structure in it. I can't stress enough how important a good resource is for learning a language. MDN is wonderful for learning about each of the available objects/methods. Additionally, treat JavaScript: The Good Parts as required reading. Ask lots of questions. As for the actual structure of the program: //wrap your code in a self-executing closure to prevent global namespace pollution (function () { //use strict because it's good to brush your teeth "use strict" //initialize all vars at top of functions var a, b, c, d; //declare your functions after your variables function foo(bar, baz) { var fizz, buzz; function subfunction() { //some code } //more code } //whatever code needs to run should follow function declarations a = 1; b = 2; c = foo(a, b); //if you need to make something globally accessible, do it explicitly window.foo = foo; }()); Also: HTML, CSS, and JS work together in an MVC pattern if you use them correctly. Keep your HTML in .html files, your CSS in .css files, and your JavaScript in .js files. Don't use inline events <body onload="whatever();"> breaks the separation of content from style from interaction. rowData = [] function something () { return rowData } Update: Now lets take the Array contains a lot of Objects. So we say that this would return an Array of Objects. I am just confused a lot. Does this return an Object or Array of Object Or just an Array. [] is an array literal so that function returns an empty Array. In JavaScript, arrays are really objects and they are a little different than traditional arrays. From Douglas Crockford's JavaScript: The Good Parts JavaScript provides an object that has some array-like characteristics. It converts array subscripts into strings that are used to make properties. And... Unlike most other languages, JavaScript's array length is not an upper bound. If you store an element with a subscript that is greater than or equal to the current length, the length will increase to contain the new element. There is not array bounds error. someSingleton = (function() { var someFunction = function() { console.log(this); someOtherFunc(); }; var someOtherFunc = function() { console.log(this); }; return { method: someFunction } })(); someSingleton.method(); If run you this you'll notice the first method will return the object as expected and the second nested method call, someOtherFunction, will return the DOMWindow object. Other than passing the instance (this) as a parameter to the second method, how do I make it so that the second method call is referencing the containing object and not DOMWindow. Understanding this in javascript can be a challenge. I can recommend reading Douglas Crockford's Javascript: The Good Parts for a better understanding. Meanwhile, you can check out this link :) It's quite common to assign the parent object to a variable that. This way, you can access it's properties and functions through it: (function(){ var that = this; that.someFunc = function(){}; that.someOtherFunc = function(){ console.log(that); }; })(); So I am learning JavaScript right now and I am making this calculator. Started it like any other JavaScript. Make html file, put in all the html tags and so on, make the special <script></script> tags into which I will write the code. Now my solution involved a lot of variables and if statements and so on.. But then I wondered how others have done it and i Stumbled upon this: <FORM NAME="Calc"> <TABLE BORDER=4> <TR> <TD> <INPUT TYPE="text" NAME="Input" Size="16"> <br> </TD> </TR> <TR> <TD> <INPUT TYPE="button" NAME="one" VALUE=" 1 " OnClick="Calc.Input.value += '1'"> <INPUT TYPE="button" NAME="two" VALUE=" 2 " OnCLick="Calc.Input.value += '2'"> <INPUT TYPE="button" NAME="three" VALUE=" 3 " OnClick="Calc.Input.value += '3'"> <INPUT TYPE="button" NAME="plus" VALUE=" + " OnClick="Calc.Input.value += ' + '"> <br> <INPUT TYPE="button" NAME="four" VALUE=" 4 " OnClick="Calc.Input.value += '4'"> <INPUT TYPE="button" NAME="five" VALUE=" 5 " OnCLick="Calc.Input.value += '5'"> <INPUT TYPE="button" NAME="six" VALUE=" 6 " OnClick="Calc.Input.value += '6'"> <INPUT TYPE="button" NAME="minus" VALUE=" - " OnClick="Calc.Input.value += ' - '"> <br> <INPUT TYPE="button" NAME="seven" VALUE=" 7 " OnClick="Calc.Input.value += '7'"> <INPUT TYPE="button" NAME="eight" VALUE=" 8 " OnCLick="Calc.Input.value += '8'"> <INPUT TYPE="button" NAME="nine" VALUE=" 9 " OnClick="Calc.Input.value += '9'"> <INPUT TYPE="button" NAME="times" VALUE=" x " OnClick="Calc.Input.value += ' * '"> <br> <INPUT TYPE="button" NAME="clear" VALUE=" c " OnClick="Calc.Input.value = ''"> <INPUT TYPE="button" NAME="zero" VALUE=" 0 " OnClick="Calc.Input.value += '0'"> <INPUT TYPE="button" NAME="DoIt" VALUE=" = " OnClick="Calc.Input.value = eval(Calc.Input.value)"> <INPUT TYPE="button" NAME="div" VALUE=" / " OnClick="Calc.Input.value += ' / '"> <br> </TD> </TR> </TABLE> </FORM> It's not indented really well but the point is that, it's javascript as I understand yes? And the person has not even used the script tags for it. Just putting the code randomly in a html file and bam it work. How can this be? As I said, this is horrible code. If you are learning Javascript, this is a great example of how not to do it. It works because they've put Javascript code in the event handlers and even without specifying most (all) browsers will interpret that as Javascript. They can access the various inputs by exploiting that most browsers will automatically create a variable for any named controls. And then for bonus points they use eval which is evil. Seriously, this is really bad code. You'd see a lot of code like this in the early 90's. Just move on and learn Javascript properly. Start here: JavaScript: The Good Parts The code below uses Javascript to create a base class, eventRaiser, that has the internals needed to allow clients to subscribe to events, and subclasses to raise these events. The idea is that other classes, like ThingWithEvent, will inherit from eventRaiser and expose the subscribe method, and fire off the raise method internally. The jQuery init function demonstrates this. The way this is written, there's nothing stopping a client from directly raising an event. In other words, adding er.raise("Y"); to the jQuery init function causes the Y event to be raised without difficulty. Ideally I'd like to make it so that outside code, interacting with eventRaiser through some class that inherits from it, with can only subscribe to events, and not raise them. In other words I'd like raise to be the equivalent of C# protected—visible only to itself, and classes that inherit from it. Is there some slick ninja closure I should use to achieve this, or should I recognize that Javascript is not meant to incorporate OO Encapulation, rename raise to _raise to imply to client code that _raise is private and should not be invoked, and move on? $(function() { var er = new ThingWithEvent(); er.subscribe("X", function() { alert("Hello"); }); er.subscribe("X", function() { alert("World"); }); er.subscribe("Y", function() { alert("Not Called"); }); er.doSomething("X"); }); function eventRaiser() { var events = {}; this.subscribe = function(key, func) { if (!events[key]) events[key] = { name: key, funcs: [] }; events[key].funcs.push(func); }; this.raise = function(key) { if (!events[key]) return; for (var i = 0; i < events[key].funcs.length; i++) events[key].funcs[i](); }; } function ThingWithEvent() { eventRaiser.call(this); var self = this; this.doSomething = function() { alert("doing something"); self.raise("X"); } } function surrogate() { } surrogate.prototype = eventRaiser; ThingWithEvent.prototype = new surrogate(); ThingWithEvent.prototype.constructor = ThingWithEvent; I hate answering my own question, let alone accepting my own answer, but it turns out this is not only possible, but insanely easy. The idea behind this code comes from Douglas Crockford's JavaScript The Good Parts. The trick is to ditch constructors (neoclassical inheritance) altogether and use functional inheritance. This code not only achieves public, protected, and private access levels, but it's much cleaner, and easier to read IMO than inheriting constructors and swapping prototypes and constructors around. The only catch is that this code will be slightly slower since each object creation necessitates the creation of each of the object's functions, instead of getting all that dumped in for free with a constructor's prototype. So, if you need to create tens of thousands of objects in your web site then you might prefer a constructor. For...everyone else, this code is likely for you. function eventRaiser(protectedStuff) { protectedStuff = protectedStuff || {}; var that = {}; var events = {}; //private protectedStuff.raise = function(key) { if (!events[key]) return; for (var i = 0; i < events[key].funcs.length; i++) events[key].funcs[i].apply(null, Array.prototype.slice.call(arguments, 1)); }; that.subscribe = function(key, func) { if (!events[key]) events[key] = { name: key, funcs: [] }; events[key].funcs.push(func); }; return that; } function widget() { var protectedStuff = {}; var that = eventRaiser(protectedStuff); that.doSomething = function() { alert("doing something"); protectedStuff.raise("doStuffEvent"); }; return that; } $(function() { var w = widget(); w.subscribe("doStuffEvent", function(){ alert("I've been raised"); }); w.doSomething(); w.protectedStuff.raise("doStuffEvent"); //error!!!!! raise is protected w.raise("doStuffEvent"); //and this obviously won't work }); Titanium SDK version: 1.6. iPhone SDK version: 4.2 I am trying out the cache snippet found on the Appcelerator forum but I get an error: [ERROR] Script Error = Can't find variable: utils at cache.js (line 9). I put this one () in a file called cache.js and implemented the code from this one () in the calling script, but I get the error. What is wrong? I copied the code exactly. All input are welcome! Your problems is whilst the first pastie defines utils.httpcache. The variable utils is not defined outside of this function closure (because it is not defined anywhere in global namespace). As below shows. (function() { utils.httpcache = { }; })(); To make it all work in this instance add the following code to the top of your cache.js file. var utils = {}; This declares the utils variable in global namespace. Then when the function closure is executed below it will add utils.httpcache to the utils object. The problem is actually not specific to Appcelerator and is just a simple JavaScript bug. Checkout Douglas Crockfords book, JavaScript the Good Parts. Reading it will literally make you a more awesome JavaScript developer. Using jQuery, I am binding some image tags with a click event like this: $('.imageClass > a > img').bind('click', onImageClick); this.onImageClick = function() { $.post("/blah/123", { test : 'a' }, function(data) { myCallback(this, data); }, "json"); } this.myCallback(event, data) { alert($(event).parent.attr("href")); }; My DOM looks like this: <div class="imageClass"> <a href="#"><img src="/images/1.jpg" alt="1"></a> <strong>hello</strong> <a href="#"><img src="/images/2.jpg" alt="2"></a> </div> I want to alter the text 'hello' in mycallback somehow using data.Message I can't seem to pin point the strong tag, and i'm not sure if I am passing the correct value into mycallback either! To change the text in strong with data from the ajaxcall, try this: $(".imageClass > a > img").click(on_image_click); function on_image_click() { var image = this, strong = image.parent().next(); $.getJSON("/blah/123", {test: 'a'}, function (data) { strong.text(data.Message); }); } It seems like you are a little unsure how to use the this-operator, which is understandable. Once understood, it's a powerful concept. I've tried finding a good article on the net. Quirksmode has one, but it is slightly confused as well. I can however heartily recommend Douglas Crockfords Javascript: the good parts. I'm pretty new to web development and an trying to build a set of rules for good programming practice before I start learning bad habits. Therefore I wanted to ask you all for any wise words on what practices you would recommend to a newbie to adopt early on both in terms of code re-usability and readability for others. Below I've shared a few 'rules' that I've picked up so far for myself (please feel free to correct/update if any of these are 'old' or irrelevant): Double vs single quotes: Indenting: echoto output HTML code, use \nfor carriage return and \tfor a tab (when in double quotes - on linux server) Classes and Functions: include('includes/functions.php')) to store all classes/functions to be used on the website Keep below structure so that lines can be cut/pasted in their entirety class name { classproperty='value'; function name ($a) { methodproperty='value'; } } External scripts: Combine all slow scripts into one external file and load with the below code (replacing defer.js with your script> AJAX/POST/GET: Databases: Prepare()and BindParam()/ BindValue()to ensure protection against code insertion PHP miscellaneous: require_once()and include_once()to save unnecessary loading (unless using it to reconnect to a database); Define substrings individually and then insert into a compiled variable to echo out, eg: foreach($users as $user) { $id=$user['id']; $value=$user['name']; $selected=($user['name']=$_POST['username'] ? 'SELECTED' : ''); echo "<option id='$id' $selected >$value</option>"; } Happy coding! I'm not going to say anything specific about good programming practice with PHP since that subject is very general but I'll share my opinion on your 'good programming practices'. Double vs single quotes: - Echo statements with double quotes so that variables can be resolved in-line (including html tags and carriage return/tabs - but not functions) - Html tag id/name/value values in single quotes Indenting: - Nesting with indents External scripts: <body>tag. If you wish to be very disciplined over JavaScript I'd recommend JavaScript: The Good Parts - the bible of JavaScript good programming practices. AJAX/POST/GET: - Use AJAX when REQUESTING data from the server - Use POST/GET when SUBMITTING data to the server GET. It's used for getting data from the server. Don't submit data using GET. Databases: - PDO connections are more versatile than mysqli (procedural or object orientated) as can handle multiple types of databases - Use Prepare()and BindParam()/ BindValue()to ensure protection against code insertion PHP miscellaneous: - Use require_once()and include_once()to save unnecessary loading (unless using it to reconnect to a database); require_once()and include_once()exist is because sometimes including a script more than once can cause an error. Like when you have define()d variables. - Define substrings individually and then insert into a compiled variable to echo out, eg: foreach($users as $user) { $id=$user['id']; $value=$user['name']; $selected=($user['name']=$_POST['username'] ? 'SELECTED' : ''); echo "<option id='$id' $selected >$value</option>"; } To wrap it up: Don't do preemptive performance fixes. You seem like a smart person so do what you think is logical. Write readable and documented code. Use a framework. Cannot stress this enough. Try Laravel, Symfony, Zend. Those are the major/most popular ones. Use a good IDE. My personal favorite is PHPStorm. And last but not least, code. Just write code, create applications. Skill will follow naturally and with time you'll be amazed how much your programming has improved. Good luck.: The basic idea for writing good code is that the code must be readable, well-commented and documented. Other basic facts for writing good code regarding all the program languages are structuring the code in directories and files and indentation of course. In the case of javascript the things could be more complicated, because the language allows you to use different style to accomplish similar task. For example there are three different ways to define a JavaScript class. Said that, which are the best resource (books/sites) or suggestion for writing good code (library) in javascript? I'd highly recommend reading JavaScript: The Good Parts by Douglas Crockford to get you started on writing quality JavaScript code. At the first place i would suggest you to get more familiar with JS object model I would suggest you to take Douglas Crockford's article on prototypal inheritance: and make comparison with classical inheritance model More systematic approach of pros and cons of JavaScript can be found in his book JavaScript: The Good Parts If you search for more broader architectural approach JQuery, ExtJs (a.k.a. Sencha), MooTools are great java script libraries/frameworks to start looking at their design principles. Does anyone have a preference on getting feedback on their JavaScript code / apps? I am looking for general performance and architecture tips and wondering if there are best place for this? Upload everything to GitHub? post snippets on Stack Overflow? Just keep re-writing my code every few months? ;-P Would love to know opinions... feel like I am at that point where I can really absorb some advice from JS ninjas out there. thanks, s Just grab a few good books like JavaScript: The Good Parts and jQuery In Action. The former is particularly good for giving you an excellent, concise introduction to good JavaScript. I am trying to get indepth knowledge on object literal and prototypes? how they relate and differ and when to use? Is there any good websites and book which dives into indepth on object literal and prototype with plenty of examples etc? Thanks JavaScript: The Good Parts by Douglas Crockford is a book you're looking for. Somehow, my code does not work. I can't figure out why, I'm completely new to javascript and thought this would work, in php it's similar. if(string != "string") works in PHP, but not in javascript, in javascript the code just continues. If I do it with =! it doesn't works... <SCRIPT LANGUAGE="JavaScript"> var lastsite; function checkSite (form){ if (document.getElementById('steam').checked && lastsite != 'steam') { $('#signaturestuff').append('<b>Style:</b> <input type="radio" name="style" value="1" id="steamstyle1" onclick="testButton();"> Style 1'); var lastsite = "steam"; } } </SCRIPT> You can compare strings with "==" in PHP and Javascript (but not in C, C++, C# or Java) You probably should compare strings with Javascript compareLocale () In either case, you need to look at the value of "lastsite" in order to figure out why your comparison isn't working. Who knows - maybe you just forgot to assign it ;) Firebug is a wonderful tool, if you're not already familiar with it. "Javascript: The Good Parts" is a wonderful book, if you've not already read it. May be this question duplicate or redundant but i want to elaborate my question so: i have tried looking to google and flipkar,amazon that ...but by just looking at the book you can't really judge how it will be...and it's always good ask someone who has experience...because i can't keep on buying to find good book I want to buy books on jquery and javascript,and please consider that i am not a experienced in javascript and jquery neither a beginner ...so i want buy a book that has a very high level ....so that all goes above my head... if some experienced one can reply to this it will be helpfull...and all others(less experienced) are also welcome..... Hoping i will get good answer :) First book to become JS developer is JavaScript: The Good Parts I love this book as well Eloquent Javascript: has very basics of JS and best for that if you want to test your perfection there is a way... A Test-Driven JS Assessment: A set of failing tests that cover various JavaScript topics; can you write code to make the tests pass? 10 things I learned from the jQuery Source will help you understand how to dismantle others JS scripts perfectly .netajaxangularjsanimationappceleratorarchitecturearraysasp.netasp.net-ajaxasp.net-mvcbackbone.jsbit.lybrowsercc#cachingcallbackcanvascartclassclient-sideclosurescoding-stylecomparison-operatorscompatibilityconstantsconstructorcontrol-structureconventionscopycssdata-structuresdatabase-connectiondesigndesign-patternsdesign-principlesdictionarydocumentationdojodomdownloaddurationdynamic-languageseclipseecmascript-6encapsulationequalityequality-operatorequivalenceevented-ioeventsfirefoxfor-loopframeworksfrontendfunctiongetjsonglobal-variablesglobalsgoogle-apps-scriptgoogle-spreadsheetgroovygwthidden-featureshtmlhtml5hyperlinkidentity-operatorinheritanceinstanceintegrationinternet-explorer-6iosipadiphonejavajavascriptjavascript-eventsjavascript-objectsjoinjqueryjrubyjscriptjslintjsonjspjvm-languagesjythonlanguage-agnosticlanguage-constructlanguage-featuresloopsmathmemoizationmobilemorfikmysqlinamespacesnew-operatornode.jsobjectobjective-coopoperatorsoptimizationoverridepdophpprecisionprogramming-languagespromiseprototypeprototype-programmingprototypejspythonraphaelrecursionrefactoringreferenceregexregex-lookaroundsresourcesrhinoroundingrubyruby-on-railsscopescript#scriptingsmartystandardsstring-substitutionstrutsstylessyntaxtestingthistransitivityurl-shortenerv8vb.netvideoweb-applicationsweb-serviceswebglwhitespacexhtmlxml-attributeyui
http://www.dev-books.com/book/book?isbn=0596517742&name=JavaScript
CC-MAIN-2019-04
refinedweb
43,626
64.3
Building GraphQL API with Nodejs, TypeGraphQL , Typegoose and Troubleshooting common challenges. Published on Dec 27, 2020 I recently started out with this project where I am using Apollo GraphQL with TypeGraphQL , typegoose as mongoose wrapper and Express.js to create an API. I have been searching for different articles on using TypeGraphQL with Typegoose but seems that no has used it before 🤷♂️ also individually their documentation are top notch , but when trying to use them together I encountered a lot of bugs and challenges. So It’s probably worth posting out this article so that it could be an help for other developers and to briefly explain some of the codes and concepts around GraphQL. I have created an boilerplate GraphQL API with Node.js, Apollo, TypeGraphQL , TypeScript , Nx, MongoDB , typegoose. You may want to check that out, here's the repository github.com/DevUnderflow/nx-node-apollo-grahql-mongo What. Basically it is new API standard that enables a better way of implementing API's and a great alternative to REST. In REST we need maintain a bunch API endpoints, While in GraphQL there is just a single API endpoint created. So GraphQL has two major components : Schema : GraphQL server uses a schema to describe the shape of request / graphs. This schema basically defines a hierarchy of types with fields that are populated from back-end data stores. type User { username: String email: String } Resolvers : Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers. Resolvers can be of three types- Queries { user { username email } } Mutations mutation { createUser(username: "test", email: "test@test.com") { username email } } - Subscriptions subscription { users } Why choose GraphQL over REST Challenges with REST We have been using REST API's for a long time now. But there exists some problems with REST like fetching data from REST API comes with lot of unnecessary data being fetched. Also there is a need to remember a lot of API endpoints. With GraphQL we describe in the client which data we want to have instead of just asking all the data. GraphQL Solves the issue In the backend, we need to define our data types which will form our schemas. and the resolvers to resolve the request coming frontend. In GraphQL we only need to maintain a single endpoint where we would request only those data that we need on the frontend. GraphQL basically reduces the network call by enabling us to fetch all the data that we need in a single query from a single endpoint. GraphQL also comes with a set of challenges which we would discuss later in this article. Using Apollo with TypeGraphQL While the most used library for GraphQL is Apollo. Apollo Server comes with a lot of features like caching , external data loader and many more. The Apollo Client is a tool which helps you use GraphQL in the frontend. It provides different features like in-memory caching, state management etc. It can be integrated with multiple JavaScript frameworks like React, React Native, Vue, Angular and for iOS and Android, there are also possibilities to use the Apollo Client. TypeGraphQL TypeGraphQL is modern framework for creating GraphQL API's. While apollo is really great and solves many problems that we have. But developing a GraphQL API in Node.js with TypeScript is sometimes a bit of a pain. This makes it easy to use with typescript as your first language. Creating a sample resolver would look like : class UserResolver { private userCollection: User[] = []; async users() { return await this.userCollection; } } Using TypeGraphql with Typegoose Well Typegoose is basically a TypeScript wrapper around mongoose. It is easy to use in typescript environment and provides a lot features. The first challenge I encountered while Integrating typegoose with typegraphql is that I had to define multiple interfaces one for typegoose, then one for typegraphql schema, So there was lot of redundancy happing around. So the solution I found was just to use typgraphql decorators on top of typegoose methods. @ObjectType() export class User { @Field() readonly _id: string; @Field() @prop() public username: string; @Field() @IsEmail() @prop() public email: string; } So here we define our mongoDB models with prop() decorator from typegoose and along with we simultaneously define our GraphQL schemas with ObjectType() and Field() decorators form typegraphql. It basically removes all the redundant interfaces we had earlier. The second challenge I encountered is that during the initial phase I was writing all my core logic directly into resolver methods which eventually created lot of problems in maintaining the codebase So the solution was that I started refactoring all my codebase into different folder structure. I started using typescript decorator features for services and used dependency Injector to inject all my Database models and Services directly into Resolvers. import { Service, Inject } from "typedi"; () export class UserService { constructor("userModel") private readonly UserModel) {} (async getAll() { return this.UserModel.find(); } } So here we are creating UserService which injects userModel. now once we have our service running we can inject this directly into our Resolvers as : @Resolver() export class UserResolver { constructor( private readonly userService: UserService, ) { } @Query(() => [User]) async users() { return this.userService.getAll(); } } Most Common Challenge you'll face When using GraphQL we have a lot advantages but it comes with its own set of challenges or cons you would say. The most common problem you would face is that server making a lot of multiple request to the database then expected. Suppose you have a list of posts, in which each of post has a user document to it. Now you may want to fetch all of these posts, with user data. When using REST this would be like having two database calls. One for posts and one for users corresponding to these posts. But what in GraphQL? we now have an extra call to fetch each user data per resolver that is per. Now let's say we have 10 posts and each post also has 5 comments, each of which has an user document. So the number of calls we'll have is one for the list of posts, 10 for the post authors, 10 for each sub-list of 5 comments and 50 for the comment users which sums up to around 71 database calls to fetch a set of data! Nobody would want this to happen, waiting 15 secs to load a set of posts. To solve this problem we have Dataloader library. Dataloader basically lets will let you combine or batch multiple similar requests and cache database calls. Now the dataloader detects that posts having similar id's and batch them together and will reuse the user document which it already has in memory instead of making a new database call. So These were the challenges I have came across till now while building a GraphQL based API. The source code for the Nx-Node-Apollo Graphql API is here github.com/DevUnderflow/nx-node-apollo-grahql-mongo Thanks for reading, stay awesome! ❤ I hope you have enjoyed this article and you may avoid above problems beforehand , I also hope that if it gave you some sort of inspiration for your work. If you may want to checkout other articles its right here blogs.smithgajjar.me. Feel free to follow me on LinkedIn. Do checkout my website at smithgajjar.tech.
https://blogs.smithgajjar.tech/building-graphql-api-with-nodejs-typegraphql-typegoose-and-troubleshooting-common-challenges?guid=none&deviceId=584e3ba3-5f12-4bbd-832e-0dd08958e301
CC-MAIN-2021-31
refinedweb
1,233
61.87
... problem is data is not inserting into DB even though the program is executed... for more information. Thanks.  delete query problem - Hibernate editor shows the following output log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j... correctly , the problem is only delete query. 2) query.executeUpate(); -> hibernate problem hibernate problem please help me.... log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Exception in thread spring rmi - Log4J spring rmi HI, iam using eclipse for developing spring based rmi application. my problem is whenever a method is called in a server the log should..., http Problem in running first hibernate program.... - Hibernate Problem in running first hibernate program.... Hi...I am using.../FirstExample Exception in thread "main" "... programs.It worked fine.To run a hibernate sample program,I followed the tutorial below java - Log4J java a small servlet application with procedure that how to get logg statements in that servlet application. Hi friend, Logging Filter Servlet application related u r Problem. Read for more Hibernate Logging using Log4j This section contains detail description of how you can use Log4j for logging configuration... Is there any specific log4j statements for Hibernate Envers Hibernate - Hibernate for me to provide you the solution if problem is clear. please post all code...Hibernate Hai this is jagadhish while running a Hibernate application i got the exception like this what is the solution for this plz inform me L4j in WebApplication with common logging - Log4J configure log4j for WebApplication configure log4j for WebApplication Hello,I seems that log4j.properties file is missing in your... of the web application.Hope this will solve your problem. Don?t forgot to update your hibernate code problem - Hibernate hibernate code problem suppose i want to fetch a row from the table... . Please visit for more information. If you have any problem this send me detail and source code log4j - Log4J log4j could u pls help me out regarding the log4j coding JSP cannot log to FileAppender - Log4J Log4j. At the moment, it logs fine to console when run from class main method... Try to write log Hi friend, For solving the problem on log4j String SQL_QUERY =" from Insurance...: " + insurance. getInsuranceName()); } in the above code,the hibernate...= request.getParameter("name"); For more information on hibernate visit to : http A program solution needed A program solution needed I need a solve for this problem please ! a program that displays grade statistics. The program should read any number of grades (up to 100) and ends when the user enters -1, the program should reject j2me solution - MobileApplications send me the solution for this problem i am grateful to you. Thanks & Regards solution solution A developer wants you to develop a simple take away restaurant order service. The system reads from a file containing information about the restaurant (such as the name, place and menu). The system then allows the user Hibernate Isolation Query. - Hibernate Hibernate Isolation Query. Hi, Am Using HibernateORM with JBOSS... the records from that table. Which not happening now ? I want to have the solution for the problem solution for mapping hibernate and pojos from net beans through database solution for mapping hibernate and pojos from net beans through database ... application Employee . i am using hibernate to connect to database which i have... which contain hibernateutil.java Then i create hibernate mapping and pojos from Java - Hibernate , this type of output. ---------------------------- Inserting Record Done Hibernate... FirstExample { public static void main(String[] args) { Session session = null... = null; try{ // This step will read hibernate.cfg.xml and prepare hibernate what is problem of tree loading hibernate - Hibernate Java Compilation error. Hibernate code problem. Struts first example - Hibernate Java Compilation error. Hibernate code problem. Struts first example Java Compilation error. Hibernate code problem. Struts first example Fleet Management Solution India solution at market's best price to its customers. Fleet management task is more..... All these are possible only because of any efficient fleet management solution...., which has recently entered in this field has a perfect fleet management solution hi - Log4J hi Please give me the clear definition of Log4J and give me the example java - Log4J java Q What is the real use for log4J? Hi Friend, Please visit the following link: Thanks.  hibernate - Hibernate hibernate Hai,This is jagadhish I have a problem while developing..., As per your problem exception is related to ant.Plz check the lib for Ant. For read more information: code - Hibernate Hibernate code firstExample code that you have given for hibernate to insert the record in contact table,that is not happening neither it is giving... inserted in the database from this file. Retrieve Value from Table - Hibernate retrieve values From database using hibernate in web Application. As I new to hibernate I couldn't find solution for this problem.. Can anyone help please.. ...:// select Query result display problem Hibernate: select cc0.id as col00 from cc cc0_ Cc$$EnhancerByCGLIB$$2235676a cannot be cast to [Ljava.lang.Object; can any one suggest the solution Hibernate advantages and disadvantages the solution of your problem on the web. You can even download and learn Hibernate...Hibernate advantages and disadvantages In this section we will discuss Hibernate advantages and disadvantages, and see why we should or shouldn't Tomcat installation problem - Hibernate Interview Questions Tomcat installation problem Hello Explain Transparent Persistence - Hibernate Explain Transparent Persistence Hi Friends, Can u plz explain Transparent Persistence briefly Hi Follow this link to find solution of your problem... program session.invalidate() problem with session.invalidate() i stuck by a line with "session.invalidate()", after user logout also by pressing the back button of the browser... the solution to fix this ....thank u Could not read mappings from resource: e1.hbm.xml - Hibernate /*tHIS IS THE HIBERNATE cONFIGURATION*/ /*THIS IS THE HIBERNATE... org.hibernate.cfg.Configuration; import org.hibernate.cfg.*; public class FirstExample System Error messge - Log4J System Error messge Hi I am implementing log4j to my application I am getting this error message ?log4j: WARN No appenders could... Please initialize the log4j system properly.? I don?t have any Updating log4j programatically Updating log4j programatically Is there a ready made utility which I can use to edit the log4j.xml programmatically Skyline Problem . Your method should solve the problem three different ways; each solution... is the line tracing the largest y value from any rectangle in S The Problem: Write java log4j - Java Beginners java log4j which is the best site to prepare log4j in java since i am new to it Hi Friend, Please visit the following link: Hope that it will be helpful log4j in web application log4j in web application Hi all, I am new to log4j. I want to use log4j in my web application. I need to write the debug,info,warn into a file. But i don't know how to do the same. Please send one example with explaination Struts-Hibernate-Integration - Hibernate Struts-Hibernate-Integration Hi, I was executing struts hibernate... the solution for folllowing issues javax.servlet.ServletException... the following link: Wimax solution jsp solution Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/42229
CC-MAIN-2015-40
refinedweb
1,212
50.33
Hi! As of a recent buzz around the community, after the introduction of the C# vNext in the world of .NET languages, (more precisely on C# and VB.NET) its time to let you through and understand how the features are working in current scenario. Well, it is true a large mass of people is writing about it but believe me, I didn't saw any which gives you the full example under one shot. Hence, I thought I might give it a try. In this post I will try to cover most of the bits related with Async programming model and also to give you a chance to understand the concept and give feedback on the same. SideNote : One of my article is in monthly survey, you would like this article too.It is also present here(another) It had been a long way to go if I have to start talking about C# from the very beginning. But its quite interesting if I give you the whole shot of entire evolution of C# as a language just now before going into the latest C# adjustment. In PDC 10, Anders pointed out the entire evolution of C# language, lets go into it first : Basically C# is continuously getting enriched with newer concepts and hence gradually its becoming the industry best language but it does include backward compatibility of each of the existing language features. In the above figure, you can see, C# was introduced as a language way back in 2001 when it was first introduced as truly Managed Code language. The initial C# language was great, but had lots of things absent. Later on, C# 2.0 was introduced. It introduced with a great new feature Generics which was never introduced before. C# 3.0 was actually for LINQ, a truly language integrated query syntax, where you can dealt with querying your existing .NET data structures using simple lambdas or LINQ expressions without manually traversing the list yourself. Finally its in .NET 4.0 the Task Parallel Library was introduced, which lets you create more responsive applications by giving away Tasks for each ongoing operation. If you have used Parallel Extensions to .NET, you might already know that Task was introduced to represent the future. It represents an Ongoing operation that will result you an output in future. Task object has few features which you might address : ContinueWith So task is the basic unit of Task Parallel Library which wraps up everything we need to invoke a Thread and allows to run a program module parallely. Thread C# 5.0 is introduced with one main motive in mind, that is to mold the language in such a way that the programmer can program the logic as he would have done synchronously maintaining the original flow of the program. C# already have Threads to deal with asynchronous kind of programming. With C# 2.0 it is very easy to write Async style of programming where you can create a Delegate and call its own implementation of BeginInvoke and EndInvoke and put a callback in, which will be called as and when the execution is done. But basically what happens, your code is getting more and more complex as you increasingly introduce more and more asynchronous patterns. You need to have callbacks for each of those calls so that when the call gets finished, the operation will finally invoke the callbacks and your rest of the logic gets executed. Thereby, with greater extent of asynchrony in your code(which we often require) your code will look more and more complex and hard to decipher for others. C# 5.0 keeps the notion of the programming model intact, but lets you write your application just as you would have done for synchronous programming style with the same logical flow and structure, but with few adjustments in your code and the work will work asynchronously. Delegate BeginInvoke EndInvoke So if you go on with the Asynchronous pattern, in terms of Parallelism, we call the new pattern as Task Asynchronous Pattern. It is the first attempt to change the language a bit after Threads are introduced in C# 1.0 to make it easier to write truly responsive applications. By Responsive applications we mean, that we can leverage more work on one thread rather than blocking threads for UI responsiveness. Most of us has confusion in the concept of Asynchrony and concurrency. Well, I would say you think differently than what you think now. Lets take the example of Parallelism. If you think of concurrency we are thinking of dealing with CPU cycles. Say for instance, you want to do a big calculations for your application. In such a situation, you want to do the calculation in parallel. So what you think? You need to have multiple Threads running in parallel which finally gets you the output. Thus, if you think of a certain time in between running of your application, you actually have more than one CPU busy with your calculation and makes maximum utilization of the CPU, and concurrently accessing your resources. This is what we call Concurrency. Asynchrony on the other hand, is a super set of Concurrency. So it includes concurrency as well as other asynchronous calls which are not CPU bound. Lets say you are saving a big file in your hard drive, or you want to download some data from the server. These things does share your CPU time-slices. But if you can do this in asynchronous pattern, it will also be included in Asynchrony. So to summarize, Asynchrony is a pattern which yields control instantly when called, but waits the callback to arise later in future. Concurrency on the other hand, parallel execution of CPU bound applications. Literally speaking, No... Its not. In present scenario, if you need to create a Responsive application you always think of creating a new Thread from the ThreadPool, calling the Resource (which eventually blocks the Thread for the moment) and finally get the result back when the device says he is ready. But does it makes sense always? No. Say you are downloading a movie, which is Network bound. So basically there is no involvement of CPU in this scenario. So according to Microsoft people, your UI Thread is actually creating the Message and thows to the Network device to do this job and returns back immediately without getting the result. The Network device will do its task accordingly (downloading the url) and finally find the UI thread using SynchronizationContext appropriately and return the result. Hence, when the Network device finishes its work, it can communicate to the appropriate thread and invoke the callback. Isnt it sounds good? SynchronizationContext Yes, say you have 10 numbers of network calls to be made in parallel. In case of previous approach, you would have created 10 Threads each of which will call the Network API and block itself until it gets the response. Hence, even though you are not using a single time slice of CPU, all your ThreadPool threads gets exhausted. Well you might wonder, how about increasing the ThreadPool threads size? Well, you probably can, but this would give additional pressure if all the network resources gets available after a while. Hence Async pattern can help you in this regard. Such that, you would have called each of the resources asynchronousy from the same thread, and wait for the Callback to arise. ThreadPool Before I proceed what we have introduced, it is very interesting to know what is available now, so that you could compare between the two approaches. Say you want to download few links from the server, as of now I am doing it synchronously, I might use : const string Feed = "{0}"; private void btnSync_Click(object sender, RoutedEventArgs e) { this.SynchronousCallServer(); } public void SynchronousCallServer() { WebClient client = new WebClient(); StringBuilder builder = new StringBuilder(); for (int i = 2; i <= 10; i++) { this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); string currentCall = string.Format(Feed, i); string rss = client.DownloadString(new Uri(currentCall)); builder.Append(rss); } MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); } In the above method, I have called a WebServer Url directly using WebClient and downloaded the entire string which I later on append to the builder object and finally when all the links are downloaded (sequentially) we show a MessageBox to the user. You should also notice, we are also updating a status message while downloading the urls. Now lets run our application and call the method : WebClient MessageBox In the above figure you can see the application stops responding, as UI thread gets blocked when the DownloadString is called. You should also notice, the screed does not update itself with the status message, as we can see only the final status message after all the strings gets downloaded. DownloadString Now this is not a good UI design. Is it ? I say no. So let us make it asynchronous to call the download string sequentially as we are doing. So how different the code should look like: const string Feed = "{0}"; private void btnaSyncPrev_Click(object sender, RoutedEventArgs e) { StringBuilder builder = new StringBuilder(); this.AsynchronousCallServerTraditional(builder, 2); } public void AsynchronousCallServerTraditional(StringBuilder builder, int i) { if (i > 10) { MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); return; } this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); WebClient client = new WebClient(); client.DownloadStringCompleted += (o,e) => { builder.Append(e.Result); this.AsynchronousCallServerTraditional(builder, i + 1); }; string currentCall = string.Format(Feed, i); client.DownloadStringAsync(new Uri(currentCall), null); } OMG! This is terrific. The code looks completely different. First of all the DownloadStringAsync of WebClient does not return the string, as the control is returned back immediately and hence to get the Result we need to add an EventHandler for DownloadStringCompleted. As the EventHandler is actually a completely different method we need to send the StringBuilder object every time to the Callback method and eventually the callback recursively calls the same method again and again to create the entire structure of data. So basically, asynchronous call to the same method looks totally different. DownloadStringAsync EventHandler DownloadStringCompleted EventHandler StringBuilder Asynchronous pattern is been simplified like heaven with the introduction of C# vNext. As shown in the PDC 10 by Anders Hejlsberg here, introduces two new keywords "async" and "await" which totally simplifies the asynchrony from the language perspective (You can also read my post which I have posted just after PDC). Before we delve into these, let me take a look at the same code in this approach: const string Feed = "{0}"; public async Task AsynchronousCallServerMordernAsync() { WebClient client = new WebClient(); StringBuilder builder = new StringBuilder(); for (int i = 2; i <= 10; i++) { this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); string currentCall = string.Format(Feed, i); string rss = await client.DownloadStringTaskAsync(new Uri(currentCall)); builder.Append(rss); } MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); } So the code looks identically the same with two keywords "async" and "await". Does it work? Yes, when you try running the code, it works the same way as it would have done with synchronously. You have noticed that I have used DownloadStringTaskAsync, which actually an asynchronous implementation of DownloadString with the same approach. It is an extension method which will be available only if you install async CTP. DownloadStringTaskAsync Asynchronous pattern is still in CTP, so you need to install few bits on your machine which will update your Visual Studio 2010 to allow these two keywords. After you install both of them in your machine, reference AsyncCTPLibrary which could be found in %MyDocument%\Microsoft Visual Studio Async CTP\Samples\AsyncCtpLibrary.dll to your application. AsyncCTPLibrary %MyDocument%\Microsoft Visual Studio Async CTP\Samples\AsyncCtpLibrary.dll Following the PDC, we can saw async is a new modifier for a method, which lets the method to return immediately after its been called. So when a method is called, the control is yielded immediately until it finds the first await. So await is a contextual keyword which might be placed before any Task (or any object which implements GetAwaiter) object which lets you to return the control back immediately while the method gets executed. Once the method gets executed the caller finds the same block and invokes a GoTo statement to the same position where we have left and registers the rest of the code as we wrote. Each of those adjustments are made automatically from the compiler itself so no user intervention is required. Task GetAwaiter Well, compilers are good at State Machines. If you think of C# IEnumeramble, the compiler actually builds a State Machine internally for each yield statement you invoke. So when you write a logic which corresponds to a method which has yield statement in it, the whole State Machine logic is prepared by the compiler so that on a certain yield, it automatically determines the probable next yield based on the work flow. C# asynchrony builds on top of the same approach. The compiler made appropriate modifications to your program to build the complete state machine for the block. Hence, when you write await for a block it actually yields the control after calling the method, and returns back a Task object that represents the ongoing method. If the ongoing method returns something it is returned as Task<T>. Lets look at the figure below: IEnumeramble Task<T> The code runs in two phazes. First it calls AsynchronousCallServerMordern method until it finds an await, which returns a Task object immediately after registering the rest of the method in its State Machine workflow step. But after it is returned to the caller, it again invokes an await, which returns the control back to the UI (void return type in async method means call and forget). Hence the UI will be available immediately. After the call to DownloadStringTaskAsync gets finished, one time slice is taken by the program to run the existing code until it finds the next await, and it goes on until all of the links are downloaded successfully. Finally the control is free for the UI totally. AsynchronousCallServerMordern async While you think of this situation, you might be thinking how is it possible to return the control before executing the whole method instance. As I didnt told you the entire fact in this regard, this type of confusion might occur to you. Let me try to clarify this a bit more. So, when you are creating an async method, you are actually creating a new instance of the method. Methods are generally to be run. But if you think of method in real time, its the instance which runs. .NET actually cretes a statemachine object which holds different steps of the method body. If you have already used up StateMachine, you must know, state machine can easily keep track of the current state of the flow. So the method instance is nothing but the instance of a state machine, which holds the parameters, local variables, the state of the method that it is currently is. Thus when you are going to encounter the await statement, it actually saves the satemachine object as a variable which it resumes again when the awaiter gets the response. For instance, I write the code as below : Console.WriteLine("Before await"); await TaskEx.Delay(1000); Console.WriteLine("After await"); Now, when you compile the assembly, it actually creates an object of StateMachine with two Method (1 for each state). Console.WriteLine("Before await"); await TaskEx.Delay(1000); Say for instance, it names it as State 1. Console.WriteLine("After await"); So basically there is no single method body here, but the compiler creates 2 method(I will clarify those in detail just after I define TaskAwaiter) of which the first one is called first, and the object stores the current state as State1, and after a wait, when the Task Placeholder gets the appropriate result, it invokes the Next State and gives its completion. TaskAwaiter How wonder, Exception Handling works the same as synchronous calls as we do for asynchronous. Prevously while dealing with async code, say for instance for WebClient.DownloadStringAsync we need to manually check for every DownloadComplete calls if e.Error has any value or not. But in case of async pattern, you can use your very own Try/Catch block to wrap around your async code and the error will be thrown automatically to catch in the block. So if you want to put the exception handling for the code you would write : WebClient.DownloadStringAsync DownloadComplete e.Error public async Task AsynchronousCallServerMordernAsync() { WebClient client = new WebClient(); StringBuilder builder = new StringBuilder(); for (int i = 2; i <= 10; i++) { try { this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); string currentCall = string.Format(Feed, i); string rss = await client.DownloadStringTaskAsync(new Uri(currentCall)); builder.Append(rss); } catch(Exception ex) { this.tbStatus.Text = string.Format("Error Occurred -- {0} for call :{1}, Trying next", ex.Message, i); } MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); } Cool. Yes it is. The async pattern does not need to do any modification to work with exceptions. As everything is done, you might be thinking is it not possible to invoke each of the statement parallely rather than sequentially, so that we could save some time. Yes, you are right. It is absolutely possible to deal with multiple tasks all at once and later on await for all at a time. To do this, let me modify the code : private async void btnaSyncPresParallel_Click(object sender, RoutedEventArgs e) { await this.AsynchronousCallServerMordernParallelAsync(); } public async Task AsynchronousCallServerMordernParallelAsync() { List<task><string>> lstTasks = new List<task><string>>(); StringBuilder builder = new StringBuilder(); for (int i = 2; i <= 10; i++) { using (WebClient client = new WebClient()) { try { this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); string currentCall = string.Format(Feed, i); Task<string><string>(lstTasks); foreach(string s in rss) builder.Append(s); } catch {} MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); } </string> So basically, what we need to do, is to create the object of WebClient inside the loop, and also need to remove the await for the DownloadStringTaskAsync call. As I have already told you that await immediately returns the control back to the caller, we do not need it to return immediately. Rather we create a list of all the Tasks and finally aggregate all the tasks into one using TaskEx.WhenAll and invoke await on that. Hence the TaskEx.WhenAll will return you an array of strings, which you might use when all the tasks finishes. OMG, the call to it is returned immediately. TaskEx.WhenAll Another important part of the code is to cancel the existing ongoing task. For that, async pattern introduces a new object called CancellationTokenSource. You can make use of it to cancel an existing operation that is going on. Lets take a look at the sample application to demonstrate the cancellation. CancellationTokenSource In this application, we have two Buttons, one of which calls Codeproject RSS feed, while the cancel button invokes the cancellation for the operation. Lets take a quick pick, how I build the application. string url = ""; CancellationTokenSource cancelToken; private async void btnSearch_Click(object sender, RoutedEventArgs e) { var result = await LoadArticleAsync(); this.LoadArticleList(result); await TaskEx.Delay(5000); if (cancelToken != null) { cancelToken.Cancel(); tbstatus.Text = "Timeout"; } } private void btnCancel_Click(object sender, RoutedEventArgs e) { if (cancelToken != null) { cancelToken.Cancel(); tbstatus.Text = "Cancelled"; } } void LoadArticleList(string result) { var articles = from article in XDocument.Parse(result).Descendants("item") let subject = article.Element("subject").Value let title = article.Element("title").Value let description = article.Element("description").Value let url = article.Element("link").Value let author = article.Element("author").Value let publishdate = article.Element("pubDate").Value select new Article { Subject = subject, Title = title, Description = description, PublishDate = publishdate, Author = author, Url = url }; ICollectionView icv = CollectionViewSource.GetDefaultView(articles); icv.GroupDescriptions.Add(new PropertyGroupDescription("Subject")); this.lstArticles.DataContext = icv; } async Task<string> LoadArticleAsync() { cancelToken = new CancellationTokenSource(); tbstatus.Text = ""; try { tbstatus.Text = "Searching... "; var client = new WebClient(); var taskRequest = await client.DownloadStringTaskAsync(this.url); tbstatus.Text = "Task Finished ... "; return taskRequest; } catch (TaskCanceledException) { return null; } finally { cancelToken = null; } } </string> So basically, I have used a WPF application (To simplify I didn't used MVVM) where I have invoked a web DownloadStringTaskAsync call. The only thing that you need to do for TaskCancellation is to create the instance of CancellationTokenSource inside the block which you want to cancel. In the above code, I have created the object inside the method LoadArticleAsync, hence whenever I invoke cancelToken.Cancel, the await for this call will be released. You can even do calls like cancelToken.CancelAfter(2000) to cancel the operation after 2 seconds. TaskCancellation CancellationTokenSource LoadArticleAsync cancelToken.Cancel await cancelToken.CancelAfter(2000) Last but not the least, what if, you really want to use a new Thread to call your method? With async pattern, it is even easier to do than ever before. Just take a look at the code : Thread async private async void btnGoCPUBound_Click(object sender, RoutedEventArgs e) { await new SynchronizationContext().SwitchTo(); //Switch to net Thread from ThreadPool long result = this.DoCpuIntensiveWork(); //Very CPU intensive await Application.Current.Dispatcher.SwitchTo(); MessageBox.Show(string.Format("Largest Prime number : {0}", result)); } public long DoCpuIntensiveWork() { long i = 2, j, rem, result = 0; while (i <= long.MaxValue) { for (j = 2; j < i; j++) { rem = i % j; if (rem == 0) break; } if (i == j) result = i; i++; } return result; } In the above case we use SynchronizationContext.SwitchTo to get a YieldAwaitable which creates a new thread from the ThreadPool and returns an object that implements GetAwaitable. Hence you can await on the same. Later on, you can use your Dispatcher.SwitchTo to return back to the original thread again. So isn't it easy enough? Yes really, its now fun switching from one thread to another. SynchronizationContext.SwitchTo YieldAwaitable ThreadPool GetAwaitable Dispatcher.SwitchTo There are quite a few things to remember in this regard, lets list them : async MyMethodAsync Task Result GoTo This is basically what you must know to deal with async pattern. In later section, I will try to go more deeper aspect of the async framework. Well, it is always good to go deeper into what exactly happening with this. To check, I have used Reflector and found few interesting facts: As I have already told you, await works only for objects which implements GetAwaiter. Now Task has the method GetAwaiter, which returns another object (called TaskAwaiter) which is used to actually register the await pattern. Any awaiter object should include basic methods like BeginAwait and EndAwait. There are quite a number of methods implemented into the library which is awaitable. Now if you look into the BeginAwait and EndAwait, its basically creating some delegates similar to what you might do in case of normal asynchronous pattern. BeginAwait EndAwait The BeginAwait actually calls TrySetContinuationforAwait, whic actually breaks apart the existing method body into two separate blocks and registers the next part of each await statement to the continuation of the Task, just like you are doing like TrySetContinuationforAwait Task1.ContinueWith(Task2); where Task2 represents the Rest of the code to run in callback. So if you want your object to work with asynchronous patter, you must have GetAwaiter implemented which returns an object BeginAwait and EndAwait defined. As of surprise, extension methods can also be used for writing the same for now, I am eager to see if it is possible in original version. As in the previous section, I showed how to build an awaiter, but lets look into how our own application looks like after compiler does the trick To demonstrate this, let me create one of the most simplest application with single await and try to demonstrate the IL of it. Lets look into the code : public class AsyncCaller { public async void GetTaskAsync(List<task> tasks) { await TaskEx.WhenAny(tasks); } }</task> So, I created one class library and added this method to it. It basically awaits for any task to complete from the list of Tasks. Now if you look inside the assembly, it would look : public void GetTaskAsync(List<task> tasks) { <gettaskasync>d__0 d__ = new <gettaskasync>d__0(0); d__.<>4__this = this; d__.tasks = tasks; d__.MoveNextDelegate = new Action(d__.MoveNext); d__.$builder = VoidAsyncMethodBuilder.Create(); d__.MoveNext(); } </gettaskasync> There is a compiler generated type which separates the two parts of the code into two tasks and allows it to continue with the other method which is created using VoidAsyncMethodBuilder.Create WhenAll [CompilerGenerated] private sealed class <GetTaskAsync>d__0 { // Fields private bool $__disposing; private bool $__doFinallyBodies; public VoidAsyncMethodBuilder $builder; private int <>1__state; public List<Task> <>3__tasks; public AsyncCaller <>4__this; private Task <1>t__$await1; private TaskAwaiter<Task> <a1>t__$await2; public Action MoveNextDelegate; public List<Task> tasks; // Methods [DebuggerHidden] public <GetTaskAsync>d__0(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] public void Dispose() { this.$__disposing = true; this.MoveNext(); this.<>1__state = -1; } public void MoveNext() { try { this.$__doFinallyBodies = true; if (this.<>1__state != 1) { if (this.<>1__state == -1) { return; } this.<a1>t__$await2 = TaskEx.WhenAny(this.tasks).GetAwaiter<Task>(); this.<>1__state = 1; this.$__doFinallyBodies = false; if (this.<a1>t__$await2.BeginAwait(this.MoveNextDelegate)) { return; } this.$__doFinallyBodies = true; } this.<>1__state = 0; this.<1>t__$await1 = this.<a1>t__$await2.EndAwait(); Task task1 = this.<1>t__$await1; this.<>1__state = -1; this.$builder.SetCompleted(); } catch (Exception) { this.<>1__state = -1; this.$builder.SetCompleted(); throw; } } Yes the CompilerGenerated nested type creates the necessary adjustment to hide the original call to BeginAwait. If you see MoveNext, you can definitely get the idea that TaskEx.WhenAny is called from there which gets the Awaiter. The Awaiter is then registered to MoveNextDelegate which stores the continuation part of the program. Once the MoveNext finished its task it notifies using builder.SetCompleted which eventually try to call the probable next delegate (which isn't there). CompilerGenerated MoveNext TaskEx.WhenAny builder.SetCompleted d__.MoveNextDelegate TaskAwaiter.BeginAwait EndAwaiter You should note, these kind of creating large computer generated Type will not take place in final release, but I just showed this to demonstrate the concept and also for better understanding. I would also recommend you to look into it to learn more about it. Nothing much so far for Debugging, but still there is a class named DebugInfo inside System.Runtime.CompilerServices.AsyncMethodBuilder. Though the class is internal but yet you can invoke the static method ActiveMethods to get few data available for debugging such as the methods which are not yet finished, or more precisely the methods which have intermediate statemachine available in the context will be listed here. The ActiveMethod is actually returns a List<DebugInfo> which lists : DebugInfo System.Runtime.CompilerServices.AsyncMethodBuilder ActiveMethods List<DebugInfo> When any Task is awaited, every time it builds a State Machine object which holds each step of the method body. During the initilization phaze of this, the AsyncMethodBuilder is called. In the constructor, the DebugInfo was created. If you see in reflector you will see : The AsyncMethodBuilder actually adds the Task object to create a DebugInfo inside it, which is then removed when the Task completes. The DebugInfo actually lists only ActiveMethods while others are not browsable from Debugger. This is basically in very priliminary stage, so I think it will add few more in later builds of Async framework.To see those information, you can add the variable in Watch window of Visual studio and have a quick pick on those. For more details you can browse my blog post on this. AsyncMethodBuilder After the introduction of new Async pattern, I was thinking to learn the same by trying a few applications myself. I did everything just for fun. If I do any mistake please let me know about it. Also do give your feedback on this new pattern. Thank you for reading This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) tec-goblin wrote:Good but nothing we couldn't have seen in the PDC10 presentation. Ayan Sengupta wrote:This is a very good article...although I hardly understood how it is working without a second thread!!! Ayan Sengupta wrote:2. I want to register multiple block of codes from different assemblies that should be executed when an asynchronous execution(from another assembly) completes(the concept of multicast delegate). Ayan Sengupta wrote: I want to create an assembly that encapsulates the logic of an asynchronous operation and raise a notification to the UI on completion and the UI would react accordingly. public void YourCall() { try{ //starting async operation string result = await youroperation() ; //probably the async opeation // write your callback code ... } catch { //write your error handler code } } public async Task AsynchronousCallServerMordernParallelAsync() { List> lstTasks = new List>(); StringBuilder builder = new StringBuilder(); for (int i = 2; i <= 10; i++) { using (WebClient client = new WebClient()) { try { this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); string currentCall = string.Format(Feed, i); Task(lstTasks); foreach(string s in rss) builder.Append(s); } catch {} MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); } WebClient.Dispose() Hristo Bojilov wrote:C# is becoming more and more complicate Hristo Bojilov wrote:How many really big enterprise projects based on .NET do you know outside of MS? Hristo Bojilov wrote:According to the some statistics only maximum 2% of the developers on the Earth use C# Abhishek Sur wrote: I think it is made easier. Abhishek Sur wrote:Believe me there are many. Even big enterprise companies rely on .NET heavily now. Abhishek Sur wrote:Where did you get such statistics? General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/127291/C-5-0-vNext-New-Asynchronous-Pattern?fid=1596414&df=90&mpp=10&noise=1&prof=True&sort=Position&view=None&spc=None
CC-MAIN-2015-32
refinedweb
4,947
56.45
Thanks James. That code is from the node driver, I will try to get some advice from it's developer. Thanks, On Mon, May 18, 2015 at 6:34 PM, James Taylor <jamestaylor@apache.org> wrote: > Hi Isart, > That code isn't Phoenix code. This sounds like a Node JS issue. Vaclav > has done a lot with Node JS, so he may be able to give you some tips. > Thanks, > James > > On Mon, May 18, 2015 at 9:06 AM, Isart Montane <isart.montane@gmail.com> > wrote: > > Hi Eli, > > > > thanks a lot for your comments. I think you are right. I found the client > > code that's causing the issue. Do you have an example I can use to patch > it? > > is that the recommended way to access phoenix? I've seen on the web that > > there's also a query server available, is it worth a try? > > > > > > public String[] query(String sql) > > { > > List<String> lsResults = new ArrayList(); > > Connection conn = null; > > try > > { > > conn = this.dataSource.getConnection(); > > ResultSet rs = conn.createStatement().executeQuery(sql); > > ResultSetMetaData data = rs.getMetaData(); > > int numberOfColumns = data.getColumnCount(); > > List<String> lsRows = new ArrayList(); > > for (int i = 1; i <= numberOfColumns; i++) { > > lsRows.add(data.getColumnName(i)); > > } > > lsResults.add(join("\t", lsRows)); > > lsRows.clear(); > > while (rs.next()) > > { > > for (int i = 1; i <= numberOfColumns; i++) { > > lsRows.add(rs.getString(i)); > > } > > lsResults.add(join("\t", lsRows)); > > lsRows.clear(); > > } > > rs.close(); > > conn.close(); > > } > > catch (Exception e) > > { > > e.printStackTrace(); > > return null; > > } > > return (String[])lsResults.toArray(new String[lsResults.size()]); > > } > > > > On Mon, May 18, 2015 at 5:43 PM, Eli Levine <elilevine@gmail.com> wrote: > >> > >> I don't have info on what your app does with results from Phoenix. If > the > >> app is constructing some sort of object representations from Phoenix > results > >> and holding on to them, I would look at what the memory footprint of > that > >> is. I know this isn't very helpful but at this point I would try to dig > >> deeper into your app and the NodeJS driver rather than Phoenix, since > you > >> mentioned the same queries run fine in sqlline. > >> > >> On Mon, May 18, 2015 at 7:30 AM, Isart Montane <isart.montane@gmail.com > > > >> wrote: > >>> > >>> Hi Eli, > >>> > >>> thanks a lot for your answer. That might be a workaround but I was > hoping > >>> to get a more generic answer I can apply to the driver/phoenix since > that > >>> will require me lots of changes to the code. > >>> > >>> Any clue on why it works with sqline but not trough the node driver? > >>> > >>> On Mon, May 18, 2015 at 4:20 PM, Eli Levine <elilevine@gmail.com> > wrote: > >>>> > >>>> Have > >>>> > >>>> > >>> > >> > > >
https://mail-archives.eu.apache.org/mod_mbox/phoenix-user/201505.mbox/%3CCAP1P9Pv5DbkDnNcfoO2voPuzwUV176wKDSO6-i7PEfVmu156aA@mail.gmail.com%3E
CC-MAIN-2021-21
refinedweb
427
77.13
Search: Search took 0.02 seconds. - 15 May 2009 10:39 PM - Replies - 913 - Views - 664,548 Having the same problem here with missing icon images in 3.0rc1.1 in IE only. Did you find a fix yet? - 14 May 2009 7:05 PM - Replies - 2 - Views - 1,074 The code I am working with is the 3.0 API browser: - 14 May 2009 5:59 PM - Replies - 2 - Views - 1,074 Is this a CSS problem? I can't seem to get rid of the extra line under the active tab in Internet Explorer, and I noticed that the 3.0 API browser has the same issue. See the pics. - 11 Feb 2009 8:16 AM - Replies - 1 - Views - 1,188 I need help figuring out how to get ctrl-click to work on the Image Organizer sample. I also tried using "simpleSelect" with that sample and you arent able to select anything with simpleSelect=true - 12 Aug 2008 5:13 AM - Replies - 6 - Views - 3,200 Ext.onReady(function() { var form = new Ext.form.FormPanel({ baseCls: 'x-plain', items: [{ xtype: 'radiogroup', fieldLabel: 'Auto Layout', ... - 11 Aug 2008 10:16 PM - Replies - 6 - Views - 3,200 I'm using the new "radiogroup" xtype in 2.2 in a formpanel that is in a window and I am having a hard time with the background color around the group. It comes up white no matter what I do. See... - 11 Aug 2008 8:46 PM - Replies - 18 - Views - 6,655 Is this in 2.2? I could not find it. - 9 Jun 2008 5:06 AM Thank you so much! First off, I tried "bodyStyle: 'font-size:0;line-height:0;'", and that helps, but still leaves a sliver of white space. I also tried adding different doctypes to no avail. So, I... - 8 Jun 2008 5:34 PM Thanks, but it didn't help. I added the buttons but still have white space in IE7. var btn1 = new Ext.Button({ text: 'Test', handler: function() { ... - 8 Jun 2008 4:59 PM Hi Eric. I appreciate the help, but the problem persists. New code: viewport = new Ext.Viewport({ layout:'border', items: [{ region: 'north', height: 10, bbar:... - 8 Jun 2008 1:46 PM Here is a simpler example: viewport = new Ext.Viewport({ layout:'border', items: [{ region: 'north', bbar: ["-"] },{ region: 'center', - 8 Jun 2008 6:13 AM ok, here is a screenshot of the above code in IE7. The extra space is showing up in "south" above the bbar. - 7 Jun 2008 6:56 PM js: viewport = new Ext.Viewport({ layout:'border', defaults: { collapsible: true, split: true }, items: [{ - 6 Jun 2008 10:16 PM I am having the same problem with extra space and toolbars, in IE only. Did you ever find a fix for this? - 5 Jun 2008 1:27 PM - Replies - 13 - Views - 5,789 I found the culprit. I was using: labelStyle: 'padding-left:20px;width:130px;' I changed that to : labelWidth: 130, labelStyle: 'padding-left:20px;' and that fixed the problem for me. It... - 5 Jun 2008 12:34 PM - Replies - 13 - Views - 5,789 I am having the same problem mentioned above. The exclamation shows up on top of the trigger in FireFox (it doesnt happen in IE). - 6 Dec 2007 10:14 PM - Replies - 1 - Views - 1,187 I saw an example with this, but now i cant find it. In my database I have separate fields for 'first_name' and 'last_name'. In the grid, I want to have only one column 'Name', that concatenates the... - 1 Dec 2007 10:37 AM - Replies - 13 - Views - 4,663 Animal, I can't get your code to work as is. Specifically, doing an eval on "response" is not working. success: function(response) { win.add(eval(response)); win.doLayout(); } - 30 Nov 2007 8:54 PM - Replies - 1 - Views - 1,311 I wanted to do the same, and this is what I came up with: MyGrid.bottomToolbar.displayEl.update('new text here'); - 25 Nov 2007 7:42 PM Jump to post Thread: Extra bar on FormPanel in IE by gmoney - Replies - 9 - Views - 2,159 In case anyone is interested, here is a fix for the above mentioned bug: fp.on('render', function(){ if(Ext.isIE) ... - 25 Nov 2007 7:23 PM - Replies - 66 - Views - 89,757 Hi.. I love the black theme and appreciate your work. I am having a couple issues with it. First, under FireFox, the grid paging toolpar text is black, and so are the column headings. In your... - 23 Nov 2007 11:08 AM - Replies - 23 - Views - 7,286 Using sead's code above, this is what I am doing... not sure if this is 100% correct, but it works. I am still not sure why this is necessary since this is the type of thing I'd expect Ext to handle... - 23 Nov 2007 10:07 AM Thanks! This works, although I have to put "border:false, bodyBorder:false" in four different places. I suppose this is because I am declaring the TextFields separately and then including them in... - 23 Nov 2007 9:25 AM I changed the code as you suggested but the problem persists. - 21 Nov 2007 9:49 PM I am getting a border around my TextFields. What am I doing wrong? Ext.namespace('MyNS'); MyNS.module = function(){ var field1 = new Ext.form.TextField({ fieldLabel:... Results 1 to 25 of 42
https://www.sencha.com/forum/search.php?s=aa5b3859bfe066220935a03ed47804cf&searchid=14270904
CC-MAIN-2016-07
refinedweb
899
83.96
SQL″". DTS:ObjectData ScriptProject Let’s go back to the file called "sS_LoadAssembly.dtsx[Design". sS_LoadAssembly.dtsx[Design Right click the script task and click on "Edit" Edit Under the Script Task Editor, change the "ScriptLanguage" to "Microsoft Visual C# 2010". ScriptLanguage Click Edit Script. Close the script. Save the changes. Go back to the "sS_LoadAssembly.dtsx[XML]" XML file. You will notice that additional elements have been added under node "DTS:ObjectData". We are interested in the node called "ItemGroup".". Collapse "Namespaces". Insert the following: using Microsoft.SqlServer.Management.IntegrationServices; Voilà! Now you can go ahead and access the new API for scripting SSIS 2012. Cheers, Sifiso. CodeProject This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
https://www.codeproject.com/Articles/547312/LoadplusIntegrationplusServicesplusAssemblyplusFil
CC-MAIN-2018-26
refinedweb
128
61.63
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Defining Access Levels6:13 with Pasan Premaratne Now that we know the different access levels available let's see how we can define them in our code - 0:00 An important thing to know about access controls is that you cannot define - 0:04 an entity in terms of another entity that has a lower or - 0:09 more restrictive access level. - 0:11 What does this mean? - 0:12 It means that you cannot for example define a public stored property - 0:17 whose type is internal, final private or private type. - 0:22 This is because if we try to use the property in a different module - 0:26 which is what the public access level allows the underlying type won't be - 0:31 available because it's either internal file private or private. - 0:35 To define an access level we use one of the keywords either. - 0:39 Either open, public, internal, fileprivate, or private before the entity. - 0:46 For custom types, we place this in front of the declaration and for - 0:51 variables, constants, and functions or methods, they go at the beginning as well. - 0:56 The access control level of a type defines what access control level it's members, - 1:02 that is it's properties, methods, initializers, and subscripts have. - 1:08 If you define a class as a private class or file private - 1:13 then the default access level of its members is also file private or private. - 1:18 A member cannot have a higher or - 1:21 less restrictive access level than the enclosing time. - 1:25 So inside a private class, you cannot have a public method. - 1:29 But you can go the other way around. - 1:32 Inside a public class, you can have a final private method, - 1:36 a private method, or an internal property. - 1:39 Basically you can have a more restrictive or lower access level inside a type. - 1:46 The only other bit that's important to know is when it comes to subclassing. - 1:51 You can subclass any class that can be accessed within its current context. - 1:56 So, if you have a final private class for - 1:59 example, it can be subclassed within that source file, but not outside of it. - 2:04 Because the base class is private to that file. - 2:08 A subclass cannot have a higher access level than its superclass. - 2:13 So, you cannot have a public subclass of a private superclass. - 2:18 You can also override any class member again a property - 2:23 method initializer or sub script in the sub class - 2:28 as long as it is visible in the access context and override can - 2:32 make an inherited class member more accessible than it superclass version. - 2:38 So, in the code you see here, - 2:40 our base class is a public class with a file private method named someMethod. - 2:46 This subclass is an internal class, so it has a lower access level. - 2:51 But the overridden implementation of some method is now marked internal - 2:56 Which is a higher access level than file private. - 3:00 Now all this is complicated. - 3:01 That's okay, we're not going to touch on this as much though because honestly - 3:05 we won't really be writing any such specific access control for a while. - 3:10 It's just something you should be aware of because - 3:13 as you inspect header files of the iOS SDK, the Swift standard library and - 3:17 other people's code you will come across all sorts of access control keywords. - 3:22 And it's important to know how they affect your ability to interact with that code. - 3:28 Code that we use from the sources I just mentioned is code from a different module. - 3:33 Remember we import foundation and you like it in other different modules to use it. - 3:38 This means we need to understand that open and - 3:40 public code is accessible to us one internal private and file private are not. - 3:46 Another important distinction that I probably should mention, - 3:49 even though we won't use it at all, is that while open and - 3:52 public are the same access level within a module. - 3:56 Across modules, you can only subclass classes that are marked as open. - 4:01 You can use a public class, but you cannot subclass it. - 4:05 A final class, which we've learned about before, - 4:08 is how you prevent subclassing from within a module. - 4:11 Okay, that's enough learning. - 4:13 I think it's safe to say that we've covered a lot of content in this course. - 4:18 In general, we took our Swift fundamentals like initialization, properties, - 4:22 and protocols and found out just how flexible and powerful they really are. - 4:27 We pulled back the covers on memory management and - 4:30 explained why being weak can actually be a good thing. - 4:33 If this seemed like a lot of new concepts and syntax and - 4:37 you didn't quite digest it all then I warn you, you may be a mortal human being. - 4:42 If that may be the case I strongly suggest you focus on the concepts and - 4:46 functionalities that we showcased. - 4:49 Syntax will come with time, practice, and - 4:51 frankly, from looking at the docs when you need to. - 4:54 As you grow as a developer, you are constantly adding tools to your tool belt - 4:58 and truthfully by now that belt is getting pretty heavy. - 5:02 No doubt some of the tools you use less often can just live in your truck. - 5:06 But don't take that to mean they aren't important. - 5:09 Just because you'll probably use computed properties - 5:12 more often than convenience initializers doesn't mean they aren't both critical. - 5:17 What you really need to take away from this course is remembering that - 5:20 both of these tools exist. - 5:22 So when you're presented with a tricky challenge you know it's - 5:25 time to walk out to your tool box for the tool that's just right for the job. - 5:29 Very often we need to watch, read or hear things multiple times to actually get it. - 5:35 I certainly do. - 5:36 And this course you just completed is filled with that type of elusive content. - 5:41 As you progress please revisit this grab bag of goodies. - 5:45 The time you spend re-familiarizing will, I assure you, - 5:50 be repaid ten fold in the form of cleaner, more elegant code, less debugging time, - 5:55 and a deeper more stable knowledge of Swift's exciting features. - 5:59 You have just made a big leap in terms of your understanding of Swift, - 6:03 both in terms of features and underlying concepts. - 6:07 Congratulations, this is big stuff. - 6:09 You should feel proud for meeting the challenge. - 6:11 See you soon in the next course.
https://teamtreehouse.com/library/defining-access-levels
CC-MAIN-2018-34
refinedweb
1,257
68.81
revalidate_disk(9) [centos man page] REVALIDATE_DISK(9) The Linux VFS REVALIDATE_DISK(9) NAME revalidate_disk - wrapper for lower-level driver's revalidate_disk call-back SYNOPSIS int revalidate_disk(struct gendisk * disk); ARGUMENTS disk struct gendisk to be revalidated DESCRIPTION This routine is a wrapper for lower-level driver's revalidate_disk call-backs. It is used to do common pre and post operations needed for all revalidate_disk operations. COPYRIGHT Kernel Hackers Manual 3.10 June 2014 REVALIDATE_DISK(9) STRUCT CLASS(9) Device drivers infrastructure STRUCT CLASS(9) NAME struct_class - device classes SYNOPSIS struct class { const char * name; struct module * owner; struct class_attribute * class_attrs; struct device_attribute * dev_attrs; const struct attribute_group ** dev_groups; struct bin_attribute * dev_bin_attrs; struct kobject * dev_kobj; int (* dev_uevent) (struct device *dev, struct kobj_uevent_env *env); char *(* devnode) (struct device *dev, umode_t *mode); void (* class_release) (struct class *class); void (* dev_release) (struct device *dev); int (* suspend) (struct device *dev, pm_message_t state); int (* resume) (struct device *dev); const struct kobj_ns_type_operations * ns_type; const void *(* namespace) (struct device *dev); const struct dev_pm_ops * pm; struct subsys_private * p; }; MEMBERS name Name of the class. owner The module owner. class_attrs Default attributes of this class. dev_attrs Default attributes of the devices belong to the class. dev_groups Default attributes of the devices that belong to the class. dev_bin_attrs Default binary attributes of the devices belong to the class. dev_kobj The kobject that represents this class and links it into the hierarchy. dev_uevent Called when a device is added, removed from this class, or a few other things that generate uevents to add the environment variables. devnode Callback to provide the devtmpfs. class_release Called to release this class. dev_release Called to release the device. suspend Used to put the device to sleep mode, usually to a low power state. resume Used to bring the device from the sleep mode. ns_type Callbacks so sysfs can detemine namespaces. namespace Namespace of the device belongs to this class. pm The default device power management operations of this class. p The private data of the driver core, no one other than the driver core can touch this. DESCRIPTION A class is a higher-level view of a device that abstracts out low-level implementation details. Drivers may see a SCSI disk or an ATA disk, but, at the class level, they are all simply disks. Classes allow user space to work with devices based on what they do, rather than how they are connected or how they work. COPYRIGHT Kernel Hackers Manual 3.10 June 2014 STRUCT CLASS(9)
https://www.unix.com/man-page/centos/9/REVALIDATE_DISK/
CC-MAIN-2020-45
refinedweb
411
55.54
Fabulous Adventures In Coding Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric. Good afternoon all, I am happy to announce that we are releasing a second Community Technology Preview release of Roslyn, the project I actually work on, today. I am super excited! So, let's cut to the chase. Key facts: I believe many of your blog readers, ego certainly included, are super excited as well. Please keep up the good work, Mr. Lippert! Great News! Unfortunately, I cannot install Rosyln with the latest Visual Studio 2012 RC =[. Anyone else having similar issues? I get the following: 0x81f40001 a compatible version of visual studio 2012 rc sdk was not detected The log shows: Registry key not found. Key = 'SOFTWARE\Microsoft\DevDiv\vssdk\Servicing\11.0\finalizer' and Error 0x81f40001: Bundle condition evaluated to false: (VisualStudio11ProCoreInstalled AND VisualStudio11SdkInstalled) OR (NOT VisualStudio11ProCoreInstalled AND NOT VisualStudio11SdkInstalled) @Kurt Have you installed the VS 2012 SDK? Great! This CTP is much sooner than I expected. Can't wait to try it out. It looks like a detailed list of changes is posted at social.msdn.microsoft.com/.../2341e1f5-ce2e-48ff-93d6-bdd1bdbabd81 Jason's blog looks at it as an experimental add on to VS2012: )." Do you know if it will be an option you can select when installing VS2012, or you would have to download and install separately? Also do you know if there is anything similar in the works for C++ or Javascript? That is so cool Eric! When do you think C# will get non-nullable reference types? That is so cool Eric! When do you think C# will get non-nullable reference types? Or, if there is a fundamental difficulty with it, would you consider a series of posts uncovering it? Thanks! Another question Eric, do you think it's a good idea to use Visual Studio macros as for ad-hock refactoring routines based on the Roslyn assemblies? Does Roslyn know anything about EnvDTE90 namespace? Thanks! Last question Eric, why does the title of the right column of this blog reads "About Carl Nolan - Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric." ? Thanks!
http://blogs.msdn.com/b/ericlippert/archive/2012/06/05/announcing-microsoft-roslyn-june-2012-ctp.aspx
CC-MAIN-2014-15
refinedweb
368
57.98
2 years, 5 months ago. STM32L0 RTC with UART We are using the STM32L073 and the mBed LoRaWAN application. This works fine and provides serial debug on PA2, PA3 at 115200 which is 8us per bit. However, we wanted to add the RTC. When rtc_init(), is called, the uart speed changes to 28us per bit. Why is this happening - especially when the RTC runs from a different part of the clock module for the L0 parts. 1 Answer 2 years, 5 months ago. I checked this example on mbed IDE + NUCLEO_L073RZ (mbed lib v136) and no problem seen with the USART. Can you please share your code ? #include "mbed.h" Serial pc(SERIAL_TX, SERIAL_RX); DigitalOut myled(LED1); int main() { int i = 1; time_t seconds; pc.baud(115200); pc.printf("Hello World !\n"); wait(1); pc.printf("Hello World again !\n"); set_time(1387188323); printf("Date and time are set.\n"); while(1) { wait(1); pc.printf("This program runs since %d seconds.\n", i++); seconds = time(NULL); printf("Time as a basic string = %s\n", ctime(&seconds)); myled = !myled; } } You need to log in to post a question
https://os.mbed.com/questions/77184/STM32L0-RTC-with-UART/
CC-MAIN-2019-35
refinedweb
187
87.01
Hello I am trying to build a function that i can use in to search for an object or item from its name, Here is what I have in sfind.py def findobj(searchTxt,items): """ This function will help you find an object or an item from list of items passed to it. """ print items import re for each in items: print each result = re.search(searchTxt, each) #returns None if search fails if result: print each #and do whatever you need... return True else: print("Not found") but every time i enter something to seach I get Not found. try: reload(sfind) sfind.findobj("lambert1",['lambert1','lambert2','grey']) except: import sfind sfind.findobj("lambert1",['lambert1','lambert2','grey']) please help me, I guess something wqrong with the seach behaviour....
https://www.daniweb.com/programming/software-development/threads/435425/search-function
CC-MAIN-2017-17
refinedweb
129
74.19
IFRAMEs have a bad reputation. I understand the sometimes confusing search engine arguments against (search links will often point to the iframe alone, rather than to the enclosing page as a whole). However, I run a discussion forum on my boat building website that now has 20,000 posts. It's a valuable addition to the boat building community and to my website. But I want that forum to appear as the contents of a block element <div> inside my content management system (Robopages). Stripping the <html> <head> and <body> elements from the forum's *.tpl templates won't work without major php code modifications, because the forum's links are generated the wrong way (not to work as a plugin to an enclosing system) and because of conditional header branching: if ($php_condition) header("location: $this);else header("location: $that); .......................................this sort of thing results in chaos for an enclosing CMS I just finished several days of work hacking a simpler open source forum so it could be used in embedded mode. But that simpler forum lacks features I want.What ARE the arguments against simply putting my original forum inside an iframe, so it can appear as an integral part of my enclosing CMS. Even though it isn't? If it's just the search engine argument perhaps I don't care. Why doesn't SOMEBODY make an open source forum that can indeed be embedded? What happens if someone links directly to a forum thread from an external site? I'd recommend customising the forum itsself with your logo and general colours and simply link to it from your main site, and providing a link back from the forum. Which forum software are you using? sometimes it may be possible to embed the forum, but my suggestion would be to either convert your entire site + forum to some other CMS rather than using Iframe because a user wont be able to link to individual posts. Depending on the forum software it can be relatively easy to a major pain. Here are some ideas each of differing merit. Trying to reengineer a web template is awkward. Not sure what happens if you later upgrade the forum software, say, to deal with an exploit or security issue. You're in danger of losing your changes. This is quite a difficult option to get to work in practice. I understamd Nabble is an embeddable forum. Its not really open source but a hosted solution. Its prbably the easiest option. () You may be able to modify the template on the fly before it gets embedded into the iframe. This will require some link rewriting. Its effectively adding a proxy between your iframe and the forum. This is what I consider to be medium difficulty. The advantage here is that security updates dont break your modifications. Anyway, without thinking it through too deeply those are my thoughts. Here's another one I found: Talki looks interesting. But it is Wordpress specific. Yes, re-engineering *.tpl templates is difficult (worse than coding....well it is coding) and precarious, because new software updates (as you pointed out) so often break your *.tpl modifications. I used templates when I was a java programmer. Then they make sense because you can edit templates directly from the keyboard without recompiling the enclosing Java codes. For interpreted languages I don't really like templates. You gain a little and lose a lot. The templates are tightly coupled to calling statements hidden who knows where in the enclosing language (usually PHP). Templates are supposed to separate content from programming logic. But they don't do that. They just move the content into a mess of hard-to-deal-with IF AND OR ELSE templating logic, where simple changes are easy but complex changes are now more difficult. This is off topic I guess. But I hate templating and never use it myself. I'd rather write good code. Ok, sorry, when you mentioned php on one hand and cms on the other I assumed wordpress. What you could do then is the proxy idea of using something like php and curl to fetch the iframe contents in the background and then parse the html and remove the header and rewrite the links to your preferred url namespace and then display it in the iframe. When someone clicks on a forum link you will need to either capture the request data from a custom php module or rewrite it back to how the forum software understands or .maybe use apache url rewriting if you're using apache. Because all of this rewriting is taking place in memory and not in the template it shouldn't be particularly brittle. curl......didn't think of that for some reason.I'll give it a try. Thank you.
http://community.sitepoint.com/t/embedding-a-forum-as-an-iframe/37439
CC-MAIN-2014-41
refinedweb
804
65.42
JavaScript | Array every() function Array.every() function checks whether all the elements of the array satisfy the given condition or not that is provided by a function passed to it as the argument. The syntax of the function is as follows: arr.every(function[, This_arg]) Argument The argument to this function is another function that defines the condition to be checked for each element of the array. This function argument itself takes three arguments: - array (optional) - index (optional) - element (Compulsory) This is the array on which the .every() function was called. This is the index of the current element being processed by the function. This is the current element being processed by the function. Another argument This_arg is used to tell the function to use this value when executing argument function. Return value This function returns Boolean value true if all the elements of the array follow the condition implemented by the argument function. If one of the elements of the array does not satisfy the argument function, then this function returns false. Examples for above function are as follows: Example 1: function ispositive(element, index, array) { return element > 0; } print([11, 89, 23, 7, 98].every(ispositive)); Output: true In this example the function every() checks if a number is positive for every element of the array. Since the array does not contain negative elements therefore this function returns true as the answer. Example 2: function isodd(element, index, array) { return (element % 2 == 1); } print([56, 91, 18, 88, 12].every(isodd)); Output: false In this example the function every() checks if every number in the array is odd or not. Since some of the numbers are even, therefore this function returns false. Codes for above function are as follows: Program 1: Output: true Program 2: Output: false Recommended Posts: - JavaScript | Array.of() function - JavaScript | Array some() function - How to pass a PHP array to a JavaScript function? - JavaScript | array.includes() function - JavaScript | Array.prototype.map() function - JavaScript | Array find() function - JavaScript | Array fill() function - JavaScript | Array join() function - JavaScript | Array findIndex() function - JavaScript | array.toLocaleString() function - How to pass an array as a function parameter in JavaScript ? - How to compare two JavaScript array objects using jQuery/JavaScript ? - How to convert Integer array to String array using JavaScript ? - How to get the elements of one array which are not present in another array using JavaScript? - What’s the difference between “Array()” and “[]” while declaring a JavaScript.
https://www.geeksforgeeks.org/javascript-array-prototype-every-function/
CC-MAIN-2020-05
refinedweb
407
56.25
import all of the how-to articles from the pkgsrc.se wiki **Contents** [[!toc]] # Things needed A NetBSD/i386 installation. A Maple install cd (hybrid version for Windows/Mac OS X/Linux). A linux emulation package. procfs turned on. I use Maple 10 on NetBSD 3.1 with the suse10 package from pkgsrc. # Install Maple Mount the CD. From the user that will be using the maple install: run installMapleLinuxSU from the root directory on the CD. Follow through the steps. Remember to choose an install folder you have write access to. I will use my home folder. Upon finishing the install process you will be asked to activate Maple. I advise that you activate it now instead of trying to later. Quit the installer. # Tell Maple your OS Maple uses [[basics/uname]] to detect the system type. Running Maple now will result in it telling you that your operating system is unsupported. We need to tell Maple that our system is linux so we can run it under emulation. Using your favorite text editor open the file ~/maple##/bin/maple.system.type This file is a script that runs at startup. Looking at the file we see that many different system types can be detected and launched. The one we wish to use is bin.IBM_INTEL_LINUX There are two ways of doing this: 1: We can add a NetBSD section to the script. Just sneak it in under the Darwin entry: "Darwin") # the OSX case MAPLE_BIN="bin.APPLE_PPC_OSX" ;; # OUR ADDED SECTION "NetBSD") MAPLE_BIN="bin.IBM_INTEL_LINUX" ;; # END OF OUR SECTION *) 2: Add one line just above the bottom: # OUR ADDED LINE $MAPLE_BIN="bin.IBM_INTEL_LINUX" # END LINE echo $MAPLE_BIN exit 0 # Launch Maple From the ~/maple##/bin directory launch either maple or xmaple. Enjoy your NetBSD Maple math fun!
https://wiki.netbsd.org/cgi-bin/cvsweb/wikisrc/tutorials/how_to_run_maple_on_netbsd__92__i386.mdwn?rev=1.1;content-type=text%2Fx-cvsweb-markup
CC-MAIN-2015-48
refinedweb
298
78.65
10.21. Functions that Produce Lists¶ The pure version of doubleStuff above made use of an important pattern for your toolbox. Whenever you need to write a function that creates and returns a list, the pattern is usually: initialize a result variable to be an empty list loop create a new element append it to result return the result Let us show another use of this pattern. Assume you already have a function is_prime(x) that can test if x is prime. Now, write a function to return a list of all prime numbers less than n: def primes_upto(n): """ Return a list of all prime numbers less than n. """ result = [] for i in range(2, n): if is_prime(i): result.append(i) return result
http://interactivepython.org/runestone/static/thinkcspy/Lists/FunctionsthatProduceLists.html
CC-MAIN-2017-22
refinedweb
125
68.4
* I have to make a maze with 21 rows and 77 columns, allow some for the user's input and for messages. * It also has to have A multidimensional array containing the board. * A function to print the board. * Find the user's starting location (i.e. the location of the 'i') * Loop forever, doing the following: Print the board (using your handy board printing function) If the character is: 'w': move the 'i' up, if possible 'a': move the 'i' left, if possible 's': move the 'i' down, if possible 'd': move the 'i' right, if possible * If the square that 'i' is trying to move to does not contain a space: If the character is an '=', then the user won! Say so, and exit the program (using return 0;). If the character is a '*', then you probably want to do nothing. If you were being adventerous, and you included characters for lava and other such dangers, you should handle them accordingly. So far, I have something like this but I'm not really sure how to make the i move, I did it in a small scale first. #include <iostream> using namespace std; int main() { int maze[4][9]; const int rows = 4; const int columns = 9; int choice= 9; char board[rows][columns + 1] = { "** === **", "* *", "* *", "*** i ***", }; for (int i = 0; i< 21; i++) { for (int j = 0; j < 77; j++) { cout << board[i][j]; } cout << endl; } int Prow = 44; int Pcol = 38; if (choice == 'w') { if(board[Prow][Pcol] == ' ') { Prow= Prow + 1; board[Prow][Pcol] = 'i'; } cout << "Enter a character " << choice; } if (choice == 's') { if(board[Prow][Pcol] == ' ') { Prow= Prow -1; board[Prow][Pcol] = 'i'; } } system("pause"); return 0; } 0
https://www.daniweb.com/programming/software-development/threads/478348/maze-using-asterisks-2-d-array
CC-MAIN-2017-43
refinedweb
282
61.9
out any parts about setting up eclipse. You'll also need ANT,, and the java sdk.. Next you'll need to make a project. Open the command prompt and type: android create project \ --target <target_ID> \ --name <your_project_name> \ --path /path/to/your/project \ --activity <your_activity_name> \ --package <your_package_namespace> See more instructions here: ... r-ide.html So I would put in the batch file: cd\android\projects\myApp Then you need to put the command to compile the project: ant -debug Then save the batch file as compile.bat Whenever you want to compile your project just click the compile.bat file. This is all you need to do to compile your app. Since I use TextPad there is an easier way to do this than making a batch file. In TextPad click on tools, then run: In the command textbox type: ant In the parameters textbox type: debug In the initial folder box type: the directory of your project, example: c:\android\projects\myApp The run options will stay set until you change them. Then whenever you want to compile your app, just save the source code your editing, then go to tools, and run. Next we want to run our app in the emulator. First you'll have to make a avd for the emulator, see the instructions here: ... s/avd.html.: emulator @yourAVDname where @yourAVDname is the name you choose when you created your avd. Save this as emulator.bat Now whenever you want to start the emulator just click the emulator.bat file. Next you want to install your app on the emulator. We'll make a batch file for this as well. Open a text file and enter: adb install c:\android\projects\myApp\bin\myApp-debug.apk Save it as install.bat: adb uninstall com.myApp where com.myApp is the package name you chose when creating your project. Save the file as uninstall.bat.. When you want to compile your app for release to the market: First you'll need a keystore. See here for instructions on creating your own keystore: ... gning.html Once you have a keystore, you'll want to compile for release. Change the option in textpad under tools -> run -> options from debug, to release or change your compile.bat file to: ant -release Next you edit a new text file and enter this: (we need to sign the apk with our keystore) jarsigner -keystore c:\folderforyourkeystore\myKeystore.keystore c:\android\projects\myApp\bin\myApp-unsigned.apk myAlias (Next you need to zip align the package) zipalign -v 4 c:\android\projects\myApp\bin\myApp-unsigned.apk c:\android\projects\myApp\bin\myAppRelease.apk. Save the file as release.bat. When you run release.bat it will create myAppRelease.apk signed and zipaligned for you. If any of this is confusing or you need help please comment and I will try to explain. Thanks!
http://www.anddev.org/novice-tutorials-f8/developing-android-apps-without-eclipse-t13912.html
CC-MAIN-2015-11
refinedweb
481
67.45
In this article, which is part 3 of a larger machine learning series, you will learn how you can change the color of an RGB LED by just saying the color. We will use the Wekinator software as the machine learning platform, and after training Wekinator, we will use processing to get Wekinator’s output, from where we will send it to the Arduino. Catch up on the rest of the Wekinator Machine Learning series here: Circuit Diagram Connect the longest leg of the RGB LED to the ground of Arduino. Connect the other legs to pins 9, 10, and 11 of Arduino through the 220-ohm resistor as shown in the below circuit diagram. How to Run the Program First of all, paste the code given for Arduino at the end of this post in the Arduino IDE and upload the code. Then you will need to download the sketch from the examples page of Wekinator. Download the executable file for MFCCs (mel-frequency cepstral coefficients). I have a 64-bit operating system, so I have downloaded “win64” from there. After downloading, unzip it and run the “.exe” file. It will look like as shown below. Now you need a microphone to give the input to Wekinator. If you have attached an external microphone, make sure it is selected in the sound settings of your computer. You will require another sketch (“output sketch”) to get the output from Wekinator. This sketch is given at the end of this post. Paste it into the new processing window and run the sketch. Now open the Wekinator and make the settings as shown in the figure below. Set the inputs to 13 and the outputs to 1. Set the type to “All dynamic time warping” with 3 gesture types and click on “next”. Now hold the “+” button in front of the output_1 and say “red”. Then hold the “+” button in front of the output_2 and say “green”. Then hold the “+” button in front of output_3 and say “blue”. After that, click on “Train”, then click “Run”. Now the color of the RGB LED will change according to the color name you say. Arduino Code #include <VSync.h> //Including the library that will help us in receiving and sending the values from processing ValueReceiver<1> receiver; /*Creating the receiver that will receive 1 value. Put the number of values to synchronize in the brackets */ /* The below variable will be synchronized in the processing and they should be same on both sides. */ int output; // Initializing the pins for led's int red_light_pin= 11; int green_light_pin = 10; int blue_light_pin = 9; void setup() { /* Starting the serial communication because we are communicating with the Processing through serial. The baudrate should be same as on the processing side. */ Serial.begin(19200); pinMode(red_light_pin, OUTPUT); pinMode(green_light_pin, OUTPUT); pinMode(blue_light_pin, OUTPUT); // Synchronizing the variable with the processing. The variable must be int type. receiver.observe(output); } void loop() { // Receiving the output from the processing. receiver.sync(); // Matching the received output to light up the RGB LED if (output == 1) { RGB_color(255, 0, 0); // Red } else if (output == 2) { RGB_color(0, 255, 0); // Green } else if (output ==3) { RGB_color(0, 0, 255); // Blue } } void RGB_color(int red_light_value, int green_light_value, int blue_light_value) { analogWrite(red_light_pin, red_light_value); analogWrite(green_light_pin, green_light_value); analogWrite(blue_light_pin, blue_light_value); } Processing Code (Output Sketch) { } } void draw() { // Nothing to be drawn for this example }
https://maker.pro/arduino/projects/machine-learning-for-makers-how-to-voice-control-an-rgb-led
CC-MAIN-2021-10
refinedweb
563
62.78
Here. Scenario Use In my case, I needed the .NET 3.0 components and the WCF extensions for Visual Studio: 1. .NET 3.0 Runtime Components 2. WCF and WPF extensions for Visual studio Summary of Steps - Step 1. Create the test service - Step 2. Add a Hello World Method - Step 3. Test your WCF service - Step 4. Enable meta-data for your WCF Service. - Step 5. Create the test client. - Step 6. Add a Web Services reference to your WCF Service. - Step 7. Add the namespace to your - Step 8. Call your WCF service Step 1. Create the test service In this step, we’ll create a WCF service that uses HTTP bindings, for backward compatibility (non-.NET 3.0 clients) - In Visual Studio, click File -> New Web Site - Select WCF Service - Browse to a directory to store your project: (e.g. D:\Dev\WCF\Test1\Serve ) - Enable wsHttpBinding. To do so, right-click Web.config and click Edit WCF Configuration … Expand Services > expand MyService -> expand Endpoints. Click (Empty Name). Change wsHttpBinding to basicHttpBinding - Create the virtual directory. In your File Manager, right-click your Server folder (i.e. D:\Dev\WCF\Test3\Server) and click Properties, then Web Sharing, and click Share this folder, then click OK. Step 2. Add a Hello World Method In Service.cs, you’ll add your Hello World method: - Add the HelloWorld operation contract below public interface: [ServiceContract()] public interface IMyService { [OperationContract] string MyOperation1(string myValue1); [OperationContract] string MyOperation2(DataContract1 dataContractValue); [OperationContract] string HelloWorld(); } - Add your HelloWorld method below public class MyService : public class MyService : IMyService { public string MyOperation1(string myValue1) { return “Hello: ” + myValue1; } public string MyOperation2(DataContract1 dataContractValue) { return “Hello: ” + dataContractValue.FirstName; } public string HelloWorld() { return “Hello World”; } } Compile and debug any errors. Step 3. Test your WCF service - In IIS Manager, under Default Web Site, right-click expand Server (the virtual directory you just created) - Right-click Service.svc and click Browse. There’s two issues you might hit here: - You don’t have ASP.NET installed/enabled. To fix this, first run aspnet_regiis /i from your .NET installation directory (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727) Then, allow ASP.NET in your IIS Manager. To do so, in IIS Manager, expand Web Service Extensions, select ASP.NET v.2.0.50727 and click Allow. - You might see “Security settings for this service require ‘Anonymous’ Authentication but it is not enabled for the IIS application that hosts this service.” To fix this, first enable anonymous access. In IIS Manager, right click your v-dir (Server), click Properties, click Directory Security, click Edit under Authentication and Access control, click Enable Anonymous Access, then OK your way out of the dialogues. Next, recycle IIS. In a command prompt, type IISreset. If successful, when you browse your Service.svc file from IIS Manager (e.g.). you’ll get a message that starts with the following: This is a Windows© Communication Foundation service. Metadata publishing for this service is currently disabled. Step 4. Enable meta-data for your WCF Service. - In VSTS, right-click Web.config and click Edit WCF Configuration. In WCF Configuration, expand Advanced, then expand Service Behaviors, then right-click returnFaults and click Add Service Behavior Element Extension. Select serviceMetadata and click Add. - In WCF configuration, select serviceMetadata and change HttpGetEnabled to True. Close the dialogue and save changes. - Test your service again. Browse to and this time you should see your service (e.g. MyService Service). You will see a message that starts with the following: “You have created a service.” Step 5. Create the test client. In this step, we’ll create a quick console app to call the WCF service: - In Visual Studio, click File -> New -> Project - Select Console Application. - Browse to a directory to store your test client: (e.g. D:\Dev\WCF\Test1\WCFClient) Step 6. Add a Web Services reference to your WCF Service. In this step, we’ll add a Web Services reference. - Right-click References - Click Add Web Reference … - In the Add Web Reference dialogue, add the path to your WCF Service () - Click Add Reference to close the dialogue. You should then see your Web Service reference show up under Web References. Step 7. Add the namespace to your - Browse to your Reference.cs file. You’ll find the file below Reference.map under your Web service reference. You might need to click the Show All Files button on the Solution Explorer so you can see the files under your Web service reference. - Find the namespace. You’ll see a line similar to the following: namespace ConsoleApplication1.localhost - Add the using statement to your Program.cs file. using ConsoleApplication1.localhost; Step 8. Call your WCF service In your test client, call your WCF service: static void Main(string[] args) { MyService service = new MyService(); string foo; foo = service.HelloWorld(); Console.WriteLine(foo); } When you compile and run your console application, you should see the following: Hello World Press.
https://blogs.msdn.microsoft.com/jmeier/2007/10/15/how-to-create-a-hello-world-wcf-service-using-visual-studio/
CC-MAIN-2016-30
refinedweb
824
60.61
I understand that stdin and stdout (at least in UNIX parlance) are stream buffers, and that stdout is used to output from a program to the console (or to then be piped by a shell, etc), and that stdin is for standard input to a program.. So why is it, at least on macOS, that they can be used interchangeably (stdout as stdin, and vice versa? Examples: cat /dev/stdin cat /dev/stdout echo "Hey There" > /dev/stdout echo "Hey There" > /dev/stdin #include <iostream> #include <string> #include <fstream> int main(int argc, const char * argv[]) { std::string echoString; std::fstream stdoutFile; stdoutFile.open("/dev/stdout"); stdoutFile << "Hey look! I'm using stdout properly!\nNow You trying using it wrongly: " << std::endl; stdoutFile >> echoString; stdoutFile << "You Typed: " << echoString << std::endl; } Because, typically, when a program is invoked from an interactive terminal, with no redirection, both standard input and standard output are connected to the same terminal device, such as /dev/tty (the actual device name varies based on the operating system). The terminal device is a read/write device. Reading from the terminal device reads terminal input. Writing to the terminal device generates output on the terminal. You still have discrete file descriptors, 0 and 1, but they're connected to the same device. Think of it as single, bi-directional pipe, that's duped to both file descriptors 0 and 1. Linux behaves the same way (you can echo Foo >/dev/stdin and see the output): $ ls -al /proc/self/fd/[01] lrwx------. 1 mrsam mrsam 64 Nov 22 21:34 /proc/self/fd/0 -> /dev/pts/1 lrwx------. 1 mrsam mrsam 64 Nov 22 21:34 /proc/self/fd/1 -> /dev/pts/1 So, for this process, file descriptors 0 and 1 is connected to the /dev/pts/1, the same pseudo-terminal device. Whether you are reading from file descriptor 0 or file descriptor 1, you end up reading from the same underlying /dev device, so it makes no difference which actual file descriptor you use. This is, of course, operating system-dependent. Other POSIX-based operating systems may implement their standard input and output in other ways, where you can't actually write to standard input and read from standard output.
https://codedump.io/share/TBpbrc2iHprz/1/why-are-stdin-and-stdout-seemingly-interchangeable
CC-MAIN-2017-34
refinedweb
375
51.58
Caution Buildbot no longer supports Python 2.7 on the Buildbot master. Caution This page documents the latest, unreleased version of Buildbot. For documentation for released versions, see. 2.5.14.13. MailNotifier¶ Buildbot can send emails should receive mail, under what circumstances mail should be sent, and how to deliver the mail. It can be configured to only send out mail for certain builders, and only send them when address a missing PyOpenSSL package on the BuildMaster system. In some cases, it is desirable to have different information than what is provided in a standard MailNotifier message. For this purpose, MailNotifier provides the argument messageFormatter (an instance of MessageFormatter), which allows for creating messages with unique content. For example, if only short emails are desired (e.g., for delivery to phones): from buildbot.plugins import reporters]). generators (list). A list of instances of IReportGeneratorwhich defines the conditions of when the messages will be sent and contents of them. See Report Generators for more information. relayhost (string, deprecated).. extraHeaders (dictionary). A dictionary containing key/value pairs of extra headers to add to sent e-mails. Both the keys and the values may be an Interpolate instance. watchedWorkers This is a list of names of workers, which should be watched. In case a worker goes missing, a notification is sent. The value of watchedWorkerscan also be set to all (default) or None. You also need to specify an email address to which the notification is sent in the worker configuration..
https://docs.buildbot.net/latest/manual/configuration/reporters/mail_notifier.html
CC-MAIN-2021-17
refinedweb
249
50.73
!ATTLIST div activerev CDATA #IMPLIED> <!ATTLIST div nodeid CDATA #IMPLIED> <!ATTLIST a command CDATA #IMPLIED> Hi all. Having some problems with Instantiating an object into the game world. Nothing fancy. Ultimately, I would like to click on a GUI Button and that will instantiate a node object that attaches to the mouse pointer to create a simple "select and drop" mechanic. But need to learn how to walk first before running... I made a prefab of a cylinder called "Node". I have some script attached to my Main Camera to handle the game's GUI. All I want at this point is to click on a button to spawn an instance of the Node prefab into the world. Here's some code: public class ElementsHUD : MonoBehaviour { public GameObject Node; // Display buttons void OnGUI() { GUILayout.BeginArea (new Rect (Screen.width/2 - 200, Screen.height/2 + 100, 300, 300)); GUILayout.Box (textOutput); GUILayout.EndArea (); if (GUI.Button(new Rect(100, 300, 100, 20), new GUIContent("Node 1"))) { GameObject objNode = Instantiate(Node, transform.position, transform.rotation); } My main concern is how do I get the script to reference the cylinder prefab I have sitting in the Hierarchy? Secondary concern is how to instantiate this cylinder at a specific vector? Sorry this seems like a very basic question but would appreciate any pointers. Thank you! asked Mar 30 '11 at 01:07 AM Mac 16 ● 3 ● 3 ● 3 edited Aug 30 '11 at 02:27 PM SisterKy 3k ● 36 ● 43 ● 64 Since Node is public, looking at the script in the inspector should show a field for "Node". To put a prefab in it, either drag and drop the prefab into it or click the little circle to the right and pick from the list. Also, you might need to put (GameObject) before Instantiate in your code, or it might throw you an error. Like this: (GameObject) Instantiate GameObject objNode = (GameObject)Instantiate(Node, transform.position, transform.rotation); If you need the object at a specific vector, you can either create the vectors from scratch in your instantiation... GameObject objNode = (GameObject)Instantiate(Node, new Vector3(0,0,0), transform.rotation); ...or you can create a variable up top and plug in a value for it from the inspector. public Vector3 placementspot; Something like that, and then use: GameObject objNode = (GameObject)Instantiate(Node, placementspot, transform.rotation); answered Mar 30 '11 at 01:14 AM Jason B 1.8k ● 30 ● 32 ● 45 Thanks Jason, that was very helpful! The syntax is a bit unfamiliar to me in terms of putting "(GameObject)" in front of the Instantiate expression. But yeah, before I was getting this error: error CS0266: Cannot implicitly convert type UnityEngine.Object' toUnityEngine.GameObject'. An explicit conversion exists (are you missing a cast?) UnityEngine.Object' to In any case, it's something I can read up on. Now on to the next step of spawning my node cylinders to the mouse pointer!: instantiate x2482 prefab x1813 vector3 x913 cs0266 x19 asked: Mar 30 '11 at 01:07 AM Seen: 3043 times Last Updated: Mar 30 '11 at 01:07 AM Instantiate object in world C# prefab null not instantiated: simple example not working? ArgumentException: The prefab you want to instantiate is null. Physics related rotation problem. (a weird one) Object spawns itself instead of it's prefab. Avoid altering prefab at runtime After instantiating an instance of a prefab and changing the value of a variable in a script attached to the prefab, that value is lost Instantiating a spaceship prefab. cannot access then change the prefabs settings Instantiating random prefabs when the player passes through a trigger load Object coordinates from PHP Database to place object EnterpriseSocial Q&A
http://answers.unity3d.com/questions/55254/instantiate-object-basics-unity-32-c.html
CC-MAIN-2014-15
refinedweb
614
56.96
Python Tutorial What is Python? Python is a freeware interpreted, object-oriented, high-level powerful programming language runs on many Unix variants, on the Mac, and on Windows 2000 and later. It's well-designed syntax and dynamic typing makes it an ideal language for scripting and rapid application development in many areas. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It is also usable as an extension language for applications that need a programmable interface. . Features of Python Open source : Python is publicly available open source software, any one can use source code that doesn't protable, which means they are able to run across all major hardware and software platforms with few or no change in source code. Python is protable. Python Is Easy to Use A simple program written in C++, C, Java and Python. All program prints "Hello world". C++ Program : #include <iostream> int main() { std::cout << "Hello World" << std::endl; return 0; } C Program : #include <stdio.h> int main(int argc, char ** argv) { printf(“Hello, World!\n”); } Java Program : public class Hello { public static void main(String argv[]) { System.out.println(“Hello, World!”); } } Python Program : print ( "Hello World") Python Environment - AIX - AROS - AS/400 (OS/400) - BeOS - MorphOS - MS-DOS - OS/2 - OS/390 and z/OS - Palm OS - PlayStation and PSP - Psion - QNX - RISC OS - Series 60 - Solaris - VMS - Windows CE or Pocket PC - HP-UX - Linux browser. 6. Pictorial presentation to help you to understand the concept better. 7. You may refer Python 3.2 Manual along with this tutorial.
http://www.w3resource.com/python/python-tutorial.php
CC-MAIN-2016-18
refinedweb
271
65.12
Opened 7 years ago Closed 5 years ago #9180 closed (duplicate) Low-level cache interface incorrectly tries to typecast bytestring Description The low-level Django cache API encodes basestrings as UTF-8 when setting, and decodes basestrings as Unicode when getting. If you're trying to store a string of bytes in the cache -- for instance, the raw bytes of an image -- the set operation will possibly modify the data by encoding it, and the get operation will potentially raise a DjangoUnicodeDecodeError if the codec can't decode bytes in the string. from django.core.cache import cache from django.utils.encoding import DjangoUnicodeDecodeError # The simplest possible GIF: a 43-byte, 1x1-pixel transparent image EMPTY_GIF_BYTES = 'GIF89a\x01\x00\x01\x00\xf0\x00\x00\xb0\x8cZ\x00\x00\x00!\xf9\x04\x00\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;' cache.set('empty_gif', EMPTY_GIF_BYTES) try: cache.get('empty_gif') except DjangoUnicodeDecodeError: print 'Tried to decode GIF bytestring as a Unicode string' else: print 'Got the raw GIF bytestring' A workaround is to create a one-tuple from the bytestring when storing, and when retrieving, returning the single element from the tuple. def raw_cache_set(key, value, timeout_seconds=None): cache.set(key, (value,), timeout_seconds=timeout_seconds) def raw_cache_get(key): value = cache.get(key) if value is not None: return value[0] raw_cache_set('empty_gif', EMPTY_GIF_BYTES) assert raw_cache_get('empty_gif') == EMPTY_GIF_BYTES One possible fix would be to expose a raw keyword argument boolean to cache.get, cache.set, cache.add, cache.get_many that would conditionally skip any smart_unicode or other encoding/decoding logic when storing or retrieving from the cache. Attachments (1) Change History (9) comment:1 Changed 7 years ago by adrian - Needs documentation unset - Needs tests unset - Patch needs improvement unset - Triage Stage changed from Unreviewed to Accepted comment:2 Changed 7 years ago by AdamG comment:3 Changed 7 years ago by AdamG - Has patch set I've tested 9180.diff using the memcache library; I'd appreciate it if someone could test it with cmemcache so we could get this to ready for checkin. comment:4 Changed 7 years ago by AdamG - Cc django.9180@… added Changed 7 years ago by AdamG Patch that fixes this issue, is backwards-compatible & includes a regression test comment:5 Changed 6 years ago by gonz - Cc gonz added comment:6 Changed 6 years ago by lvscar - Cc lvscar added - Triage Stage changed from Accepted to Ready for checkin - Version changed from 1.0 to 1.1 django 1.1 lack the patch! i patch it to django1.1 while cmemcache as my cache backend. it make django.core.cache.cache.get method work great with pickled data comment:7 Changed 5 years ago by obeattie - Cc obeattie added Any update on the checkin status of this patch? The use case I came across this on was storing zlib-compressed data in the cache. Since that needs to be preserved as raw bytes, it's not possible to store and retrieve without further processing (thus lengthening the compressed data). comment:8 Changed 5 years ago by obeattie - Resolution set to duplicate - Status changed from new to closed See also #5589. I would greatly prefer the raw kwarg, as using the 1-tuple solution would mean that Python pickles are actually being cached, which would mean that the cache can only be primed by Python code - and when using something like memcached, that's not always the case. For example, I often put output from imagemagick into memcached; right now, that's innaccessible from django.core.cache.cache due to this issue.
https://code.djangoproject.com/ticket/9180
CC-MAIN-2015-18
refinedweb
603
60.75
I have an issue which is similar to the issue here How to use TypeScript modules in Electron? however that doesn’t work for me as I can’t set the “node-integration” to false because it isn’t part of the BrowserWindowConstructorOptions type. My issue is that I have a Typescript module which exports some classes. At the main process side this is fine and I import them like this: import dataset = require("./dataset"); At the renderer process I have tried multiple ways of importing the class definitions: import dataset = require("./dataset"); import {Data, Dataset, Device, Channel} from "./dataset"; This results in the compiler accepting it, however at runtime i get an “Uncaught ReferenceError: exports is not defined” error. The generated code has this line which I understand messes up the renderer as its not running in a node environment but within the browser: Object.defineProperty(exports, "__esModule", { value: true }); This is from . What I figure out is that I have to somehow manage to import the classes in a different way. Doing this const dataset = require("./dataset"); does not include in typescript. I can’t access the types. I’m stuck and out of ideas to how to fix this afaik so I’m stuck at how to properly import typescript modules in the renderer process.
https://discuss.atom.io/t/importing-typescript-modules-in-the-renderer-process/48455
CC-MAIN-2018-47
refinedweb
218
65.01
I am new to YAML and have been searching for ways to parse a YAML file and use/access the data from the parsed YAML. I have come across explanations on how to parse the YAML file, for example, the PyYAML tutorial, "How can I parse a YAML file", "Convert Python dict to object?", but what I haven't found is a simple example on how to access the data from the parsed YAML file. Assume I have a YAML file such as: treeroot: branch1: branch1 text branch2: branch2 text Since PyYAML's yaml.load() function maps YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked: import yaml with open('tree.yaml', 'r') as f: doc = yaml.load(f) To access "branch1 text" you would use: txt = doc["treeroot"]["branch1"] print txt "branch1 text" because, in your YAML document, the value of the branch 1 key is under the treeroot key.
https://codedump.io/share/BDtgDmjKZMZ4/1/parsing-a-yaml-file-in-python-and-accessing-the-data
CC-MAIN-2017-51
refinedweb
166
77.06
Stash SSH is broken Just purchased Pythonista and first thing I did was install Stash via the Pythonista Tools plugin so I presume I have the latest version. I tried running ssh with password and got an error: usage: pip.py [-h] [--verbose] sub-command ... pip.py: error: unrecognized arguments: 0.4.10 usage: pip.py [-h] [--verbose] sub-command ... pip.py: error: unrecognized arguments: 1.16.0 Please restart Pythonista for changes to take full effect So I thought that's strange why am I getting pip error. I thought perhaps my password is weird and/or there is no .ssh directory so I did a keygen and copies the public key to a server that works that way. Got same exact error. So I started investigating on this site and read that Paramiko gets updated and you need to restart Pythonista which explains the last line. So I restarted, tried again same error. So I tried manually installing paramiko and this is what I got: [~/Documents]$ pip install paramiko Querying PyPI ... Downloading package ... Opening: Save as: /private/var/mobile/Containers/Data/Application/AB28F53F-7AD6-44D0-8845-45EF52848C92/tmp/paramiko-1.16.0.tar.gz (1335094 bytes) 1335094 [100.00%] Extracting archive file ... Archive extracted. Running setup file ... stash: <type 'exceptions.ValueError'>: substring not found So my guess is the problem is paramiko. Any help would be greatly appreciated. SSH works fine with my Raspberry Pi. Please check your stash, paramiko and pyte versions. StaSh v0.6.1 paramiko 1.16.0 pyte 0.4.10 and 0.5.2 tested import stash, paramiko print stash.stash.__version__ print paramiko.__version__ ssh --password mypassword -p 22 myuser@myip You can try a new installation, if you want. - delete the stash, paramiko and pyte folder in the site-packages folder. # 2. Simply copy the next line, paste into Pythonista interactive prompt and execute. => import requests as r; exec r.get('').text # 3. install librarys with stash pip install paramiko pip install pyte what version of pythonista and stash are you using? You do need to to a hard reset of pythonista in a few places( i.e double click home menu, and drag the app away). From your original error, it looked like you were running pip instead of ssh. You can use stashconf py_traceback 1to provide more useful error messages. Also... pip and stash both were recently extensively updated... maybe one of the options slipped through testing. edit: i can confirm the pip install paramiko error -- i think the requirement was of an unexpected form. IIRC, the latest pythonista includes paramiko 1.16 already. and I think pyte comes built in? Try using the stash ssh command without messing with pip.. Pyte is not builtin as far as I can tell. Here is a pull request which fixes this issue. As a temporary measure until this gets incorporated, you can patch your local copy: wget ~/Documents/site-packages/stash/bin/pip.py then try the pyte/paramiko install again. @zoteca Sorry for the late reply. It is a bug in the new pipcommand that it could not handle some of the version specifiers like the one paramiko declared, i.e. pycrypto>=2.1,!=2.4. Thanks to @JonB for making a fix for it and I have just merged into the main branch. You can get the latest changes by running selfupdate. A bit more information about stash ssh: - Paramiko is builtin with Pythonista. However, the version that comes with 2.0 app store version (not beta) is old and has some compatibility issues with newer ssh server (2.0 beta has fixed this by bundling newer paramiko). This is why ssh tried to install paramikothe first time it runs. - The problem is only just caused by the pipinstallation. It has nothing to do with the ssh command itself. So once you have paramiko and pyte installed, ssh should just work. @ywangd First thanks so much for making such an amazing add on to Pythonista and working to keep it functional. Since I haven't done much yet, I deleted Pythonista, reinstalled, add the tools, installed stash. Then I did self update and had to manually pip install paramiko and pyte. Restarted and then did ssh. Yay, it works!!!! Thanks again for the add on tool and your help!! @ywangd FYI it's broken again. Just installed pythonista on my new iPad Pro 9.7. I can run ssh-keygen fine out of the box, but then when I do "ssh -h" I get the pip error at top of this thread (although no attempt to install paramiko). If I then manually install paramiko (and manually setuptools for otherwise I get an error) when I run ssh-keygen or try to ssh to a server I get the following error: " Multibackend cannot be initialized with no backends. If you are seeing this error when trying to use default_backend() please try uninstalling and reinstalling cryptography." Needless to say reinstalling cryptography does not help. There are obviously are some conflicts between different packages & stuff just isn't working. The problem exists w/ & w/o installing the pip patch - I installed/uninstalled pythonista multiple times to try different variants of installation methods of stash, paramiko etc Change line 67 in pip.py from class OmniClass(object): to class OmniClass(list): This reported an error when it tried to install cffi, but it did install paramiko successfully, and i was able to run the ssh keygen. Not sure if that is a long term solution, I will ley @ywangd comment. The issue was line 293 of the pycrypto setup.py sub_commands = [ ('build_configure', has_configure) ] + build_ext.sub_commands since build_ext.sub_commands was a stub, so could not be added to a list. By changing the stub OmniClass to extend list, it allows this type of usage. Not sure if there are other side effects. @JonB Thanks for the reply. So I tried what you suggested, edited pip,py, removed and installed paramiko, and still got same error re: multi-back ends. So I was a bit cobfused. When I install paramiko I noticed it uses cryptography package not pycrypto. I did in fact try manually installing pycrypto previously and got a setup error, which your pip patch does indeed fix. But a brief googling revealed that pycrypto is for paramiko 1.x & what the plain install is doing is installing paramiko 2.0. So I asked myself is that the problem? Indeed it was. Installing version 1.17 of paramiko made everything work perfectly, and I didn't even need your patch to manually install pycrypto, since the bundled version works fine. Anyway, thanks so much for your help and for putting me on right path to solve the problem, even inadvertently. Hopefully future versions support paramiko 2.0 since I understand cryptography is a more secure library :)
https://forum.omz-software.com/topic/3019/stash-ssh-is-broken
CC-MAIN-2018-39
refinedweb
1,142
77.13
> From: haskell-cafe-bounces at haskell.org > [mailto:haskell-cafe-bounces at haskell.org] On Behalf Of Paul Moore > > But, will this read the database lazily, or will it get all the rows > into memory at once? How will using result' instead of result (in > runSql) affect this? And as I said above, how can I learn to work this > out for myself? > runSql :: String -> IO [String] > runSql s = withSession (connect "USER" "PASSWD" "DB") ( do > let iter (s::String) accum = result (s : accum) > r <- doQuery (sql s) iter [] > return r > ) The iteratee function: > let iter (s::String) accum = result (s : accum) is fed one row at a time. Takusen can fetch rows from the DBMS one at a time (rather slow across a network) or fetch them in chunks (i.e. cached) and feed them to the iteratee one at a time, which is obviously much better from a network performance perspective. Currently, the default is to fetch rows in chunks of 100. So getting rows from the database is more-or-less "on-demand", but it's transparent from your point-of-view, because your iteratee only gets them one a a time. What you're interested in, I think, is what the iteratee does with the data.). If you don't need the entire list at once, then push your processing into the iteratee. You are not obliged to return all of the data from doQuery in one big data structure, like a list. You can do IO in the iteratee, and even just return (). If you want to terminate the fetch early, you can return (Left <something>) in the iteratee, rather than (Right <something>). result and result' always return (Right <something>), so they process the result-set all the way through. I'm sure someone asked Oleg and I about lazy result-set processing in Takusen (and why it's not done) a few months ago (a private email, I think), but right now I'm unable to find our. *****************************************************************
http://www.haskell.org/pipermail/haskell-cafe/2007-March/023036.html
CC-MAIN-2013-48
refinedweb
333
69.92
Skip navigation links java.lang.Object CoherenceApplicationEdition com.tangosol.net.cache.ReadWriteBackingMap.ReadQueue public class ReadWriteBackingMap.ReadQueue A queue of keys that should be read from the underlying CacheStore. protected ReadWriteBackingMap.ReadQueue() public boolean add(java.lang.Object oKey) oKey- the key object public java.lang.Object peek() public java.lang.Object peek(long cMillis) cMillis- the number of ms to wait for a key in the queue; pass -1 to wait indefinitely or 0 for no wait public boolean remove(java.lang.Object oKey) oKey- the key object protected ReadWriteBackingMap.ReadLatch select(long cWaitMillis) This method performs the selection process by iterating through the refresh-ahead queue starting with the first key in the queue. If the queue is empty, this method will block until a key is added to the queue. A key is skipped if it cannot be locked within the specified wait time. If a candidate key is found, a new ReadLatch for the key is placed in the control map and returned; otherwise, null is returned. cWaitMillis- the maximum amount of time (in milliseconds) to wait to select a key and acquire a latch on it; pass -1 to wait indefinitely public void clear() public java.lang.String toString() protected java.util.List getKeyList() protected java.util.Map getKeyMap() Note: The map returned from this method is not thread-safe; therefore, a lock on this ReadQueue must be obtained before accessing the map Skip navigation links
http://docs.oracle.com/cd/E24290_01/coh.371/e22843/com/tangosol/net/cache/ReadWriteBackingMap.ReadQueue.html
CC-MAIN-2016-36
refinedweb
241
58.89
I am trying to write a program that organizes results from a tournament of computer games using bots. I want to do interesting things with the data like rank the bots on the results of each map, results of all the maps, and on their averages ... and so on I am new to arrays so maybe arrays are a bad choice for this, so please correct me if I'm wrong. So each tournament consists of 5 maps, there are 5 players in each map ("daemia", "xaero", "ezflow", "slash", "doom"). I have used two classes: Bot.java - has methods to retrieve the bots frag (aka "kill") data, like average frags, total frags and also the bots name. RankBotsVariant.java - has the main method in which I create 5 Bot objects and put their scores in after the tournament (the Bot constructor has space for 5 int results and a String name). I am having trouble ranking the bots in terms of their results maybe you can help me or give some advice //RankBotsVariant.java //imports Bot objects from Bot.class import java.text.DecimalFormat; public class RankBotsVariant { public static void main (String[] args) { Bot bot1 = new Bot ("Daemia", 11, 4, 6, 3, 5); Bot bot2 = new Bot ("Xaero", 5, 5, 6, 9, 10); Bot bot3 = new Bot ("EZfl0w", 5, 8, 3, 6, 9); Bot bot4 = new Bot ("Slash", 6, 5, 8, 11, 4); Bot bot5 = new Bot ("D00m", 5, 3, 7, 5, 19); //print fragsAllMaps System.out.println ("***Total Frags -All Maps***"); System.out.println ("\tDAEMIA: " + bot1.getFragsAllMaps()); System.out.println ("\tXAERO: " + "\t" + bot2.getFragsAllMaps()); System.out.println ("\tezFL0W: " + bot3.getFragsAllMaps()); System.out.println ("\tSLASH: " + "\t" + bot4.getFragsAllMaps()); System.out.println ("\tDOOM: " + "\t" + bot5.getFragsAllMaps()); //best average System.out.println ("***Average Frag-rate - Over All Maps***"); System.out.println ("\tDAEMIA: " + bot1.getAvgFrags()); System.out.println ("\tXAERO: " + "\t" + bot2.getAvgFrags()); System.out.println ("\tezFL0W: " + bot3.getAvgFrags()); System.out.println ("\tSLASH: " + "\t" + bot4.getAvgFrags()); System.out.println ("\tDOOM: " + "\t" + bot5.getAvgFrags()); //prints the winner of each map: System.out.println ("*******Winner Of Each Map*********"); String [] maps = {"LostWorld", "DM18", "Shibam", "TheBouncyMap", "Hearth"}; int [] data = {bot1.getfm1(), bot2.getfm1(), bot3.getfm1(), bot4.getfm1(),bot5.getfm1()}; for (int map = 0; map < maps.length; map++) { System.out.println ("The winner of " + maps[map] + " was "); int largest = data[0]; for (int i = 0; i < data.length; i++) { if (data[i] > largest) { largest = data[i]; } } System.out.println ( + largest); } } }//Bot.java //Holds get methods for frag data used in the RankBotsVarint class. import java.util.Arrays; public class Bot { public int fm1, fm2, fm3, fm4, fm5; //frags map 1 , etc.. public int fragsfm1, fragsfm2, fragsfm3, fragsfm4, fragsfm5; public int fragsAllMaps = 0; public double avgFrags = 0; public String botName, winner, victor; private final int MAPS = 5; public Bot (String alias, int m1, int m2, int m3, int m4, int m5) { botName = alias; fm1 = m1; fm2 = m2; fm3 = m3; fm4 = m4; fm5 = m5; } public int getFragsAllMaps () { fragsAllMaps = fm1 + fm2 + fm3 + fm4 + fm5; return fragsAllMaps; } public String getBotName () { return botName; } public double getAvgFrags () { avgFrags = (fm1 + fm2 + fm3 + fm4 + fm5) / (double)MAPS; return avgFrags; } public int getfm1 () { fragsfm1 = fm1; return fragsfm1; } public int getfm2 () { fragsfm2 = fm2; return fragsfm2; } public int getfm3 () { fragsfm3 = fm3; return fragsfm3; } public int getfm4 () { fragsfm4 = fm4; return fragsfm4; } public int getfm5 () { fragsfm5 = fm5; return fragsfm5; } } --- Update --- What i'm having trouble with is the halfway down the RankBotsVariant class where it saysI cant get it to print the winners name or rank all the bots from 1-5 which is what i'd really like to do.I cant get it to print the winners name or rank all the bots from 1-5 which is what i'd really like to do.//prints the winner of each map:
http://www.javaprogrammingforums.com/collections-generics/34820-how-use-array-has-int-values-keyed-string-name.html
CC-MAIN-2015-40
refinedweb
621
72.87
CSV We see them all the time but there seems to be some confusion about what a CSV file really is. When I talk to people about CSV files, I realize that most of us equate them with Microsoft Excel documents. This is probably because Excel is usually nice columns and rows are nice and fancy. We think there is something magical going one. However, Rules for reading CSV Files - Each row in a CSV file is separated by line breaks. - Columns are separated by a known character. They are almost always comma-separated but I have seen commas, tabs, pipes ( |) and other wierd stuff. - If a field contains a comma, it should be surrounded by quotes - Example: user_id,nicknames 987,"joebob,joey,jos" - If a field contains single quotes then it should be surrounded by double quotes - Example: user_id,last_name 987,"O'Neil" - If a field contains double quotes then it should be surrounded by single quotes user_id,citation 987,'The Man said,"Who goes there?"' The moral of the story here is: Don't try to parse CSV files by manually reading a line of the file, splitting by commas into a list. There are way too many ways to get it wrong. Instead, use an existing library to do this part. In Python, the csv module is essential. It takes care of reading all of these possible things. Using the builtin Python csv module Here are the basic steps for reading a CSV file with the builtin csv Python module. - Open a CSV file for reading - Pass the file handler to the CSV reader - Iterate through the rows of the file I will walk through each one in order, showing how I would read my example file from earlier. Step 1: Open a csv file for reading ALl during this example, we are going to use the following CSV data. We will assume it is saved a file called quotes.csv sitting next to our script. quote,speaker "Don’t you call me a mindless philosopher, you overweight glob of grease!",C-3PO "We’re doomed.",C-3PO "But I was going into Tosche Station to pick up some power converters!",Luke Skywalker "Help me, Obi-Wan Kenobi. You’re my only hope.",Leia Organa "An elegant weapon for a more civilized age.",Obi-Wan Kenobi "I find your lack of faith disturbing.",Darth Vader "Mos Eisley spaceport. You will never find a more wretched hive of scum and villainy.",Obi-Wan Kenobi "You don’t need to see his identification…These aren’t the droids you’re looking for.",Obi-Wan Kenobi "It’s the ship that made the Kessel Run in less than 12 parsecs.",Han Solo "Sorry about the mess.",Han Solo "She may not look like much, but she’s got it where it counts, kid.",Han Solo "Governor Tarkin, I should’ve expected to find you holding Vader’s leash. I recognized your foul stench when I was brought on board.",Leia Organa "I felt a great disturbance in the Force. As if millions of voices suddenly cried out in terror and were suddenly silenced.",Obi-Wan Kenobi "I suggest a new strategy, Artoo: Let the Wookiee "Somebody has to save our skins. Into the garbage chute, flyboy!",Leia Organa "I got a bad feeling about this.",Han Solo "When I left you I was but the learner. Now I am the master.",Darth Vader "If you strike me down I shall become more powerful than you can possibly imagine.",Obi-Wan Kenobi "It’s not impossible. I used to bullseye womp rats in my T-16 back home, they’re not much bigger than 2 meters.",Luke Skywalker "Cover me, Porkins!",Biggs Darklighter "Use the Force, Luke.",Obi-Wan Kenobi "What an incredible smell you've discovered", Han Solo Opening a file for reading is pretty simple, but I always use the with command to do it. Doing it this way automatically closes the file. Without it you have to call _file.close() yourself or you risk loosing data or corrupting the file. Python is forgiving but I just don't like taking the risk. Here is the first part. import csv with open('./quotes.csv', 'r') as _filehandler: Step 2: Pass the CSV file handler to the Reader With the filehandler opened, pass it to the csv reader. At this point you have two ways of reading rows. You can use csv.reader to read the rows as simple lists. This method: - reads every row as a unique object - has no notion of column headers. The first line of the file is just another row of data - gives you indexed access to each row - i.e. row[0]or row[1] The second option, and the one I personally use the most, is csv.DictReader. This reader: - reads headers from first row - returns each row as a dictionary where the keys come from first row If you read it using csv.reader then the example becomes: import csv with open('./quotes.csv', 'r') as _filehandler: csv_file_reader = csv.reader(_filehandler) If you read it using csv.DictReader then we get: import csv with open('./quotes.csv', 'r') as _filehandler: csv_file_reader = csv.DictReader(_filehandler) There isn't a huge difference there but you get to decide. I personally prefer using dictionaries that remembering the proper index for the column I am looking for. Step 3: Iterate over each row The final step is to iterate over each row, doing something with it. The pattern for row in csv_file_reader: is very common. This creates an iterator [1] Our example then becomes: import csv with open('./example.csv', 'r') as _filehandler: csv_file_reader = csv.DictReader(_filehandler) for row in csv_file_reader: # Do something here print(row['quote']) print(row['speaker']) row in this script is a dictionary. We can access the quote with row['quote'] and the person who is speaking with row['speaker']. Et voila! There you go! I suspect that this pattern will become the basis of many scripting projects in the future. I recorded a quick video. In it, I show how to create the file in PyCharm and then run it. Iterators are pretty awesome when you understand what is happening. They allow for very efficient memory usage with large files, remote data, and cases where you don't know how much information will be processed. In the case of the example given here, it causes the reading to only read the file one row at a time. At no point is the entire CSV file loaded into memory. ↩︎ Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/scriptingwithpy/reading-csv-data-with-python-3o7
CC-MAIN-2021-21
refinedweb
1,099
75.71
18 June 2010 16:09 [Source: ICIS news] LONDON (ICIS news)--INEOS has declared force majeure from its share of the 300,000 tonne/year polypropylene (PP) plant at Lavera in France, the company said in a letter to customers on Friday. Cracker issues brought PP production to a halt on Thursday 17 June, and the unit was expected to be down for 8 days, said the letter. Total Petrochemicals, which shares PP production at the site with INEOS, declined to comment on the situation. Total already had force majeure restrictions in place on PP deliveries from ?xml:namespace> PP availability had been restricted for several weeks, because of a lack of propylene monomer, and other technical issues which affected PP output. PP homopolymer net prices were trading at around €1,270-1,300/tonne ($1,568-1,605/tonne) FD (free delivered) NWE (northwest PP producers in ($1 = €0. 81) For more on PP visit ICIS chemical intelligence For more on INE
http://www.icis.com/Articles/2010/06/18/9369385/ineos-sees-lavera-polypropylene-down-for-eight-days.html
CC-MAIN-2014-35
refinedweb
163
58.21
Created on 2017-07-26 19:18 by terry.reedy, last changed 2017-07-30 23:07 by terry.reedy. This issue is now closed. Followup to 31003, tests, and 30853, tracers, similar to 31004, FontTab. After creating new class, we can change names without worry about clashing with names elsewhere in ConfigDialog. Now that we know what we are doing, we can simplify the steps. These assume that #21004, PR2905, which prepares create_widgets and fixes the GeneralTest that was broken by Notebook, has been merged. For configdialog: * copy general block after FontPage; * add 'class GenPage(Frame):' and def __init__ modeled on FontPage.__init__, but no highlight parameter; * replace 'frame = dialog.tabpages...' at top of create_page_general with 'frame = self'; * comment out old code; * in create_widgets change 'self.create_page_general' to 'GenPage(note)'. For test_configdialog: * change 'GeneralTest' to 'GenPageTest * change setUpClass similarly as in FontPageTest; * change test functions similarly as in FontPageTest and otherwise as needed to keep tests passing. Made all the changes without any issue. One thing - I noticed that the var_changed_autosave, etc for the General tab were back, even though they aren't used by VarTrace. I know I had deleted them, so I'm not sure how they came back. Unless you re-added them? That's what happened to me yesterday -- changes I knew I had made were back again. Anyway, if you want them back, sorry about deleting them again. I just figured it was something that happened on my end. Also, I snuck in a change to the Notebook. I know it should be in its own PR. If you like it, I can leave it here or make a new PR. :-) Above, I left out the last step, "* remove old general block". The old configdialog had an unwritten and undocumented template and rules for pages on the dialog. It went something like the following. # def create_widgets(): * Pick names for the pages. They are both tab labels and page ids. * Send names to tabbed_pages. * Call create_page_name functions. # def load_configs(): * Call each load_name_config. # def create_page_name(): for each name. * Extract frame from tabbed_pages using name. * Define tk vars. * Create subframes and widgets * Pack widgets # def var_changed_var_name(), for each tk var * Perhaps send change to changes dict. # def other_method():, for each name, semi-sorted # def load_name_config() for each name. # Tack on extensions mostly ignoring the above. What I said in the message above is that we have redefined the template well enough to follow it. We have a mostly abstract template. class NamePage(Frame): def __init__(self, master): super().__init__(master) self.create_page_name() self.load_name_cfg() ... Note that the parameter is 'master', not 'parent', as is standard for widgets. It is also not saved, as it is not needed. TkVars for the page can use self as master. I considered making that an actual base class. But there is little common code; it does not quite fit FontPage; and would require uniform 'create_page' and 'load_cfg' names. The more specific names are easier to find with ^F ;-). I do want to add a comment block above FontPage giving the design. I also want to change FontPage to use self as master for tk vars and other widgets. Lets freeze the General page block until this is done. I did not refresh this before writing the above. It still applies, including deleting the commented out code once tests pass. See review. Whoops: I forgot that using make_default means that we can (and should) delete the replaced var_changed defs. I added the one for space_num back because I mistakenly thought it was needed to make the test pass. I will open a new issue to add a comment documenting the new TabPage(Frame) class design. The new rules will include using default var_changes when possible. Patch will include adjusting FontTab to follow the new rules. I intentionally left using non-default options other than traversal for a new issue or issues, after we finish ttk replacement. I imagine there will be discussions about choices, and I will invite other participants. I would like to direct visual design discussions, as opposed to internal implementation discussion, to idle_dev. New changeset e8eb17b2c11dcd1550a94b175e557c234a804482 by Terry Jan Reedy (csabella) in branch 'master': bpo-31050: IDLE: Factor GenPage class from ConfigDialog (#2952) New changeset 8c4e5be1dfb4d1c74e8cc7ac925e3196818e07ac by Terry Jan Reedy in branch '3.6': [3.6] bpo-31050: IDLE: Factor GenPage class from ConfigDialog (GH-2952) (#2955) Much easier the 2nd time ;-)
https://bugs.python.org/issue31050
CC-MAIN-2020-50
refinedweb
733
68.06
A good white box testing is essential for the success of software. Testing is usually done with human interaction, which is both slow and expensive. Testing is a long process which needs a lot patience and keen observation. If it is a white box testing, then we need to follow some steps and run a lot of scenarios whenever we make a small change in our software’s code. Usually, the same steps are done by testers repeatedly. To overcome this problem, a lot of Test Automation tools are available in the market. Some of the famous GUI testing tools are IBM Rational Functional Tester from IBM and Phantom Automation Language from Microsoft. This article is concentrated mainly on creating a miniature of a Test Automation tool, with the help of mouse and keyboard hooking. Keyboard and mouse hooking is no longer an undocumented activity. It is available in plenty on the internet. As we know, whenever a good technology is introduced, it has pros and cons. If we record the mouse and keyboard events without the knowledge of a user, then it is Trojan horse, key logger or a virus. But if it is done purposefully, then it is automation. The next few sections mentioned below will be fully concentrated on creating a Test Automation miniature with the help of global mouse and keyboard hooking. So hooking is a simple activity by which, we will be able to get the keyboard and mouse events in our application. Let us go in detail. Hooking of keyboard and mouse can be usually done in two ways: As the name reveals, it is only limited to a thread in a process. This can be useful in our software. So hook procedure can be placed either on an EXE or a DLL. As the name reveals, it is only limited to a thread in a process. This can be useful in our software. So hook procedure can be placed either on an EXE or a DLL. Global Hooking is a system wide hooking. The entire keyboard or mouse event is diverted to our hook procedure. The hooking function must be placed on a separate DLL in this case. Global Hooking is a system wide hooking. The entire keyboard or mouse event is diverted to our hook procedure. The hooking function must be placed on a separate DLL in this case. We achieve the mouse and keyboard hooking with he help of the Windows provided SetWindowHookEx WINAPI (Hooks many types of events ). To unhook the event, we need to give UnhookWindowsHookEx WINAPI. SetWindowHookEx WINAPI UnhookWindowsHookEx WINAPI To demonstrate the usage of hooking, I came up with an application RecordPlayer.exe. So let me introduce the application to you. It mainly consists of three components. Our application consists of two operations, recording and playback. Recording is done with the help of DLLs and playback is done with the help of two APIs mainly - keybd_event and mouse_event. Now let us go under the hood. I will demonstrate the hooking activity with the help of keyboard hooking. keybd_event mouse_event To start the keyboard hooking, firstly make a WIN32 DLL. Let us start with the header file of DLL. Then Export the functions from the DLL, so that it can be accessible from our native application that is going to get the data from the hook procedure. The code inside KeyBoardHookLib.h: #ifdef __cplusplus extern "C" { #endif // __cplusplus #define LIBSPEC __declspec(dllexport) // Our install Hook procedure. LIBSPEC BOOL InstallKeyBoardHook(HWND hWndParent); // Our uninstall hook procedure. LIBSPEC BOOL UnInstallKeyBoardHook(HWND hWndParent); #undef LIBSPEC The named events that registers to send the window message to RecordPlayer.exe. #define UWM_KEYBOARD_MSG ("UWM_KEYBOARD_USER_MSG") Let us become familiar with KeyBoardHookLib.cpp. The below steps are done to share the HANDLE mentioned inside that #pragma to be shared among DLL or to the native application from this DLL. #pragma #pragma data_seg(".SHARE") UINT UWN_KEYSTROKE; HWND hWndServer = NULL; #pragma data_seg() #pragma comment(linker, "/section:.SHARE,rws") The below mentioned step is done to register the window message so that we can send the keyboard events received inside the Hook function to the native executable. Hook UWN_KEYSTROKE= ::RegisterWindowMessage(UWM_KEYBOARD_MSG); The below mentioned static function is a keyboard procedure which receives the global keyboard events. static static LRESULT CALLBACK KeyBoardMsgProc( int nCode, WPARAM wParam, LPARAM lParam) We start the hooking of the keyboard events once InstallKeyBoardHook is called from the parent executable. In the SetWindowHookEx, we have specified the first parameter as WH_KEYBOARD to hook the keyboard event. SetWindowHookEx WH_KEYBOARD hook= SetWindowsHookEx( WH_KEYBOARD, (HOOKPROC)KeyBoardMsgProc, hInst, 0); The CallNextHookEx is a optional procedure but it is highly recommented by Microsoft. If it is not called, there is a chance that other processes that have installed hook may not get the events correctly. CallNextHookEx CallNextHookEx(hook, nCode, wParam,lParam); To uninstall the hook procedure, we need to call the UnhookWindowsHookEx specifying the Handle of returned by SetWindowHookEx. UnhookWindowsHookEx BOOL unhooked = UnhookWindowsHookEx(hook); This tool is a miniature implementation to the test automation software. But I am sure, it will give you an idea about mouse and keyboard hooking. SetWindowsHookEx can be used to inject a DLL into another process. In this article, we are dealing with WH_KEYBOARD which monitors keystroke message. The keyboard input can come from the local keyboard driver or from calls to the keybd_event function. If the input comes from a call to keybd_event, the input is "injected". WH_KEYBOARD_LL hook is not injected into another process, so it’s better. WH_SHELL can be used to get notification of the shell events. SetWindowHookEx is a very useful API, but for a good work we have to pay, so let's do so. Hooks tend to slow down the system because they increase the amount of processing the system must perform for each message. So use judiciously. If my Allah allows me, I will write more articles. SetWindowsHookEx keybd_event WH_KEYBOARD_LL WH_SHELL SetWindowHookE.
http://www.codeproject.com/Articles/67091/Mouse-and-KeyBoard-Hooking-utility-with-VC?fid=1565386&df=90&mpp=10&sort=Position&spc=None&select=4349739&tid=4159413
CC-MAIN-2016-26
refinedweb
984
65.52
A simple web framework based on asyncio. Project description A simple web framework based on asyncio. Induction is the phenomenon that drives asynchronous motors. Pictured above is Tesla’s induction motor. Installation pip install induction Usage examples If you know express and/or Flask, you’ll feel right at home. Synchronous route from induction import Induction app = Induction(__name__) @app.route('/') def index(request): return app.render_template('index.html') Async route from asyncio import coroutine from induction import Induction app = Induction(__name__) @app.route('/slow'): @coroutine def slow(request, response): yield from asyncio.sleep(10) response.write('Hello, world!') Handlers Handlers are decorated with @app.route(url_pattern). Routes are managed by the Routes library. Handlers have several way to send data back to the client: - returning: synchronous routes can return data directly. The return values are passed to the response object. Supported return values are: - A string or bytes object, which becomes the body of the response. A default status of 200 OK and mimetype of text/html are added. - A tuple of (response, headers, status), in any order and with at least one item provided. headers can be a list or a dictionnary. - writing: handlers can be defined to accept two arguments, request and response. They can then directly write data to the response. Induction objects The Induction constructor accepts the following arguments: - name: the name for your app. And the following keyword arguments: - template_folder: path to the folder from which to load templates. Defaults to 'templates' relatively to the current working directory. The following methods are available on Induction instances: route(path, **conditions): registers a route. Meant to be used as a decorator: @app.route('/') def foo(request): return jsonify({}) before_request(func): registers a function to be called before all request handlers. E.g.: @app.before_request def set_some_header(request, response): request.uuid = str(uuid.uuid4()) response.add_header('X-Request-ID', request.uuid) before_request functions are called in the order they’ve been declared. When a before_request function returns something else than None, all request processing is stopped and the returned data is passed to the response. after_request(func) registers a function to be called after all request handlers. Works like before_request. handle_404(request, [response]): error handler for HTTP 404 errors. error_handler(exc_type): registers a function to be called when a request handler raises an exception of type exc_type. Exception handlers take the request, the response and the exception object as argument: @app.error_handler(ValueError): def handle_value_error(request, response, exception): response.add_header("X-Exception", str(exception)) Note that the response may have been partially sent to the client already. Depending on what your application does, it might not be safe to set headers or even send data to the response. Setting exc_type to None lets you register a catch-all error handler that will process all unhandled exceptions: @app.error_handler(None): def handle_exception(request, response, exception): # Send exception to Sentry client = raven.Client() client.captureException() render_template(template_name_or_list, **context): loads the first matching template from template_name_or_list and renders it using the given context. Response objects The following attributes and methods are available on Response objects: status, status_line: the HTTP status code and line for this response. write(chunk, close=False, unchunked=False): writes a chunk of data to the reponse. If chunk is a string, it’ll be encoded to bytes. If close is True, write_eof() is called on the response. If unchunked is True a Content-Length header is added and the response will be closed once the chunk is written. redirect(location, status=302): redirects to location using the given status code. Releases - 0.2 (2014-09-25) - 404 error returns HTML by default. - Ability to set a catch-all error handler, e.g. for Sentry handling. - 0.1 (2014-09-19) - Initial release. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/induction/
CC-MAIN-2018-51
refinedweb
653
51.34
def resolve_playback_url(self, key): svc = RemotingService(self._AMF_ENDPOINT) rdio_svc = svc.getService('rdio') def resolve_playback_url(self, key): svc = RemotingService(self._AMF_ENDPOINT) svc.addHTTPHeader('Cookie', 'r=YOUR-R-COOKIE-VALUE') svc.addHTTPHeader('Host', '') rdio_svc = svc.getService('rdio') (2012-08-09 13:15)ampedandwired Wrote: It works! I've released a new version 1.3.4 with the fix. Let me know how you go with it. (2012-08-10 04:56)ampedandwired Wrote: @dkplayaclub - thanks, that's exactly what I was looking for. Unfortunately it doesn't tell me anything except that Rdio thinks your password is incorrect (The text "password is incorrect" is lifted directly from the Rdio login page), which we know isn't the case as you've already quadruple checked it Not too sure where to go with this one, but here are a couple of suggestions to start with: Quintuple check your password. Verify it directly in the Rdio config file by having a look at the contents of this file: <xbmc_home>/userdata/addon_data/plugin.audio.rdio/settings.xml Do you have any punctuation in your password? If so, perhaps try changing your Rdio password so that it only has letters and numbers, then change it in the Rdio XBMC settings and try again. Underscores or dashes should be OK, but stay away from any other punctuation, especially spaces, ampersands, greater/less than and single/double quotes. Let me know how you go.
http://forum.kodi.tv/showthread.php?tid=133714&pid=1167389
CC-MAIN-2016-36
refinedweb
236
59.19
Provide feedback to the user Create advanced actions Configure widgets For information on using variables in captions, advanced actions, and widgets, see the respective Help sections. Text captions Actions and Advanced actions Widgets Getting/setting variables in Adobe Captivate SWF files using JavaScript Movie navigation For example, you can use the system variable cpInfoCurrentTime in quiz slides to display the time remaining for the user to complete answering the question. You can also use the variable in a widget to provide a progress bar or a time ticker.. Apart from saving time, variables help achieve consistency and minimize errors in a project. For example, you can use user-defined variables to specify version numbers of products. At all places where you want to add the version number in a project, add the variable instead. When you set the value for the version number in the corresponding variable, the value is displayed at all places where you inserted the variable. Similarly, when you want to modify the version number, you just have to change the value of the variable. When you use system variables for this purpose, you do not have to manually correct the slide number when the slides are reordered. Customize Adobe Captivate to your requirements: You can use variables in advanced actions to provide advanced interactivity in your Adobe Captivate projects. Integrate Adobe Captivate with other applications: You can use get/set variables in Adobe Captivate from other applications. Select Project > Actions. Select the Variables tab. In the Type menu, select User. Click Add New, and enter the following information: Click Save. Some of the variable names are reserved by ActionScript. Do not use the following variable names when creating your variable: abstract, as, boolean, break, byte, case, cast, catch char, class, const, continue, debugger, default, delete, do, double, dynamic, each, else, enum, export, extends, false, final, finally, float, for, function, get, goto, if, implements, import, in, include, instanceof, interface, internal, intrinsic, is, long, name, namespace, native, native, new, null, override, package, private, protected, prototype, public, return, set, short, static, super, switch, synchronized, this, throw, throws, to, transient, true, try, type, typeof, use, var, virtual, void, volatile, while, with. In the Type menu, select System. In the View By menu, select MovieMetaData. Select the variable that you want to modify, and change its value. For example, to assign the name of your company to the cpInfoCompany variable, select it from the list. In the Value field, enter the name of your company. Click Update. In the list of variables, select the variable you want to edit. Do one of the following: To edit the variable, modify the value/description of the variable, and click Update. To delete the variable from the list, click Remove. You can control Adobe Captivate projects with variables that you can set on the Timeline. Controlling a project with variables is useful if you want to create custom SWF playback controls or if you are putting a project into a FLA file. Using variables is an advanced feature that should be implemented only by users with a solid background in Flash. The following commands are used by playback controls and preview: The following variables provide information currently used by playback controls and preview: Advanced actions
http://help.adobe.com/en_US/Captivate/4.0/Using/WSCB934979-86BE-40d2-8BB8-A66956575988.html
CC-MAIN-2015-40
refinedweb
541
52.7
A Quick Introduction to Algorithms . You also do it in a process that takes less time to calculate. This is called an Algorithm. An Algorithm is a set of instructions designed to perform a specific task. Algorithms can be simple and complex depending on what you want to achieve. History of Algorithm Knowing the history of something you learn, will always be an added advantage, as you can understand the topic better than anyone and know exactly where to use what and many more. The term “Algorithm” is derived from a 9th century Persian mathematician named Muhammad Ibn Musa Al-Khwarizmi(Father of Algebra), Latinized as Algoritmi. At first algorithm was called as Algorismus. Later in 15th century Algorisums was altered to Algorithmus(derived from Greek word Arithmetic). The modern sense English term “Algorithm” was introduced in the 19th century. Before 1842, algorithms were written on papers and were used to perform mathematical calculations. The first algorithm developed was by Egyptians for multiplying 2 numbers in 1700–2000 BC. For the first time in 1842, an algorithm for computing engine was written, by Ada Lovelace, which is why she is often cited as the first computer programmer. She wrote an algorithm for Analytical Engine(a mechanical computer that automated computations), developed by our Father of Computer, Charles Babbage to compute Bernoulli numbers. The first modern notion algorithm in electronic(non-mechanical) computers were seen in Alan Turing’s Turing Machine in 1936. How are the algorithms expressed? Algorithms can be expressed in many ways like natural languages, pseudocode, flow charts, programming languages, drakon-charts, control tables. Natural language expression of algorithms is ambiguous so they are rarely used for complex or technical algorithms. Pseudocode, flow charts, drakon-charts, and control tables are structured ways to express algorithms so they avoid many of the ambiguities compared to natural language. Programming languages are intended for expressing algorithms in a form that can be executed by a computer. In computer systems, an algorithm is a logic written by software developers in any programming language of their choice. But, there are a few set of rules that we need to remember while designing an algorithm. They are, Input: There should be one or more values to be applied in the algorithm. If there is no input given what output will the algorithm produce? Output: At least one output should be produced. There is no use of designing an algorithm if it does not produce any result. Efficiency: It should be efficient in terms of compute and memory. The output produced should be correct & fast. Simplicity: The algorithm should not be overly complex. Scalability: The algorithm must be able to scale without changing the core logic. Finiteness: The algorithm must terminate after a finite number of steps. Assume you have given wrong input, if the algorithm terminates at the first step, we would never know what’s wrong with our algorithm. Also, it should not end up in infinite loops. Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any language, and yet the output will be the same, as expected. Lets now build a simple algorithm which adds two numbers fulfilling the above pre-requisites. Step-1: Start Step-2: Declare variables num1, num2, and sum Step-3: Read values num1 and num2 Step-4: Add num1 and num2 and assign the value to sum. Step-5: Display sum Step-6: Stop Now, to test the algorithm, we are going to implement it in one of the programming language, I choose to implement it in Java language, you can implement it any programming language of your choice. public class Addition { public static void main(String[] args) { int num1, num2, sum; Scanner sc = new Scanner(System.in); System.out.println(“Enter First Number: “); num1 = sc.nextInt(); System.out.println(“Enter Second Number: “); num2 = sc.nextInt(); sc.close(); sum = num1 + num2; System.out.println(“Sum of two numbers: “+sum); } } The output is as below, Enter First Number: 121 Enter Second Number: 19 Sum of two numbers: 140 Our algorithm is working perfectly, fulfilling the above mentioned prerequisites. An algorithm developed must be efficient. An algorithm’s efficiency is defined by time and space. A good algorithm is the one that takes less time and less space, both are not possible all the time. If you want to reduce the time, then space might increase and vice versa. So, we have to compromise with either of them. The space complexity of an algorithm denotes the total space used or needed by the algorithm for its working. Time complexity is the number of operations an algorithm performs to complete its task. The algorithm that performs the task in the smallest number of operations is considered as the most efficient algorithm. The time taken by an algorithm also depends on the computing speed of your machine, but this external factor is not often considered while calculating the efficiency of an algorithm. One way to measure the efficiency of an algorithm is to count how many operations it needs to find the answer across different input sizes. Recursive Algorithm solves the problem by repeatedly breaking down the problem into sub-problems. Divide & Conquer Algorithm solves the problem by breaking down the problem into smaller sub-problems, solves them recursively, and combines them to form a solution. Dynamic Programming Algorithm(also known as Dynamic Optimization Algorithm) remembers the past results for future use. Similar to Divide & Conquer Algorithm, it breaks down complex problems into simple sub-problems, then solve each of these sub-problems only once by storing solution for future use without having to recompute their solutions again. Greedy Algorithm solves the problem by taking the optimal solution at the local level. This algorithm does not guarantee an optimal solution at the end. Brute Force Algorithm is simple & straight-forward, it simply tries all the possibilities until a satisfactory solution is found. Backtracking Algorithm solves the problem recursively in an incremental approach. It tries to get the solution by solving one piece at a time. If one of the solution fail, it backtracks and starts finding the solution. Algorithms are now being used in almost every field like data science, machine learning, agriculture, science, transport, etc. Algorithms are the reason which differs every application from each other like Google Chrome from Mozilla Firefox, Uber from Ola, etc. For example, Google Chrome and Mozilla Firefox are both search engine applications and provide the same results but the order of results varies, this is because of different sorting algorithms being used. Google has its sorting algorithm which is different from that of Firefox’s. We know algorithms are making our lives easier as algorithms are everywhere and will continue to spread, but there are also things that we need to worry about like, Humanity & human judgment are lost when data & predictive modeling becomes paramount. Unemployment will rise, as smarter and more efficient algorithms displace many human activities. In this 21st century, algorithms are like magic, as we can explain their principles and how the network was created, etc but why the particular output has resulted is beyond a mechanical explanation. This is just the beginning. “If every algorithm suddenly stopped working, it would be the end of the world as we know it.” (The Master of Algorithm by Pedro Domingos) I hope you understood, in case of any queries feel free to ask in the comment section. Open for feedback & suggestions. THANK YOU!!
https://alekya3.medium.com/what-is-an-algorithm-everything-you-need-to-know-about-algorithms-79bb99cb0c11
CC-MAIN-2021-21
refinedweb
1,254
54.83
A little off the beaten track for someone who works at Microsoft evangelising Windows, but following Ben Armstrongs recent blog posting here, here and here about getting OS/2 Warp 4.0 running under Virtual PC 2004, I just had to give it a go. After all, it's the weekend and I've been feeling a bit under the weather, so why not curl up with a warm laptop, wireless connectivity, kids quiet on the Xbox and an inviting sofa to try it out? Many years ago, I used to be somewhat of an OS/2 guru, having first used it in 1993 back at the time version 2.11 had just come out. I even attended a couple of "ColoradOS/2" conferences way back in 1995 and 1996 (if memory serves me right), and met Paul Giangarra, the lead architect for OS/2 "Merlin" (one of the codenames). What is most worrying is how much you forget after only 6 or 7 years - it all comes flooding back (not).... MPTS, LAPS, WPS, E, the buggy Netscape Navigator for OS/2, Mahjongg Solitaire (now there was a good game). As I recall, I must have been one of the very first people to have a copy of Warp as I brought it back from the states to the UK before it was publicly available over here. Installation of the OS is easy enough. However, my laptop doesn't have a floppy drive (in fact I only have one machine with a floppy drive now, and besides I don't think I have any disks hanging around anyway - how times have changed). To create the floppies, I simply created a new Virtual Floppy from an XP Virtual Machine, inserted the Warp CD (bit dusty, but still working fine), and run cdinst from the root directory. THIS WILL FAIL!, but all is OK as long as it gets to around 99%. Once you have a 99% completed disk 1, edit cdinst.cmd and see what it does to create disk 2 and the installation disk needed during boot installation, and run the commands from the command prompt. Respectively these are: \DISKIMGS\LOADDSKF \DISKIMGS\OS2\35\DISK2.DSK A: /Y/Q/F for Disk 1 and\DISKIMGS\LOADDSKF \DISKIMGS\OS2\35\DISK0.DSK A: /Y/Q/F for the Installation diskNote that the file has a %1 in the above lines which you can just lop out and run from a D: prompt. The install is fine, as long as you heeded Ben's warnings about installing NetBIOS over TCP/IP during installation. I didn't the first time, and given how much I'd forgotten about MPTS and network configuration managed to get myself into a very big mess - fix pack's half installed, network only up once in every 5 or 6 boots, shared folders not working, SVGA mode stuffed. Hence, I went back to the drawing board and started a second time. I wish I had have found this answer before giving up and going for the second install - it gives a great deal of information on setting up the Network. The installation of the VM additions was possible before installing FixPak 15 which did surprise me - however, it enabled me to download fixpak 15 from my host machine, and use the VM Shared Folders to copy the extracted file onto the local drive of the OS/2 Warp Guest. FixPak 15 wasn't quite as easy to install as I thought - unfortunately Bens link to the FTP site on IBM didn't work for me. However, it is downloadable as a .zip file from hobbes (there's a name I haven't heard of for years). To install it, you will need the CSF (Corrective Service Facility) version 1.43. If you use the link I provided, you'll need to download this separately, for example from here. Take care with the directory structure you use in the guest (ie the c:\os2serv\os2serv structure which Ben mentioned), or the fixpak installation will fail. Ben's link for the SVGA display driver and installation was perfect. Thankyou. Browsers... Back in the days I was using OS/2, before Warp 4 you were pretty much snookered. On the bright side though, these were the days of BBS's and modems and Warp had a very capable terminal emulator, and combined with PComm/2, you were pretty much sorted. Warp 4 introduced the WebExplorer, but this leaves a lot to be desired. Netscape came out with a highly unsatisfactory browser (I can't find the link now), but fortunately FireFox 1.0 is available for OS/2 today. Note that you'll need to install libc-0.5.1 runtime on which FireFox is dependent. The rendering was a little suspect, but still very usable. Now, if only Microsoft had a version of Internet Explorer 6 for OS/2.... Things to remember about OS/2. No, it's not a bit like Windows 3.x. However, it does make extensive use of the c:\config.sys (sound familiar?). Be careful how you edit it. I think I re-discovered this fact towards the end of giving up on my first installation. Now for the great stuff. Once it was installed, I had to get the machine participating in my home domain. Yes, you can indeed do this. However, you will need to reduce the security settings if you are running Windows Server 2003. Start the Domain Security Settings snap-in, navigate to Security Settings/Local Policies/Security Options and set "Microsoft network server; Digitally sign communications (always)" to disabled. If you've got everything setup right, go back to a command prompt on the VM and type "logon <username> /P:<domainpassword> /V:d /d:<yourdomain>". You should get back "The command completed successfully". Try using "net view \\<server>". Finally, a dig around found a copy of IBM VisualAge C++ for OS/2 - the compiler I used for many years. I haven't done much C programming in several years, but this did come flooding back. I still have a first edition Kernihan and Ritchie "The C Programming Language" book (the definitive C language guide) upstairs, but didn't need to refer to it to get a version of the "hello, world" program running - in fact, it compiled and ran first time. There's a load of fixups mentioned on the IBM site (most recent c.2000) , but I couldn't get any of them to download. Fortunately, I didn't need them. #include <stdio.h>void main(int argc, char* argv[]){printf("Welcome from OS/2 Under Virtual PC 2004 :-)\n");} And here's the screen shot.... I also found a copy of Database 2 for OS/2 (aka DB2/OS2), but that's for another day. Me and databases never did get along too well. I hope you found this useful - very much a trip back down memory lane personally. I'm sure I'll be reminiscing for a few weeks yet and have loads of utilities and other software on CD's somewhere or other. Now where can you get that really cool WarpSans font for Windows.....?
http://blogs.technet.com/b/jhoward/archive/2005/01/30/363410.aspx
CC-MAIN-2014-49
refinedweb
1,199
71.24
Check out our guide for embedding reports into ASP.NET MVC applications. In this step-by-step tutorial, learn how to use Telerik Report Viewer in MVC applications. In this step-by-step tutorial, I will demonstrate how to use Telerik Report Viewer in MVC applications. This tutorial covers the following topics: The Telerik Report Viewer is a pure HTML5/JavaScript/CSS3 jQuery-based widget that allows displaying Telerik reports in an HTML page. The layout or styling is based on pure HTML5 templates and CSS3 styles and is fully customizable. It supports mobile as well as desktop browsers. Report viewers, which are UI components, allow you to display the report document produced by the report engine in the application UI. To integrate the Telerik Report Viewer in an ASP.NET MVC application, you'll need to follow these prerequisites: Grab the eBook: A Quick Guide to Expert .NET Reporting Tools The Telerik Report Viewer provides an HTML helper that can be used in ASP.NET MVC applications. The easiest way to add and configure Report Viewer would be to use the Item Templates that are registered in Visual Studio during the product installation. The MVC Report Viewer View Item Template is a fully functional wizard that does all the heavy lifting for users: That workflow is described here. If you are able, that is the recommended setup. Otherwise, follow these steps to use this helper manually in MVC: Step 1: Create an ASP.NET MVC application using Visual Studio. Step 2: Add the below two references of Telerik into application and set their Copy Local properties to true in Visual Studio. Step 3: Add the previous step's added references into the web.config file in the Views folder as below: <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> ... <add namespace="Telerik.Reporting" /> <add namespace="Telerik.ReportViewer.Mvc" /> </namespaces> </pages> Step 4: The default viewer implementation depends externally on jQuery. Create a section named scripts and add a link to jQuery in the view: @section scripts { <script src=""></script> } Step 5: The Report Viewer uses the style of the desired Kendo UI theme, so please add these below references to the Less-based CSS files in the head element of _Layout.cshtml: <!-- The required Less-based styles --> <link href="" rel="stylesheet"/> <link href="" rel="stylesheet"/> Step 6: Add references to the HTML5 report viewer's JavaScript file in the respective view, as below: <script src="~/api/reports/resources/js/telerikReportViewer"></script> Step 7: Add the Telerik Report Viewer helper provided for MVC applications in the respective view: @() ) Note - For available options for this HTML helper, please check details here. Step 8: Render the deferred initialization statement for the Report Viewer scripts: @(Html.TelerikReporting().DeferredScripts()) Step 9: We have implemented the Telerik Report Viewer helper in our MVC application, and pages should look like this: _Layout.cshtml <!DOCTYPE html> <html> <head> <title>Demo</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <link href="" rel="stylesheet" /> <link href="" rel="stylesheet" /> @RenderSection("styles", required: false) @RenderSection("scripts", required: false) </head> <body> @RenderBody() </body> </html> Respective Index.cshtml view @using Telerik.Reporting @using Telerik.ReportViewer.Mvc @{ ViewBag.</script> <script src="@Url.Content("")"></script> @(Html.TelerikReporting().DeferredScripts()) } @() ) Step 10: Before running the application, please make sure the Reporting REST Service is running. Note that if the REST Service is in the same application it won’t be running until the app is started. If you're having trouble accessing the Reporting REST Service, you can check out this help article for some tips. Step 11: Finally, run the application and navigate to the view with the ASP.NET MVC Report Viewer that we have just created. It will open in the browser and you can see the output like this: The Report Viewer is divided into the main two parts. The first part on top is for toolbars, and the second part below it is used for showing the data. Let's check what tools are available for users in the Report Viewer toolbar. Top toolbar options: Filters - The below screenshot shows the filters that on the Report Viewer's right side. Based on these filters, data will be shown in the left side. You can also download this example from here. In this article, we discussed what the Telerik Report Viewer is, its prerequisites and how to use it working in an MVC application, and the Report Viewer toolbar for users. If you have any suggestions or queries regarding this article, please leave a comment. Learn It, Share it.. Jeetendra Gund is a C# Corner MVP as well as the Chapter Leader of C# Corner Pune Chapter. He holds a master’s degree in Computer Science and has worked on several different domains. He has spent six years in grooming his knowledge about Microsoft Technologies and has been sharing his experiences on technologies such as C#.Net, MVC.Net, SQL Server, Entity Framework, AngularJS, JavaScript, HTML, and .NET Static Code Analysis. He is a regular speaker at C# Corner on Microsoft Technologies. Find him: C# Corner, LinkedIn, or Twitter.
https://www.telerik.com/blogs/embedding-beautiful-reporting-asp-net-mvc-applications
CC-MAIN-2021-39
refinedweb
855
55.95
In most of the situations, we deal with estimations of the whole distribution of the data. But when it comes to central tendency estimation, we need a specific way to summarize the distribution. Mean and median are the very often used techniques to estimate the central tendency of the distribution. In all the plots that we learned in the above section, we made the visualization of the whole distribution. Now, let us discuss the plots with which we can estimate the central tendency of the distribution. Bar Plot The barplot() shows the relation between a categorical variable and a continuous variable. The data is represented in rectangular bars where the length of the bar represents the proportion of the data in that category. Bar plot represents the estimate of central tendency. Let us use the ‘titanic’ dataset to learn bar plots. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('titanic') sb.barplot(x = "sex", y = "survived", hue = "class", data = df) plt.show() In the above example, we can see that the average number of survivals of males and females in each class. From the plot, we can understand that the number of females survived than males. In both males and females, a number of survivals are from first class. A special case in barplot is to show the no of observations in each category rather than computing a statistic for a second variable. For this, we use countplot(). import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('titanic') sb.countplot(x = "class", data = df, palette = "Blues"); plt.show() Plot says that, the number of passengers in the third class are higher than first and second class. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('titanic') sb.pointplot(x = "sex", y = "survived", hue = "class", data = df) plt.show()
https://coderzcolumn.com/tutorials/data-science/seaborn-working-with-statistical-estimation
CC-MAIN-2021-04
refinedweb
323
65.01
Sylvain Wallez said the following on 13-03-2006 11:32: > hepabolu wrote: >> Sylvain Wallez said the following on 13-03-2006 10:47: >>> Carsten Ziegeler wrote: >>>>. Dojo code is committed, and I'd like people to try the new forms >>> samples. >> Great! Thanks! >> >> Haven't looked thoroughly at the code yet, but I'm wondering two things: >> >> 1. several special attributes (ajax=true and some Dojo required >> attributes) make it impossible to produce valid XHTML pages. A quick >> reading in some Dojo files showed that most dojo attributes can be >> replaced with classnames or identifiers, making valid XHTML pages >> still possible. Have you used any of those? Or are there other ways to >> produce valid XHTML pages that can already be incorporated in the >> current code? > > The ajax="true" attribute is used server-side by Cocoon and can be > filtered out by the stylesheets. Ah, that's nice. It's currently not filtered, i.e. present in the resulting code. Maybe something to add to the stylesheets before the release? > The dojoType attribute triggers the Dojo widget system. It can be > written in 3 different ways depending on the context/requirements: > - dojoType attribute (e.g. dojoType="CFormsRepeater") -- works everywhere > - namespaced dojo:type attribute (e.g. dojo:type="CFormsRepeater") -- > works on namespace-aware browsers > - CSS class (e.g. class="dojo-CFormsRepeater") > > I used the dojoType attribute variant, now we may decide to use another one. I have not enough knowledge of the various browsers, so I cannot figure out whether a namespaced dojo:type attribute is feasible to work with (a.o. which browsers do and don't support it). OTOH web designers in general (dealing mainly with CSS, graphics and layout) prefer valid XHTML + valid CSS before they are able to tackle the browser-inconsistencies in CSS. We might as well try to accommodate that (i.e. produce a valid XHTML page) by making sure that no transformation step introduces any (X)HTML errors nor warnings. In short: when the final page is not valid (X)HTML, this is due to errors made by the builder of the pipeline. > However, some widgets _require_ foreign attributes to be present. These > are the widget-specific properties. Nasty. Having chatted with some members of the Dojo community gave the impression that they don't care about valid (X)HTML as long as the javascript works. So there is a conflicting point of view. >> 2. Dojo contains a (rich text) editor, much along the lines of >> htmlarea. Have you compared the two and would it be possible to >> replace htmlarea with the Dojo version or are there features we would >> miss? In the latter case: if we stick with htmlarea, is it worthwhile >> to update to Xinha since that is a more active project around htmlarea? > > I haven't investigated in this area... Do you think it's worth the effort? Bye, Helma
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200603.mbox/%3C44154F37.7070302@gmail.com%3E
CC-MAIN-2016-26
refinedweb
480
65.93
What is this?This is Yet Another Linear Programming Solver (YALPS). It is intended as a performant, lightweight linear programming (LP) solver geared towards medium and small LP problems. It can solve non-integer, integer, and mixed integer LP problems. The outputed JS has only ~500 lines and is ~20kB in size (not minified). YALPS is a rewrite of jsLPSolver. The people there have made a great and easy to use solver. However, the API was limited to objects only, and I saw other areas that could have been improved. You can check out jsLPSolver for more background and information regarding LP problems. Compared to jsLPSolver, YALPS has the following differences: - More flexible API (e.g., support for Iterables alongside objects) - Better performance (especially for non-integer problems, see Performance for more details.) - Good Typescript support (YALPS is written in Typescript) On the other hand, these features from jsLPSolver were dropped: - Unrestricted variables (might be added later) - Multiobjective optimization - External solvers Usage Installation npm i yalps ImportThe main solve function: import { solve } from "yalps" Types, as necessary: import { Model, Constraint, Coefficients, Options, Solution } from "yalps" Alternate helper functions: import { lessEq, equalTo, greaterEq, inRange } from "yalps" ExamplesUsing objects: const model: Model = { direction: "maximize", objective: "profit", constraints: { // each key is the constraint's name, the value is its bounds wood: { max: 300 }, labor: { max: 110 }, // labor should be <= 110 storage: lessEq(400) // you can use the helper functions instead }, variables: { // each key is the variable's name, the value is its coefficients table: { wood: 30, labor: 5, proft: 1200, storage: 30 }, dresser: { wood: 20, labor: 10, profit: 1600, storage: 50 } }, integers: [ "table", "dresser" ] // these variables must have an integer value in the solution } const solution = solve(model) // { status: "optimal", result: 14400, variables: [ ["table", 8], ["dresser", 3] ] } Iterables and objects can be mixed and matched for the constraintsand variablesfields. Additionally, each variable's coefficients can be an object or an iterable. E.g.: const constraints = new Map<string, Constraint>() constraints.set("wood", { max: 300 }) constraints.set("labor", lessEq(110)) constraints.set("storage", lessEq(400)) const dresser = new Map<string, number>() dresser.set("wood", 20) // this is intended to be created programatically dresser.set("labor", 10) dresser.set("profit", 1600) dresser.set("storage", 50) const model: Model<string, string> = { direction: "maximize", objective: "profit", constraints: constraints, // is an iterable variables: { // kept as an object table: { wood: 30, labor: 5, proft: 1200, storage: 30 }, // an object dresser: dresser // an iterable }, integers: true // all variables are indicated as integer } const solution: Solution<string> = solve(model) // { status: "optimal", result: 14400, variables: [ ["table", 8], ["dresser", 3] ] } Using iterables allows the keys for constraintsand variablesto be something besides string. Equality between keys is tested using ===, Map.get, and Set.has(all essentially use strict equality). APIThis is dist/YALPS.d.tsbut with the essential parts picked out. See dist/YALPS.d.tsfor more extensive documentation if necessary. interface Constraint { equal?: number min?: number max?: number } /** * Specifies something should be less than or equal to `value`. * Equivalent to `{ max: value }`. */ const lessEq: (value: number) => Constraint /** * Specifies something should be greater than or equal to `value`. * Equivalent to `{ min: value }`. */ const greaterEq: (value: number) => Constraint /** * Specifies something should be exactly equal to `value`. * Equivalent to `{ equal: value }`. */ const equalTo: (value: number) => Constraint /** * Specifies something should be between `lower` and `upper` (both inclusive). * Equivalent to `{ min: lower, max: upper }`. */ const inRange: (lower: number, upper: number) => Constraint /** * The coefficients of a variable represented as either an object or an `Iterable`. * `ConstraintKey` should extend `string` if this is an object. * If this is an `Iterable` and has duplicate keys, * then the last entry is used for each set of duplicate keys. */ type Coefficients<ConstraintKey = string> = | Iterable<[ConstraintKey, number]> // an iterable | (ConstraintKey extends string // or an object, but ConstraintKey must extend string ? { [constraint in ConstraintKey]?: number } : never) /** * The model representing a LP problem. * `constraints`, `variables`, and each variable's `Coefficients` can be either an object or an `Iterable`. * If there are objects present, the corresponding type parameter(s) for their keys must extend string. * The model is treated as readonly (recursively) by the solver. */ interface Model<VariableKey = string, ConstraintKey = string> { /** * Indicates whether to `"maximize"` or `"minimize"` the objective. * Defaults to `"maximize"` if left blank. */ direction?: "maximize" | "minimize" /** * The name of the value to optimize. Can be omitted, * in which case the solver gives some solution (if any) that satisfies the constraints. */ objective?: ConstraintKey /** * An object or an `Iterable` representing the constraints of the problem. * In the case `constraints` is an `Iterable`, duplicate keys are not ignored. * Rather, the bounds on the constraints are merged to become the most restrictive. */ constraints: | Iterable<[key: ConstraintKey, constraint: Constraint]> | (ConstraintKey extends string ? { [constraint in ConstraintKey]: Constraint } : never) /** * An object or `Iterable` representing the variables of the problem. * In the case `variables` is an `Iterable`, duplicate keys are not ignored. * The order of variables is preserved in the solution, * but variables with a value of `0` are not included in the solution by default. */ variables: | Iterable<[key: VariableKey, variable: Coefficients<ConstraintKey>]> | (VariableKey extends string ? { [variable in VariableKey]: Coefficients<ConstraintKey> } : never) /** * An `Iterable` of variable keys that indicates these variables are integer. * It can also be a `boolean`, indicating whether all variables are integer or not. * If this is left blank, then all variables are treated as not integer. */ integers?: boolean | Iterable<VariableKey> /** * An `Iterable` of variable keys that indicates these variables are binary * (can only be 0 or 1 in the solution). * It can also be a `boolean`, indicating whether all variables are binary or not. * If this is left blank, then all variables are treated as not binary. */ binaries?: boolean | Iterable<VariableKey> } type SolutionStatus = "optimal" | "infeasible" | "unbounded" | "timedout" | "cycled" /** The solution object returned by the solver. */ type Solution<VariableKey = string> = { /** * `status` indicates what type of solution, if any, the solver was able to find. * * `"optimal"` indicates everything went ok, and the solver found an optimal solution. * * `"infeasible"` indicates that the problem has no possible solutions. * * `"unbounded"` indicates a variable, or combination of variables, are not sufficiently constrained. * * `"timedout"` indicates that the solver exited early for an integer problem * (either due to `timeout` or `maxIterations` in the options). * * `"cycled"` indicates that the simplex method cycled, and the solver exited as a result (this is rare). */ status: SolutionStatus /** * The final, maximized or minimized value of the objective. * It may be `NaN` in the case that `status` is `"infeasible"`, `"cycled"`, or `"timedout"`. * It may also be +-`Infinity` in the case that `status` is `"unbounded"`. */ result: number /** * An array of variables and their coefficients that add up to `result` * while satisfying the constraints of the problem. * Variables with a coefficient of `0` are not included in this by default. * In the case that `status` is `"unbounded"`, * `variables` may contain one variable which is (one of) the unbounded variable(s). */ variables: [VariableKey, number][] } /** An object specifying the options for the solver. */ interface Options { /** * Numbers equal to or less than precision are treated as zero. * Similarly, the precision determines whether a number is sufficiently integer. * The default value is `1E-8`. */ precision?: number /** * In rare cases, the solver can cycle. * This is usually the case when the number of pivots exceeds `maxPivots`. * Alternatively, setting this to `true` will cause * the solver to explicitly check for cycles. * The default value is `false`. */ checkCycles?: boolean /** * This determines the maximum number of pivots allowed within the simplex method. * If this is exceeded, then it assumed that the solver cycled. * The default value is `8192`. */ maxPivots?: number /** * This setting applies to integer problems only. * If an integer solution is found within `(1 +- tolerance) * * {the problem's non-integer solution}`, * then this approximate integer solution is returned. * This is helpful for large integer problems where * the most optimal solution becomes harder to find, * but other solutions that are relatively close to * the optimal one may be much easier to find. * The default value is `0` (only find the most optimal solution). */ tolerance?: number /** * This setting applies to integer problems only. * It specifies, in milliseconds, the maximum amount of time the solver may take. * The current sub-optimal solution, if any, is returned in the case of a timeout. * The default value is `Infinity` (no timeout). */ timeout?: number /** * This setting applies to integer problems only. * It determines the maximum number of iterations * for the main branch and cut algorithm. * It can be used alongside or instead of `timeout` * to prevent the algorithm from taking too long. * The default value is `32768`. */ maxIterations?: number /** * Controls whether variables that end up having a value of `0` * should be included in `variables` in the resulting `Solution`. * The default value is `false`. */ includeZeroVariables?: boolean } /** * The default options used by the solver. * You may change these so that you do not have to * pass a custom `Options` object every time you call `solve`. */ let defaultOptions: Options /** Runs the solver on the given model and using the given options (if any). */ const solve: <VarKey = string, ConKey = string>(model: Model<VarKey, ConKey>, options?: Options) => Solution<VarKey> PerformanceWhile YALPS generally performs better than javascript-lp-solver, this solver is still geared towards small-ish problems. For example, the solver keeps the full representation of the matrix in memory as an array. I.e., there are currently no sparse matrix optimizations. As a general rule, the number of variables and constraints should probably be a few thousand or less, and the number of integer variables should be a few hundred at the most. If your use case has large-ish problems, it is recommended that you first benchmark and test the solver on your own before committing to using it. For very large and/or integral problems, a more professional solver is recommended, e.g. glpk.js. Nevertheless, here are the results from some benchmarks of medium/large problems comparing YALPS to other solvers (all times are in milliseconds): YALPS vs jsLPSolver Large Farm MIP.json: 35 constraints, 100 variables, 100 integers: t=5.65, jsLPSolver took 59.04% more time on average compared to YALPS jsLPSolver: (n=10, mean=67.77, stdErr=3.81) YALPS: (n=10, mean=42.61, stdErr=2.30) Monster 2.json: 888 constraints, 924 variables, 112 integers: t=14.19, jsLPSolver took 150.36% more time on average compared to YALPS jsLPSolver: (n=5, mean=196.74, stdErr=3.02) YALPS: (n=5, mean=78.58, stdErr=7.76) Monster Problem.json: 600 constraints, 552 variables, 0 integers: t=8.74, jsLPSolver took 208.00% more time on average compared to YALPS jsLPSolver: (n=6, mean=6.31, stdErr=0.46) YALPS: (n=6, mean=2.05, stdErr=0.16) Sudoku 4x4.json: 64 constraints, 64 variables, 64 integers: t=4.46, jsLPSolver took 126.71% more time on average compared to YALPS jsLPSolver: (n=32, mean=3.86, stdErr=0.47) YALPS: (n=32, mean=1.70, stdErr=0.10) Vendor Selection.json: 1641 constraints, 1640 variables, 40 integers: t=11.01, jsLPSolver took 25.55% more time on average compared to YALPS jsLPSolver: (n=5, mean=522.75, stdErr=7.20) YALPS: (n=5, mean=416.37, stdErr=6.44) YALPS vs glpk.js Large Farm MIP.json: 35 constraints, 100 variables, 100 integers: t=-8.58, GLPK took -73.82% more time on average compared to YALPS GLPK: (n=7, mean=11.76, stdErr=0.42) YALPS: (n=7, mean=44.91, stdErr=3.84) Monster 2.json: 888 constraints, 924 variables, 112 integers: t=18.41, GLPK took 187.38% more time on average compared to YALPS GLPK: (n=4, mean=217.21, stdErr=5.25) YALPS: (n=4, mean=75.58, stdErr=5.62) Monster Problem.json: 600 constraints, 552 variables, 0 integers: t=7.49, GLPK took 249.37% more time on average compared to YALPS GLPK: (n=6, mean=9.08, stdErr=0.70) YALPS: (n=6, mean=2.60, stdErr=0.51) Sudoku 4x4.json: 64 constraints, 64 variables, 64 integers: t=-19.27, GLPK took -56.64% more time on average compared to YALPS GLPK: (n=4, mean=0.69, stdErr=0.05) YALPS: (n=4, mean=1.59, stdErr=0.01) Vendor Selection.json: 1641 constraints, 1640 variables, 40 integers: t=-26.49, GLPK took -70.50% more time on average compared to YALPS GLPK: (n=4, mean=127.70, stdErr=2.64) YALPS: (n=4, mean=432.85, stdErr=11.22) The code used for these benchmarks is available under tests/Bechmark.ts. Measuring performance isn't always straightforward, so take these synthetic benchmarks with a grain of salt. It is always recommended to benchmark for your use case. Then again, if your problems are typically of small or medium size, then this solver should have no issue (and may be much faster!).
https://npmtrends.com/yalps
CC-MAIN-2022-40
refinedweb
2,109
51.44
Tk_CreateErrorHandler, Tk_DeleteErrorHandler - handle X protocol errors #include <tk.h> Tk_ErrorHandler Tk_CreateErrorHandler(display, error, request, minor, proc, clientData) Tk_DeleteErrorHandler(handler) Display whose errors are to be handled. Match only error events with this value in the error_code field. If -1, then match any error_code value. Match only error events with this value in the request_code field. If -1, then match any request_code value. Match only error events with this value in the minor_code field. If -1, then match any minor_code value. Procedure to invoke whenever an error event is received for display and matches error, request, and minor. NULL means ignore any matching errors. Arbitrary one-word value to pass to proc. Token for error handler to delete (return value from a previous call to Tk_CreateErrorHandler).: The error must pertain to display. Either the error argument to Tk_CreateErrorHandler must have been -1, or the error argument must match the error_code field from the error event. Either the request argument to Tk_CreateErrorHandler must have been -1, or the request argument must match the request_code field from the error event. Either the minor argument to Tk_CreateErrorHandler must have been -1, or the minor argument must match the minor_code field from the error event.. callback, error, event, handler
http://search.cpan.org/~srezic/Tk-804.032/pod/pTk/CrtErrHdlr.pod
CC-MAIN-2015-35
refinedweb
204
59.5
You may have already heard about the two new Arduino development boards — the Arduino Nano BLE and BLE Sense — that were announced in late July. While Arduino boards that offer out-of-the-box Bluetooth connectivity are nothing new, these two new devices have the potential to significantly reduce the complexity of your projects. Let’s take a look! Arduino Nano 33 BLE and BLE Sense Features Both new boards, the Nano 33 BLE and the more expensive Nano 33 BLE Sense, are powered by an nRF52840 microcontroller (PDF) with a clock speed of 64 MHz. They both offer one megabyte of flash memory and 256KB RAM. Furthermore, both boards have onboard Bluetooth 5.0 support, which is managed by a NINA B306 module (PDF). From these initial specs, it seems like there’s nothing new and exciting about these boards, right? Well, if you examine them a little closer, you’ll find that both boards have a built-in nine-axis tilt-sensor. This sensor module contains a 3D digital linear acceleration sensor, a 3D digital angular rate sensor, and a 3D digital magnetic sensor. In addition to the LSM9DS1 sensor, the more expensive Nano 33 BLE Sense comes with a wide array of different sensors for measuring temperature and barometric pressure, relative humidity, digital proximity, ambient light, and color. It also has a gesture sensor and a built-in microphone. These built-in sensors are what separate these boards from other Arduinos. With everything built-in, there’s a great potential to reduce the overall complexity, size, and cost of your projects. Compatibility With Other Arduino Boards The new boards have the same physical size as the well-known Arduino Nano and the two 13-Pin headers are pin-to-pin compatible with the original Nano board. Both new boards are the same size as and pin-to-pin compatible with the original Nano. Image courtesy of Arduino. However, it’s very important to note that these two new devices will only support a maximum of 3.3V inputs and they’ll get damaged when you directly connect 5V signals. Furthermore, the 5V GPIO pin will not accept any input. Instead, it’s directly connected to the 5V line of the USB plug. What Projects Will Benefit the Most? Regardless of which board you get, wearable and connected projects will benefit from the new devices due to the built-in motion sensor, Bluetooth support, and low power consumption. Additionally, if you get the more expensive version, any project that uses one of the now built-in sensors will benefit. Some examples that come to mind include weather stations, home security projects, color-sensing devices, sound-sensing devices (for example clap activated projects), and battery-powered gadgets. Mbed OS: The New Arduino Core Another big change that came with these boards is the announcement of a new Arduino Core based on Arm’s Mbed OS. Both new Arduino boards can still be programmed with the familiar Arduino IDE. However, because a different microcontroller was used, there was no official core available. Mbed OS, which is a real-time operating system, was adopted as the foundation for the new development boards. This new core is capable of running multiple threads at the same time and offers a new low-power mode as well as support for other real-time features. This new core doesn’t mean that you have to use these advanced features, which can be quite tricky on traditional systems. The standard Arduino functions will still work like with any other classic board. However, if you want to use the new RTOS components, you can easily do so. All the Mbed infrastructure is available under the mbed:: namespace. This means that all Mbed boards are now also supported by the Arduino IDE and that Mbed developers can now utilize Arduino functions and libraries in their projects. Time to Get Building! These two new Arduino boards offer a wide array of impressive features and personally, I’m really looking forward to receiving mine. Making large and complex projects that rely on a lot of common sensors will be quite a bit easier and less frustrating with these boards. At the time of this writing, both boards are still set as pre-order and the announcement states they’ll be shipping mid-August.
https://maker.pro/arduino/tutorial/new-arduino-nano-33-ble-and-ble-sense-with-arm-mbed-os-core
CC-MAIN-2020-40
refinedweb
723
62.07
Part 5 covers: Maya Exporter Installation Setting Up Units What you need to know before exporting Textures DDS Plugin Material file creation Setting LODs CoJ2 Bound in Blood Video Notes: Download Maya Exporter for Maya 2009 CoJModding.com (link is no longer active) Install the Exporter Place: ChromeExporter and userSetup Into MyDocuments\maya\2009\scripts Place: AnimConverter and chromeAnimexport.mll and chromemeshexport.mll Into Maya2009 Installation Folder\bin\plug-ins Launch Maya2009 and you should see Chrome pull-down menu Set up proper units inside Maya. ChromEd uses centimeters. Window --> Settings/Preferences --> Preferences Under Settings/Working Units change it to centimeters Scale Before Exporting from Maya make sure to: Proper Scale Name: name your object objectname_0 0-3 = level of detail (LOD) that gets rendered objectname_0 objectname_1 objectname_2 objectname_3 Create a simple collision for your object and name it collisionhull_0 This collisionhull_0 has to be placed in the same space as your objectname_0 (in the 0, 0, 0) - not shown below UV your model and make sure no UVs intersect. Triangulate all of your models. Select all of your models and go to Mesh --> Triangulate Delete History on all of your objects Parent your collisionhull_0 to your objectname_0 Position your collisionhull_0 and objectname_0-3 at 0, 0, 0 Select everything except collisionhull_0 Chrome --> Export Mesh Select Detect lods and set Mesh scale to 1.000 Hit Export selected objects Save it as the same name of your object without the _0 Place the custom exported object into your maps directory. You can create subfolders if you want. Model browser will be able to read into any subfolders you create. Textures: Photoshop DDS Plug-in: Creates DDS textures. Material Files: You need to create the following material files. Use notepad to create them. Make sure that .mat file gets two breaking spaces after the last }. Just press enter twice. objectname.skn Skin("Custom Crate") { Replace("customcrate.mat", "customcrate.mat") ReplaceSurface("Wood", "", "") } objectname.mat import "templates.mtt" sub material() { use mtt_objects( s_clr = "objectname.dds", s_nrm = "customcrate_nrm.dds", s_shn = "customcrate_shn.dds", f_shn_factor = 1.0, f_nrm_factor = 1.0); } Place the custom exported objects and all of your textures and materials into your maps directory. You can create subfolders if you want. Model browser will be able to read into any subfolders you create. Create a 96x96 png file named objectname_prvw.png This is a preview that will show up in your model browser Go to your model browser in ChromEd and under All, navigate into your map folder for your custom object. Place it into your map. To set LOD distance at which our custom lods get switched over. In ChromEd go to View --> Other Windows --> Mesh visibility params Find your object and set LODs. Object must be placed into your map for this to
https://www.worldofleveldesign.com/categories/call-of-juarez-2-bound-in-blood/call-of-juarez-bound-in-blood-leveldesign-part5.php
CC-MAIN-2019-04
refinedweb
461
50.12
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE DeriveDataTypeable, BangPatterns #-} {-# OPTIONS_GHC -funbox-strict-fields #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.QSem -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (concurrency) -- -- Simple quantity semaphores. -- ----------------------------------------------------------------------------- module Control.Concurrent.QSem ( -- * Simple Quantity Semaphores QSem, -- abstract newQSem, -- :: Int -> IO QSem waitQSem, -- :: QSem -> IO () signalQSem -- :: QSem -> IO () ) where import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar , putMVar, newMVar, tryPutMVar) import Control.Exception import Data.Maybe -- | . -- data QSem = QSem !(MVar (Int, [MVar ()], [MVar ()])) -- The semaphore state (i, xs, ys): -- -- i is the current resource value -- -- (xs,ys) is the queue of blocked threads, where the queue is -- given by xs ++ reverse ys. We can enqueue new blocked threads -- by consing onto ys, and dequeue by removing from the head of xs. -- -- A blocked thread is represented by an empty (MVar ()). To unblock -- the thread, we put () into the MVar. -- -- A thread can dequeue itself by also putting () into the MVar, which -- it must do if it receives an exception while blocked in waitQSem. -- This means that when unblocking a thread in signalQSem we must -- first check whether the MVar is already full; the MVar lock on the -- semaphore itself resolves race conditions between signalQSem and a -- thread attempting to dequeue itself. -- |Build a new 'QSem' with a supplied initial quantity. -- The initial quantity must be at least 0. newQSem :: Int -> IO QSem newQSem initial | initial < 0 = fail "newQSem: Initial quantity must be non-negative" | otherwise = do sem <- newMVar (initial, [], []) return (QSem sem) -- |Wait for a unit to become available waitQSem :: QSem -> IO () waitQSem (QSem m) = mask_ $ do (i,b1,b2) <- takeMVar m if i == 0 then do b <- newEmptyMVar putMVar m (i, b1, b:b2) wait b else do let !z = i-1 putMVar m (z, b1, b2) return () where wait b = takeMVar b `onException` do (uninterruptibleMask_ $ do -- Note [signal uninterruptible] (i,b1,b2) <- takeMVar m r <- tryTakeMVar b r' <- if isJust r then signal (i,b1,b2) else do putMVar b (); return (i,b1,b2) putMVar m r') -- |Signal that a unit of the 'QSem' is available signalQSem :: QSem -> IO () signalQSem (QSem m) = uninterruptibleMask_ $ do -- Note [signal uninterruptible] r <- takeMVar m r' <- signal r putMVar m r' -- Note [signal uninterruptible] -- -- If we have -- -- bracket waitQSem signalQSem (...) -- -- and an exception arrives at the signalQSem, then we must not lose -- the resource. The signalQSem is masked by bracket, but taking -- the MVar might block, and so it would be interruptible. Hence we -- need an uninterruptibleMask here. -- -- This isn't ideal: during high contention, some threads won't be -- interruptible. The QSemSTM implementation has better behaviour -- here, but it performs much worse than this one in some -- benchmarks. signal :: (Int,[MVar ()],[MVar ()]) -> IO (Int,[MVar ()],[MVar ()]) signal (i,a1,a2) = if i == 0 then loop a1 a2 else let !z = i+1 in return (z, a1, a2) where loop [] [] = return (1, [], []) loop [] b2 = loop (reverse b2) [] loop (b:bs) b2 = do r <- tryPutMVar b () if r then return (0, bs, b2) else loop bs b2
http://www.haskell.org/ghc/docs/latest/html/libraries/base/src/Control-Concurrent-QSem.html
CC-MAIN-2014-23
refinedweb
506
51.58
Hello, I'm trying to make some low-poly water. So I have a plane and I put a script on it that I found online: using UnityEngine; using System.Collections; public class Water : MonoBehaviour { public float scale = 7.0f; public float heightScale = 1.0f; private Vector2 v2SampleStart = new Vector2(0f, 0f); void Update () { MeshFilter mf = GetComponent<MeshFilter>(); Vector3[] vertices = mf.mesh.vertices; for (int i = 0; i < vertices.Length; i++) { vertices[i].y = heightScale * Mathf.PerlinNoise(Time.time + (vertices[i].x * scale), Time.time + (vertices[i].z * scale)); } mf.mesh.vertices = vertices; } } Ok, great. So it makes the plane wiggle and looks like water. However the changes that are made by this script do not cause the material to react to the lighting. Since the plane starts totally flat, and is uniformly lit with no shadows or specular on anything, once this script starts, the vertices move around but there's no shading at all. It's totally flat. I've confirmed the lighting/material works by exporting a plane from Cinema4D that has a little bit of displacement baked onto it, and this is affected by the lighting. However, even when I put the script on this one, the lighting doesn't change! Polygons that were lit/shadowed from the beginning retain their same exact color. Am I missing something simple here? Thanks! plane with displacement from script: plane with displacement baked into model: Answer by shapirog · Mar 16 at 09:30 AM Well I made some progress... I got it to update the shading with RecalculateNormals(); but it resets the smoothing to the default so it no longer looks flat shaded. Is there a way to have it update the normals but keep the flat-shaded look? Or would it be better to try a totally different approach to get the water to look low-poly/flat sh see full Metallic shine in the shadow of directional light? 0 Answers Lighting problems using tiled mesh terrain is creating edges between tiles 0 Answers Procedurally generated mesh having some faces that don't receive light 1 Answer [Mesh] Unity 4 to Unity 5 Mesh Export 0 Answers Textures, Materials, Meshs and Maps? 1 Answer
http://answers.unity3d.com/questions/1326700/changing-a-mesh-with-code-but-it-doesnt-react-to-t.html
CC-MAIN-2017-34
refinedweb
366
65.83
Socialwg/2016-05-31-minutes Contents 31 May 2016 Attendees - Present - tantek, wilkie, rhiaro, dmitriz, ben_thatmustbeme, aaronpk, eprodrom, cwebber, bengo, annbass - Regrets Chair - eprodrom, tantek - Scribe - wilkie Contents - Topics - Summary of Action Items - Summary of Resolutions <tantek> <wilkie> I can scribe <tantek> scribenick: wilkie <ben_thatmustbeme> i can stay on a bit longer probably but i'll be in the car at that point <eprodrom> uh tantek: I don't hear eprodrom ... one thing was ben_thatmustbeme asked for reordering the agenda to place jf2 first because he has to leave eprodrom: are you chairing this meeting? tantek: I was until you showed up JF2 eprodrom: the idea is to have ben_thatmustbeme tell us what he proposes ben_thatmustbeme: yes, I propose to have jf2 move to a working draft this week <tantek> ben_thatmustbeme: I asked for people to have a look at it for this week <tantek> this is a FPWD (first public working draft) AFAIK eprodrom: just quickly, has everybody read the current editor's draft? <KevinMarks> I have <sandro> (haven't read this draft) <ben_thatmustbeme> tantek, yes it would be <tantek> I have eprodrom: kevin, you are co-editor, so I would hope you've read it hah tantek: has it been stable for a while or has there been changes? ben_thatmustbeme: there have been minor changes. there is a note in the document to say it is meant as a note. no substantial changes. eprodrom: aaronpk? aaronpk: I remember that the changes made have been made based on implementations using it <sandro> why not rec track? <tantek> because we accepted it in December as Note-track eprodrom: I haven't read the document yet. have you aaronpk? aaronpk: yeah, skimmed it. and re-reading it. eprodrom: so we are making this a note ben_thatmustbeme? ben_thatmustbeme: yeah we agreed about this at the last f2f sandro: anybody remember the reasoning for that? ben_thatmustbeme: partly time constraints, and so it doesn't seem as a competitor for as2 sandro: that makes sense ... the reason I ask is it is easier to start on the rec track than to switch later <eprodrom> PROPOSED: publish current Editor's Draft of JF2 as First Public Working Draft in Note track sandro: not wanting to mislead makes sense <tantek> +1 <KevinMarks> +1 eprodrom: I put up a proposal to add this working draft to the note track. does that make sense, ben_thatmustbeme? ben_thatmustbeme: yeah <aaronpk> +1 eprodrom: unless there is any other discussion before we engage with this, please give your votes <sandro> +1 <wilkie> +1 <eprodrom> +1 <bengo> +1 <rhiaro> +0 <ben_thatmustbeme> +1 (obviously since i proposed it) RESOLUTION: publish current Editor's Draft of JF2 as First Public Working Draft in Note track eprodrom: unless we have anyone else who feels strongly about this... going once, going twice... ... going to mark this resolved [reads resolution] ... so I got 12 minutes after the hour. hopefully you can make it to your closing, ben_thatmustbeme ... thanks sandro: before publishing we need to know what the name is going to be ... we can do that later but it's easier to do it now tantek: does a short name work? sandro: yeah <sandro> tantek: does jf2 work as is? sandro: yeah tantek: so should we say if anybody wants to propose alternatives, they can do so sandro: this is kind of an odd name. it usually stands for something <sandro> json-microformats2 ? eprodrom: it is jf2 because it is mf2 with json right? <tantek> "unify various simplified versions of the Microformats-2 representative JSON format" sandro: I was thinking "json microformats 2" ... that is, if I had never heard of jf2 before eprodrom: once it has a URI it is kind of engraved in stone right? <tantek> ok with that too sandro: yeah, kind of ... not impossible to change later, you can forward the URL KevinMarks: this isn't too bad. we had some other acronyms that were much more adventurous. <tantek> sandro does it help to allow for either? in case w3c management doesn't like our first choice? <eprodrom> PROPOSED: publish JF2 FPWD with short name "jf2" <sandro> +0 seems harmless eprodrom: let me see if I can form a proposal... with what do you call it.. "short name" <KevinMarks> +1 <ben_thatmustbeme> +1 eprodrom: alright that proposal is up <tantek> +1 and also ok with sandro's proposal "json-microformats2" <eprodrom> +1 <wilkie> +1 <aaronpk> +1 <bengo> +1 <cwebber2> +1 eprodrom: alright. unless there are any objections, I will mark this resolved. <KevinMarks> we had proposed JFDI but that was not wholly serious RESOLUTION: publish JF2 FPWD with short name "jf2" eprodrom: [reads proposal] <sandro> ACTION: sandro get domain lead approval for JF2 [recorded in [[1]|]]] <trackbot> Created ACTION-90 - Get domain lead approval for jf2 [on Sandro Hawke - due 2016-06-07]. <KevinMarks> ben_thatmustbeme++ <Loqi> ben_thatmustbeme has 147 karma eprodrom: fantastic. thanks KevinMarks and ben. thanks for your work on the document. looking forward to seeing it live. ... anything else on jf2? ... alright. great. let's move on to next/first item: minutes from last week <eprodrom> <tantek> Approval of Minutes of 05-24-2016 <tantek> yes <tantek> +1 <rhiaro> +1 <eprodrom> PROPOSED: adopt as minutes for 24 May 2016 meeting eprodrom: [reads proposal] <eprodrom> +1 <aaronpk> +1 <tantek> +1 <wilkie> +1 eprodrom: given we have overwhelming support, we'll mark this as resolved RESOLUTION: adopt as minutes for 24 May 2016 meeting eprodrom: we're going through these quickly ... another item on the agenda is next week's f2f ... I don't think there is further discussion to have about the f2f. but this is a good time to bring those up tantek: we are starting to put together the specific agenda for the f2f ... one thing sandro and I noticed to cover is implementation updates and so we put that first for monday morning ... for the most mature/advanced specs going toward the newer/less-implemented latter in the process ... chairs are actively putting the agenda together <tantek> tantek: if anybody has things they want to discuss, add them <tantek> next Monday eprodrom: all right. great. any other issues we need to discuss for next tuesday ... thank you... next monday. <tantek> we are expecting possibly 2-3 more attendees eprodrom: I think our attendee list is stable. if you are on the fence or considering, get your name on there because we are planning. ... if there is no other discussion on this, I'd like to move on to as2 <tantek> Activity Streams 2.0 <eprodrom> eprodrom: two weeks ago we decided to publish new working drafts of AS2 <tantek> (and last week we agreed also) <eprodrom> eprodrom: we have the core document (i've dropped the URL) and a vocabulary document ... and they are up on the IRC channel ... these are not materially different from the version we've had as an editor's draft for the past weeks ... there were validation issues and small changes but nothing noticeable by anybody not a as2 validator <tantek> (only editorial markup changes) eprodrom: it has been reasonably stable ... yes, editorial markup changes, thank you tantek ... the question from last week was whether to move as2 to a candidate recommendation ... in march in the last f2f we resolved to take it to CR following correction of some outstanding issues, which have been addressed along with additional ones since the f2f ... the intention was to discuss taking it to CR today <tantek> only one open isuse: <Zakim> sandro, you wanted to discuss normative references <tantek> sandro: one small problem that is trivial to fix is when you go to CR you have to fix up the normative references <tantek> (editorial non-blocking) sandro: we saw this with webmention ... basically w3c wants to make sure external specs are as stable as this spec ... when I looked at the normative references... all the ones in vocab are fine, but core had 2 normative references that looked problematic <sandro> sandro: but I think they are easy to solve ... all are w3c or ietf standards except for as1 and CURIE <tantek> can we drop CURIE? <tantek> that seems confusing to have it referenced separately than JSON-LD sandro: but where as1 and curie are used are in non-normative references or, for CURIE, to note json-ld supports them ... I think we can just take out the CURIE reference <tantek> as1 as informative makes sense <sandro> +1 tantek, take out "(or CURIE's for short) [curie]." eprodrom: as what we can do is make as1 an informative reference, which I think I can do ... and the second is to remove reference to CURIE sandro: yep <tantek> good catches sandro eprodrom: it is mentioned as an aside, so we just remove the aside and the reference to it sandro: yeah eprodrom: great ... so those are two important issues to handle right now ... my question is if we decide to go to CR today can we do so conditionally that we resolve these two <eprodrom> sandro: we can go to CR given we do the changes decided at this meeting ... maybe there will be other issues today <eprodrom> eprodrom: absolutely ... just dropping the issue links into the channel ... there was one more issue that rhiaro raised a few days ago <eprodrom> eprodrom: I think it was about JSON-LD... well, rhiaro, if you are here, can you give us an overview? rhiaro: the json-ld version on w3c is not up-to-date. we can easily fix that. eprodrom: it is just an update process, but we should probably get that done. ... sandro, can you follow through on that? sandro: I can definitely do that eprodrom: sounds good ... let me know if there is anything I can do for that process ... that file has been updated so it is best to use the one on github right now ... I feel funny being both chair and advocate for this, but hopefully we can handle that. ... if tantek wants to chair for this we can do that <tantek> chair: tantek tantek: I think you are doing great but I can do that if you want annbass: eprodrom, I sent you in snail-mail some english type edits. did you receive that? ... I didn't have a chance to read through this version. ... I'm just looking at misspellings and words being left out, etc. eprodrom: I did receive those. sorry I didn't mention those. they were all editorial changes... super helpful. ... some have been changed already, some have not. I want to get the ones that haven't into github issues. annbass: I leave this to your judgment. I want to know if we need to do a re-read. any before CR? sandro: no. editorial changes don't need that. annbass: ok. I'll make an effort to go through this version. eprodrom: fantastic. ... so, if there is no further discussion, I would love to propose the current working draft as CR. I forget the exact phrasing for the options we have. tantek: so, we are proposing to take the current working draft with the edits agreed in this meeting to CR. <tantek> PROPOSED: Take current WD of AS2, with edits agreed in this telcon to CR tantek: and those edits include the normative references: one being made informal and one being dropped. <cwebber2> +1 eprodrom: yes <annbass> +1 <tantek> PROPOSED: Take current WDs of AS2, with edits agreed in this telcon to CR <cwebber2> +1 <wilkie> +1 <KevinMarks> +1 <rhiaro> +1 annbass: it is both documents, right? tantek: correct <sandro> +1 both core and vocab tantek: that's why I wanted to update that proposal <bengo> +1 <cwebber2> my second +1 was to updated proposal, not stuffing ballots ;) <annbass> haha <aaronpk> +1 tantek: looks we have the vast majority of people in the call which is awesome <annbass> +1 and +1 RESOLUTION: Take current WDs of AS2, with edits agreed in this telcon to CR <annbass> whoeee <eprodrom> +1 tantek: I'm going to mark this resolved. thank you every one. congratulations to the editors. sandro: we need to draft a transition request tantek: right, like we did for webmention and make that call ... I think that means, eprodrom, you can make those changes to the draft. ... I don't think we need to republish with that sandro: did you publish those changes eprodrom: I did, they are live ... unfortunately I have one more thing we need to discuss before we do that ... at our last meeting, there was discussion about moving our github repos to the w3c organizational namespace ... I'm not sure where we closed on that ... as we move to CR, does that become more important? ... just because the github repos are embedded in the document ... if we were to do that, we should do that now before publishing a new WD sandro: so. w3c has an organizational committment to preservation of info and data. ... most w3c working groups use repos under the w3c organization and the team has set up an archiving system to archive those repos. ... during the webmention transition call it was brought up that we aren't doing that for this group's work ... I made an action item to look in if we can do that and the team said 'no, if you want to archive that you should move' ... as a decentralization guy I'm inclined to say 'no!' ... there are options but I haven't looked at them much ... one of the tools I found written in a language that scares me and it puts the issues inside the repo which seems elegant ... basically if one person wants to figure this out and run this either on a w3c machine or your own that you can curl when you need ... anybody want to help me with that? eprodrom: tantek, you are still chairing? tantek: yeah eprodrom: ok great. I appreciate the concept of decentralization. keeping us decentralized on the same centralized code-hosting service, I'm not committed to it. ... unless jasnell has a strong objection, I'd prefer to use the w3c namespace. ... github has some mechanisms for redirects when you reassign the owner of a repository ... I believe it will retain the issue history, etc. they do a pretty good job of it. ... I'm not proposed to it for as2 sandro: that's true. the movement from one editor to another editor highlights why you may want to do that ... I don't think we should twist aaronpk's arm to do the same thing tantek: eprodrom, it sounds like you have a specific proposal to make eprodrom: yes, I propose we move the official repo for as2 to the w3c [github] namespace <eprodrom> <eprodrom> tantek: can you give me a url for the proposal <sandro> sandro: one slight glitch on that is that I see this already exists <rhiaro> Don't we need to go to /swwg/activitystreams? sandro: seems like harry made this a year ago <rhiaro> the other WGs have all their drafts in one sub directory I think sandro: it might be hard, but maybe we can just delete the existing one and then make a new one aaronpk: yeah, you just need to delete the old one first sandro: ok, yeah ... oh, rhiaro is saying it goes under the workgroup name? tantek: sounds like rhiaro has a counter-proposal. can we get that in IRC <rhiaro> Yeah I agree with the things that are a bad idea about that <rhiaro> Just saying aaronpk: that sounds like a bad idea because it seems issues get merged into a single repo sandro: no, we definitely want separate repos per spec aaronpk: I see a bunch of seperate specs <rhiaro> I was thinking of sandro: I see some repos for groups and some for specs and I think repos for working groups is a bad idea and they didn't realize it at the time tantek: looks like annotations did exactly what you say is a bad idea sandro: no, yeah. and I see people talking about this and they have to tag issues.. yeah tantek: it's a pain sandro: I think using short-names, and yeah for activity streams we merge two into one, but we can do that tantek: do we use one URL for both of them... is it activitystreams or activitysteams dash vocab? eprodrom: I can live with either. let's keep it under activitystreams then tantek: one repo then? eprodrom: yeah one repo <aaronpk> tantek: activitystreams slash vocab?? sorry, I'm looking for specifics for the minutes <sandro> rename to <aaronpk> then merge activity-streams-vocab into there? sandro: so I'm renaming the old repo to the new repo, right? eprodrom: and the directory structure would stay the same <eprodrom> activitystreams-core -> core <eprodrom> activitystreams-vocabulary -> vocabulary <aaronpk> it looks like both specs are already in the same repo? eprodrom: yeah, they are both already in one repo right now aaronpk: we are just renaming one repo then? eprodrom: yeah <tantek> PROPOSED: move AS2 WDs repo into the w3c namespace, to with the directories activitystreams-core renamed to core and activitystreams-vocabulary to vocabulary <cwebber2> +1 tantek: eprodrom, does that match your understanding? eprodrom: perfect and very specific <rhiaro> +1 <wilkie> +1 <sandro> +1 <eprodrom> +1 <annbass> +1 <bengo> +1 RESOLUTION: move AS2 WDs repo into the w3c namespace, to with the directories activitystreams-core renamed to core and activitystreams-vocabulary to vocabulary tantek: that looks good. I'm going to resolve that. ... is that all, eprodrom? eprodrom: we will need a proposal to publish a WD with those changes tantek: from the new repo? eprodrom: exactly annbass: small question for eprodrom... from the version I printed that was 40 pages... were there any significant changes to that? eprodrom: no there were not <annbass> May 17 version to May 31 sandro: I'm going to delete the repo harry made ... should I talk to jasnell about the changes or what? eprodrom: I'll talk to him <tantek> PROPOSED: Publish updated AS2 WDs with the edits agreed in this telcon from its new repo <eprodrom> +1 <rhiaro> +1 <aaronpk> +1 <bengo> +1 <sandro> +1 tantek: ok. the proposal is to publish a new WD with the changes to the repo. when combined with earlier proposal, it is clear this is still what will become the CR. <annbass> +1 <wilkie> +1 <cwebber2> +1 <sandro> github says: Your repository "w3c/activitystreams" was successfully deleted. RESOLUTION: Publish updated AS2 WDs with the edits agreed in this telcon from its new repo <aaronpk> only an owner of the w3c org will be able to move the repo to it, so you'll probably have to give sandro full permissions on james' repo tantek: I think you have everything you need from the group <eprodrom> chair: eprodrom tantek: with the edits and changes, you will have the working draft the group wants to put to CR eprodrom: I will take over as chair to get through the rest of the agenda ... we have 2 items and I'm concerned that we don't have enough time ... I would like to ask the 2 editors involved to ask if it would make sense to put these on the agenda of the f2f <tantek> +1 to extend <sandro> +1 to extend eprodrom: or we could extend the meeting 15 minutes to address them <tantek> (or see how quickly they can go) eprodrom: so aaronpk and rhiaro? <annbass> +1 to extend aaronpk: I have a short update but I'm ok to extend rhiaro: I would like to extend eprodrom: barring any objections, I'm going to extend the meeting 15 minutes. continuing until 2:15 ... since aaronpk is giving only an update I'll put you at the end of the agenda ... so, rhiaro. next up is Social Web Protocols. Could you give us an update? Social Web Protocols rhiaro: I rewrote the document. I would like to publish a new working draft. I closed many issues and I was hoping to address the rest. ... annbass gave great editorial changes. I think everybody read it and had time to raise issues. <tantek> I only skimmed it - seems like a big update eprodrom: I have not had a chance to read through it fully but have skimmed it and it seems like an improvement in terms of readability. ... from my point of view, it seems like there is a strong argument to going to a next working draft unless significant problems with this version. <aaronpk> it looks like a big update, i haven't read the whole thing, but I trust amy's judgment on it eprodrom: another option is to make it required reading for the f2f and propose at the f2f ... I think it is a significant enough improvement to share this with the world as a WD <tantek> I think publishing is also a good way to get more people in the group read it for the f2f :) sandro: is there anything in this draft you feel would give people the wrong impression? rhiaro: there are a few gaps but I have called them out and I think they're fine tantek: a lot has changed since we published a draft of this. I feel there is more confusion leaving the old one there. rhiaro: exactly eprodrom: my question, is there any work that needs to be done before pushing this to working draft? ... so it is ready, this version, for a WD? rhiaro: yes eprodrom: what I would like to do propose we publish the editor's draft of 31 May 2016 of Social Web Protocols as a Working Draft? ... this is the 2nd WD? rhiaro: yeah <rhiaro> <eprodrom> PROPOSAL: publish Editor's Draft 31 May 2016 of Social Web Protocols as a Working Draft eprodrom: good <tantek> +1 <wilkie> +1 <aaronpk> +1 <KevinMarks> +1 eprodrom: is that right, rhiaro? <eprodrom> +1 rhiaro: yep sounds good <rhiaro> +1 <sandro> +1 <annbass> +1 <cwebber2> +1 RESOLUTION: publish Editor's Draft 31 May 2016 of Social Web Protocols as a Working Draft eprodrom: unless there are any objections, I'll mark this as resolved ... [reads proposal] <annbass> BTW, I thought this doc was really good, and will be really helpful as a partner to the other documents eprodrom: thank you rhiaro for all the hard work. looks like a lot of effort went into it and I appreciate it. ... that went a lot quicker than I thought which is good news. I'd like to move on to webmention test suite. Webmention Test Suite aaronpk: what I did was go through the implementation checklist into todo items for code to write for each ... those are all open issues on the test suite itself ... this process turned up editorial issues in the spec which are issues opened on the spec itself ... I would appreciate anyone to chime in about those issues ... on webmention.rocks right now there are two tests receiving webmentions so you can try those out ... it will actually post comments on your site eprodrom: great ... any additional comments on webmention test suite? tantek: this isn't about the test suite it is about the f2f eprodrom: oh cool. there is one more item on the agenda and that is document status Document Status eprodrom: I want to touch base with cwebber2 and rhiaro about document status ... I want to ask the editors of documents we haven't addressed already the meeting for a status update ... this is an excellent time to do new versions before the f2f ... cwebber2, update? <tantek> rhiaro, I'm going to make an executive action, could you add a "Required Reading" to the similar to previous f2f Required Reading section? <rhiaro> tantek: sure cwebber2: I just finished moving and I have not had time. and tsyesika has just started moving. so no updates. eprodrom: good to know ... aaronpk, any other updates on micropub? <annbass> it's a moving plague! cwebber, tsyesika and ben_thatmustbeme ... sheesh <KevinMarks> writing specs and moving house is a theme <tantek> rhiaro, feel free to add latest editor's drafts of Webmention, AS2, Micropub, Activitypub to that list aaronpk: I don't think anything has changed since last call. I was working on webmention stuff. eprodrom: tantek, has there been any activity on post-type-discovery tantek: yes, I got help from ben roberts on doing a github version of the spec and want to have a version of that for FPWD for the f2f eprodrom: do you think there will be a version before the f2f to make it required reading <tantek> tantek: what I can do is to point you to the wiki. I don't think there will be any non-editorial changes. <cwebber2> I have to go <cwebber2> later, everyone <tantek> <eprodrom> Thanks cwebber2 tantek: in particular the only piece that will be important to discuss is the algorithm so I'll point directly to that eprodrom: I'm going to add this as required reading for the f2f next week ... rhiaro, you took yourself off the queue, but I would like to add the latest version of Social Web Protocols to required reading too <rhiaro> yeah I'll do it tantek: I asked rhiaro to go ahead and make that section <eprodrom> Thanks! eprodrom: thank you! one less task for me! ... if there is nothing else, then I would like to call on tantek. <tantek> tantek: the last point is for the f2f, many will be here earlier. I want to encourage you all to add arrival dates. ... there will be opportunities to meet up before the meeting eprodrom: any other business before the end of the meeting? <tantek> thanks for chairing eprodrom <tantek> wilkie++ for minuting! <Loqi> wilkie has 31 karma eprodrom: if not, I'd like to say thanks everyone for giving more of your time. I think we used it well. I'd like to call the meeting to a close. thanks everyone. <eprodrom> wilkie++ <Loqi> wilkie has 32 karma <annbass> thanks eprodrom and wilkie! eprodrom++ <Loqi> eprodrom has 33 karma <tantek> trackbot, end meeting Summary of Action Items [NEW] ACTION: sandro get domain lead approval for JF2 [recorded in] Summary of Resolutions - publish current Editor's Draft of JF2 as First Public Working Draft in Note track - publish JF2 FPWD with short name "jf2" - adopt as minutes for 24 May 2016 meeting - Take current WDs of AS2, with edits agreed in this telcon to CR - move AS2 WDs repo into the w3c namespace, to with the directories activitystreams-core renamed to core and activitystreams-vocabulary to vocabulary - Publish updated AS2 WDs with the edits agreed in this telcon from its new repo - publish Editor's Draft 31 May 2016 of Social Web Protocols as a Working Draft
https://www.w3.org/wiki/Socialwg/2016-05-31-minutes
CC-MAIN-2019-04
refinedweb
4,460
69.41
import "github.com/cmcoffee/go-logger" logfile.go logger.go syslog.go Enables or Disables Debug Logging Enables or Disables Trace Logging Close connection to remote syslog. Log as Debug. Log as Error. Log as Fatal, then quit. Opens a new log file for writing, max_size_mb is threshold for rotation in megabytes, max_rotation is number of previous logs to hold on to. Log as Info. Log as Notice. Sets channel for notifying when logger.Fatal is used. Change flag settings for logger(s). Change output for logger(s). Opens connection to remote syslog, tag specifies application name that will be prefixed to syslog entry. ex: logger.RemoteSyslog("udp", "192.168.0.4:514", "application_name") (+build !windows,!nacl,!plan9) Log as Trace. Log as Warn. Package logger imports 11 packages (graph) and is imported by 1 packages. Updated 2018-03-07. Refresh now. Tools for package owners.
https://godoc.org/github.com/cmcoffee/go-logger
CC-MAIN-2018-26
refinedweb
146
55.5
28 April 2008 23:50 [Source: ICIS news] WASHINGTON (?xml:namespace> ?xml:namespace> Arguing that ethanol-driven increased demand for corn is causing “skyrocketing” prices for both human foods and livestock feed, Perry, also a Republican, has filed a formal request with the US Environmental Protection Agency (EPA) to reduce the newly enacted renewable fuel standard (RFS) by 50% across the country. Perry’s spokeswoman, Allison Castle, said the governor also has sent letters to an unspecified number of other governors, urging them to make similar appeals to the agency. Hutchison is circulating a letter among her Senate colleagues to urge EPA to provide guidelines for state waiver requests, and her spokesman said that 20 other members of the 100-seat Senate have already signed on to the appeal. In addition, Hutchison spokesman Matt Mackowiak said the The Energy Independence and Security Act (EISA), passed by Congress and signed into law by President George Bush late last year, mandates US renewable fuel production and consumption of 36bn gal/year by 2022, including some 15bn gal/year of corn-based ethanol. Current In his request for a cutback in the renewable fuel standard, Perry said that corn prices have increased 138% and general food prices are up 83% in the last three years globally, at least in part due to ethanol-driven demand for corn. “With implementation of the new RFS mandate [the 36bn gal/year requirement], some estimates predict corn prices will rise to $8/bushel for the 2008 crop,” Perry said. “The artificial demand for grain-derived ethanol is devastating the livestock industry in The EISA statute provides that EPA may waive the renewable fuels mandate if it is determined that the biofuels requirement is causing significant harm to a state or region. Legislation that Hutchison is to introduce later this week will freeze the new ethanol mandate at its targeted 2008 level of 9bn gal/year, Mackowiak said. Such a move essentially would end the renewable fuels mandate. Given the popularity of corn ethanol in Congress, Hutchison’s bill would be a tough sell, especially in this election year. However, the new ethanol mandate has already raised concerns in Congress that the targeted goal is too
http://www.icis.com/Articles/2008/04/28/9119471/texas-governor-senator-challenge-ethanol-rule.html
CC-MAIN-2015-14
refinedweb
368
50.09
Some prediction problems require predicting both numeric values and a class label for the same input. A simple approach is to develop both regression and classification predictive models on the same data and use the models sequentially. An alternative and often more effective approach is to develop a single neural network model that can predict both a numeric and class label value from the same input. This is called a multi-output model and can be relatively easy to develop and evaluate using modern deep learning libraries such as Keras and TensorFlow. In this tutorial, you will discover how to develop a neural network for combined regression and classification predictions. After completing this tutorial, you will know: - Some prediction problems require predicting both numeric and class label values for each input example. - How to develop separate regression and classification models for problems that require multiple outputs. - How to develop and evaluate a neural network model capable of making simultaneous regression and classification predictions. Let’s get started. Develop Neural Network for Combined Classification and Regression Photo by Sang Trinh, some rights reserved. Tutorial Overview This tutorial is divided into three parts; they are: - Single Model for Regression and Classification - Separate Regression and Classification Models - Abalone Dataset - Regression Model - Classification Model - Combined Regression and Classification Models Single Model for Regression and Classification It is common to develop a deep learning neural network model for a regression or classification problem, but on some predictive modeling tasks, we may want to develop a single model that can make both regression and classification predictions. Regression refers to predictive modeling problems that involve predicting a numeric value given an input. Classification refers to predictive modeling problems that involve predicting a class label or probability of class labels for a given input. For more on the difference between classification and regression, see the tutorial: There may be some problems where we want to predict both a numerical value and a classification value. One approach to solving this problem is to develop a separate model for each prediction that is required. The problem with this approach is that the predictions made by the separate models may diverge. An alternate approach that can be used when using neural network models is to develop a single model capable of making separate predictions for a numeric and class output for the same input. This is called a multi-output neural network model. The benefit of this type of model is that we have a single model to develop and maintain instead of two models and that training and updating the model on both output types at the same time may offer more consistency in the predictions between the two output types. We will develop a multi-output neural network model capable of making regression and classification predictions at the same time. First, let’s select a dataset where this requirement makes sense and start by developing separate models for both regression and classification predictions. Separate Regression and Classification Models In this section, we will start by selecting a real dataset where we may want regression and classification predictions at the same time, then develop separate models for each type of prediction. Abalone Dataset We will use the “abalone” dataset. Determining the age of an abalone is a time-consuming task and it is desirable to determine the age from physical details alone. This is a dataset that describes the physical details of abalone and requires predicting the number of rings of the abalone, which is a proxy for the age of the creature. You can learn more about the dataset from here: The “age” can be predicted as both a numerical value (in years) or a class label (ordinal year as a class). No need to download the dataset as we will download it automatically as part of the worked examples. The dataset provides an example of a dataset where we may want both a numerical and classification of an input. First, let’s develop an example to download and summarize the dataset. Running the example first downloads and summarizes the shape of the dataset. We can see that there are 4,177 examples (rows) that we can use to train and evaluate a model and 9 features (columns) including the target variable. We can see that all input variables are numeric except the first, which is a string value. To keep data preparation simple, we will drop the first column from our models and focus on modeling the numeric input values. We can use the data as the basis for developing separate regression and classification Multilayer Perceptron (MLP) neural network models. Note: we are not trying to develop an optimal model for this dataset; instead we are demonstrating a specific technique: developing a model that can make both regression and classification predictions. Regression Model In this section, we will develop a regression MLP model for the abalone dataset. First, we must separate the columns into input and output elements and drop the first column that contains string values. We will also force all loaded columns to have a float type (expected by neural network models) and record the number of input features, which will need to be known by the model later. Next, we can split the dataset into a train and test dataset. We will use a 67% random sample to train the model and the remaining 33% to evaluate the model. We can then define an MLP neural network model. The model will have two hidden layers, the first with 20 nodes and the second with 10 nodes, both using ReLU activation and “he normal” weight initialization (a good practice). The number of layers and nodes were chosen arbitrarily. The output layer will have a single node for predicting a numeric value and a linear activation function. The model will be trained to minimize the mean squared error (MSE) loss function using the effective Adam version of stochastic gradient descent. We will train the model for 150 epochs with a mini-batch size of 32 samples, again chosen arbitrarily. Finally, after the model is trained, we will evaluate it on the holdout test dataset and report the mean absolute error (MAE). Tying this all together, the complete example of an MLP neural network for the abalone dataset framed as a regression error of about 1.5 (rings). So far so good. Next, let’s look at developing a similar model for classification. Classification Model The abalone dataset can be framed as a classification problem where each “ring” integer is taken as a separate class label. The example and model are much the same as the above example for regression, with a few important changes. This requires first assigning a separate integer for each “ring” value, starting at 0 and ending at the total number of “classes” minus one. This can be achieved using the LabelEncoder. We can also record the total number of classes as the total number of unique encoded class values, which will be needed by the model later. After splitting the data into train and test sets as before, we can define the model and change the number of outputs from the model to equal the number of classes and use the softmax activation function, common for multi-class classification. Given we have encoded class labels as integer values, we can fit the model by minimizing the sparse categorical cross-entropy loss function, appropriate for multi-class classification tasks with integer encoded class labels. After the model is fit on the training dataset as before, we can evaluate the performance of the model by calculating the classification accuracy on the hold-out test set. Tying this all together, the complete example of an MLP neural network for the abalone dataset framed as a classification accuracy of about 27%. So far so good. Next, let’s look at developing a combined model capable of both regression and classification predictions. Combined Regression and Classification Models In this section, we can develop a single MLP neural network model that can make both regression and classification predictions for a single input. This is called a multi-output model and can be developed using the functional Keras API. For more on this functional API, which can be tricky for beginners, see the tutorials: - TensorFlow 2 Tutorial: Get Started in Deep Learning With tf.keras - How to Use the Keras Functional API for Deep Learning First, the dataset must be prepared. We can prepare the dataset as we did before for classification, although we should save the encoded target variable with a separate name to differentiate it from the raw target variable values. We can then split the input, raw output, and encoded output variables into train and test sets. Next, we can define the model using the functional API. The model takes the same number of inputs as before with the standalone models and uses two hidden layers configured in the same way. We can then define two separate output layers that connect to the second hidden layer of the model. The first is a regression output layer that has a single node and a linear activation function. The second is a classification output layer that has one node for each class being predicted and uses a softmax activation function. We can then define the model with a single input layer and two output layers. Given the two output layers, we can compile the model with two loss functions, mean squared error loss for the first (regression) output layer and sparse categorical cross-entropy for the second (classification) output layer. We can also create a plot of the model for reference. This requires that pydot and pygraphviz are installed. If this is a problem, you can comment out this line and the import statement for the plot_model() function. Each time the model makes a prediction, it will predict two values. Similarly, when training the model, it will need one target variable per sample for each output. As such, we can train the model, carefully providing both the regression target and classification target data to each output of the model. The fit model can then make a regression and classification prediction for each example in the hold-out test set. The first array can be used to evaluate the regression predictions via mean absolute error. The second array can be used to evaluate the classification predictions via classification accuracy. And that’s it. Tying this together, the complete example of training and evaluating a multi-output model for combiner regression and classification predictions on the abalone dataset. A plot of the multi-output model is created, clearly showing the regression (left) and classification (right) output layers connected to the second hidden layer of the model. Plot of the Multi-Output Model for Combine Regression and Classification Predictions In this case, we can see that the model achieved both a reasonable error of about 1.495 (rings) and a similar accuracy as before of about 25.6%. Further Reading This section provides more resources on the topic if you are looking to go deeper. Tutorials - Difference Between Classification and Regression in Machine Learning - TensorFlow 2 Tutorial: Get Started in Deep Learning With tf.keras - Best Results for Standard Machine Learning Datasets - How to Use the Keras Functional API for Deep Learning Summary In this tutorial, you discovered how to develop a neural network for combined regression and classification predictions. Specifically, you learned: - Some prediction problems require predicting both numeric and class label values for each input example. - How to develop separate regression and classification models for problems that require multiple outputs. - How to develop and evaluate a neural network model capable of making simultaneous regression and classification predictions. Do you have any questions? Ask your questions in the comments below and I will do my best to answer. Hi, Are there examples from healthcare where neural networks can solve the problem of both regression and classification? Sure. You can search scholar.google.com hi jason can you explain one example of classification model with microarray gene expression dataset Thanks for the suggestion. Hi Jason, this model can be performed on data with multi-outputs? Thanks Perhaps this would be a more appropriate model: Thanks, I will check. You’re welcome. Hi Jason, Would it be possible to use the Sequential method for the “Combined Regression and Classification Models” ? (Like in the Regression and Classification Model examples). y_values could be a numpy array array([y, y_class ]) The unit of last Dense layer would be equal to 2. But in that case, what would be the activation of this last layer ? And what would be the loss attribute in the compile function ? Thank you very much I don’t see why not. You may have to make large changes to the model. Hi Jason, Very interesting tutorial !. Specially to get familiar with API Model Keras. Thank you. Anyway, I think both problems are better analyzed in a separate way. I share my code experiment. – It was simply to use the own model.evaluate () method to get out the metrics. “mae” for regression part of the full model and ‘accuracy’ for the classification part. Previously I have to add, at the compilation model method, the ‘metrics’ argument equal to [‘mae’, ‘accuracy´]. The only confusing thing is when you get the output of model.evaluate() you have all cross combinations for ‘mae’ and ‘accuracy’, even for the opposite layer of classifier and regressor. So I decided to put names on the outputs layers (at model creation) to get a better identification of the right ones! Thanks. Hmmm, perhaps evaluate() is not a good tool for such a complex model. I think the code needs a little revision: 1) The name should be dataframeinstead of dataset 2) We should use ilocto access the dataframein index format >>> X, y = dataframe.iloc[:, 1:-1], dataframe.iloc[:, -1] >>> X, y = X.astype(‘float’), y.astype(‘float’) >>> n_features = X.shape[1] I prefer to work with numpy arrays directly. Hello Jason, Your blogs are great. This is what exactly I was looking for. This works great but I need a slight modification can you please suggest me the best solution. I have a classification and regression problem for the image dataset. My regression is dependent on the classification, i.e. for example: If Class=1, then Regression prediction should be = 0. How will I force my ML model to predict zero when Class=1 without building different classification model. Thank you so much. Thanks! Perhaps you can chain the models sequentially, perhaps manually. Thanks Jason, Is it possible to train both models together if it is sequentially chained? Hi Jason, I have a scenario where i need to forecast a single sequence of time series values first based on the last 10 sequences and based on the forecasted value sequence i need to check under which class label that single sequence falls out of 7 classes. Thanks I recommend testing a suite of models in order to discover what works well or best for your dataset. Can you please provide me an example or a brief explanation on what you meant by suit of models ? Thanks Sorry, I mean many different model types or configurations. Thanks got it 😉 Hi Jason, Thank you for the insightful article on combined regression and classification neural network model. I had few queries from my side concerning the model. 1. Does the model capture the dependency between the two output variables or do we assume they are independent of each other? 2. In the given example, it seems that the same output variable is being classified and same output variable is used for regression. Can we use two different output variables, one for regression and other for classification and run the model ? The model should not assume (1) but it will learn it. Remember, the network model is non-linear. The dependency in that case is not as trivial as linear dependency. For (2), I don’t see that is the same. Note that there are y and y_class, which the latter is a transformed result of the former. Hi Adrian, Thank you for your response. In the model I am working on, I have 2 different variables dependent on each other and are outputs. One variable is numeric and other variable is categorical. The rest of the variables are inputs. I tried running the combined model and found that the regression aspect of the model was working well returning almost the same outputs as compared to a neural network model that does only regression (The second categorical output variable that I mentioned earlier was input to this model). However, when it comes to classification, I am getting very low numbers (of the order 10^-5) instead of class labels(6 classes). Any insights from your side would help. Otherwise, can we connect on LinkedIn or email? When I tried to run the code given on this page as it is, the regression part is giving good predictions. But the classification part is giving predictions of the order of 10^-5 or even lower. The loss function values for both regression and classification were exactly the same values which are shown in this web page. Is there anything else I need to do for the classification part? It is not my case. You can try add these two lines at the end after you print the accuracy to compare the output side by side: import pandas as pd print(pd.DataFrame({“y”:y_test.ravel(), “yhat”:yhat1.ravel(), “y_cls”: y_test_class.ravel(), “yhat_cls”:yhat2.ravel()})) Thanks for your insights Adrian. The code is working fine now. For general insight, could you elaborate a bit on how the model predicts 2 output variables. Let us say we have inputs x1….x7 & output variables y1 and y2. For predicting y1, does the model take x1…x7 as input or does the model take x1…x7 including y2 as input. Similarly how does it do for y2 ? Can I use this technique to predict on data across multiple quarters (time-series). If yes, in what way can I modify it ? Usually we will not have y1 and y2 in the input, because if you call it the output, that means we should not know it beforehand. But for time-series, you may include the lagged version of y1 and y2. For example, predicting GDP of next quarter, you may use the GDP of this quarter, stock market performance, unemployment rate of today, etc. Hello Jason, thanks for your example. My question is related with the Loss, is there a problem if you are combining differents functions to calculate it? To calculate the weights of the NN, how can be affected if you are ussing different losses at the same time? or simply the NN will adjust the weights onto minimizes the general output error? You can define your own loss function but you use one loss function to train the neural network (or otherwise, gradient descent won’t work). You can make use of a different loss function to keep track on the performance of partially-trained network, e.g., in the validation steps. If you are to train a model, there should only be one loss function for the training. This is the loss that training will try to minimize. For validation, however, you can use many different functions. Thank you for very interesting post. Could you please explain how the dense layer (hidden1 layer) weights are updated in the training phase? Hi Ngoc-Tuan Do…Weights and bias are adjusted during training via backgpropagation utilizing a form of gradient descent for optimization. The following may be of interest to you: In the above example, you can do one regression, one classification, but got multiple outputs in a similar way. (The labels to classify are biased (in many cases), but in the case of multiple outputs, how do you stratified sampling? Hi Jason, I have a question about the classification part – we obtain at the end Accuracy: 0.256. Isn’t it too low and how we can improve it? If I understand this article right it is approach to combine the two models which does not improve the accuracy but rather sparing one pass. Hi Anthony…The tutorial was meant to be an example of how to approach the technique, however the models were not optimized. Hey James! First of all, thank you very much for your work! you have already helped a lot me with all your tutorials. In regard to the two output layers (Regression and Classification) and the keras functional API: can i somehow combine that with the ImageDataGenerator? It seems that iterator_train = datagen.flow( x = x_train, y = [y_train_reg, y_train_class], batch_size=batch_size, seed = datagen_seed ) does not work :/ thanks! Hi Marian…Thank you for the feedback and support! Please clarify or describe how your model “does not work”. This will enable us to better assist you. Sure! So i have build a network with two outputlayers. One outputlayer has 3 Neurons with relu activation and mse as loss for regression and the second outputlayer has 1 Neuron for classificaiton (loss is binary_crossentropy). thats how the end of the network looks like x = keras.layers.Dense(256, activation=”relu”)(x) x = keras.layers.Dropout(0.5)(x) out_reg = keras.layers.Dense(3, activation=last_layer_activation_function_reg)(x) out_clas = keras.layers.Dense(1, activation=last_layer_activation_function_clas)(x) building the model works fine, also training it without the ImageDataGenerator works as well. The Error arises when I try to train the model with a generator with two label vecotors y_train_reg and y_train_clas (ImageDataGenerator from Keras) # image augmentation horizontal_flip = True vertical_flip = True rotation_angle = 5 brightness_range = None zoom_range = [1.0, 1.5] shear_range = 0.2 datagen = ImageDataGenerator( horizontal_flip=horizontal_flip, vertical_flip=vertical_flip, rotation_range=rotation_angle, #brightness_range=brightness_range, zoom_range=zoom_range, shear_range=shear_range ) iterator_train = datagen.flow( x = x_train, y = [y_train_reg, y_train_class], <————————————– HERE batch_size=batch_size, seed = datagen_seed ) Error Message: iterator_train = datagen.flow( File "C:\Users\Anwender\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\preprocessing\image.py", line 884, in flow return NumpyArrayIterator( File "C:\Users\Anwender\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\preprocessing\image.py", line 463, in __init__ super(NumpyArrayIterator, self).__init__( File "C:\Users\Anwender\AppData\Local\Programs\Python\Python38\lib\site-packages\keras_preprocessing\image\numpy_array_iterator.py", line 89, in __init__ (np.asarray(x).shape, np.asarray(y).shape)) File "C:\Users\Anwender\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\core\_asarray.py", line 83, in asarray return array(a, dtype, copy=False, order=order) ValueError: could not broadcast input array from shape (5449,3) into shape (5449)
https://machinelearningmastery.com/neural-network-models-for-combined-classification-and-regression/
CC-MAIN-2022-27
refinedweb
3,778
54.93
Ubuntu Tweak Software to Change Hidden Desktop Settings Generally,). Want to stay up to date with the latest Linux tips, news and announcements? Subscribe to our free e-mail newsletter or full RSS feed to get all updates. You can Email this page to a friend. You may also be interested in... - Ubuntu 6.06 available for download - Ubuntu 6.10 available for download - Howto create ringtones with Linux and open source software - Mega Download of the day: Ubuntu Linux 8.04 CD / ISO Image - Ubuntu Linux Edgy Eft Knot 2 Released Discussion on This Article: We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site! Tags: configuration database, gnome panel, management settings, network icon, panel settings, power management, screen edge, security settings, session control, settings menu, settings screen, splash screen, system security, trash icon, tweaking ubuntu, tweaks for ubuntu, ubuntu, ubuntu 7.04 tweaks, ubuntu desktop tweaks, ubuntu feisty tweaks, ubuntu performance tweaks, ubuntu speed tweaks, ubuntu tweaks ~ Last updated on: January 10, 2008 Hello, And thanks for this. Having a little trouble installing, though. When I ran the ‘Quick Installation’ code at got the following terminal output: mn@ubuntu:~$ cd /tmp; wget _0.2.4-ubuntu2_all.deb –16:36:59– 2_all.deb => `ubuntu-tweak_0.2.4-ubuntu2_all.deb.1′ Resolving ubuntu-tweak.googlecode.com… 72.14.253.82 Connecting to ubuntu-tweak.googlecode.com|72.14.253.82|:80… connected. HTTP request sent, awaiting response… 200 OK Length: 130,088 (127K) [application/x-archive application/x-debian-package] 100%[====================================>] 130,088 48.27K/s 16:37:02 (48.18 KB/s) - `ubuntu-tweak_0.2.4-ubuntu2_all.deb.1′ saved [130088/130 088] mn@ubuntu:/tmp$ sudo dpkg -i ubuntu-tweak_0.2.4-ubuntu2_all.deb Selecting previously deselected package ubuntu-tweak. (Reading database … 114539 files and directories currently installed.) Unpacking ubuntu-tweak (from ubuntu-tweak_0.2.4-ubuntu2_all.deb) … Setting up ubuntu-tweak (0.2.4-ubuntu2) … mn@ubuntu:/tmp$ ubuntu-tweak & [1] 23865 mn@ubuntu:/tmp$ Traceback (most recent call last): File “./ubuntu-tweak.py”, line 8, in ? from Computer import DISTRIB File “/usr/share/ubuntu-tweak/Computer.py”, line 8, in ? from aptsources import distro ImportError: No module named aptsources mn@ubuntu:/tmp$ ~ My mistake, or…? Thanks in Advance, mike This worked for me dh@local:/tmp$ sudo ubuntu-tweak &
http://www.cyberciti.biz/tips/download-ubuntu-tweaking-software.html
crawl-001
refinedweb
398
52.87
I do it like this: /etc/map/adobe/sling:match = http/adobe.example.com/(.+) /etc/map/adobe/sling:internalRedirect = /content/adobe/$1 /etc/map/day/sling:match = http/day.example.com/(.+) /etc/map/day/sling:internalRedirect = /content/day/$1 And, I find all <a href="/content/adobe/foo/bar.html"> and transform it to <a href=""> . And, <a href="/content/day/foo/bar.html"> becomes <a href=""> @Component(immediate = true, label = "canonical url stuff") @Service @Properties({ @Property(name = "pipeline.mode", value = "global"), @Property(name = "service.ranking", intValue = -1) }) public class CanonicalHrefFactory implements TransformerFactory { @Override public Transformer createTransformer() { new CanonicalHref(); } private static class CanonicalHref extends ContentHandlerDelegate { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { final ContentHandler contentHandler = getContentHandler(); final Attributes modified = "a".equalsIgnoreCase(localName) ? DO_THE_HREF_URL_REWRITE_HERE_TO_YOUR_LIKING(attributes) : attributes; contentHandler.startElement(uri, localName, qName, modified); } } } In this method, DO_THE_HREF_URL_REWRITE_HERE_TO_YOUR_LIKING(), I could look into /etc/map and find suitable entry (by looking at sling:internalRedirect property). If the longest match is found, I can parse sling:match of the node to get hostname. But, as you can see, sling:match regex might not contain hostname.. It could be something like http/(adobe|day)\.com/(.+) I don't think org.apache.sling.jcr.resource.internal.JcrResourceResolver.resolve(HttpServletRequest, String) is injective (url a,b,c rewrites to d. inverse of that isn't a function). If there is no instance where siteA links to siteB, you can just implement TransformerFactory and strip out the prefix, /content/<siteName>, from href (as long as you structured your repository consistently). On Tue, Feb 7, 2012 at 7:38 AM, David Gonzalez <davidjgonzalez@gmail.com>wrote: > Sam, doesn't etc/map require a root mapping which can't be a regex > (can't be regex for outgoing mapping atleast)? How would I structure > the etc/map nodes to only match on the resource path? Would I just put > the resource mapping directly under scheme (http) node I lieu of the > root mapping? > > Thanks > > > > On Feb 7, 2012, at 7:18 AM, "sam ”" <skynare@gmail.com> wrote: > > > You can rewrite from http server. > > > > For the urls appearing in html, you can use rewriter: > > > > > > > Or, since your mappings are simple, you can roll out your own utility > that > > walks /etc/map for sling:internalRedirect. And, find the longest matching > > internalRedirect against resourcePath. > > Once found, you can construct url from there. > > > > > > On Mon, Feb 6, 2012 at 10:42 PM, David G. <davidjgonzalez@gmail.com> > wrote: > > > >> Hey, > >> > >> I'm using dispatcher running under httpd as cache. > >> > >> One of the things I am trying to get around is serving pages from the > >> usual /content/<site>/<lang>/page.html structure. > >> > >> I need to validate, but I think I could > >> > >> 1) handle incoming rewrites: mysite.com/page.html > > >> /content/mysite/en/page.html > >> 2) use the JCR Resource Resolver mappings to rewrite all my in-page > links > >> to point at /page.html > >> > >> I haven't looked at the source code to see why sling can't handle > >> bi-directional mapping when using regex (it seems like it should be able > >> to, but I must be missing something). > >> > >> Thanks > >> > >> -- > >> David Gonzalez > >> Sent with Sparrow () > >> > >> > >> On Monday, February 6, 2012 at 12:29 PM, James Stansell wrote: > >> > >>> On Mon, Feb 6, 2012 at 5:26 AM, David Gonzalez < > davidjgonzalez@gmail.com(mailto: > >> davidjgonzalez@gmail.com)>wrote: > >>> > >>>> Does mod-rewrite support rewriting all the links in the documents > >>>> returned in the response? > >>>> > >>> > >>> > >>> Probably not. In fact right now a lot of our links are > >>> /content/<site>/en/page.html and we have rewrite rule which gives a > >>> redirect to /page.html. > >>> > >>> It should be possible to use a sling filter to modify the links when > >>> serving the page but we haven't looked into that yet. > >>> > >>> > >>>> Have you seen perf hits doing this? (I'm assuming every html response > >>>> must be parsed and rewritten.) > >>>> > >>> > >>> > >>> As far as I know our performance concerns are in other areas. Our sling > >> is > >>> actually part of CQ5 so we already were using httpd in order to host > the > >>> dispatcher plugin for caching the pages. Plus we are using mod_rewrite > >> for > >>> rewriting 1000s of legacy URLs so I don't think we ever considered > >> another > >>> option. > >>> > >>> > >>>> Are there any gotchas w mod_rewrite that you've run into rewriting > >>>> incoming and outgoing urls? > >>>> > >>> > >>> > >>> Our biggest problems have been with the legacy URLs. I guess a general > >>> gotcha could be the regexes for the rewrite; not thinking of anything > >> else. > >>> > >>> If we were using plain sling we would probably be caching with > varnish. I > >>> wonder if that has any rewrite support? Are you using a web cache? > >>> > >>> > >> > >> > >> >
http://mail-archives.apache.org/mod_mbox/sling-users/201202.mbox/%3CCACrt3pyvWnDPXt5sXwbdvy1D6HrWM4B6Jzt=8SAU2LSznp48Ug@mail.gmail.com%3E
CC-MAIN-2014-23
refinedweb
768
57.77
Edited to add: I've tracked the below down to occurring only when MS_DGNAPPS = RUNMACRO is set, regardless of whether MS_DGNMACROS is set or not. Another discovery: This actually happens if MS_DGNAPPS variable EXISTS. Even if it's set to nothing. Which I think means I can't actually fix it for anyone else without a complete overwrite of the .ucf file. Is there any way to save an "ActiveWorkspace.RemoveConfigurationVariable" command like there is with an "AddConfigurationVariable"? I thought this was related to a conflict between a local custom menu/toolbox (.dgnlib with .r01), but even after deleting these entirely, removing all user preference files and configuration variables that point to them, and taking the steps in the Wiki entry below to restore Microstation Powerdraft to defaults, the problem persists. (I ran this as admin, but note other users on our site will not be able to do so): This error appears when selecting Tools... Geographic. Menu entry #1 is missing entirely. I am not familiar with the tool that belongs there and do not think we even use it. One user reported that he first saw this after running a macro and following that, when he would attempt to place text it was significantly offset from his cursor, but I have not been able to replicate that. We have several versions of Microstation Powerdraft v8i installed throughout the company, which may or may not have had the menus working correctly - many people had no macros installed or did not know how to use them. I have SS1 Version 08.11.07.172 and SS2 08.11.07.443 installed on Windows 7, and both have this issue. The user who brought it up to me is using SS1 Version 08.11.07.172 on Windows 10. I do not seem to have the menu options shown in the first wiki link above which list the Icon ID. There is no "Application- Tool Reference" menu Is there anything else I can try to resolve this, since it persists even after removing the .DGNLIB and config variables referencing it? I cannot reinstall Powerdraft for all users, but I can push any files or settings which don't require admin access to all users, such as a repaired .dgnlib or user config variables. Scott Clarke said:Is there anything else I can try to resolve this Your screenshot shows a key-in starting with macro. That starts a MicroStation BASIC macro named profilemacro. macro profilemacro A BASIC macro has a .bas extension when editing, and compiles to a .ba file. Does profilemacro.bas or profilemacro.ba exist on your computer or in any folder specified by MS_MACRO? .bas .ba profilemacro.bas profilemacro.ba MS_MACRO? Regards, Jon Summers LA Solutions That macro does exist, and it works. It turns out that even removing the dgnlib entirely and resetting to defaults, then reconfiguring without custom menus did not fix it; PowerDraft breaks when MS_DGNAPPS is set true. My only guess, which is a complete shot in the dark far beyond my level of expertise, is that MS_DGNAPPS may share a namespace with VBA applications and conflict with OnProjectLoad, or some other function/variable I have defined as public. I've solved the problem for now by adding a function in my OnProjectLoad to call the old MS_DGNMACROS. I may actually experiment to see if it hurts anything to just handle the MS_DGNMACROS list directly, because I don't want to remove the ability for users to run macros of their choosing. Scott Clarke said:MS_DGNAPPS may share a namespace with VBA applications MS_DGNAPPS is a configuration variable that specifies one or more MDL apps. to load when you open a DGN file. VBA macros live in one or more folders specified by configuration variable MS_VBASEARCHDIRECTORIES. That's it! It's not clear what you mean by 'share a namespace', but it's easy to find out by performing an MSDEBUG. MS_DGNAPPS MS_VBASEARCHDIRECTORIES Scott Clarke said:That macro [profilemacro] does exist, and it works So you can eliminate that BASIC macro as the source of the error message. What else in your list of BASIC macros or customised workspace has a dialog or toolbox? Once I removed all the customizations by deleting the folder with the .dgnlib, deleting the folder with the .BA macros, removing the .dgnlib from the configuration variables, and all MS_DGNMACROS from the configuration variables, I am fairly sure nothing does have a dialog or toolbox. One of the VBA macros has a form. As far as I know that's working too, because nobody has complained and it's one of the few that are completely necessary for some workflows. Scott Clarke said:One of the VBA macros has a form A VBA UserForm is a Microsoft product and is very different from MicroStation development tool products. There would never be an error message about MGDSHOOK emanating from a VBA macro.
https://communities.bentley.com/products/administration/f/product-administration-forum/172086/v8i-error-unable-to-load-create-dialog-item-of-type-iconcmd-id-29-from-dialog-mgdshook-solutions-in-wiki-do-not-work
CC-MAIN-2019-13
refinedweb
821
63.29
Here is some XSLT scripts for macro-expanding a set of XSD schemas into a single file with references removed, as a more optimal form for schema interrogation and conversion. Converting an XSD schema into Schematron involves three stages: - Preparing the XSD schemas so they are in an optimal form for transforming out from - Converting the grammar and datatype constraints of this prepared schema into Schematron for elements and datatypes - Converting the other constraints such as KEY and ID into Schematron. This blog item gives some beta XSLT code for the first part. A pipeline of three XSLT scripts are used: - INCLUDE: starting from a schema, substitute all the included and imported schemas in-place. (<redefine> is not supported in this version.) - FLATTEN: move schemas for different namespaces to the top-level, removing duplicates. - EXPAND: substitute references to complexType, group, attributeGroup and remove declarations (substitution groups and wildcards are not supported in this version.) The result is a document with a top-level element of <schemas> contain <namespace> elements each containing an XML Schema module for a single namespace. These modules contain element, attribute and simpleType declarations, but structural references have been replaced. This resolved form makes the job of converting to Schematron much easier, because there are fewer cases to consider and simpler paths. And all the schemas are gathered into a single file. I have put the beta XSLT files here. It will go to sourceforge or somewhere eventually: watch this space. But I have been frustrated by the lack of tools that expand out XSD schemas, so this code may be useful for other things (I may rewrite Topologi’s XSD to RELAX NG converter to use this as the front end, for example): I would like to acknowledge JSTOR as the sponsor for this code. Thanks to Matt Stoeffler. It is licensed under GPL as open source. I've written XSLT scripts to do the same thing a couple of times. From a quick look at "include.xslt", it will work if the Schema locations are absolute, but may not if they are relative (especially if the includes have their own relative includes). Whether that is an issue depends on your Schemas. Cheers, Tony.
http://www.oreillynet.com/xml/blog/2007/10/converting_xml_schemas_to_sche_1.html
crawl-002
refinedweb
368
61.56
HTML is a set of tags that tell a Web browser how to display text. Tags mostly come in pairs of opening and closing tags, like <em> and </em>. Any text surrounded by a pair of tags is displayed the way the tags tell your browser to display it. E2's built-in HTML toolbar is designed to insert common tags for you at the press of a button. The basic tags and examples of their effects are shown below. Put emphasis on stuff with <em>stuff</em> (the button is marked i on E2's built-in HTML toolbar because most browsers will display emphasised text in italics) Make stuff strong with <strong>stuff</strong> (the button is marked b on E2's built-in HTML toolbar because most browsers will display strong text in bold) Make stuff small with <small>stuff</small> Make stuff big with <big>stuff</big> <h1>Biggest heading</h1> <h2>Second-biggest heading</h2> <h3>Smaller heading</h3> <ul> <li>makes</li> <li>order</li> <li>difference</li> <li>no</li> </ul> <ol> <li>Order</li> <li>makes</li> <li>a</li> <li>difference.</li> </ol> "The distracting effect of overdependence on adjectives and alliteration is well-illustrated by the following excerpt.. Blah, blah, blah." <blockquote>. </blockquote> Note: Due to a change in HTML code, if you are putting multiple paragraphs in a block quote, you will need the blockquote tag around each paragraph. <hr> Everything2 will automatically insert paragraph tags and line breaks as long as it doesn't find any in a writeup, but it may be useful to be aware of these tags all the same. This is one paragraph And this is another. <p> This is one paragraph</p> <p> And this is another. </p> One paragraph... broken into three lines... is still not a poem. <p> One paragraph... <br> broken into three lines... <br> is still not a poem. </p> Keep in mind that the actual appearance of your text depends on style settings and other factors, so the way others see it may differ from the way you see it. For more advanced HTML features, see N-Wing's extensive guide... 2: Character Formatting 2.1: Bold and Italics and Underline vs. STRONG and EMphasis 2.1.1: Bold / Italic / Underline Creating new lines was easy enough, right? Now to make some text stand out from the rest. The tags used to create bold and italics text is pretty easy to remember. To make something bold, put a <b> tag at the start of the bold text, and </b> at the end of the bold text. To make something italics, put <i> at the start of the italics text, and </i> at the end of the italics text. If you guess you should use <u> before and </u> after what you want to be underlined, you would be correct. For example, <b>This</b> is bold, <i>this</i> is italics, <b><i>this</i></b> is <i><b>both</b></i>. <u>This sentence is underlined.</u> produces This is bold, this is italics, this is both. This sentence is underlined. Note that you can nest tags, and order doesn't matter. Just be sure to not close them in an improper order, like this: <b><i>Never do this!</b></i> The result is undefined, but it usually just looks messed up. If you are really unlucky, it will make all the rest of the page have wrong formatting, too. I highly recommend not underlining text in HTML: people expect underlined text to be a link. <b> </b> <i> </i> <u> </u> <b>This</b> is bold, <i>this</i> is italics, <b><i>this</i></b> is <i><b>both</b></i>. <u>This sentence is underlined.</u> <b><i>Never do this!</b></i> 2.1.2: STRONG / EMphasis The strong and emphasis tags generally display as bold and italics. However, it is recommended to use strong and emphasis instead of bold and italics (an explanation follows, in the next section). To mark something as strong use the <strong> tag before the strong text, and </strong> after it. Most browsers show this as bold. To mark something as having emphasis, put the <em> tag before the emphasized text, and </em> after it. Most browsers show this as italics. For example, <strong>This</strong> is strong and <em>this</em> is emphasized. renders as This is strong and this is emphasized. Again, you can nest tags, order doesn't matter, and be sure they are closed in the correct order. <strong> </strong> <em> </em> <strong>This</strong> is strong and <em>this</em> is emphasized. Note that while it common to denote the source of a quotation (citation), there are special tags for these cases; this is covered in the later section Giving Credit Where Credit is Due. 2.1.3: B/I vs. STRONG/EM Now, you may be wondering why there are 2 tags to do bold, and 2 tags to do italics. The short answer is: there isn't. Oh, you want to know the longer answer, even though I may bore you to death? Yay! First, some background... A physical style tells the browser, "I want the text to look exactly like this". A logical style tells the browser, "this text has a certain significance, but I'll let you decide how it should look". The user is more likely to override the display logical styles. For example, somebody may not like to read a lot of italics text because it can be hard to read a lot of. But if a page uses the italics a lot, that person would be unhappy. However, if the emphasis tag is used, they could set that tag to display as something else for them. They may choose to show it as green on a blue background, and not the italics they dread. For the most part, though, it doesn't matter to much, as: I personally generally use <strong>strong</strong> and <em>em</em> for general emphasis, and the others in special circumstances: (I kind of think of it as like programming analogy: physical styles : magical numbers :: logical styles : constants .) However, most people (i.e., normal people) just use <b> and <i> because they are easier to remember, and require less typing. 2.2: Do you like 'em big or small? Another way to draw attention to things is by changing the font size. Of course, a change in font size can be used for other purposes, too... Help me! I went to a shrink, and I was really shrunk! The <small> and <big> tags are easy to remember. Multiple nestings of the same tag will cause text to get really big, or really small. Here is how to use them by themselves: <small>Small</small> and <big>big</big>. show as: Small and big. Multiple nestings, like: <small><small><small>Very small</small></small></small> and <big><big><big>very big</big></big></big>. will show as: Very small and very big. <small> <big> <small>Small</small> and <big>big</big>. <small><small><small>Very small</small></small></small> and <big><big><big>very big</big></big></big>. One neat thing to do with the smaller and bigger tags is to make "small caps". So to make this official-looking title: EVERYTHING 2 HTML TAGS you would type: <big><big>E</big></big><small>VERYTHING</small><big><big> 2 HTML T</big></big><small>AGS</small> <big><big>E</big></big><small>VERYTHING</small><big><big> 2 HTML T</big></big><small>AGS</small> One last (but rather sad) note: character-cell-based (console-only) browsers, like Lynx or Links, are unable to show different font sizes. This is because they use a monospaced, or monowidth font, so each character takes up the same amount of room. Although the old fossils people who use these browsers are decreasing, just remember a general rule in HTML (that I just made up) - formatting should add to existing text, and should not subtract from the text if absent. 2.3: SUPer VARiable SUBmarine 2.3.1: SUPerscript and SUBscript Imagine a excellent underwater submersible that changes. That is a super variable submarine. * groan * Ok, ok, no more lame puns to introduce some tags... You're really cramping my style.. my cascading style! <rimshot> If you are going to type in mathematical and/or chemical and/or math-related expressions, you should know about the subscript and superscript tags. You could guess what tags you use to show this: I like subscript and superscript. But don't feel bad if you think <sup> should be "super"; it messes up even experienced HTML-writers (like me, waaaahhh). I like <sub>sub</sub>script and <sup>sup</sup>erscript. With these tags, I like to also use the <small> tag, so it looks nicer. (Alternatively, if you are only raising something to the second and third power, you can also use the widely supported ² and ³ for a superscript of 2 and 3, which is shown like this² and this³.) If the use of superscripts and/or subscripts is important to correctly read your writeup, you may want to see Everything number presentation. <sup> I like <sub>sub</sub>script and <sup>sup</sup>erscript. ² ³ 2.3.2: VARiables <var> <var>d</var> = <var>b</var><sup><small>2</small></sup> - 4<var>ac</var> 2.4: Monospaced Text a.k.a. Computers and HTML There are several tags for displaying monospaced, or fixed-width text. (Could it be because HTML was developed for computers, so displaying code, text to key in, display text, etc. would be popular? Nah.) All these tags pretty much all display the same on each browser, so you'll probably end up just picking one or two that you like, and using it/them a lot. 2.4.1: Inline Monospaced Tags Quick diversion: an "inline" tag is an HTML tag that can be used on text that is in part of a line; that is, the text that is formatted via an inline tag can be in with other text that is formatted differently. The 4 tags explained here are all inline, so they can be used almost anywhere you want. The first inline fixed-width tag allowed on here, on E2, was the teletype text tag. This tag is used to indicate teletype text. I would use this tag to show people how to type basic *nix and/or DOS commands: type cd and press the "Enter" key which I would enter as: type <tt>cd</tt> and press the "Enter" key Of course, on Lynx it would look the same, since every character is already the same width, but it would stand out for the majority of people who use graphical browsers. If it is important that it stands out, you might also want to surround the text with strong tags. type <tt>cd</tt> and press the "Enter" key A slightly more relevant tag to use, though, would be the keyboard tag, which indicates text to key in via a keyboard (or punch card if you're on a primitive machine). So the example changes to: type cd and press the "Enter" key which I would now enter as: type <kbd>cd</kbd> and press the "Enter" key type <kbd>cd</kbd> and press the "Enter" key "But what if I was to show the output of the command?" you ask. (Ask it, ... ask it, ... Ask it now! Thank you.) That is what the <samp> tag is for - sample output. After I type in cd and press the "Enter" key (under Unix), I might see: 42 ~ # as my tcsh prompt*, which is simple to write HTML for: <samp>42 ~ # </samp> (* Yes, a root prompt. I'm 1337.) <samp> <samp>42 ~ # </samp> The last inline fixed-space tag (but not least, of course) is <code>. This is used for code examples. In this official E2 HTML guide™©etc., I use this tag in almost every example of what HTML code should be used to create something. However, I'm currently a little sick of HTML, so here is an example from Java: the line macroText.put(MACRO_SOURCE_LINES, Integer.toString(lineCount)); stores the number of lines in the E2 HTML tags source file for later use which I entered as: the line <code>macroText.put(MACRO_SOURCE_LINES, Integer.toString(lineCount));</code> stores the number of lines in the E2 HTML tags source file for later use Note how an end-of-line character is normally converted into a space by your web browser ... <code> macroText.put(MACRO_SOURCE_LINES, Integer.toString(lineCount)); the line <code>macroText.put(MACRO_SOURCE_LINES, Integer.toString(lineCount));</code> stores the number of lines in the E2 HTML tags source file for later use 2.4.2: PRE-formatted text ... although the next tag I'm going to show you will tell the browser to start a new line. If you have large code examples, or what to make some nice (or ugly) ASCII art, it is usually easier to just enter in a straight block of text, instead of using many HTML tags. The pre-formatted tag allows you to do this by surrounding (usually multiple) line[s]s of text with <pre> and </pre>. For example, a short C++ program might be: <pre> </pre> #include <iostream> #define EDB_GONE true void main() { if(EDB_GONE) cout << "Hello, Everythingites!" << endl; else cout << "EDB, please don't eat me!" << endl; } <pre> #include <iostream> #define EDB_GONE true void main() { if(EDB_GONE) cout << "Hello, Everythingites!" << endl; else cout << "EDB, please don't eat me!" << endl; } </pre> < pre 2.5: 'Editing' 2.5.1: INSert and DELete Now, for some rarely, almost never-seen tags. (You can skip right to "STRIKE That", if you want.) You still here? Wow, you're insane. I've never used the insert and delete tags, but I guess you'll find out the hard way how useless they are... <ins> indicates where text has been inserted (usually since a previous draft). <del> indicates where text has been deleted. Here is a sample of an edited document: Yo, idiotHonored sir, I would greatly appreciate it if you do business with me, or you're toast. Netscape 4 does not support these tags, so this is what it looks like in a non-stupid browser (and some stupid ones, too, like IE): Yo, idiotHonored sir, I would greatly appreciate it if you do business with me, or you're toast. Here is the code to generate the first example: <del>Yo, idiot</del><ins>Honored sir</ins>, <ins>I would greatly appreciate it if you</ins> do business with me<del>, or you're toast</del>. <ins> <del> <del>Yo, idiot</del><ins>Honored sir</ins>, <ins>I would greatly appreciate it if you</ins> do business with me<del>, or you're toast</del>. 2.5.2: STRIKE That There is another way to indicate crossed-out text, which is by using one of the strikethrough tags. Both <s> ... </s> and <strike> ... </strike> do the exact same thing. One way to use these tags is to "officially" say one thing, but let the reader know what you are really thinking: You are such a pushover easy-going person. I don't know if I could stand being so spineless flexible. This was typed as: You are such a <s>pushover</s> easy-going person. I don't know if I could stand being so <strike>spineless</strike> flexible. Yes, you could use ^H instead of strikethrough, but morons^H^H^H^H^H less well-educated people could get confused. :) <s> </s> <strike> </strike> ^H … --» … Log in or register to write something here or to contact authors.
http://everything2.com/title/E2+HTML+tags?showwidget=showCs377783
CC-MAIN-2014-10
refinedweb
2,640
73.07
Hey there, last question for a while I swear I've become somewhat familiar with the functions associated under System:: but can't seem to figure out how to use them in a MFC app. Whenever I try to compile get errors that System is not a namespace and mscorlib.dll must be compiled using /clr method. I've added /clr and also tried CL to compile but got errors there too. I've added references to System under COM for my project but it didn't work and don't seem to have the feature for creating managed C++ apps with my program. Does this mean I have to forget everything I know in C++ to learn .NET? All I want to add is this: That's all!That's all!Code:#using <mscorlib.dll> using namespace System; Thanks, Rob Sitter
http://cboard.cprogramming.com/cplusplus-programming/72177-using-mscorlib-system-namespace-mfc.html
CC-MAIN-2014-49
refinedweb
142
72.05
Created on 2013-11-20 01:27 by james, last changed 2019-01-21 14:36 by jdemeyer. Decorator syntax currently allows only a dotted_name after the @. As far as I can tell, this was a gut-feeling decision made by Guido. [1] I spoke with Nick Coghlan at PyTexas about this, and he suggested that if someone did the work, there might be interest in revisiting this restriction. The attached patch allows any testlist to follow the @. The following are now valid: @(lambda x:x) def f(): pass @(spam if p else eggs) def f(): pass @spam().ham().eggs() def f(): pass [1] Thanks for this! Tests should exercise the now-valid syntaxes, which also need documentation. On second thought, as this patch allows one form that Guido doesn’t want (bar().foo()), maybe there should be a discussion on python-ideas. Nice! As a syntax change (albeit a minor one), I believe this will require a PEP for Python 3.5. I know Guido indicated he was OK with relaxing the current restrictions, but I don't remember exactly where he said it, or how far he was willing to relax them. I don't feel very strongly, but I do think that most of the things the new syntax allows are not improvements -- they make the decorator harder to read. It was intentional to force you to compute a variable before you can use it as a decorator, e.g. spamify = (spam if p else eggs) @spamify def f(): pass > they make the decorator harder to read. I agree. I see this as removing a restriction and a special-case from the decorator syntax (noting, of course, that these were introduced deliberately.) In terms of whether the new forms are improvements, my preference is to leave this up to the judgement of the programmer, moderated of course by their prevailing coding guide. I would argue that this change does not force any additional complexity on the programmer (who is free to take or leave it) or on the interpreter (- the straightforwardness of the patch corroborates this.) I would also argue that there are certainly cases where, in the midst of some large codebase, the dotted_name restriction may seem a bit arbitrary. This is likely true for: class Foo: def bar(self, func): return func @staticmethod def baz(func): return func @staticmethod def quux(): def dec(func): return func return dec # invalid @Foo().bar def f(): pass # valid @Foo.baz def f(): pass # valid @Foo.quux() def f(): pass For completeness' sake, I have attached a patch with an additional unit test and amended documentation. Should we proceed with writing a PEP for Python 3.5? Yes, a PEP for 3.5 on this will be valuable, whether it's accepted or not (although I personally favour moving these restrictions out of the compiler and into the PEP 8 style guide). If I recall the past python-ideas threads correctly, the main objections to the current syntax restrictions were: - you can't look up decorators through a registry by default, since "@registry[name]" is disallowed - it's not really a limitation anyway, since a pass through function still lets you write whatever you want: def deco(x): return x @deco(registry[name]) def f(): ... Now that the precedent of keeping decorator expressions simple has been well and truly established, simplification of the grammar is the main reason removing the special casing of decorator syntax from the compilation toolchain appeals to me. I think the complexity delta in the grammar is exactly 0. While I think that the dotted_name restriction should be relaxed and it should instead be a style guide issue, I have to agree with Benjamin here: the difference in grammar complexity is zero and shouldn't drive the decision. Yes, please get rid of this restriction. It's trivial to get around - you don't even need to define your own "pass-through", one already exists in the standard library: >>> @(lambda: [lambda x: x][0])() File "<stdin>", line 1 @(lambda: [lambda x: x][0])() ^ SyntaxError: invalid syntax >>> from functools import partial as _ >>> @_( (lambda: [lambda x: x][0])() ) ... def f(x): return x*x ... >>> f(3) 9 I don't know the rational behind disallowing bar().foo(), but it is the use-case I have in mind - something like: @MainDecoratorFactory(params).tweakedDecorator(tweak_params) def f(x): pass or even @MainDecoratorFactory(params).\ tweakedDecorator(tweak_params) def f(x): pass It should be no more controversial than chaining decorators. The alternative with the current restrictions would be tweakedDecorator(MainDecorator(params), tweak_params) which is more ugly and visually separates the "tweak" concepts. It's not appropriate to merge MainDecoratorFactory and the tweaks together: there are several MainDecoratorFactories taking care of one main concern; they don't care about the tweaks. And vice versa; the tweaks shouldn't care about the main decorators. Nobody has posted a real use case. All the examples are toys. What are the real use cases that are blocked by this? Readability counts! TL;DR - Use case is dynamic decorators. Not all of the syntax would make sense, see below. The main benefit of this feature would be for dynamic decorators (as was evidenced from others in this issue). In a project I contribute to, we use dynamic decorators to set a function as being a command, and we use the object (a wrapper around the function) directly, so we need a bit more boilerplate around the place. Ultimately, we would definitely use such a feature (just the '@spam().eggs()' part; we'd have no use for the other ones) , but we probably won't notice its absence either; we've worked around it for years, after all. As far as readability goes, I think allowing only the '@spam().eggs()' version would actually improve readability quite a bit, by reducing the need to separate the decorator assignment in two (or more) parts. I can see the desire to have a '@spam[eggs]' kind of syntax though, again for the dynamic decorators case. I see no reason to allow creating lambdas or conditional expressions inside decorators expressions. If anything, that'll encourage anti-patterns, whereas e.g. '@spam(value=eggs)' would be more readable, and would let the decorator decide what it wants to do with the value. And if your decorator can be expressed as a lambda, why don't you put that in/below the function? Surely it's less work than writing the lambda everytime ;) Could you link to an example decorator definition and its call site(s) that would benefit? I'm lacking the imagination to understand what a "dynamic decorator" might be. @spam().eggs() is not enough to help me understand -- I understand quite well what syntax people are requesting, but I am unclear on what they actually want to do with it. I worry there's some extreme use of higher-order functions here that would just get in the way of readability, but a real-world example might dispell my fear. (That's what I meant when I said "use case".) Sure, here goes; this is an IRC game bot which I contribute to. Apologies for the long links, it's the only way to make sure this consistently points to the same place regardless of future commits. The 'cmd' decorator we use is defined at - we use its __call__ method to add the function to it; see next link. How it's used: - ideally, a syntax such as the following would be nice for these definitions: @cmd("myrole", <keyword arguments here>).set def myrole(cli, nick, chan, rest): # ... do stuff here ... Historically (we used an arcane closure-based version that no one understood), we could call that function after directly, like any normal function. Now, though, we have to call it like this: I'd like to state again that, while we'd use this new syntax, we've already worked around this lack of syntax. Whatever comes out of this, we won't be negatively affected, but decorators are meant to bring whatever alters the function right where it starts, so having syntax that eases that would make sense (to me, anyway). OK, so if you wanted to be able to call myrole(...) instead of myrole.caller, why doesn't cmd.__call__ return self.caller rather than just self? We want to be able to access the instance attributes (as is done e.g. here: ). I realize we can set the attributes directly on the functions, but we've decided to not do that (it's a style thing, really). Although I guess a class method which then returns our desired method could work out for us. While I still think that this kind of syntax might be useful for dynamic decorators (I know I'd use that when playing with decorators), I'm afraid I'm out of concrete examples to send your way. OK, maybe someone else wants to provide a real-world example. Otherwise I am really going to close this (again). Real world example where this actually came up: There is again some discussion about this at
https://bugs.python.org/issue19660
CC-MAIN-2019-43
refinedweb
1,524
62.38
Content-type: text/html regcmp, regex - Compile and execute regular expression Standard C Library (libc.so, libc. a) #include <libgen.h> char *regcmp( const char *string1, ... /*, (char *)0 */); char *regex( const char *re, const char *subject, ... ); Interfaces documented on this reference page conform to industry standards as follows: regcmp(), regex(): XPG4-UNIX Refer to the standards(5) reference page for more information about industry standards and associated tags. Points to the string that is to be matched or converted. Points to a compiled regular expression string. Points to the string that is to be matched against re. responsibility of the process to free unneeded space so allocated. A null pointer returned from regcmp() indicates an invalid argument. The regex() function executes a compiled pattern against the subject string. Additional arguments of type char must be passed to receive matched subexpressions back. A global character pointer, __loc1, points to the first matched character in the subject string. The regcmp() and regex() functions support the simple regular expressions which are defined in the grep(1) reference page, but the syntax and semantics are slightly different. The following are the valid symbols and their associated meanings: The left and right bracket, asterisk, period, and circumflex symbols retain their meanings as defined in the grep(1) reference page. A dollar sign matches the end of the string; \n matches a new line. Used within brackets, the hyphen signifies an ASCII character range. For example [a-z] is equivalent to [abcd...xyz]. The - (hyphen) can represent itself only if used as the first or last character. For example, the character class expression []-] matches the characters ] (right bracket) and - (hyphen). A regular expression followed by a + (plus sign) means one or more times. For example, [0-9]+ is equivalent to [0-9][0-9]*. Integer values enclosed in {} braces indicate the number of times the preceding regular expression can be applied. The value m is the minimum number and u is a number, less than 256, which is the maximum. The syntax {m} indicates the exact number of times the regular expression can be applied. The syntax {m,} is analogous to {m,infinity}. The + (plus sign) and * (asterisk) operations are equivalent to {1,} and {0,}, respectively. symbols defined above are special characters, they must be escaped to be used as themselves. The regcmp() and regex() interfaces are scheduled to be withdrawn from a future version of the X/Open CAE Specification. These interfaces are obsolete; they are guaranteed to function properly only in the C/POSIX locale and so should be avoided. Use the POSIX regcomp() interface instead of regcmp() and regex(). Upon successful completion, the regcmp() function returns a pointer to the compiled regular expression. Otherwise, a null pointer is returned and errno may be set to indicate the error. Upon successful completion, the regex() function returns a pointer to the next unmatched character in the subject string. Otherwise, a null pointer is returned. Commands: grep(1) Functions: malloc(3), regcomp(3) Standards: standards(5) delim off
http://backdrift.org/man/tru64/man3/regcmp.3.html
CC-MAIN-2017-22
refinedweb
502
57.87
A Portion of Buff Everybody else had one, so... Noise 0.3 released I've put a new cut of Noise, the premier solution for C# VST developers (ahem), up on GForge. The changelog: * Finished implementing v1.0 of the SDK _apart from_ setChunk()/getChunk() because I don't know how best to handle them yet. It would be nice to do something a bit smarter than a byte stream. Suggestions welcome. * Refactored ManagedBridge a little bit so it directly returns values instead of using out params. * Added very basic error handling to HostPlugin - if your plugin fails to initialise properly, it will report nicely back to the host. * Added an example of a compressor. Doesn't work properly yet, but it _sort of_ sounds compressor-like. * You can now provide your own unique ID to the host (see CompressorPlugin for an example). * Made some of the process classes mono, which makes them a bit easier to understand. The subdued garbage collector I want Noise to support any .Net language, not just C# (although why anyone would use another language...). At the moment, the plugin interface exposes unsafe methods - Process and ProcessReplacing - which take float* parameters and are therefore unusable by a pussy language like VB.Net. Pointers are used because it allows us to write directly to the host's memory instead of allocating our own buffers and copying them back to the host. If we are prepared to take a performance hit, we can make this interface safe. Not only is there the cost of copying unmanaged memory to a managed buffer on the way in, and then back again on the way out, we need to allocate some managed memory in the first place. Allocations lead to collections, collections lead to hate, hate leads to suffering. However, we can take advantage of the fact that the maximum number of samples being passed to the plugin rarely changes (usually not until the host's latency setting has been changed, which is hardly ever under normal use), although the host is free to send fewer samples if it wishes. The host tells us the maximum block size by calling the SetBlockSize() method, which is a good place to allocate our buffers: public override void SetBlockSize(int blockSize) { leftBufferIn = new float[blockSize]; rightBufferIn = new float[blockSize]; leftBufferOut = new float[blockSize]; rightBufferOut = new float[blockSize]; } and in the Process or ProcessReplacing methods, we can just fill these buffers using the Marshal class: public override void ProcessReplacing(float* inLeft, float* inRight, float* outLeft, float* outRight, int sampleFrames) { Marshal.Copy(new IntPtr(inLeft), leftBufferIn, 0, sampleFrames); Marshal.Copy(new IntPtr(inRight), rightBufferIn, 0, sampleFrames); Marshal.Copy(new IntPtr(outLeft), leftBufferOut, 0, sampleFrames); Marshal.Copy(new IntPtr(outRight), rightBufferOut, 0, sampleFrames); //... } It doesn't matter if sampleFrames is less than blockSize, we just copy that many samples to our buffers. This enables us to call out to a safe method which deals with float arrays, and performance is constant because no new allocations occur. Hurrah. Noise 0.2 source released Now installs to the GAC (this was the only way I could let hosts load a plugin from an arbitrary location. Sometimes assembly-resolution sucks). Added a reverb plugin to the package, and generally fixed up the solution. To get up and running: 1) Download and extract noise-source-0.2.zip somewhere. 2) Download the VST Plugin SDK from 3) Copy everything from vstsdk2.3\source\common into Noise\HostPlugin\vst 4) Build the solution 5) Open project properties for Noise.ManagedVst, go to Configuration Properties-->Debugging 6) Change Debug Mode to "Program" 7) Change "Start Application" to point to VstHost.exe (under Noise\ by default) 8) Hit [ctrl +] F5 9) Load up your favourite synth plugin, then chain HostPlugin.dll after it (deployed in Noise\build). 10) Enjoy On microbenchmarks and red faces Dear VB.Net H8t3R, Keeping it real-time (3) These late nights are going to catch up with me, but until then... I've kicked off Noise, an open source project for this managed VST plugin thing I'm working on: (Last year I was working on an abortive software synthesizer called "Noise!", so it seemed appropriate to recycle the name). It's obviously quite rough at the moment, but please, if you use any VST-compatible audio software (Cubase, SoundForge, FruityLoops etc), download it, give it a try, and let me know if you had any problems (positive feedback is nice too). If you don't have a VST host, there's a free one included, so you can still play around if you're interested. So far I've got delay, lo/hi-pass filter, gain and reverb plug-ins - the latter being the most fun to do and the most difficult to get my head around. One thing that struck me tonight was just how incredibly fast computers are. I know I should be accustomed to that, being a developer, but when you're writing code which applies 12 different filters to 44,100 stereo samples per second, in parallel to a software synthesizer which is generating those 44,100 stereo samples per second with its own oscillators, filters and envelopes, on top of a host application routing all these samples from the synth, through your plugin (via layers of C, Managed C++ and C#) and out to a sound card, and it only takes 3% of available CPU time, it kind of brings it home. Here's a stereo comb filter: public class CombFilter { float feedback; float damp1; float damp2; float lastLeftValue; float lastRightValue; int leftIndex; int rightIndex; float[] leftBuffer; float[] rightBuffer; public CombFilter(int leftTuning, int rightTuning, float damp, float feedback) { this.feedback = feedback; this.damp1 = damp; this.damp2 = (1 - damp); this.leftBuffer = new float[leftTuning]; this.rightBuffer = new float[rightTuning]; } public float ProcessLeft(float input) { lastLeftValue = (leftBuffer[leftIndex] * damp2) + (lastLeftValue * damp1); leftBuffer[leftIndex] = input + (lastLeftValue * feedback); if (++leftIndex >= leftBuffer.Length) { leftIndex = 0; } return leftBuffer[leftIndex]; } public float ProcessRight(float input) { lastRightValue = (rightBuffer[rightIndex] * damp2) + (lastRightValue * damp1); rightBuffer[rightIndex] = input + (lastRightValue * feedback); if (++rightIndex >= rightBuffer.Length) { rightIndex = 0; } return rightBuffer[rightIndex]; } } Keeping it real-time (2) I had a request for more (more!!!), so I'll explain how some more of the managed plugin system works. At the root of it, we have the VST SDK-derived class. This is a standard C++ class which inherits from AudioEffectX (defined as part of the SDK). Any VST host will expect an instance of this type, and will call certain methods to both interrogate your plugin about its capabilities and pass it the magical float** inputs and outputs. (I remember reading somewhere about three star C programmers, and how they were a breed unto themselves. We only have two stars here, but as .Net programmers, I think we should allow ourselves a smug grin). As Managed C++ classes cannot inherit from unmanaged classes, our root plugin must be unmanaged. However, unmanaged classes can have references to managed classes, via the gcroot<> template (there may be other ways - I have not discovered them yet). A VST host will typically want to know how many inputs and outputs a plugin can handle, whether it can be a parallel ("send") or serial ("insert") effect, whether it has its own GUI for editing parameters, etc. My goal is to delegate as much as possible to C#, so most of these calls must be marshalled directly to managed classes. The good news is that MC++ makes this marshalling really fricken easy. Anyone who's done much P/Invoke will know how fiddly all those MarshalAs attributes can be to get right. Well, most of the time, with MC++, It Just Works. You have to make a few decisions about which side owns which piece of memory, but I'm 90% convinced that doing interop from the unmanaged side is just easier. Although maybe that's just the pointers talking. An example: void VstToManaged::process (float **inputs, float **outputs, long sampleFrames) { m_pPluginBridge->Process(inputs, outputs, sampleFrames); } That takes us from an unmanaged, VST 0wn3d method to MC++. No mucking about with DllImport, just include the header file. Did I just say that? Anyway, taking the process() method further, I decided that most C# weenies wouldn't know what to do with two levels of indirection, so I dereferenced the left and right channels and created an interface thusly: public interface IVstPlugin { unsafe void Process(float* inLeft, float* inRight, float* outLeft, float* outRight, int sampleFrames); } There's more on this interface than that, but I'll keep it simple for now. The code from an MC++ point of view? void ManagedBridge::Process(float **inputs, float **outputs, long sampleFrames) { float *in1 = inputs[0]; float *in2 = inputs[1]; float *out1 = outputs[0]; float *out2 = outputs[1]; plugin->Process(in1, in2, out1, out2, sampleFrames); } Interop schminterop. And, as I'm feeling philanthropic, here's a mono Biquad filter in C#. Feed it a stream of samples and see what comes out: using System; namespace ManagedVst.Processes { public enum FilterType : byte { LPF, HPF, } //Ported and adapted from Tom St Denis' C version () public struct BiQuad { //Coefficients. Don't ask me what they do. double A0, A1, A2, A3, A4; //X1 is the input from the previous step, X2 is the input before that //Y1 is the output from the previous step, Y2 is the output before that double X1, X2, Y1, Y2; public void Init(FilterType filterType, double sampleRate, double frequency, double bandwidth) { //A frequency of 0 can lead to the filter producing //very small (denormal) numbers and NaNs. This is bad because //most processors are very slow at calculating very small floating point numbers, so we should //clamp such values to something larger. This might be slightly superstitious, but including //the following check banished 100% CPU usage spikes. Alternatives welcome (double.Epsilon didn't //appear to work). if(frequency == 0d) { frequency = 0.00000000000001d; } const double LogE2 = 0.69314718055994530942; double omega = 2 * Math.PI * frequency / sampleRate; double sinOmega = Math.Sin(omega); double cosOmega = Math.Cos(omega); double alpha = sinOmega * Math.Sinh(LogE2 / 2 * bandwidth * omega / sinOmega); double a0 = 1 + alpha; double a1 = -2 * cosOmega; double a2 = 1 - alpha; double b0 = 0; double b1 = 0; double b2 = 0; if (filterType == FilterType.LPF) { b0 = (1 - cosOmega) / 2; b1 = 1 - cosOmega; b2 = (1 - cosOmega) / 2; } else //filterType == FilterType.HPF { b0 = (1 + cosOmega) / 2; b1 = -(1 + cosOmega); b2 = (1 + cosOmega) / 2; } A0 = b0 / a0; A1 = b1 / a0; A2 = b2 / a0; A3 = a1 / a0; A4 = a2 / a0; } public float Step(float input) { double output = A0 * input + A1 * X1 + A2 * X2 - A3 * Y1 - A4 * Y2; X2 = X1; X1 = input; Y2 = Y1; Y1 = output; return (float)output; } } } Keeping it real-time Since we last spoke, I have realised that a managed VST plug-in is a far from practical application for hosting the CLR. Which means no more COM haxx0ring. Shame. Practical applications for CLR hosting. Eat Static I answered a question in a C# forum the other day from someone looking to do runtime subclassing, similar to NMock. The question went something like this: How big are your priv.
http://weblogs.asp.net/jarnold
CC-MAIN-2015-27
refinedweb
1,846
61.77
Greetings, I am hoping the someone can point me in the right direction; as I have been unable to pinpoint the source of this error: Event Type: Warning Event Source: DNS EventID: 7062 "The DNS Server encountered a packet addressed to itself on IP address x.x.x.x. The packet is for the DNS name _ldap._tcp.dc._msdcs.mydomain2.com. The packet will be discarded" I have a W2K3 AD environment. Two DNS servers. I have checked the Forwarders, Root Hints, Master and Notify Lists, etc. Any help would be appreciated. Thanks. 1 Reply Apr 29, 2008 at 1:13 UTC Greetings. Have you gone through Microsoft's thing? http:/ How to troubleshoot 7062 errors logged in DNS event log This article was previously published under Q235689 Article ID : 235689 Last Review : February 26, 2007 Revision : 3.3 SUMMARY This article describes how to troubleshoot the cause or causes of event ID 7062 on a DNS server that is running Microsoft Windows 2000 or Microsoft Windows NT Server 4.0. If event ID 7062 logs on your DNS server, it will appear as follows: EVENT message 7062: DNS Server encountered a packet addressed to itself -- IP address<actual IP address>. The DNS server should never be sending a packet to itself. This situation DNS server. As part of your troubleshooting, you may find that none of the steps that are listed in event ID 7062 apply to your DNS server. However, event ID 7062 may continue to log on your DNS server. This article discusses some of the other reasons why this issue may occur. Step 4 of event ID 7062 may lead you to conclude that for the event to be triggered, a primary DNS server must create a delegation of a subdomain. However, the root DNS servers maintain the .com, .net, and other domains. Additionally, the root DNS servers delegate the namespace under those domains to other DNS servers. Therefore, although your DNS server may be the primary DNS server for example.com, your DNS server has been delegated that responsibility by the ".com" DNS server or servers. This means that if you have registered a domain with the NSFnet Network Information Center (InterNIC), and they delegate that domain to your DNS server, it is your responsibility to make sure that your DNS server can handle all requests for the registered domain. For example, you have a DNS server at dns.example.com, and you have recently registered example.org with InterNIC. After InterNIC delegates example.org to your DNS server, you must create a zone file that can answer queries for example.org. The following hypothetical sequence of events describes how event ID 7062 may continue to log to your DNS server if you have not configured it to maintain zone files for domains that you have registered. 1. A client computer tries to contact. The client computer sends a query for to the root servers. The root servers determine that the Start of Authority (SOA) for example.org is the DNS server dns.example.com at IP address 10.1.1.1. IP address 10.1.1.1 is your DNS server. 2. The client computer sends a request to 10.1.1.1 for. Your DNS server examines its zone files and determines that it is not the SOA for example.org because it does not have a zone file for. 3. Your DNS server sends an iterative query for example.org to the root servers. 4. The root servers respond to the iterative query from your DNS server by telling your DNS server that the SOA, or owner of the domain, for example.org is at 10.1.1.1. Your DNS server examines itself for the answer to the query, and does not find one. 5. If the root hints that are in Windows 2000 point to the same computer, event ID 7062 will log. For additional information about replacing the existing root hints with the default root hints, click the following article number to view the article in the Microsoft Knowledge Base: 249868 (http:/ Note Event ID 7062 will log even when zone transfers are disabled. For more information about this behavior, see "Event ID 7062 logs even when zone transfers are disabled" in the More Information section. MORE INFORMATION How to find the actual requested domains To find the actual requested domains, you must debug your DNS server. After you have created a log file, open it in Microsoft Word or Microsoft Excel. We do not recommend that you open the file in Notepad because Notepad does not parse characters into an easily readable format. When you have the log file open, search for "7062." This search should bring you to the first error. After you find the error, scroll up. A DNS query log looks similar to the following code. dns_ProcessMessage() for packet at 00A5E524. dns_AnswerQuestion() for packet at 00A5E524. Node for (3)www(10)mycompany(3)com(0) NOT in database. Closest node found"com." Encountered non-authoritative node with no matching RRs. dns_ProcessMessage() for packet at 00A5EAC4. Processing response packet at 00A5EAC4. Packet contains RR for authoritative zone node: "dns.hello.com." -- ignoring RR.dns_ContinueCurrentLookup() for query at 00A5E524. dns_AnswerQuestion() for packet at 00A5E524. dns_AnswerQuestionFromDatabase() for query at 00A5E524 node label = www question type = 0x0001 ERROR: Self-send to address 10.1.1.1!!! Log EVENT message 7062 (80001B96): The following describes what occurs during the important phases of this log: 1. The DNS query log starts with dns_ProcessMessage(). 2. The node for the request is. 3. Your DNS server cannot handle the request Encountered non-authoritative node. 4. Your DNS server sends a dns_ProcessMessage to the root servers. 5. The root servers send a response packet, Processing response packet, to your DNS server. This response indicates that your DNS server is the SOA for example.org. 6. Your DNS server ignores the response packet. 7. Event ID 7062 logs on your DNS server. Event ID 7062 logs even when zone transfers are (http:/ Event ID 7062 will log even if zone transfers are disabled if the Notify option has been configured to notify a DNS server or servers that are listed on the Name Servers tab. By default, a Windows 2000-based primary DNS server that has multiple zones is configured to notify the servers that are listed on the Name Servers tab. Note Disabling zone transfers does not disable the Notify option. If the Notify option is set to notify a DNS server or servers that are listed on the Name Servers tab, it will continue to do this. To disable zone transfers, follow these steps: 1. Click Start, click Run, type regedit, and then click OK. 2. Locate and then click the following subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DNS\Zones\ZoneName 3. In the right pane, right-click NotifyLevel, and then click Modify. 4. Type 0, and then click OK. 5. Quit Registry Editor. REFERENCES For more information, see the following Microsoft Knowledge Base article: 218814 (http:/ APPLIES TO • Microsoft Windows 2000 Server • Microsoft Windows 2000 Advanced Server • Microsoft Windows 2000 Professional Edition • Microsoft Windows NT Server 4.0 Standard Edition
https://community.spiceworks.com/topic/14038-dns-error-packet-addressed-to-itself
CC-MAIN-2016-44
refinedweb
1,198
66.74
If you think about it, a lot of web development has something to do with forms. Every time you capture information, you most likely require a form. It's one of the basic skills for a front-end developer. There are plenty of options for React and I've reviewed the directions briefly on my slides. To get a better idea of one of them, I'm interviewing Nikolay Nemshilov about A+ forms. I met Nikolay over the internet roughly a decade ago while I was writing my first bigger web application. I used his RightJS library there. It was sort of an alternative for jQuery at the time. It has been fun to see both of our careers evolve since those days. Well, over the years of trying to answer this question, I narrowed it down to the following: Hi, I'm Nikolay, I'm here to help.Well, over the years of trying to answer this question, I narrowed it down to the following: Hi, I'm Nikolay, I'm here to help. That's usually enough to start. But, I suppose you want something more tangible in this case. Well, I'm a software engineer, I think. And I've been doing this long enough to start feeling a bit awkward about it. I guess my "career" as a software engineer began when IE4 was the tip of the spear and I still had my hands on the keyboard every single day. Recently, however, I've been more focused on building teams of software engineers at my day job. I see this as just another way to create software. I suppose it's a natural outcome of attempts to realize more extensive and more significant projects. Ok, I admit, this was a bit vague. Don't get me wrong; I am not trying to dodge the question. But I feel like a personal story of a Siberian born, working-class nerd who lives in Australia is going to be a bit confusing and besides the point. A+ forms is a React forms library that helps you not cry yourself to sleep every time your boss asks you to build a twelve-field form. It solves tedious problems like state management, validation, and data transformation in a predictable manner with minimal configuration. I think this question can be answered from multiple perspectives: how it works internally, what it exposes externally, and how it works in the context of an engineering team. It primarily revolves around the concept of an input field. I started with the familiar idea of an HTML input tag with its name, value, and onchange attributes and then applied these to all fields. Fields may also have sub-fields. In some cases, a form is one large field. The big idea here is to work with the grain of engineers' understanding of forms. Engineers think of forms as a bucket of input fields that spits out a blob of data which we then retrieve and send to the server. A+ forms provide this the type of developer experience. For example: import { Form, TextInput, PasswordInput } from 'a-plus-forms'; cosnt sendToServer = ({ username, password }) => { /* ... */ }; <Form onSubmit={sendToServer}> <TextInput name="username" label="Username" /> <PasswordInput name="password" label="Password" /> <button type="submit">Sign In</button> </Form> The above is just a simple example that doesn't do justice to the level of complexity A+ forms can handle. But it demonstrates the principle behind the library: Here are my fields. Please give me the data entered into them, because I don't care about anything else at the moment. This mentality is shared by engineers and teams. It's a universal truth of forms if you will. All you want is data. Ok, let's get this straight. I'm not going to say anything negative about other solutions - I'm not here to bash other people's work. Besides, given enough determination, most problems can be solved with any tool available. Instead, I'll explain what's important to me. As the technology matures, we humans try to use it to solve increasingly complex problems. Which in turn requires increasingly sophisticated solutions. Over time this complexity starts accumulating until we forget what we were doing in the first place. Most solutions on the market address the complexity of the task with increased complexity. Over time this inevitably becomes taxing. A+ forms differ here by attempting to keeping the task of creating and maintaining complex forms simple. To become rich and famous and achieve world domination, naturally. But seriously, I think I have little patience for wasting time in my work. I don't know about you, but I'm easily distracted and discouraged when things are not going smoothly. There are so many awesome things waiting to be built in the world, and spending time dealing with mundane problems that have already been solved is unproductive. That's the same principle why you use React. You could devote yourself to vanilla JavaScript and DOM. But after ten times of writing the same repetitive boilerplate code and dealing with browser inconsistencies, you probably just want to focus on building the actual app, not figuring out why change events are not triggered on a range input in IE 10. I built A+ forms for the same reason, so my engineers and I don't have to solve this problem over and over again and can focus on making what we want to develop. I'm glad you've asked. A+ forms itself represents just the data handling core. All the components are just standard HTML-looking abstractions, which depending on a context, can be implemented in all sorts of things. Those "all sorts of things" is the next step in my view. Here are the next extensions that I'm planning to build: 1) Bootstrap-tailored fields A+ forms have a bunch of standard fields out of the box, but they're not tied to any particular UI component implementation. I want to create an extension that will convert those fields into standard Bootstrap fields as a means to simplify adoption further. This has been done. See a-plus-forms-bootstrap. 2) React Native fields This one is my favorite. Form management in native mobile apps is alien to us web developers. But it doesn't have to be like this. If we re-implement those fields in React Native components, then engineers could have the same developer experience between web and native apps. Heck, they could even finally share their forms code between them. 3) HTML5 props validator At my day job, we're using JSON Schema as a way to validate forms, but it's a bit overkill for more straightforward cases. I want to build an extension that will read standard validation props like required and pattern on the input fields and set validation rules accordingly. The goal is to make A+ forms into a sort of "Barbie doll", where the community can build extensions and extra accessories for it and share their solutions with each other. If you ask my opinion, I think we should stop calling it "web development" and instead just use the term "development". From first-hand experience since almost the beginning of widespread adoption of the web, I can say one thing: engineers tend to be overprotective of their reputation, to the point of being real jerks. When I started my career, the word "web developer" was an oxymoron. The older generation didn't even want to call us "developers", they called us "webmasters" as a way to distance themselves from us. They saw themselves as "real engineers", where we were just playing with toys. If you joined the bandwagon a bit later, you might have seen web developers belittled as not being "real programmers". Humans do nasty stuff to each other now and then. But, by now techniques developed for the "web" have become pretty much the standard practice in most areas of software. For example, the process for building UIs we've developed for the "web" beats the traditional "native" UI practices. The same goes for building APIs. Node.js based microservices, Serverless, load balancing, high-efficiency networking, and so on all grew out of the "web". The child has grown into an adult and feels strong. Now that adult just needs to learn how to act like an adult. That will be a trend in the near future. Tread without fear, my friends. The "web" is here to stay. Don't listen to anyone who tells you it's not "real software engineering". Also, a bit of a downer: 99% of your time won't be about "writing clever algorithms". The sooner you accept that the better off you will be. It's just a fairy tale that has nothing to do with reality. It's called "development", not "slinging out code" for a reason. It's really about building things, not showing how smart you are. Because guess what, everyone else is just as bright :) This observation brings us to the third and last piece of advice. Learn how business works. I know, business, ewww! But it will help you to make better decisions and understand how other people see your role in a company. Most importantly, this will help you to keep hassle to a minimum and get back to doing what you love - creating things. Ooh, I love this! Okay, so, anyone really from Thinkmill, Envato or Buildkite. They are all strong technically, and most of them are outstanding people. Don't forget to eat well, get enough sunlight, and, if you're an introvert, don't forget to give yourself plenty of downtime cuddling with a book to recharge your batteries. The world is an exhausting place, but it has pancakes in it. Thanks for the interview Nikolay! A+ forms looks like a solid form handling solution for React. You can learn more about A+ forms at GitHub.
https://survivejs.com/blog/a-plus-interview/
CC-MAIN-2022-40
refinedweb
1,662
73.27
On 2020-04-08 17:53, Guido van Rossum wrote: Look at the following code. def foo(a, b): x = a + b if not x: return None sleep(1) # A calculation that does not use x return a*b This code DECREFs x when the frame is exited (at the return statement). But (assuming) we can clearly see that x is not needed during the sleep (representing a big calculation), we could insert a "del x" statement before the sleep. I think our compiler is smart enough to find out *some* cases where it could safely insert such del instructions. And this would potentially save some memory. (For example, in the above example, if a and b are large lists, x would be an even larger list, and its memory could be freed earlier.) For sure, we could manually insert del statements in code where it matters to us. But if the compiler could do it in all code, regardless of whether it matters to us or not, it would probably catch some useful places where we wouldn't even have thought of this idea, and we might see a modest memory saving for most programs. Can anyone tear this idea apart? Can you be sure that 'sleep' isn't inspecting the stack and using x?
https://mail.python.org/archives/list/python-ideas@python.org/message/5KYLXDL6MZV3FETTIA5JIB5YSRUHAKZ2/
CC-MAIN-2021-43
refinedweb
216
67.28
Smashing Magazine we smash you with the information that will make your life easier. really. 30 More Excellent Blog Designs November 22nd, 2007 in Design Showcase | 182 - this one melts clever portfolio and blog Blogsolid Carsonified Jrvelasco — quite noisy, but the noise fits to the subject of the weblog. Simon Reynolds Jonathan Durán Nice And Original Blog Designs Tobias Baeck Chris Murphy — don’t forget to check the design of the archive section and the footer. Anthony Casey split da diz — interesting design: unusual approach for site structure. Adrian Pintilie — the top section of the site is pretty colorful. Cult Foo She Unlimited Tickerville Amy Hoy moddular — the design might look a little bit noisy, but it definitely has its personal style. Victoria van Roosmalen — OK, this cat looks Owen (November 22nd, 2007, 9:05 pm) You call praegnanz.de an excellent blog design? *ggg* You must be kidding. Phil (November 22nd, 2007, 9:17 pm) There is some serious inspiration here… I have been considering a redesign myself and really want to now! Thanks! Chris (November 22nd, 2007, 9:19 pm) TNTPixel would look a lot better without the big header picture imo. I still love the design *g* Damien (November 22nd, 2007, 9:24 pm) It’s just awesome, I love Blogsolid and Cult Foo ! Very nice design. bmunch (November 22nd, 2007, 9:52 pm) There are some creative people here on this list. I wonder how the people in Smashing Magazine surf the web to frequently find such high quality web sites designs to showcase. Excellent. Stevie K (November 22nd, 2007, 10:03 pm) Thanks Smashing, I can always rely on you for inspiration at times when I am lacking it. TechDune (November 22nd, 2007, 10:14 pm) Now,that’s what i call blog designs…. Bloghash.com (November 22nd, 2007, 10:20 pm) Thanks for yet another great post. My blog design is underway and I am designing it myself. I have been referring to your earlier posts on WP design and they came very handy for my new theme design. Cheers!! > Raj fen (November 22nd, 2007, 10:26 pm) Very nice, I love them. TylerD (November 22nd, 2007, 10:48 pm) Thanks for this list. It’s a very good inspiration… :o) Ray Drainville (November 22nd, 2007, 10:50 pm) The Dilbert blog. Are you kidding me?!? Gonzague Dambricourt (November 22nd, 2007, 11:16 pm) Oh :-) congrats to my very friend Polo for Split Da Diz which is being mentionned in this post ! Crazyleaf (November 22nd, 2007, 11:19 pm) Some great blog designs. Most of them I already knew. The Cult Foo has a superb design. Bravo ! Aditya (November 22nd, 2007, 11:30 pm) Some of the designs up there are quite innovative and creative. Thanks for the linkage. kevinzahri (November 23rd, 2007, 12:48 am) very cool blogs….i like how uniquely different but nicely done they all are :D eMeRiKa (November 23rd, 2007, 1:49 am) I add one, my blog : Link [] :p Chris (November 23rd, 2007, 2:01 am) Great post like always. Really great designs. split da diz and cult foo were new to me. :D Stoyan (November 23rd, 2007, 5:54 am) Thanks for the inspiration! Dan (November 23rd, 2007, 7:21 am) Where is Bittbox? Rubén Lozano (November 23rd, 2007, 7:40 am) Link [] Another blog to consider, well, is a theme for wp. Jan (November 23rd, 2007, 9:07 am) While i don’t think that praegnanz.de is the best amazingly well designed blog on earth i like how Gerrit works with whitespaces. Starfeeder (November 23rd, 2007, 10:32 am) wow nice collection :o def great inspiration… Andres Santos (November 23rd, 2007, 10:45 am) I dont want to be vain, but check this one out, new theme, fresh and professional: Link [andufo.com] Greets from a concurrent reader. David Englund (November 23rd, 2007, 10:45 am) I especially love “verbalized” that’s a very simple + powerful design style, I love designing, I eat, breath and burp it every day (well maybe not burp) - see below Link [one.revver.com] FPM (November 23rd, 2007, 11:07 am) I used to be a homeless rodeo clown but now I am a world class magician ! Bubs (November 23rd, 2007, 11:20 am) I’m in love with Elitist Snob. Verbalized is cute, too ;) jayhan (November 23rd, 2007, 11:51 am) Top notch list! I like Cult Foo’s. Great inspiration, thanks again, as always. Mike (November 23rd, 2007, 12:10 pm) I think Link [] is a great web 2.0 site. designcode (November 23rd, 2007, 12:21 pm) A very rich and healthy article from SM after a long time. Loved it. Jermayn Parker (November 23rd, 2007, 12:31 pm) Some good inspiration, thanks!! psycholq (November 23rd, 2007, 4:20 pm) praegnanz.de … plz ;] try to be serious guys :) V1 (November 23rd, 2007, 6:55 pm) LOL, u see everybody here say: i found another great design! XD the praegnanz.de blog should stay there anyways it may not be the most pretty design of this list. But if u like clean clear styles, thats a really good blog design Hubbers (November 23rd, 2007, 7:08 pm) Oh no I just realised that my own blog is UGLY!!! easypctips (November 23rd, 2007, 8:12 pm) Mine too…oh well, that’s why I came - for inspiration. TNTPixel looks very two point oh! Igor (November 23rd, 2007, 8:14 pm) I’m wondering how TNTPixel was chosen to this list. Open: Link [] Then open: Link [] Designer when design TNT must be looked to alistapart… shame HotBertaa (November 23rd, 2007, 8:44 pm) I’ve been holding off on submitting my site to the css sites for a while, waiting for it to be fully finished… but saw this and thought why not. Take a look, Link [] Its not got all the finishing touches, but I’m really pleased with the javascript and composition JOY (November 23rd, 2007, 9:13 pm) Very creative and beautiful blog designs. Himanshu Kapoor (November 23rd, 2007, 9:55 pm) The best part is that there is enough of design treasure(graphics, layouts, tutorials etc) in most of the blogs. Thank you smashing magazine. RP (November 23rd, 2007, 10:13 pm) Why is everyone so down on praegnanz.de? Have you actually been to the site? It may not be the most graphically impressive but it is designed very well and is clean and easy to read and navigate. Isn’t that a part of good design? john (November 23rd, 2007, 10:24 pm) Another great compilation! 70311 (November 23rd, 2007, 10:30 pm) So the definition or “excellent” in terms of blog design is “shit loads of wasted space”. deprisa (November 23rd, 2007, 11:31 pm) All of them are great designs in my oppinion, but I love the cat of evilgrin! It is just… So clean and so funny jaja David Boyd (November 24th, 2007, 12:15 am) ahhhh. a fresh wave of new designs…which one will I choose… Avatariz (November 24th, 2007, 12:28 am) Nice blog Blogsolid Cristian (November 24th, 2007, 1:19 am) What do you think about mine? Link [] Wordpress based and widgets for the external columns. Carlos Eduardo (November 24th, 2007, 2:52 am) I think my blog has a better layout than moddular, for example… You give some nice examples, but some of them are just “ok”. Tyler (November 24th, 2007, 3:09 am) Nice list, why stop at 30? HotBertaa (November 24th, 2007, 4:36 am) most of these sites are found through cssremix or cssvault… while cultfoo has a nice header, I’d say its let down by its content. As much as the header is great, I dont feel inclined to read through the blog itself. TheMystical (November 24th, 2007, 6:20 am) Meh, I guess it’s my personal taste, but I only like few of them. Anders (November 24th, 2007, 9:40 am) Nice designs, but many of them have too large headers. Water Buffalo (November 24th, 2007, 12:27 pm) You guys are simply reposting the same websites that you show in all the other round-ups. For example, the “praegnanz.de” blog was featured in your “45 Excellent Blog Designs” article as well. Inkboy (November 24th, 2007, 6:13 pm) With my blog i try to do something simple, colorful and original: Link [] Vitaly Friedman & Sven Lennartz (November 24th, 2007, 6:38 pm) @Water Buffalo: praegnanz.de is reposted by mistake. Sorry for inconvenience. Vladimir (November 24th, 2007, 7:54 pm) Nice collection. Blog solid gets my vote for best designed one. Haris (November 24th, 2007, 9:23 pm) Awesome designs! I might use one of these for my blog :) Mike - Digitalismo (November 24th, 2007, 9:37 pm) Great post and inspirational. Cheers Naser (November 24th, 2007, 11:20 pm) Wow, great job again. Blogs like Elitist Snob or Grantmx Designs stand as testament to how far web-design has come since flashy, glittery GIF’s and annoying MS-Frontpage made ticker messages (oh, wait, I forgot about Myspace). I hope someday, I too can get a few bucks under my belly and buy me a unique domain to do some freelance designing. Until then, I’m Link [atunu.blogspot.com] :( vishal sharma (November 25th, 2007, 8:09 am) its a good collection of blogs and reference site. Sean (November 25th, 2007, 9:48 am) Hi Mr. Lennartz, I’m a PR student at the University of South Florida and we are studying the growing popularity of blogging. If I wanted to get an influential blogger’s attention such as you, how would I go about getting my issue out to the masses? Yogi (November 25th, 2007, 9:51 am) Nice list, but IMHO some of them shouldn’t be on the list :) ChakraGoddess (November 25th, 2007, 11:24 am) awesome list — some of them (eg CultFoo) I want to dive right in! xx Anita hafifi (November 25th, 2007, 12:42 pm) Nice themes! what should i do if i want use it on my blog? Ben May (November 25th, 2007, 7:01 pm) Nice collection!!!! could be some more web 2.0 ones though xexagon (November 26th, 2007, 5:47 am) praegnanz.de is really good; it’s obviously designed to be read (check out the attention to leading and margins, and the measure). Most of these are graphically superb, but that doesn’t make them great design. Rodrigo (November 27th, 2007, 12:41 am) Hi Igor, Save for the navigation, which looks kind of similar I guess, I fail to see any other similarities. I based my design of various newspaper clippings I have laying around in my house. That’s the look I was going for. Kind of like old newspaper sections. I think ALA is going for a similar “old print” kind of look, and in that regard, that particular headline style is a very very used formula in print. Go ahead, get some newspapers, you’ll see. Unoriginal? mmm, perhaps. Plagiarism? NEVER. You should inform yourself better before pointing your finger, Igor. Plagiarism is a very nasty thing, I don’t condone it, and I don’t do it. I looked at your site, and I could assume you copied it from a MYRIAD of other sites that look identical to yours. But I understand that it’s obvious that you will run into many many similarities through some sites (especially when you are trying to mimic a particular style, like print). Plagiarism is by far the worst thing you can call a designer, but I assume you don’t know that since you are clearly not one yourself… shame. SNaRe (November 27th, 2007, 6:13 am) I have nothing to say they are really excellent themes. I hope one day i can design myself. Mike (November 27th, 2007, 7:24 am) really cool! but my website looks better badbul (November 28th, 2007, 7:58 am) good job design.. i love most of all that design! awesome! David (November 28th, 2007, 4:36 pm) a lot of good stuff! plejeru (November 28th, 2007, 6:08 pm) After seeing Blogsolid I want to hide my blog somewhere deep ; Intotherain.org (November 28th, 2007, 9:19 pm) Wow there are some great blog designs there. I love Elitist Snob and Cult foo Casey (November 29th, 2007, 12:55 am) Let’s say there was a writer who had an appreciation for design and an artistic inclination, but sucked technically…how would said person go about making his or her blog as cool looking as some of these? Hypothetically speaking of course. cellocoffee (November 29th, 2007, 1:23 am) Hi, love your information here. I am a blog newbie, and I write in Chinese. Is it OK to translate this post in Chinese and link to your page? Thanks, cellocoffee Sam Wilson (November 29th, 2007, 10:29 pm) Hey Casey, I’m the person who did Tickerville above and I’m happy for my client that it was included here. My suggestion to you is to pick up a book list CSS Mastery and open up your mind to thinking in terms of CSS. CSS wasn’t my forte when I begin that site, but I found the book to be crucial in turning designs into an actual site. Sam Wilson (November 29th, 2007, 10:33 pm) My advice is to pick up a copy of CSS Mastery by Andy Budd and make it your new Bible. I barely knew CSS when I did Tickerville but that book helped me execute the design pretty faithfully. The biggest thing is having patience. With a lot of patience and reading the right books, you’ll be stunned with what you can do in a few weeks. Sam Wilson (November 30th, 2007, 12:34 am) Sorry for the double post above guys, my mistake. coky (November 30th, 2007, 12:10 pm) really cool! but my website looks better Ibrahim (December 1st, 2007, 12:56 pm) wow, great designs! Lukin (December 2nd, 2007, 5:48 am) Hmmn, Jrvelasco blog looks similar to Dept. of Spanish & Portuguese of UC Berkeley site. Too similar. Take a look and compare: Link [spanish-portuguese.berkeley.edu] Rodrigo (December 3rd, 2007, 10:36 pm) He designed both of them: Link [] MediaRoots (December 5th, 2007, 9:13 am) The SuperJam Blog running on blogger is pretty cool. I would never have guessed it was powered by blogger. Link [] ordinary (December 6th, 2007, 9:16 am) well as always smashing magazine have great post. i would like to pass this one that i love the design as the post. Link [], see this one. Utah Web Design (December 8th, 2007, 1:52 pm) Very nice designs! I need to revamp my own. Ronny-André (December 13th, 2007, 6:22 pm) I LOVE Jared Christensens blog! Peter Chen (December 27th, 2007, 10:44 pm) Great templates, but no mention of which blogging platform they are from. I am only interested in 3 column Blogger templates and I clicked on “TNT pixels” and that lead to a blog, no template download link. Plus at the bottom of the page, it says, “proudly powered by Wordpress”. At least let visitors know what blogging service the templates are for. Don’t know if you read or respond to comments. And hope you don’t consider the links in my signature lines as spam or advertisement. Peter Link [buzz.blogger.com] Link [blogger-tricks.blogspot.com] Drew (January 16th, 2008, 12:25 pm) Check this one out Link [] Clean and dark, very hard to find this days. wizinga (January 25th, 2008, 9:39 am) Very, very, very nice designs!!! Congratulations! Link [] Tracy (February 20th, 2008, 6:27 pm) very nice and thank the collection. Junni (February 21st, 2008, 5:19 am) I’m integrating a Wordpress blog at this moment, into my existing website. Maybe I get some inspiration out of those designs. I like the layouts, but I prefer more simplistic ones. Robin (February 21st, 2008, 6:49 am) I wish I could find the Jared Christensen design but I wasn’t able to. bangjeehyun (February 28th, 2008, 4:03 pm) Good! I’d like to make as them. Thinkbytes (February 28th, 2008, 5:51 pm) great looking blogs! Chris (April 1st, 2008, 4:52 am) Great Post! I love it! Enlargement (April 2nd, 2008, 7:36 pm) First of all I d’like to say. This blogs have lots of imfomation and thay all imfomation is very important for me. Link [] XavYeah (April 15th, 2008, 10:20 pm) Great design, i hope one day, mine will be in Smashing Magazine ! :) [ Link [] ] Maresa Sumardi (April 21st, 2008, 12:49 am) love 80% of those designs, the other 20% is totally commonplace
http://www.smashingmagazine.com/2007/11/22/30-more-excellent-blog-designs/
crawl-001
refinedweb
2,808
72.97
Yesterday night I wanted to have some “no-purpose coding session” and thought it was a nice idea to record the session and do a speedcoding video. The original video has been collapsed from 45 minutes to 3 minutes circa. The main concept is once again based on perlinNoise which (I am sure you already guessed) is something I do like very much. So please start call me “The PerlinNoise Guy” or “Perlinator”. So this is my first speedcoding video (be sure to look at it in high quality): Here’s the interactive demo: Click to launch. Move mouse (x position) to change smoothness (my favourite values are around 100) The code consist on a Branch.as class file (click to download) and some timeline code to assemble the demo: import com.oaxoa.fx.Branch; const w:uint=stage.stageWidth; const h:uint=stage.stageHeight; var ct:ColorTransform=new ColorTransform(1,1,1,1,1,1,1); var renderView:BitmapData=new BitmapData(w, h, true); var bmp:Bitmap=new Bitmap(renderView); addChild(bmp); var tf:TextFormat=new TextFormat("_sans", 16, 0, true); var label:TextField=new TextField(); label.width=400; label.defaultTextFormat=tf; addChild(label); var timer:Timer=new Timer(10); timer.addEventListener(TimerEvent.TIMER, ontimer); timer.start(); function ontimer(event:TimerEvent):void { addNew(); } function addNew():void { label.text="Smoothness: "+String(mouseX-w/2); var tt:Branch=new Branch(mouseX-w/2); tt.x=stage.stageWidth/2; tt.y=stage.stageHeight/2; tt.addEventListener(Event.COMPLETE, oncomplete); addChild(tt); renderView.colorTransform(renderView.rect, ct); } function oncomplete(event:Event):void { var t:Branch=event.currentTarget as Branch; var matrix:Matrix=new Matrix(); matrix.translate(t.x, t.y); renderView.draw(t, matrix); removeChild(t); t.removeEventListener(Event.COMPLETE, oncomplete); t=null; } I didn’t forget about the lightning class part 3 that I will publish soon As usual if you liked this drop a line in the comments. Ciao 11 Comments Great effect! I like the idea of a “no-purpose coding session”, I might have to give that a try soon. Absolutely Beautiful! If you are the Perlinator, us readers are starting to become little Perlinies LOL! great work, as you did before, you’re a master! would you be kind enough to let me adapt it to a onyx-vj plug-in? you will be credited of course… I try to adapt some plug-ins, you can check on for this open-source flash-based vj software Thanks I’ve been to your site and onyx-vj seems very interesting. It would be a pleasure if you’ll adapt it to become a plugin. p.s.: that little box in homepage at looks like a similar effect. Is it a modified version of my class? Bye Awesome File, very inspirational. Great indeed I loved it. BTW I thought you write unnecessary code there. You’d have a mush faster speedcoding session if you used some other interface for coding. Using eg. Flashdevelop doing imports and declaring vars is done using CTRL-SHIFT-1, then you’ll speedcode at ridiculous speeds. Good advice. I usually use Flex Builder for as3 projects. Not evolved as FTD but a good IDE. However when I just want let random ideas flow, I often use Flash as it lets you just write down some raw/sketch frame code and draw some vector shape. No, it is from Lucas Swick and Don Relyea, called HairParticle. Sorry for the late reply… This is deffiently nice. Thanks for sharing all this talent with us. ^^
http://blog.oaxoa.com/2009/05/05/actionscript-3-speedcoding-video-session-1-black-branches/
CC-MAIN-2017-17
refinedweb
587
67.55
At this point, you've created the initial implementation of the StockWatcher application and it seems pretty stable. As the code base evolves, how can you ensure that you don't break existing functionality? The solution is unit testing. Creating a battery of good unit test cases is an important part of ensuring the quality of your application over its lifecycle. To aid you with your testing efforts, GWT provides integration with the open-source JUnit testing framework. You'll be able to create units test that you can run in both development mode and production mode. In this section, you'll add a JUnit unit test to the StockWatcher project. Note: For a broader guide to JUnit testing, see JUnit Testing.. If you are using ant, replace all references to path_to_the_junit_jar to point to the location of junit on your system. Note: If you just completed the Build a Sample GWT Application tutorial but did not specify the -junit option with webAppCreator, uncomment the javac.tests, test.dev, test.prod, and test targets in StockWatcher/build.xml and replace all references to path_to_the_junit_jar to point to the location of junit on your system before continuing. When you specified the -junit option, webAppCreator created all the files you need to begin developing JUnit tests. It generates a starter test class, ant targets to run the tests from the command line, and launch configuration files for Eclipse. Starting with GWT 2.0, the former command-line tool junitCreator has been combined into webAppCreator. In Eclipse, navigate down to the StockWatcherTest class by expanding the test/ directory. If you are adding JUnit testing to an existing application you will need add the test/ directory as a source folder within you Eclipse project and update your Build Path to include a reference to an existing JUnit library. Take a look inside StockWatcherTest.java. This test class was generated in the com.google.gwt.sample.stockwatcher.client package under the StockWatcher/test directory. This is where you will write the unit tests for StockWatcher. Currently it contains a single, simple test: the method testSimple. package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.junit.client.GWTTestCase; /** * GWT JUnit tests must extend GWTTestCase. */ public class StockWatcherTest extends GWTTestCase { // (1) /** * Must refer to a valid module that sources this class. */ public String getModuleName() { // (2) return "com.google.gwt.sample.stockwatcher.StockWatcher"; } /** * Add as many tests as you like. */ public void testSimple() { // (3) assertTrue(true); } } (1) Like all GWT JUnit test cases, the StockWatcherTest class extends the GWTTestCase class in the com.google.gwt.junit.client package. You can create additional test cases by extending this class. (2) The StockWatcherTest class has an abstract method (getModuleName) that must return the name of the GWT module. For StockWatcher, that is com.google.gwt.sample.stockwatcher.StockWatcher. (3) The StockWatcherTest class is generated with one sample test case—a tautological test, testSimple. This testSimple method uses one of the many assert* functions that it inherits from the JUnit Assert class, which is an ancestor of GWTTestCase. The assertTrue(boolean) function asserts that the boolean argument passed in evaluates to true. If not, the testSimple test will fail when run in JUnit. Before you start writing your own unit tests for StockWatcher, make sure the components of the test environment are in place. You can do that by running StockWatcherTest.java which will execute the starter test, testSimple. You can run JUnit tests four ways: The build.xml file generated by GWT webAppCreator includes three generated targets used for testing: Note: In order to run tests from the command-line, you will need to have JUnit installed on your system. If you just downloaded the StockWatcher project, you must first open build.xml and replace all references to /path/to/junit-3.8.1.jar with the path to junit on your system. ant test.dev [junit] Running com.google.gwt.sample.stockwatcher.client.StockWatcherTest [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 15.851 sec ant test.prod [junit] Running com.google.gwt.sample.stockwatcher.client.StockWatcherTest [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 37.042 sec The Google Plugin for Eclipse makes it easy to run tests in Eclipse. Run As > GWT Junit Test Run As > GWT Junit Test (production mode) You can run unit tests in Eclipse using the launch configurations generated by webAppCreator for both development mode and production mode. Run > Run Configurations... StockWatcherTest-dev -XstartOnFirstThread -Xmx256M Apply Run Run > Run Configurations... StockWatcherTest-prod -XstartOnFirstThread -Xmx256M Apply Run If you want to select the browser on which to run unit tests, use manual test mode. In manual test mode, the JUnitShell main class runs as usual on a specified GWT module, but instead of running the test immediately, it prints out a URL and waits for a browser to connect. You can manually cut and paste this URL into the browser of your choice, and the unit tests will run in that browser. In Depth: To learn how to run unit tests in manual mode, see the Developer's Guide, Creating a Test Case. In a real testing scenario, you would want to verify the behavior of as much of StockWatcher as possible. You could add a number of unit tests to the StockWatcherTest class. You would write each test in the form of a public method. If you had a large number of test cases, you could organize them by grouping them into different test classes. However, to learn the process of setting up JUnit tests in GWT, in this tutorial you'll write just one test and run it. /** * Verify that the instance fields in the StockPrice class are set correctly. */ public void testStockPriceCtor() { String symbol = "XYZ"; double price = 70.0; double change = 2.0; double changePercent = 100.0 * change / price; StockPrice sp = new StockPrice(symbol, price, change); assertNotNull(sp); assertEquals(symbol, sp.getSymbol()); assertEquals(price, sp.getPrice(), 0.001); assertEquals(change, sp.getChange(), 0.001); assertEquals(changePercent, sp.getChangePercent(), 0.001); } [junit] Running com.google.gwt.sample.stockwatcher.client.StockWatcherTest [junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 16.601 sec To see what happens when a unit test fails, you'll reintroduce the arithmetic bug you fixed in the Build a Sample GWT Application tutorial. Originally, the percentage of change was not calculated correctly in the getChangePercent method. To make the unit test fail, you'll break this bit of code again. public double getChangePercent() { return 10.0 * this.change / this.price; } Testsuite: com.google.gwt.sample.stockwatcher.client.StockWatcherTest Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 16.443 sec Testcase: testSimple took 16.238 sec Testcase: testStockPriceCtor took 0.155 sec FAILED junit.framework.AssertionFailedError: at com.google.gwt.sample.stockwatcher.client.StockWatcherTest.testStockPriceCtor(StockWatcherTest.java:38) at com.google.gwt.sample.stockwatcher.client.__StockWatcherTestunitTestImpl.doRunTest(_StockWatcherTest_unitTestImpl.java:7) ... Note: When running from the command line, complete test reports (including stack traces) will be located in the reports/htmlunit.dev/ directory for development mode tests and reports/htmlunit.prod/ directory for production mode tests. [junit] Running com.google.gwt.sample.stockwatcher.client.StockWatcherTest [junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 16.114 sec Best Practices: Because there can be subtle differences between the way GWT applications work when compiled to JavaScript and when running as Java bytecode, make sure you run your unit tests in both development and production modes as you develop your application. Be aware, though, that if your test cases fail when running in production mode, you won't get the full stack trace that you see in development mode. At this point, you've created a JUnit test for StockWatcher and added a simple test case to it. To learn more about all kinds of unit testing in GWT, see the Developer's Guide:
http://www.gquery.org/doc/latest/tutorial/JUnit.html
CC-MAIN-2018-09
refinedweb
1,311
58.69
User:Fasten/TestWiki From OLPC TestWiki as been added as a request for enhancement to the Wikimedia bugtracker: #17129 TestWiki The TestWiki (working title) will allow to generate multiple-choice tests and other tests in a wiki and to annotate those tests publicly or privately using the wiki syntax. Tags of the TestWiki syntax will be in their own sub-namespace "Test": {{Test::Tag}} Question types Question types will include multiple-choice, grouping, table choice, ordering and comparison with expressions. A complex question will be able to combine several questions types (e.g. making a comparison the right answer in a multiple-choice test or a multiple-choice test inside an ordering question, possibly with different choices depending on the order of items) The software will be able to ask questions out of order and will keep track of successful answers to questions, showing successfully answered questions less often. The software will also be able to mix questions from several modules. Questions will allow to specify a pool of right and wrong answers from which only a small subset is shown in each test question. The order of the questions will also be permuted randomly. (Answering the test isn't learned based on the structure and layout of the test). Categories TestWiki will allow to group tests into course modules with the module tag: {{Test::Module|<page>}} The module tag marks content as part of a course module which is described on the wiki page <page>. Additionally test authors and users will be able to add their own non-standard categories independently. (Every user will have his own namespace of categories and will be able to ignore author categories.) Module page A module information page can use the following tags: {{Test::Topic|<name>|<description>}}- the topic of a module {{Test::Publisher|<name>|url=<url>}}- the publisher of a module {{Test::License|<name>|url=<url>}}- the license for a module {{Test::URL}}- the home page of a module (e.g. a wiki that publishes the test) {{Test::Version|<major>|<minor>|<patchlevel>|<date>}} {{Test::Module|<page>}}- a containing module, unspecified information are inherited from this module. {{Test::}}-tags will be invisible or appear as customizable markup when a test page is displayed with the MediaWiki software. - {{Test::Item|<name>}} is the beginning of a test item. - Parameters: - difficulty - the difficulty parameter assigns a numerical difficulty between 0 and 0x7fffffff (usually 0 to 10). - option - the option parameter can specify an identifier (a short word) that can be used to add or remove the question from a test scenario (as an option). - {{Test::Q|<id>}} is the beginning of a question. A test can have several questions in order to phrase the same test item in different ways. Each question is followed by its own list of answers. - {{Test::A|<id>}} is the beginning of an answer to the previous question. Test format Tests will be formatted in XML in order to allow a well-defined and exchangeable database format for test databases. Templates could optionally generate XML tags, so the generation of the test database would be a simple extraction of tags from a special output form of the wiki page. Testing Users can add their own comments in wiki format but during a test comments are only shown after a question has been answered. During a test conducted by a teacher the database of comments could be temporarily disabled or the pupils may be using a different computer. Quiz extension The syntax could be combined with that of the Quiz extension.
http://wiki.laptop.org/index.php?title=User:Fasten/TestWiki&oldid=223978
CC-MAIN-2016-07
refinedweb
590
50.06
Proposal will help New Delhi save on foreign exchange as it pays Tehran in rupee As its current account deficit widens and the value of the rupee dwindles, India plans to increase crude oil imports from Iran so as to save $8.5 billion in foreign exchange. Petroleum and Natural Gas Minister Veerappa Moily has sent the proposal to Prime Minister Manmohan Singh. Yielding to sanctions imposed on Tehran by the U.S. and the European Union so as to force it to roll back its nuclear programme, India slashed crude imports from Iran by 26.5 per cent during 2012-13, buying just 13.1 million tonnes, against 18.1 million tonnes the previous year. In his note to Dr. Singh, Mr. Moily said that in the remainder of the year, the country should import 11 million tonnes so as to save $8.5 billion on foreign exchange. New Delhi, which spent $144.29 billion for oil imports last fiscal, pays Tehran in rupee, unlike other countries. Officials in the Petroleum Ministry said about two million tonnes had so far been imported from Iran. Import of an additional 11 million tonnes would help to cut the foreign exchange outgo by $8.47 billion (given that crude rules at $105 a barrel). Because of the sanctions, India pays Iran in rupee through a UCO Bank branch in Kolkata. Since July 2011, India had been paying Iran through the Ankara-based Halkbank in euro for 55 per cent of its oil purchases. The rest was remitted in rupee in the accounts of the National Iranian Oil Company in UCO Bank. However, payments in euro ceased on February 6. Iran was India’s second biggest supplier after Saudi Arabia in 2010-11. However, during 2012-13, it supplied only 13.1 million tonnes, lagging behind Saudi Arabia, Iraq, Venezuela, Kuwait and the United Arab Emirates. In 2011-12, Iran stood third with 18.1 million tonnes, against 32.5 million tonnes from Saudi Arabia and 24.1 million tonnes from Iraq. In 2009-10, it supplied 21.2 million tonnes. During 2012-13, Iranian supplies accounted for 7.2 per cent of India’s oil imports, down from 10.5 per cent during 2011-12. Keywords: subsidised fuel sale, Veerappa Moily, Manmohan Singh, oil manufacturing companies, global oil prices Even after 67 years of our independence we are toeing the line of US and UK .It is evidence of failure of our foreign policy and no coordination with ministries of commerce, petroleum, steel etc. There is no plan to execute the vision statement of ministry of commerce. Economy and Geo-Politic go hand in hand is a fact our leaders fail to appreciate and acknowledge. We are sleeping over North sea and the Arctic exploration. Back home CAIRNS is still waiting for the clearance People who are saying iran is the true friend of india shouldn't forget that iran too used to accept payments in us dollars.....the economic sanctions put up by the US and EU forced it to shed the payments in dollars or euros( the decision to accept ruppes was not voluntary). It is good that India has to do away with hard currency of US Dollar. Oil Payments in Indian Rupees will increase trade between Iran and India. Current Account deficit can be tide over with proper planning. That's not just a good decision but also a slap on america....India is not puppet of america and india should do what benefits them....go India go.... Good move if it happens. While US and their allies base their own national intersts for each and everything they do, the developing countries like India are forced to be a pray for their needs, by sacrificing our own requireemnts. I wish Mr Moili will proceed with this proposal as this will help the general public a lot, and also to save our rupees. This move should have been embraced to when this crisis was gathering momentum.Given the shortage of strategic petroleum reserve in India and volatility of it's currency it,in the first place,should not have reduced it's import from the country which was being paid in Indian rupees. Indian policy makers should take some cues from their chinese counterpart who even in the wake of sanctions imposed by U.S.A and European union continued the import of crude oil from Iran unabated. Paying price because of government stupidity. But we need to give another chance to this same party, otherwise new party will start blame game and result in nothing. Let them correct their worst performance themselves Ministry of Petroleum has taken a right decision by increasing the oil import from Iran. USA's basis of foreign policy is national interest and this applies to all nations. Need of hour is to maintain the previous import quota from Iran. If we continue to tow USA line our foreign policy will be compromised and national interest harmed. Americans have problem from Iran for various reasons which may also be applied to India. Iran is a threat to Israel and USA is bound to support Israel as millions of Jews are living in America and they are working pressure on America. How is India concerned with this equation ? Why should India buckle under pressure from USA. Who is now the friend of India Iran or US?Iran only since Iran accepts our rupee payment for import of oil from them.Hence India must do all its possible help to Iran in all ways of extending our know how in IT, export Rice and wheat and other basic products on rupee paymet or exchange of oil imports, since US has to be paid only in DOllar, valueable foreing exchange we now need to strengthen our rupee.Once govt/p[eople boycott all foreign goods as we did during our Indepenance struggle by Mahatma,and use only our indian pructs, discard all wall mart and any foreing establishmet and their products, we bring back the value of rupee shortly,Let their unity amongst all indian and those who are not,discard them in society itself. I think its a good idea to import from Iran. India's energy requirements are not going to fall and importing from Iran going to give us a cushion against falling rupee. The money used to import oil is taxpayer's hard earned money and wasting it just because of falling rupee is no intelligence. Iran may be able to use the rupee they accumulate to purchase medicines or other necessities from India. Now India should bargain with more gulf countries to sell fuel for Indian rupee. the exports we make to gulf for Indian diaspora working in gulf can be paid back in rupees. How many times has it not happened in the past decade, we have always been the puppet operated by the Uncle Sam economy. Its still not that far, for we can promote our products (driven to World Class Quality) & hence achieve an economy with strong immune against the global downturn. This can only be achieved when the Govenance subsidises indian Industries & trains the Labour class to International standards. This can only be achieved with great level of maturity with Indians as a customer & a service provider. Indian Govt should consult and get proposals from all the IIM /IIT institutes to control and improve the economy , As they have launched for their rupee design and then they should formulate strategies bring back Rupee value against dollar during Nehru period Slashing oil imports for Iran was undergoing a nuke program is an absurd reason for Indian Government. While it forgets that even we were in line to be a nuke superpower sometime in past and it is necessary for security and peace at world level. Back to economic point of view, this decision will provide huge relief to Indian foreign reserves at the time when our economy is shattered the most. Though it may not please some of the westerners but one cannot make happy everyone happy all the time. Its time for some historic and neck breaking decisions for our good. its not INR because in world trade $ is much more valued than that of the Indian Rupee. But I am unaware of Indian trade with Iran in INR, I wonder would Iran give INR back to India for its imports or would the INR be converted to their currency or sth else? @vyasan - Iran buys goods and services from India, so there is no problem for our two nations to use the Indian Rupee in bilateral trade. There is no need to depend on a third currency in this case. This should have been done in forethought, not in afterthought. There was absolutely no strategic reason for India to toe the USA's line, ever. Hopefully this will open some eyes and shut some mouths that wanted to "wean" India off Iranian oil! This could be a significant step in controlling the fall of Rupee. India is finally waking up to address its own issues first before bowing to international pressures. Buying oil from any other country requires dollars but Iran sells oil in exchange for Rupee. Really a good move. At last the govt has waken. If this decision had been taken long before we wouldn't have been in such a pathetic situation. Our country should have considered this before reducing the imports from Iran because of US. US should not have influence on our policy/decisions. We should stick to our Non Aligned Movement-Policy. Lets hope for the best on Iran decision on this. I wonder what does Iran plan to do with the Indian rupee hoard that no other country in the world will accept for any purchase. Indian import of Indian goods is small compared to its oil export revenue. Unless Iran is willing to dramatically increase its imports of Indian goods and agricultural produce there is little long term future for such rupee trade. I will believe it when this happens, Iranians are not stupid. Lets see if they have the determination to do this and defy the Uncle Sam's order. Your headline sounds as if India is being "driven" to resort to an undesirable, horrible Iran, much against its wishes. Instead of making it a marriage of convenience, secretely under fear of the US dictators and sanctioneers, it is wiser for both the emerging economies to develop a full-fledged relationship in various fields of business and commerce. Sooner or later, many other sovereign nations would also like to get independent of the USD. Nothing better than getting out of the clutches of the US that tries in ever so many subtle and not-so- subtle ways to exploit and extort weaker countries and currencies Necessity is d mother of innovation.such innovative ideas are most welcome at such a critical scenario of indian economy @vyasan; "why do the iran government accept indian rupee instead of dollar or euro? Where do they spent the collected indian rupees? Can they purchase anything from any other nations using this rupee?" The Iranian government would accept Indian rupees to buy goods from India. This essentially amounts to barter, which essentially means to eliminate middle men. The Iranian government has been working for 25 years to eliminate middle men who end up pocketing nearly 20% of oil revenues. There are basically three types of middle men in the oil trade. Currency manipulators, insurance companies and the transporters. India needs to emulate Chinese policies. manufacture A to Z locally. no more imports. Export surplus. Generate employment- bring down inflation -Target 10% growth. Bring back money from swiss and other foreign banks, Use the gold lying dead stocks in the temples - by using it as collateral for generating economy. No more religion in politics. Less talk more work. work is worship. quality no compromise. Research and developt in every area of operations. E-governance to be mandatory to cut down on man power in govt offices. Corruption should be zero level. crisp-efficient-clean -transparent -result oriented governance needed. Build grass root economy start from the villages. Emphasize on only ECONOMY -ECONOMY AND ECONOMY. Buy oil and gas using Indian currency-barter exchange -no more dollars till we evolve strong. The Indian government has got its calculations wrong. The whole thing will sour as happened in the case of the former Soveit Union with Soveits selling huge quantities of items and accumulating a huge balance in Rupees but India not being able to clear the account. In the end India had to settle the deficit with dollars. Iran sells oil and will accumulate a huge balance in rupees which India will not be able to clear as Iranians are aghast at the quality of Indian goods and prefer western or Japanese goods. Recent example is milk powder which was rejected by the Iranians. The Iran based Hindujas have tried to sell trucks and cars plus parts to the Iranians during the last 30 years.Hindujas have employed European based former Iranian diplomats at astronomical fees to lobby on their behalf and get huge projects but the money has gone waste. Other then false propaganda in newspapers of big Iranian projects Hindujas have acheived nothing and nothing will be acheived by the Indians in Iran Go India Go... Such bold steps are the need of the hour..!! Inflation needs to be tackled at all costs..this is the biggest problem since several decades..Even countries like Ukraine have managed to reduce the inflation levels and now their economy is growing in a healthy manner..Building infrastructure to improve exports & building more Nuclear Plants(one in every state) to control crude consumption could help in improving the Forex levels.. A bold decision. Dollar monopoly needs to be driven out. Another short sighted approach ... Instead of boosting the use of hybrid cars , renewable energy and solar power they are turning to Iran. Now get ready for sanctions from other countries. Good Decision. If such a option was available this should have been taken a bit earlier. Anyway, 'better late than never'. We all know that weak kneed GOI broke a very advantageous deal with Iran last year to placate USA. Do you really think this government will have guts to go for Iran when US is eyeing its petro fortune? Just to make us fools. The headline looks critical. This is an action our government should have taken long ago. Iran was is not our enemy and the purchase would also benefit Iran. So a win win situation. Wise though belated decision. The step is quite interesting and it is the basic norms of a nation to adopt the strategic decisions according to the situation wants & warrants. What is the world politics? Is it standing on the queue to vote in favor of the big brothers of the governing group? The Iranian government was very keen & flexible to keep up our credibility to have strategic long term bonding to strengthen the bilateral relationship as well as the national striving ecosystem. If we were responded positively economically a great leap could have happen in terms of the dollar reserves in-addition to huge export openings. There were crystal clear chances to accept the India rupee instead of US dollars on other hand India had the opportunity to fulfill the Iranian domestic requirements. These two ways favorable operational advantage could have boost the economy against the disastrous current scenarios. At this scene we as a responsible citizens, strongly endorse the initiative of PNG minister V. Moily. A correct decision by Indian govt.Why india should pay more if it can procure petrol in less prices.India should surely go ahead with this decision Ideally such measures should have been taken before getting into current economic diaspora, however let’s hope this measure help us to strengthen our currency value. While the current violent massacre of innocents in Syria are condemnable by all, the rest of the world must call for atleast a temporary moratorium on transactions with US and US interests if it anymore tries to foist its vested interest under the guise of humanitarian aid and democracy and at the expense of international comity of nations and violation of UN Charter by unilaterally causing further turmoil in the middle-east or anywhere in the world. US will cause to aid the spiraling rise of crude oil prices by its precipitated war action which intentionally or otherwise only benefit US State Oil companies revenues and US Weapons Manufacturing lobby that largely funds US elections. It is hightime that the UN, World Bank and IMF are re-structured in the process to have developing nations and receipients regcognised as true partners in progress and not cater to imperialistic actions and become colonial era dumping grounds of Western products and services or that of war weapons. Why not buy oil from each of the countries in the currency of that country or INR. Why trade in dollars? If this is going to help retrieve the sagging economy, why wasn't it done earlier? If current account deficit narrows down appreciably by direct purchases from Iran, why wasn't the foreign policy so regulated to ensure that Indian economy does not get trapped in this bad situation. Means, our policy planners have failed the country on more than one account. The left hand does not seem to know what the right hand is doing? This is terrible. Do whatever is necessary. Don't buckle under US pressure for everything. You can't bring country to the brink of economic disaster to appease Americans. Regional cooperation should be the new focus of our foreign policy. Economy should take precedence over everything else. Don't allow Pakistan to slip out of your hands. Improve ties strengthening economic cooperation. Help Pakistan recover. That will be in our interests too. The days plenty of everything especially of those commodities that we have to depend on outside resources is gradually coming to close. Every citizen must seek what is absolutely required for a decent living.By containing our need strictly to essentials will stabilize not only cost but also the availability. Tougher days are ahead for all. This approach was discovered only now?!! I got a doubt, why do the iran government accept indian rupee instead of dollar or euro? Where do they spent the collected indian rupees? Can they purchase anything from any other nations using this rupee? This is called realpolitik. So instead of listening to what US wants us to do, we're finally being forced due to our own situation to do what is needed. Hopefully, the Govt. will keep that in mind when it tries to do something good for the USA than ourselves Should have happened long ago, but the government was occupied with trivia and selling populist programs. Why can't he decide himself rather then sending a note to the PM ? After all D Raja the former Telecomm minister acted without informing Mr Singh ! Please Email the Editor
http://www.thehindu.com/news/national/crisis-drives-india-to-turn-to-iran-for-oil/article5083472.ece
CC-MAIN-2015-18
refinedweb
3,189
64.51
Craps November 4, 2011. Tried my hand at a Common Lisp solution. Wow, that might be the first R solution I’ve seen posted here. Makes sense, though, if you’re working with random variates and statistics. If there’s a way to vectorize the code, I don’t see it; so far the only thing I came up with was roll <- sum(sample(1:6, 2, replace=T))(which isn’t very impressive). Graham, I think it does help though.. That solution is approaching novel lengths.. Do you guys see GDean’s R code as properly indented? For me it’s flush left in both Chromium and Firefox. This happened to me previously even though I used the advertised sourcecode tags that used to work. The HTML source for the R code is indented but the whitespace is not preserved. Jussi: as far as indentation goes, I usually post longer solutions offsite (github, codepad, etc.) and for shorter ones follow the instructions in the HOWTO link at the top of this page. I fixed the comment formatting. I changed < and " to their ascii equivalents, added a [sourcecodx lang=”css”] to the top of the code, and [/sourcecodx] at the bottom of the code (note that I purposely mangled the word sourcecodx to prevent WordPress from writing my comment incorrectly). Looks fine to me. Jussi: Only a small number of languages are directly supported by the sourcecodx tag. You may have said something like [sourcecodx lang=”fortran”]. I just looked at the WordPress support page linked in the HOWTO, and it appears they have added more languages since I wrote the HOWTO, and also added a feature for “plain text” source code: just say [sourcecodx] with no language parameter. I just checked by editing GDean’s code — that works, too. It’s too bad WordPress doesn’t support the <pre> tag. Graham: Unless the code is extremely long, it is better to have it here than elsewhere. In the first place it is more easily seen (I checked the stats — 110 people saw your comment, but only 9 clicked the link), and in the second place you can interrupt the code with annotations, as I frequently do in my suggested solutions. Thank you, praxis, GDean’s R code looks good now. My unindented Python code is in the McCarthy thread. I said [sourcecodx lang=”python”] — [/sourcecodx] unless I mistyped something (clever “x”) and python is listed as supported in the “how topost source code” page. Here, let me just try to see if it works: (Sorry about the off-topic code.) Ok, looks good. Probably I have mistyped something when I submitted the McCarthy entry. Sorry for the noise. I fixed your McCarthy entry. It doesn’t look like you mistyped anything. I changed “lang” to “language” and it worked fine. I’ve seen this problem before, and don’t know how to deal with it. Sometimes “lang” works, and sometimes “language” works. I have no idea why. The workaround is probably to just ignore the language parameter and bracket your code with [sourcecodx] … [/sourcecodx] tags. You will lose the clever language-based formatting, but that should work with anything. The other approach is to format your code for html using the “foo-to-html” translator on the HOWTO page. That’s what I do for all the code presented in the suggested solutions. It’s inconvenient, but makes the code more integral to the running text. Private emails to me have one overwhelming complaint: readers can’t edit their own comments. I’ve considered moving from the WordPress comment forums to DISQUS, but haven’t done it because managing one blog is hard enough, and managing two things would doubtless be harder. Does anyone have experience with DISQUS? The HOWTO page seems to suggest that HTML code tags work in this comment box. I just experimented with HTML style attributes, where style="white-space: pre"should preserve all whitespace. It worked in my tests. If this comment box allows both the code tags and the attribute, the following test code appears properly indented without any special markup in the code itself: (define (gcd m n) (cond ((< m n) (gcd m (- n m))) ((< n m) (gcd (- m n) n)) (else m))) If not, not. I think it stripped the attribute out. Just one repeat to test that I did not forget to type it in. And why would it preserve linebreaks then? Also, I’m now replacing the less-than signs with the entity, which I did not do above. (define (gcd m n) (cond ((< m n) (gcd m (- n m))) ((< n m) (gcd (- m n) n)) Without the style attribute but with the non-breaking spaces suggested in the HOWTO, and nothing about linebreaks: (define (gcd m n) (cond ((< m n) (gcd m (- n m))) ((< n m) (gcd (- m n) n)) Ok, it seems like specifying the white-space style as pre or pre-wrap for the code element should work since the software recognizes the code tags. It does not preserve the style attribute, however, and I failed to find out how it manages to obey line breaks in code while ignoring indentations. Wait. I did not fail to find out. It adds br-elements at line breaks inside code elements. It’s doing too much and too little at the same time. So we continue to indent the hard way. Ok. When I first started the blog, I spent a day experimenting, as you have done. I’m pretty sure the choices are what I listed in the HOWTO, except that now WordPress seems to handle a [sourcecodx] . . . [/sourcecodx] without a language designator as plain text, which it did not do back then. I’ll add that to the HOWTO. Thanks for trying, Phil Here’s some on-topic code, indented with sed as in the HOWTO page. The rules of the game are encoded in a generator that produces one game. >>> seed(exp(1)) >>> list(game()) [(6, None), (9, None), (4, None), (4, None), (6, 'win')] The log odds (meant to be to the base that Turing and Good used) thing is sometimes positive, sometime negative, which seems to suggest that the game is more or less fair. >>> logodds(100) 0.17374096069422723 >>> logodds(100) -0.6963592814139442 This is Python 3. The magic keyword is yield. A couple of the generator things below produce indefinitely long sequences. In theory, gamecould do so but in practice it of course never does. It is safe to ask for the next game, or the next grade, or the 100 next games as above. from random import seed, randrange from math import exp, log10 from itertools import islice def die(): return 1 + randrange(6) def game(): # graded shots of a single game shot = die() + die() grade = ( "loss" if shot in (2, 3, 12) else "win" if shot in (7, 11) else None ) yield shot, grade point = shot while not grade: shot = die() + die() grade = ( "win" if shot == point else "loss" if shot == 7 else None ) yield shot, grade def games(): # graded games, indefinitely while True: shots = list(game()) yield ( [ shot for shot, grade in shots ], shots[-1][1] ) def grades(): # grades, indefinitely for shots, grade in games(): yield grade def logodds(n): # 10 log10 (wins / losses) in n games iswin = lambda g : g == "win" wins = list(filter(iswin, islice(grades(), n))) return 10 * log10(len(wins) / (n - len(wins))) This can be done in Scheme but it would be a much longer story. Python has these built-in. Since we’re discussing it, and just to put us back off topic again (sorry), I would like to point out that perl is another supported language by whatever is handling the attribute. The HOWTO seems to leave it out, but I’ve posted several perl sources this way I agree with Jussi on the usefulness of yieldand generators in Python; if I have time, I’ll post a Python version myself later. A Clojure solution:
http://programmingpraxis.com/2011/11/04/craps/?like=1&source=post_flair&_wpnonce=e5382928c8
CC-MAIN-2014-52
refinedweb
1,333
79.9
Given a function ‘int f(unsigned int x)’ which takes a non-negative integer ‘x’ as the input and returns the value where f() becomes positive for the first time Example INPUT: f(x) = x^2 – 4x -8 OUTPUT: The value x where f(x) becomes positive is 6 Time Complexity: O(logn) In this method the main idea is to apply binary search, but for binary search we need low and high values. Below algo shows how to find the values and implement binary search. Algorithm 1. Till f(i) is greater than zero, double the i value. Once f(i) is greater than zero, then take i as the high and i/2 as the low. 2. Now search for the first positive value of f(i) in between i/2 and i. Binary search 3. Till high greater than or equal to high, find the mid a. If f(mid) is greater than zero and mid is equal to low or f(mid -1) is less than or equal to zero ie, f(mid>0) && (mid==low || f(mid-1) <=0), then return mid b. If f(mid) is less than zero, then search in the right half recursively. c. If f(mid) is greater than zero, then search in the left half recursively. C++ Program #include <bits/stdc++.h> using namespace std; int binarySearch(int low, int high);//declaring //function f(x) int f(int x) { return x*x - 4*x -8; } //prints the value x void printFirstPositive() { if (f(0) > 0)//if for 0 f(x) >0, then 0 is the answer { cout<<"The value x where f(x) becomes positive first is 0 "<<endl; } int i =1; //finding low and high for binary search while(f(i)<=0) { i = i*2; } cout<<"The value x where f(x) becomes positive first is "<<binarySearch(i/2,i)<<endl; } //binary search implementation int binarySearch(int low, int high) { int mid = (low + high)/2; while(high>=low) { if ((f(mid)>0) && (mid==low || f(mid-1)<=0)) { return mid; } else if(f(mid)<=0) { return binarySearch(mid+1,high); } else { return binarySearch(low, mid-1); } } } int main() { printFirstPositive(); }
https://www.tutorialcup.com/interview/array/monotonically-increasing-function.htm
CC-MAIN-2020-10
refinedweb
361
63.02
Talk about synchronicity, the day I post this article the CCR and DSS become a downloadable product. You can find the new product here. I suggest you watch this product, I suspect this to be a corner stone in concurrent .NET software development. I often revisit applications I've written to improve areas of the code with ideas and lessons I pick up over time. There seems to always be one primary goal and this is to improve performance. When it comes to improving performance there are many things you can do, but in the end you'll always look to multithreading. It's theoretically the simplest suggested concept but not always the easiest to implement. If you've ever run into resource sharing problems you'll know what I mean and although there are many articles on how to do it, it doesn't always mesh with every solution. Sometime ago I came across something called the CCR, it was like magic code created by two wizards, Jeff Richter and George Chrysanthakopoulos. Part of the magic was to properly roll the syllables in Chrysanthakopoulos neatly off your tongue in one breath and when you get past that you'll see the light at the end of the multithreaded hallway of horrors. This managed DLL is packed with oodles of multithreaded fun and provides many levels of simplicity to common threading complexities. In other words, if you want to improve performance of your applications by implementing a multithreaded layer then you need to live and breathe the CCR. For some great background and fun, grab some popcorn and visit Jeff and George at this link. After watching the video cast, you should come away with some confidence and revelation along with some courage to start using the CCR. So you'll open up your latest project and... where do you start? Well one place you can start is by creating a simple asynchronous logger. Most applications I design have varying levels of logging for production diagnosis, but if you don't use a threaded model when utilizing your logger class then you've created blocking code and obvious room for improvement. So to get you started, I'll show you how to implement a CCR'd logger class that writes to a local file. There are many ways to log data but for this demo I'm using simple local logging. You will most likely be interested in this article; it will explain the many faces of the CCR. The following code can be dropped into your application and be utilized right away and although basic, it can act as a replacement for any logging methods you currently implement. The first thing we need to do is to new up something called a Dispatcher, think of this as the thread "pool". Notice the "1", this means we only want one thread handling these calls therefore all "posts" to the class will execute async but sequential. If you're writing to a SQL database you can try increasing this number but be aware that data may not arrive sequentially! When utilizing a dispatcher for other non sequential tasks, try increasing this number. Dispatcher 1 //Create Dispatcher private static readonly Dispatcher _logDispatcher = new Dispatcher(1, "LogPool"); Secondly you'll want a DispatcherQueue. The DQ manages your list of delegates to methods, methods you need to execute when needed. DispatcherQueue //Create Dispatch Queue private static DispatcherQueue _logDispatcherQueue; Next you need a PORT, ports are like input queues. You'll "post" to ports to invoke your registered methods. //Message Port private static readonly Port<string> _logPort = new Port<string>(); Now for the class, don't forget to include the CCR in the directives! using System; using System.IO; using System.Threading; using Microsoft.Ccr.Core; namespace CCRing_Demo { public static class DataLogger { //Create Dispatcher private static readonly Dispatcher _logDispatcher = new Dispatcher(1, ThreadPriority.Normal, false, "LogPool"); //Create Dispatch Queue private static DispatcherQueue _logDispatcherQueue; //Message Port private static readonly Port<string> _logPort = new Port<string>(); //Fields private static string _logFileName; private static void Init() { _logDispatcherQueue = new DispatcherQueue("LogDispatcherQueue", _logDispatcher); Arbiter.Activate(_logDispatcherQueue, Arbiter.Receive(true, _logPort, WriteMessage)); _logFileName = "DMT_Message_Log_" + String.Format("{0:yyMMddHHmmss}", DateTime.Now) + ".log"; } private static void WriteMessage(string messageString) { using (var sw = File.AppendText(_logFileName)) sw.WriteLine("[{0:HH:mm:ss tt}] {1}", DateTime.Now, messageString); } public static void Log(string messageString) { if (String.IsNullOrEmpty(_logFileName)) Init(); _logPort.Post(messageString); } //Any thread tasks still running? private static bool PendingJobs { get { return (_logDispatcher.PendingTaskCount > 0 || _logPort.ItemCount > 0) ? true : false; } } //Since we are not using background threading we need to add this method to //dispose the DQ for application end public static void StopLogger() { while (PendingJobs){Thread.Sleep(100);} _logFileName = null; _logDispatcherQueue.Dispose(); } } } The CCR doesn't come with the latest version of Visual Studio. It's part of the Microsoft Robotics Studio but instead of downloading the entire studio, I've included the DLL above so you can add it as a reference to your project. One thing you should notice from the code above is the lack of callback nesting that is involved here, truly a nice model. Also, if you're using background threading your primary/initial thread will wait on the Dispatcher, even if all Queued posts are completed. You can handle this in a number of ways, such as newing up the Distpatcher without background threading but in this case you'll want to check to make sure all jobs are completed with PendingJobs. Distpatcher PendingJobs Although this class is fairly simplistic in its design and purpose, you should at least come out seeing the power the CCR holds with just a few lines of code. Step through the code and add some additional ports for fun. The more you understand the CCR the more you'll see how it can improve just about any application you write from here forward. Happy CC.
http://www.codeproject.com/Articles/30519/CCRing?fid=1529462&df=90&mpp=25&noise=3&prof=False&sort=Position&view=Quick&spc=Relaxed
CC-MAIN-2015-18
refinedweb
984
62.98
How to auto rotate the image using Deep learning!!! 5 simple steps to auto rotate the image to get the right angle in the human photos using computer vision: - Read the input image. - Detect Face by Caffe model. - If the face is not detected then rotate the image. - Again detect face with rotated images. - Rotate the image with three angles until face detect. Before going to implement this technique we will see what are the dependency library and model needed. - OpenCV - Numpy - Caffe model(Deep learning) Step 1:- Import all the above required libraries. import cv2 import numpy as np Step 2:- Download the Caffe model and file and prototxt file. Let us see why we need those two files and what that is. What is the Caffe model file? Caffe is a deep learning framework developed by the Berkeley Vision and Learning Center (BVLC). It is written in C++ and has Python and Matlab bindings. After training the model with our data set, we will get the trained model in a file with an extension. What is deploy.prototxt file? The prototxt is a text file that holds information about the structure of the neural network: A list of layers in the neural network. The parameters of each layer, such as its name, type, input dimensions, and output dimensions. The connections between the layers. That prototxt file is only to deploy the model and cannot be used to train it. Step 3:- This is the main method to read an image file using OpenCV. Then pass image into detect_face method(Step 4) it will give you True(Detected) or False(Not Detected). If it returns FALSE then the image is not the correct angle hence we need to rotate the image angle as per below angles step by step. Rotate Angle -> 90 -> 180 -> 270 def main(): frame = cv2.imread(‘6.jpg’) original_status = detect_face(frame) (h, w) = frame.shape[:2] # calculate the center of the image center = (w / 2, h / 2) scale = 1.0 angle_90 = 90 angle_180 = 180 angle_270 = 270 if original_status is None: status_90 = rotate_image(frame,center,scale,angle_90) if status_90 is None: status_180 = rotate_image(frame,center,scale,angle_180) if status_180 is None: status_270 = rotate_image(frame,center,scale, angle_270) Step 4:- Here is the detect_face method to detect face using the Caffe model. We can use OpenCV dnn module to read Caffe models using the readNetFromCaffe method. Then convert our image into the blob to pass neural network based on output weight it will return probability values. I have used 0.7 as min accuracy values. if the value is more than that we can detect face images. The Caffe model was trained by right angle faces images so it will detect only if the face image is the correct angle. def detect_face(frame):net = cv2.dnn.readNetFromCaffe(‘deploy.prototxt’, ‘res10_300x300_ssd_iter_140000.caffemodel’) (h, w) = frame.shape[:2]blob = cv2.dnn.blobFromImage(cv2.resize(frame,(300,300)), 1.0, (300,300), (104.0,177.0,123.0))net.setInput(blob)faces = net.forward()for i in range(0, faces.shape[2]): confidence = faces[0,0,i,2] if confidence < 0.7: continuebox = faces[0,0,i,3:7] * np.array([w,h,w,h]) (startX, startY, endX, endY) = box.astype(‘int’)text = “face “ + “{:.2f}%”.format(confidence * 100)cv2.imwrite(‘test.jpg’,frame) return True Step 5:-Let us see how to rotate the image using OpenCV. def rotate_image(frame,center,scale,angle): (h, w) = frame.shape[:2] M = cv2.getRotationMatrix2D(center, angle, scale) frame = cv2.warpAffine(frame, M, (h, w)) return detect_face(frame) Conclusion That’s it. You made it!! Finally, you can see the correct angle image. Happy Learning to all!! if you need any help or assistance please connect with me on LinkedIn and Twitter.
https://medium.com/analytics-vidhya/how-to-auto-rotate-the-image-using-deep-learning-c34b2e0e157d
CC-MAIN-2021-04
refinedweb
627
60.21
ADC change the attenuation level to 11dB - overlander last edited by Hi, I'm using wipy 2.0 with the expansionboard that measures the battery voltage on P16.I want to detect whether the wipy is powered from external powersource or if its running on battery. When I read the value i always get 4095,the highest value from 12 bit range.So I tried to change the attenuation level to 11db that allows 3,3V input voltage to get a lower reading. When I do: apin = adc.channel(pin='P16',attn='ADC.ATTN_11DB') an Type Error: Cant convert string to INT appears! Has somebody sucessfull changed the attenuation level on the adc? Can please somebody tell me how this right. - overlander last edited by @robert-hh thank you for your quick reply.I see it-the quotes are wrong :( @overlander The error message is quite clear, the way of telling maybe confusing: from machine import ADC adc = ADC() apin = adc.channel(pin='P16',attn=ADC.ATTN_11DB) See:
https://forum.pycom.io/topic/2086/adc-change-the-attenuation-level-to-11db
CC-MAIN-2021-43
refinedweb
168
66.33
Over the last several lessons, we've learned quite a bit about API calls. We've learned what they are and how to make an API call using Postman. We also took a more in-depth look at working with and parsing JSON. The skills we've covered so far are applicable for working with APIs no matter what programming language you use. Whether you are writing in Ruby, JavaScript, C#, or another language, there are tools for making and receiving requests and then parsing JSON or any other type of data the API returns. Now we are ready to build out a JavaScript application that will make an API call. There are many different ways to make an API call in JavaScript ranging from using vanilla JavaScript to jQuery to using other tools that vastly simplify making API calls. We will use a vanilla JavaScript approach in this lesson. In later lessons, we will rewrite our code to make our API call in different ways. In the process, we'll also learn different tools for working with asynchronous code. After all, APIs are async. While we will only be learning how to apply async tools to API calls in this section, the async tools we learn can also be used for other asynchronous JavaScript operations as well. However, we're not quite ready to jump off the async deep end just yet. In this lesson, we are making an API call the old-fashioned way - with just vanilla JavaScript. All the tools that jQuery uses to make API calls are based off this old-fashioned way. But we won't be covering the jQuery approach in this section because there's an even better approach called the Fetch API. Fetch is also built on top of this old-fashioned way. So while you may not be using this approach for this section's independent project (you can if you want!), you will have a better understanding of how tools like Fetch work when we actually use them later in this section. We will not include all the code for building out our environment below. However, the repository at the end of the lesson has the sample code below in a fully functioning webpack environment. If you build out this project yourself, you should include a webpack environment - whether you want to build that yourself or use the repository at the end of the lesson. Note that because we aren't testing, we don't need a __tests__ directory. For now, we also don't need a js directory. All of our JS code in this lesson will be in main.js - the same naming convention we've been using with webpack projects. So for the code example below, we really just need to look at two files: index.html and main.js. Let's start with the HTML, which is very simple: <html lang="en-US"> <head> <title>Weather</title> </head> <body> <div class="container"> <h1>Get Weather Conditions From Anywhere!</h1> <label for="location">Enter a location:</label> <input id="location" type="text"> <button class="btn-success" id="weatherLocation">Get Current Temperature and Humidity</button> <div class="showErrors"></div> <div class="showHumidity"></div> <div class="showTemp"></div> </div> </body> </html> We have a simple form input for a location. We also have several divs for showing errors, the temperature, and the humidity. Now let's look at the code for the API call: import $ from 'jquery'; import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './css/styles.css'; $(document).ready(function() { $('#weatherLocation').click(function() { const city = $('#location').val(); $('#location').val(""); let request = new XMLHttpRequest(); const url = `{city}&appid=[YOUR-API-KEY-HERE]`; request.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { const response = JSON.parse(this.responseText); getElements(response); } }; request.open("GET", url, true); request.send(); function getElements(response) { $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`); $('.showTemp').text(`The temperature in Kelvins is ${response.main.temp} degrees.`); } }); }); We start with our import statements. We have a click handler that grabs a city value from a form, stores that value in a variable called city, and then clears the form field with $('#location').val("");. This part is all review. The new code starts with the following line: let request = new XMLHttpRequest(); We instantiate a new XMLHttpRequest (XHR for short) object and store it in a variable called request. The name XMLHttpRequest is a bit misleading. These objects are used to interact with servers - exactly what we want to do with API calls. They are not specific to XML requests. As we mentioned before, XML is one relatively common data format that APIs use. However, JSON is much more common these days - and XMLHttpRequest objects can be used with JSON and other types of data as well, not just XML. Next, we save the URL for our API call in a variable: const url = `{city}&appid=[YOUR-API-KEY-HERE]`; This isn't necessary but it makes our code a bit easier to read. Note that you'll need to put your own API key in [YOUR-API-KEY-HERE] for the code to work correctly. (We'll learn how to protect our API key in the next lesson.) Our string is a template literal with an embedded expression ( ${city}) so the value the user inputs into the form is passed directly into our URL string via our city variable. The rest of the code consists of three parts: readyStateof the XMLHttpRequest First, let's look at the function that listens for changes to the XMLHttpRequest: request.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { const response = JSON.parse(this.responseText); getElements(response); } }; Our XMLHttpRequest object has a property called onreadystatechange. We can set this property to the value of a function that does whatever we want. In the example above, we have an anonymous function (an unnamed function) which is set to the value of that property. We could even update the code to just log when the ready state changes: request.onreadystatechange = function() { console.log(this.readyState); }; If we did, we'd see the following in the console. The comments have been added (you won't see the comments in the console if you try this yourself): 1 // Opened 2 // Headers Received 3 // Loading 4 // Done These numbers correspond to the different states our XMLHttpRequest object can be in. (You wouldn't see 0, which corresponds to Unsent because this is the initial state - and the readyState hasn't changed yet.) Note: If you try this in the console yourself, ESLint will freak out with a no-unused-vars error. This is because the getElements() function we define later in the code is no longer used. You'll need to temporarily comment it out to soothe ESLint. Also, make sure to return the code to its original state after you're done. We don't want to do anything until the readyState is 4 because the data transfer won't be complete yet. This is classic async at work. Once this.readyState === 4 and this.status === 200, we'll do something with the data. Why does this.status === 200 need to be part of our conditional? In the last lesson, we mentioned that a 200 response indicates a successful API call. In other words, this conditional states that the API call must be successful and the data transfer must be complete before our code processes that data. Once the conditional is met, we run the following line of code: const response = JSON.parse(this.responseText); As you may have guessed, this.responseText is another built-in property of XMLHttpRequest objects. It's automatically populated once a response is received from a server. By now, it should be clear that XMLHttpRequest objects are really powerful and do a lot of work for us. We parse this.responseText with JavaScript's built-in JSON.parse method. This ensures that the data is properly formatted as JSON data. Otherwise, our code won't recognize the data as JSON and we'll get an error when we try to use dot notation to get data from it. The JSON.parse() method is essential for working with APIs. As we mentioned in a previous lesson, other programming languages also have methods for parsing JSON as well. Next, we'll make a callback with the data stored in the response variable: getElements(response); When a function calls another function, it's called a callback. We'll cover this more in just a moment. Before we do, let's go into a bit more detail about XMLHttpRequest objects. We can see exactly what properties an XMLHttpRequest object has by adding a breakpoint inside our conditional and then running the code in the browser. (You don't need to do this right now - it's fine to just look at the image below - but we recommend taking a closer look at an XMLHttpRequest object at some point.) request.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { debugger; ... } }; Adding a breakpoint from the Sources tab is better - the snippet above just shows where the breakpoint should go. If we take a look at the XMLHttpRequest object in the console, it will look something like this: As you can see, an XMLHttpRequest object has a lot of functionality. You don't need to worry about most of these properties right now. However, there are a few that will be helpful during this section: responseText: We've already discussed this one. It includes the text of the response. (There's also a response property which has the same text here.) status: The status is the API status code. A 200 means it was successful. There are many other codes such as 404 not found and so on. We will use the status in a future lesson. statusText: We'll see here that it's "OK". That's standard with a 200 status code. It means we are good to go! However, if something went wrong, this is where we might get a more detailed error message such as "not found" or "not authorized." Now let's return to our new code: let request = new XMLHttpRequest(); const url = `{city}&appid=[YOUR-API-KEY-HERE]`; request.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { const response = JSON.parse(this.responseText); getElements(response); } }; // We've covered everything except for the two lines below! request.open("GET", url, true); request.send(); We've discussed everything but the last two lines (the comment highlights what we haven't covered yet). At this point in our code, we've created a new XMLHttpRequest object and added a function to the onreadystatechange property to listen for changes to the object's ready state, but we haven't actually done anything with the object yet. We still need to open and send the request. request.open("GET", url, true); request.send(); XMLHttpRequest.open() takes three arguments: the method of the request (in this case GET), the url (which we stored in a variable called url), and a boolean for whether the request should be async or not. Once again, we want the request to be async; we don't want the browser to freeze up for our users! For the API calls we make in this section, the three arguments will almost always be the same - the only exception will be if you make a "POST" or other type of request instead of "GET". Once we've opened the request, we send it. As we've already discussed, the readyState of the XMLHttpRequest object will change while the function we've attached to the object's onreadystatechange will trigger each time the readyState changes. Finally, when our conditional is triggered in the function we've attached to the onreadystatechange property, our getElements() function will be called. When a function calls another function, it is known as a callback. Callbacks can get confusing very quickly, especially when one function calls another which then calls another and so on. For that reason, they can be very intimidating for beginners. When you see examples of scary-looking callbacks out in the real world, just remember, a callback is just a function calling another function. We will talk about why callbacks can be so scary in a future lesson when we discuss a concept known as "callback hell." For now, it's important to know that callbacks are one way for JavaScript developers to deal with async code. A long time ago, it was the only way to deal with async code. Fortunately, there are new tools at our disposal that will make our lives easier. We'll learn about some of these tools later in this section. The reason we need to use a callback here is because we need to wait until our conditional is triggered before we call getElements(). Remember that JavaScript is non-blocking. It's going to keep running code even if some of it is async. Let's take a look at what will happen if we don't use a callback. // Note: This code will not work! It's meant to show why we need to structure our code to use a callback. let response; request.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { response = JSON.parse(this.responseText); } }; request.open("GET", url, true); request.send(); getElements(response); In the code above, when we call request.send(), our request is sent to the server. Remember that this takes time. The server is going to accept (or deny) our request and send a response. We have to wait for that response to load and then parse it. But JavaScript is non-blocking. That means it's not going to wait until request.send() is done before it moves on. getElements(response) will be called immediately and we'll get the following error: Cannot read property 'main' of undefined This is a classic async issue. request.send() is async but getElements(response) is not. The code will continue to run, so the response will still be undefined when getElements() is called. The response will eventually be defined, but our code will break before that happens. This is why we need a callback. Let's take a look at our original code again: request.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { const response = JSON.parse(this.responseText); getElements(response); } }; ... function getElements(response) { $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`); $('.showTemp').text(`The temperature in Kelvins is ${response.main.temp} degrees.`); } In this code, getElements(response) won't be called until the conditional becomes true. In other words, by using a callback, we ensure the function doesn't run until after we get a response from the server. Async code is one of many important use cases for callbacks. Callbacks can help us control the order that functions should run. If we need a sync function to run immediately after an async function, then we can use a callback to make sure the code runs in the order we expect. Of course, things can get weird fast when we need a series of sync and async functions to run in a specific order. That leads to callback hell - but that's a subject for a future lesson. Before we move on, there's one more thing to note: to access humidity or temp, we need to parse the JSON body of the API call. In the case of humidity, that's response.main.humidity. response just matches the name of the function's parameter - it could be something different such as text or body depending on what we decide to name the parameter. main.humidity is specific to the API call. This will always vary from API to API. That's why it's so important to test API calls and practice parsing JSON - depending on the values you want to grab from the data, the dot notation you use could vary greatly. If you ever get stumped when you're parsing JSON, just review the last lesson again - and don't forget to parse the JSON outside of your code (such as in the console) to get it working first. That means making one API call, copying the body to the console or a text editor, and then parsing until you get the value you want. Don't just keep making API calls and altering your code directly - you'll waste API calls and potentially run into problems debugging as well. In this lesson, we learned how to create and send a XMLHttpRequest object. Doing so should give you a better understanding of how JavaScript makes HTTP requests. Just as importantly, we discussed how we can use callbacks to make sure our code runs in the order we expect. Later in this section, we'll learn more concise ways to make API calls. While you may find those approaches preferable to building an XMLHttpRequest object, it's still really important to understand the basics of how an XMLHttpRequest object works. Lesson 7 of 29 Last updated April 8, 2021
https://www.learnhowtoprogram.com/intermediate-javascript/asynchrony-and-apis/making-api-calls-with-javascript
CC-MAIN-2021-17
refinedweb
2,856
65.93
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 17 January 2002 16:12, Daniel Stone wrote: > > No. > > Your original complaint was about cluttering the namespace. With this > solution, not only are you implementing TWO ugly hacks (the > /usr/lib/kde3 prefix and /usr/bin symlinks), but the namespace stays > "cluttered". /usr/lib/kde3 isn't an ugly hack. why, then large packages which have their file hierarchies in /usr/lib/<package> implementing an ugly hack? that's not the case... /usr/bin symlinks doesn't seem very good to me either. another solution is to write a wrapper script that prepends the required path (startkde3). there should be a single entry point to using KDE3. that way, you can choose running kde3 or not in the beginning (which is a good thing), KDE2 apps would continue running the same way. you would simply move the binaries to /usr/bin which would be the cleanest... wait, you can't symlink or copy KDE3 binaries to /usr/bin anyway, if you want to keep KDE2 and KDE3 together. Yes, you can use the autoconf trick to prepend all binary names with "kde3_" but that's even worse. Chris, have you been able to provide a set of KDE3 packages that do not kill KDE2? I suggest you to at least implement: "/usr/share/kde3" under which all KDE3 ro arch indep data should go in such as "/usr/share/kde/icons". Second suggestion is to implement "/usr/lib/kde3" and append the path to /etc/ld.so.conf like the atlas package does. It's the nicest way to handle that large collection of libraries.RuZefAeuFodNU5wRAtDAAJ9nXACKx9d+xJ4kQHVcNSyeRHSDnQCgmmzw +fcsOOn+el4kWnMzpIlEZ/Q= =MZm0 -----END PGP SIGNATURE-----
https://lists.debian.org/debian-kde/2002/01/msg00413.html
CC-MAIN-2017-47
refinedweb
282
66.54
Another way to parameterize an ODE - nested function Posted February 27, 2013 at 02:31 PM | categories: ode | tags: | View Comments Updated February 27, 2013 at 02:32 PM Matlab post We saw one method to parameterize an ODE, by creating an ode function that takes an extra parameter argument, and then making a function handle that has the syntax required for the solver, and passes the parameter the ode function. Here we define the ODE function in a loop. Since the nested function is in the namespace of the main function, it can “see” the values of the variables in the main function. We will use this method to look at the solution to the van der Pol equation for several different values of mu. import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt MU = [0.1, 1, 2, 5] tspan = np.linspace(0, 100, 5000) Y0 = [0, 3] for mu in MU: # define the ODE def vdpol(Y, t): x,y = Y dxdt = y dydt = -x + mu * (1 - x**2) * y return [dxdt, dydt] Y = odeint(vdpol, Y0, tspan) x = Y[:,0]; y = Y[:,1] plt.plot(x, y, label='mu={0:1.2f}'.format(mu)) plt.axis('equal') plt.legend(loc='best') plt.savefig('images/ode-nested-parameterization.png') plt.show() You can see the solution changes dramatically for different values of mu. The point here is not to understand why, but to show an easy way to study a parameterize ode with a nested function. Nested functions can be a great way to “share” variables between functions especially for ODE solving, and nonlinear algebra solving, or any other application where you need a lot of parameters defined in one function in another function. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2013/02/27/Another-way-to-parameterize-an-ODE-nested-function/
CC-MAIN-2018-30
refinedweb
305
61.56
Bookmark by style First post but a long time user. I often use NP++ for reviewing logs and I find it very easy to right-click and style all occurrences of certain text (e.g., IP addresses) without having to use the search dialog each time. What I was hoping to find is a way to bookmark all lines containing a specific style. Is there a way to do this? If not, could it be considered as an enhancement request? Thanks - Alan Kilborn last edited by Alan Kilborn @PhilBiggs said: Is there a way to do this? Not normally, no. But if you are willing to use the Pythonscript plugin, I’m sure we can get it accomplished. How about it? I’m thinking of a modification to some scripting/ideas found in these places previously: - - At first glance, these postings don’t work with “styles” but when you consider that (red)marking is just another “style”, you might start to see the applicability. Anyway, if you come back, let me know your enthusiasm for a scripted solution. could it be considered as an enhancement request? It’s probably a bit “special need” to be put into core Notepad++, but you can always make a feature request if you want. Thanks for your reply, Alan. I take your point about it being a special need. In fact, it’s not something I need to do very often. I was just looking for a quicker (low click count) way to bookmark already identified lines, mostly so that I could then copy those and paste them into a new file for further examination/manipulation. After reading those other threads I can see that my use of Notepad++ is relatively unsophisticated. I really appreciate your offer but I figured that if it was something others could see value in, then they could support the idea here - or tell me the solution already existed. I certainly would not ask you to invest any of your time in producing a solution for my corner case. @PhilBiggs said: I take your point about it being a special need This part is funny because most people don’t understand why their feature request isn’t the most valuable thing on the planet. Sure, there are some great new feature requests, but most are made by people that just don’t get why only they are trying to do something a certain way… I certainly would not ask you to invest any of your time in producing a solution for my corner case Thanks for protecting my time! :) But really, from those above links, it is really 90% written already. Here’s why, with some background: Notepad++ has a feature where you can redmark text based upon a search expression. This is similar to what you do with “styling” text, except in your case the text is constant; it isn’t a variable expression like it can be with redmarking (and regular-expressions). Often people want to be able to copy their marked search results to the clipboard, and often want to do so on a whole-line basis. It may surprise you to know that currently in Notepad++ there is no way to do the former, and the latter while possible has some limitations. That limitation is that if a search expression results in matches that span multiple lines, only the FIRST line of the match is bookmarked. Thus for individuals that need to copy ALL of these matched lines (via Search > Bookmark > Copy Bookmarked Lines), they are out of luck. So if we haven’t had a TL;DR and you are still with me, what the script found in one of the links above tries to do is to overcome this limitation by searching for all redmarked text and then bookmark all of the lines that have any redmarking on them at all. Well, since redmarking is just another type of “style” (indeed, in Notepad++ it is kind of a “sixth” style (see the last entry on the Search > Jump Up (or Down) menu), it truly is easy to extend the existing script to cover all styles. I haven’t written the script yet, but I was thinking it might have a user-interface like this when you run it: What one would do is to select a style (or styles), like so: And click OK to execute. Any thoughts from the OP or anyone else on this? Since I don’t use the highlight provided by Style #1 - #5 all that much, I went back to refamiliarize myself with how they work. I noticed something odd. If I highlight (select) some text and apply a style to it, the style highlighting will do matches in both full words and inside other words, see here: This made me suspicious so I opened the Find window and ticked Match whole words only and then cleared out my styling and then did it again. I got a different result: This sort of makes me uncomfortable. :P - Michael Vincent last edited by Can that be remedied with the Settings=>Preferences=>Highlighting=>“Use Find dialog settings” checkbox being unchecked? For instance when I do your experiment with that box unchecked and the above 2 boxes from that settings (Match Case, Match whole word only") checked, it performs as expected styling the only two “highlight” words, not the “highlighting” word. When I instead check the “Use Find dialog settings” checkbox, the above 2 checkboxes are automatically unchecked and in my Find dialog, they are unchecked as well and then styling performs as in your graphic (selecting all 3 instances, including the “highlight” portion of the “highlighting” word. Cheers. - Alan Kilborn last edited by Alan Kilborn Interesting. Here’s what it looks like when I do my case #1 from above: And here’s for my case #2: - Michael Vincent last edited by I should note I have the “Enable” checkbox under “Smart Highlighting” always checked. @Michael-Vincent said: I should note I have the “Enable” checkbox under “Smart Highlighting” always checked. Yes, but I guess my point was that I DON’T and still the “styling” is following the Find settings anyway (of course “styling” isn’t “Smart Highlighting”… so maybe it is moot). Okay, then… well, here is the script I mentioned earlier; finished it over lunchtime today. Instructions for interacting with it are pretty much found in the two screenshots a bit up in this thread. Enjoy. import re def main(): MARK_BOOKMARK = 24 # N++ normal bookmark marker number; identifier pulled from N++ source code # def is_line_bookmarked(line_nbr): return (editor.markerGet(line_nbr) & (1 << MARK_BOOKMARK)) != 0 def highlight_indicator_range_tups_generator(indicator_number): if editor.indicatorEnd(indicator_number, 0) == 0: return indicator_end_pos = 0 # set special value to key a check the first time thru the while loop while True: if indicator_end_pos == 0 and editor.indicatorValueAt(indicator_number, 0) == 1: indicator_start_pos = 0 else: indicator_start_pos = editor.indicatorEnd(indicator_number, indicator_end_pos) indicator_end_pos = editor.indicatorEnd(indicator_number, indicator_start_pos) if indicator_start_pos == indicator_end_pos: break # no more matches yield (indicator_start_pos, indicator_end_pos) user_input = notepad.prompt('Select style(s) you want to bookmark lines of:', '', '[ ] Style #1 [ ] Style #2\r\n[ ] Style #3 [ ] Style #4\r\n[ ] Style #5 [ ] Redmark\r\n\r\n[ ] CLEAR bookmarks instead of setting, for items chosen') if user_input == None: return if len(user_input) == 0: return user_input = re.sub(r'\s{4,}', '\r\n', user_input) ui_choices_list = user_input.splitlines() selected = '' for uic in ui_choices_list: m = re.search(r'[([^]]+)]', uic) if m and m.group(1) != ' ' * len(m.group(1)): selected += uic if len(selected) == 0: return indicator_number_list = [] if '1' in selected: indicator_number_list.append(SCE_UNIVERSAL_FOUND_STYLE_EXT1) if '2' in selected: indicator_number_list.append(SCE_UNIVERSAL_FOUND_STYLE_EXT2) if '3' in selected: indicator_number_list.append(SCE_UNIVERSAL_FOUND_STYLE_EXT3) if '4' in selected: indicator_number_list.append(SCE_UNIVERSAL_FOUND_STYLE_EXT4) if '5' in selected: indicator_number_list.append(SCE_UNIVERSAL_FOUND_STYLE_EXT5) if 'red' in selected.lower(): indicator_number_list.append(SCE_UNIVERSAL_FOUND_STYLE) clearing_not_setting = True if 'clear' in selected.lower() else False at_least_1_match_of_style = False at_least_1_bookmark_change_made = False for indic_number in indicator_number_list: for (styled_start_pos, styled_end_pos) in highlight_indicator_range_tups_generator(indic_number): at_least_1_match_of_style = True bookmark_start_line = editor.lineFromPosition(styled_start_pos) bookmark_end_line = editor.lineFromPosition(styled_end_pos) for bm_line in range(bookmark_start_line, bookmark_end_line + 1): if clearing_not_setting: if is_line_bookmarked(bm_line): editor.markerDelete(bm_line, MARK_BOOKMARK) at_least_1_bookmark_change_made = True else: if not is_line_bookmarked(bm_line): editor.markerAdd(bm_line, MARK_BOOKMARK) at_least_1_bookmark_change_made = True if at_least_1_match_of_style: if at_least_1_bookmark_change_made: notepad.messageBox('Lines with selected style(s) have been {}bookmarked.'.format('un' if clearing_not_setting else ''), '') else: notepad.messageBox('No changes in bookmarks made.', '') else: notepad.messageBox('No text found matching selected style(s).', '') main()
https://community.notepad-plus-plus.org/topic/18052/bookmark-by-style
CC-MAIN-2022-27
refinedweb
1,397
53.71
This question already has an answer here: This might be a question with a very simple solution but I can't get my head around it... I'm trying to implement linked list for a school proyect using structures but when I initialize the very first node, malloc seems to make no effect at all here's my code so far: #include <stdio.h> #include <conio.h> #include <stdlib.h> typedef struct Node Node; struct Node { int data; Node *next; }; void init_List(Node *head, int data) { head = (Node*)malloc(sizeof(Node)); if(head == NULL) { printf("Memory Allocation Error"); return; } head->data = data; head->next = NULL; } int main() { Node *head = NULL; int N; printf("N: "); scanf("%d", &N); init_List(head, N); printf("%d", head->data); } whatever number I read to make the first data of my node prints as cero. don't know what could be happening. thanks for the help!
http://www.howtobuildsoftware.com/index.php/how-do/foe/c-pointers-linked-list-initializing-a-pointer-to-a-struct-with-malloc-duplicate
CC-MAIN-2018-30
refinedweb
150
69.52
The Return of the Scala Rule Tutorial: The Execution The Return of the Scala Rule Tutorial: The Execution Learn about the Scala rule in this neat tutorial, including producing an actual executable! Join the DZone community and get the full member experience.Join For Free Sensu is an open source monitoring event pipeline. Try it today. This builds on the first part of this tutorial. In this post, we will make the the rule actually produce an executable. Capturing the Output from scalac At the end of the tutorial last time, we were calling scalac, but ignoring the result: ; echo '\''blah'\'' > bazel-out/local_darwin-fastbuild/bin/hello-world.sh') If you look at the directory where the action is running (/private/var/tmp/_bazel_kchodorow/92df5f72e3c78c053575a1a42537d8c3/blerg in my case) you can see that HelloWorld.class and HelloWorld$.class is created. This directory is called the execution root, it is where bazel executes build actions. Bazel uses separate directory trees for source code, executing build actions, and output files (bazel-out/). Files won’t get moved from the execution root to the output tree unless we tell Bazel we want them. We want our compiled scala program to end up in bazel-out/, but there’s a small complication. With languages like Java (and Scala), a single source file might contain inner classes that cause multiple .class files to be generated by a single compile action. Bazel cannot know until it runs the action how many class files are going to be generated. However, Bazel requires that each action declare, in advance, what its outputs will be. The way to get around this is to package up the .class files and make the resulting archive the build output. In this example, we’ll add the .class files into a .jar. Let’s add that to the outputs, which should now look like this: outputs = { 'jar': "%{name}.jar", 'sh': "%{name}.sh", }, In the impl function, our command is getting a bit complicated so I’m going to change it to an array of commands and then join them on “\n” in the action: def impl(ctx): cmd = [ "%s %s" % (ctx.file._scalac.path, ctx.file.src.path), "find . -name '*.class' -print > classes.list", "jar cf %s @classes.list" % (ctx.outputs.jar.path), ] ctx.action( inputs = [ctx.file.src], command = "\n".join(cmd), outputs = [ctx.outputs.jar] ) This will compile the src, find all of the .class files, and add them to the output jar. If we run this, we get: $ bazel build -s :hello-world INFO: Found 1 target... >>>>> # //:hello-world [action 'Unknown hello-world.jar'] find . -name '\''*.class'\'' -print > classes.list jar cf bazel-out/local_darwin-fastbuild/bin/hello-world.jar @classes.list') Target //:hello-world up-to-date: bazel-bin/hello-world.jar INFO: Elapsed time: 4.774s, Critical Path: 4.06s Let’s take a look at what hello-world.jar contains: $ jar tf bazel-bin/hello-world.jar META-INF/ META-INF/MANIFEST.MF HelloWorld$.class HelloWorld.class Looks good! However, we cannot actually run this jar, because java doesn’t know what the main class should be: $ java -jar bazel-bin/hello-world.jar no main manifest attribute, in bazel-bin/hello-world.jar Similar to the java_binary rule, let’s add a main_class attribute to scala_binary and put it in the jar’s manifest. Add 'main_class' : attr.string(), to scala_binary‘s attrs and change cmd to the following: cmd = [ "%s %s" % (ctx.file._scalac.path, ctx.file.src.path), "echo Manifest-Version: 1.0 > MANIFEST.MF", "echo Main-Class: %s >> MANIFEST.MF" % ctx.attr.main_class, "find . -name '*.class' -print > classes.list", "jar cfm %s MANIFEST.MF @classes.list" % (ctx.outputs.jar.path), ] Remember to update your actual BUILD file to add a main_class attribute: # BUILD load("/scala", "scala_binary") scala_binary( name = "hello-world", src = "HelloWorld.scala", main_class = "HelloWorld", ) Now building and running gives you: $ bazel build :hello-world INFO: Found 1 target... Target //:hello-world up-to-date: bazel-bin/hello-world.jar INFO: Elapsed time: 4.663s, Critical Path: 4.05s $ java -jar bazel-bin/hello-world.jar Exception in thread "main" java.lang.NoClassDefFoundError: scala/Predef$ at HelloWorld$.main(HelloWorld.scala:4) at HelloWorld.main(HelloWorld.scala) Caused by: java.lang.ClassNotFoundException: scala.Predef$ Closer! Now it cannot find some scala libraries it needs. You can add it manually on the command line to see that our jar does actually does work if we specify the scala library jar, too: $ java -cp $(bazel info output_base)/external/scala/lib/scala-library.jar:bazel-bin/hello-world.jar HelloWorld Hello, world! So we need our rule to generate an executable that basically runs this command, which can be accomplished by adding another action to our build. First we’ll add a dependency on scala-library.jar by adding it as a hidden attribute: '_scala_lib': attr.label( default=Label("@scala//:lib/scala-library.jar"), allow_files=True, single_file=True), Making scala_binarys Executable Let’s pause here for a moment and switch gears: we’re going to tell bazel that scala_binarys are binaries. To do this, we add executable = True to the attrs and get rid of the reference to hello-world.sh in the outputs: ... outputs = { 'jar': "%{name}.jar", }, implementation = impl, executable = True, ) This says that scala_binary(name = "foo", ...) should have an action that creates a binary called foo, which can be referenced via ctx.outputs.executable in the implementation function. We can now use bazel run :hello-world (instead of bazel build :hello-world; ./bazel-bin/hello-world.sh). The executable we want to create is the java command from above, so we add the second action to impl, this one a file action (since we’re just generating a file with certain content, not executing a series of commands to generate a .jar): cp = "%s:%s" % (ctx.outputs.jar.basename, ctx.file._scala_lib.path) content = [ "#!/bin/bash", "echo Running from $PWD", "java -cp %s %s" % (cp, ctx.attr.main_class), ] ctx.file_action( content = "\n".join(content), output = ctx.outputs.executable, ) Note that I also added a line to the file to echo where it is being run from. If we now use bazel run, you’ll see: $ bazel run :hello-world INFO: Found 1 target... Target //:hello-world up-to-date: bazel-bin/hello-world.jar bazel-bin/hello-world INFO: Elapsed time: 2.694s, Critical Path: 0.08 Error: Could not find or load main class HelloWorld ERROR: Non-zero return code '1' from command: Process exited with status 1. Whoops, it’s not able to find the jars! And what is that path, hello-world.runfiles, it’s running the binary from? The runfiles Directory bazel run runs the binary from the runfiles directory, a directory that is different than the source root, execution root, and output tree mentioned above. The runfiles directory should contain all of the resources needed by the executable during execution. Note that this is not the execution root, which is used during the bazel build step. When you actually execute something created by bazel, its resources need to be in the runfiles directory. In this case, our executable needs to access hello-world.jar and scala-library.jar. To add these files, the API is somewhat strange. You must return a struct containing a runfiles object from the rule implementation. Thus, add the following as the last line of your impl function: return struct(runfiles = ctx.runfiles(files = [ctx.outputs.jar, ctx.file._scala_lib])) Now if you run it again, it’ll print: $ bazel run :hello-world INFO: Found 1 target... Target //:hello-world up-to-date: bazel-bin/hello-world.jar bazel-bin/hello-world INFO: Elapsed time: 0.416s, Critical Path: 0.00 Hello, world! Hooray! However! If we run it as bazel-bin/hello-world, it won’t be able to find the jars (because we’re not in the runfiles directory). To find the runfiles directory regardless of where the binary is run from, change your content variable to the following: content = [ "#!/bin/bash", "case \"$0\" in", "/*) self=\"$0\" ;;", "*) self=\"$PWD/$0\";;", "esac", "(cd $self.runfiles; java -cp %s %s)" % (cp, ctx.attr.main_class), ] This way, if it’s run from bazel run, $0 will be the absolute path to the binary (in my case, /private/var/tmp/_bazel_kchodorow/92df5f72e3c78c053575a1a42537d8c3/blerg/bazel-out/local_darwin-fastbuild/bin/hello-world). If it’s run via bazel-bin/hello-world, $0 will be just that: bazel-bin/hello-world. Either way, we’ll end up in the runfiles directory before executing the command. Now our rule is successfully generating a binary. You can see the full code for this example on GitHub. In the final part of this tutorial, we’ll fix the remaining issues: - No support for multiple source files, never mind dependencies. [action 'Unknown hello-world.jar']is pretty ugly. Until next time! Sensu: workflow automation for monitoring. Learn more—download the whitepaper. }}
https://dzone.com/articles/the-return-of-the-scala-rule-tutorial-the-executio
CC-MAIN-2018-47
refinedweb
1,485
61.12
Hello, Me very new to java prgmng and got to redesign a C proj in java. Might be very insane question but not for me. My c poject has a file, called headerfile.h and the structure looks like this define ID_File1 0x6F01 define ID_File2 0x6F02 ... .. likewise all constants r declared in this file nd the main C file will include this file. Is there any way to declare such files in java, whr i have all my constants defined in my file and in future to amend this file rather than adding in main java file. Help reqd. Anne You declare constants in Java as static final fields such as: package mypackage; public class MyClass { public static final int ID_File1 = 0x6F01; public static final int ID_File2 = 0x6F02; } As long as the fields are public you can access your constants outside of the class, and if your class is also public you can access your constants from anywhere. For example, mypackage.MyClass.ID_File1. You can also use an interface instead of a class, but it is impossible to declare constants that are not members of some class or interface. Normally you would choose a class where the constants will be used heavily, especially a class that requires the constants to be given as arguments to its methods. If you cannot choose a class to hold your constants then you can make a new class that does nothing but hold your constants. For a class like that instances will probably be meaningless, so you should declare a private constructor to make it impossible to create instances of the class. Thank u thanku so much bguild....Working on it now...Thanks once again To make it more like a c header file full of defines, you can declare pubic static final members, as bguild explained, then at then start of any .java file you can import static mypackage.MyClass.*; Now you can simply use the public static member names in that file without needing to qualify them with the package/class names. For example, the java.lang package contains the Math class, and that has the useful member public static final double PI = 3.14159265358979323846; so if you import static java.lang.Math.*; you can simply refer to it as PI in your code Thank u friends, have started my code and so far smooth progress. Thank u so much for timley help. Ciao soon ... Anne
http://www.daniweb.com/software-development/java/threads/445901/creating-file-in-java
CC-MAIN-2014-10
refinedweb
404
70.23
As i'm working on an inhouse exporter script, i stumbled over a peculiar problem with PyMel. The pymel version of the ls-command seems to ignore the long parameter, while the maya.cmds version works correctly: import maya.cmds as cmds for x in cmds.ls(sl=True, l=True): print x Result: |scene_main|mesh_helix1 PyMel: from pymel.core import * for x in ls(sl=True, l=True): print x Result: mesh_helix1 Am i doing something wrong here or is this actually a bug? Has anyone encountered that problem? In PyMEL, pm.ls returns you PyNode objects, not strings - which is what cmds.ls does From the docs: Modifications: - Returns PyNode objects, not "names" - all flags which do nothing but modify the string name of returned objects are ignored (ie, 'long'); note that the 'allPaths' flag DOES have an effect, as PyNode objects are aware of their dag paths (ie, two different instances of the same object will result in two unique PyNodes) Key bit here is: "PyNode objects are aware of their dag paths" Right on, my mistake, now i feel stupid A little research in the docu also showed me how i get the full name: print ls(sl=True)[0].longName() |scene_main|mesh_helix1
http://tech-artists.org/t/pymel-ls-command-does-not-return-full-path-names/8594
CC-MAIN-2018-09
refinedweb
207
69.41
How. Note: a minimal version with screenshot is available. Introduction If you're familar with ArchGenXML and UML and have the products already installed you'll need around 7 minutes. Otherwise ~30 minutes should be enough. Prepare your development-environment: Install Poseidon CE, ArchGenXML (installation instructions) (+ all its dependencies) and open a new UML in Poseidon. Chcek out TemplateFields from Collective-SVN and install it in your zope instances Products directory. The Goal I want to show how simple one can subclass from ATDocument. In this example we're replacing the text-body field of ATDocument by a ZPTField from TemplateFields. Yes, indeed, PageTemplates as content are evil. Thats the reason why I called the Product EvilZPTDocument. Paint the new type Getting ATDocument into the model - First paint a class in the diagram and name it ATDocument. - Give the class a stereotypes <<stub>>and <<archetype>>, usually you need to add this stereotype first. - Give the class a tagged-value import_fromwith value Products.ATContentTypes.content.document(for ancient ATContentTypes 0.2/Plone 2.0.x. you have to import_from Products.ATContentTypes.types.ATDocument). Subclassing from ATDocument - Paint another class and name it ZPTDocument. - Paint an generelization arrow (the fat white one) from ZPTDocument to ATDocument by drag and drop. Overrule the text field of ATDocument in ZPTDocument - Add an attribute to class ZPTDocument and name it text. - Give the text attribute the new Type (DataType) ZPTField. - Add to the class ZPTDocument' a tagged value importswith value from Products.TemplateFields import ZPTField. - Give the text attribute a tagged value widget:typewith value TextAreaWidget. - Give the text attribute a tagged value widget:labelwith value Page (ZPT). Setting the view - On class ZPTDocument set tagged values default_viewand immediate_viewboth to value document_view. Generate it - Save the model as EvilZPTDocument.zuml. - Fire up ArchGenXML:: ./path/to/ArchGenXML.py path/to/EvilZPTDocument.zuml path/to/Zope/Instance/Products/EvilZPTDocument - Restart your Zope. - In Plone-Setup add your new Product to the your site. - Add the new Page (ZPT)to your folder. - The default PageTemplate provided in textfield shows the page-title by default. Modify it to your needs and view how it renders. Download You may want to look at the finished model? Here I provide you with the model. error in tagged value in evilzptpage.zuml model so instead of:: suppl_views | python:() change it to:: suppl_views |
http://plone.org/documentation/how-to/subclass-atct-using-archgenxml
crawl-002
refinedweb
390
52.46
Im new with C++ . Its my third day using it. I know turbo pascal. I have a code with an array that has something wrong and i dont know it. plz tell me wuts wrong. thx. dont laugh at my program . im just practising to learn the language.. im just practising to learn the language. #include <iostream.h> int a; double b; char c, question; bool d; void favthings () { d= 1; while (d == 1) { cout <<"Write your favorite letter"<<endl; cin >> c ; cout <<"Now write your favorite number"<<endl; cin >> a; cout <<"Now write your grade poing average"<<endl; cin >> b ; cout <<"Your favorite letter is "<< c <<" Your favorite number is "<< a <<" And your GPA is "<< b<< endl;; cout <<endl; cout <<"Do you want to input everything again?(y/n)"<<endl; cin >> question ; if (question == 'y') d= 1; if (question == 'n') d= 0; } } void gradearray (); { cout <<"Input your last 5 grades to get the average !!!"<<endl; int arraygrade[4] ; cin << arraygrade ; cout <<arraygrade ; } main () { favthings (); gradearray (); cout <<endl; cout <<"BYE"<<endl; cout <<endl; cout <<"Made by l33t"<<endl; cout <<endl; return 0; }
https://cboard.cprogramming.com/cplusplus-programming/15777-i-need-help-code-really-easy.html
CC-MAIN-2018-05
refinedweb
182
81.02
I'm trying to create a central event system for my game where I add some events to a priority_queue and pull off the first one as soon as it expires. But I'm having a problem of understanding if I'm adding them to the queue correctly, if they're in order, or how to pull them off. Can anyone lend a hand here? Initialize the queue. my_queue = new MyEventQueue(); Here I create 10 events and put them on a queue after assigning the current timestamp, and then the later timestamp to execute this event. for (int i = 0; i < 10; i++) { MyEvent *event = new MyEvent(); event->set_start_timestamp(); // now time event->set_execute_timestamp(); // time to execute from now my_queue->push_event(event); } Then in each frame of my game, i want to check the queue to see if the event is ready to be executed. if (my_queue->count() > 0) { MyEvent *evnt = my_queue->top_event(); // is_expired() is how i was doing it, but didn't work if (evnt->is_expired()) { execute_event(evnt->id()); my_queue->pop_event(); } } Here are my event classes ... class MyEvent { ... public: ... bool is_expired(); struct timeval start_timestamp(); double execute_timestamp(); }; struct EventPointerCompare { bool operator() (MyEvent* lhs, MyEvent* rhs) const { return ( lhs->_execute_time < rhs->_execute_time ); } }; // this is my priority_queue wrapper class MyEventQueue { private: priority_queue<MyEvent *, vector<MyEvent *>, EventPointerCompare> event_queue; public: check_queue(); has_events_of_type_x(); ... Can anyone help me use priority_queue's correctly?
https://www.daniweb.com/programming/software-development/threads/152779/priority-queue-help
CC-MAIN-2017-47
refinedweb
225
56.79
This is an incredibly simple problem (I assume) because it has to do with a very simple program. In fact, I've written much more advanced things than this such as a calculator, database, and a guessing game. For some reason I decided to take a pretty long break from C++ (As you can see my last post was quite a while ago). Well now I'm back for good. No more of that break stuff :D Unfortunately I lost almost all my work due to my over-excitement about a disk reformat. So I installed the GCC compiler, added the the bin directory to my path variable, created an ever-so-simple program: Fired up the compiler, only to get this error:Fired up the compiler, only to get this error:Code: #include <iostream> using namespace std; int main() { char test; cout << "Okay, this is a test!\n"; cin >> test; return 0; } This is despicable... I must be out of my mind...This is despicable... I must be out of my mind...Quote: test.cpp: In function 'int main()': test.cpp:6: no match for 'std::ostream& >> const char[22]' operator
http://cboard.cprogramming.com/cplusplus-programming/54416-what-world-printable-thread.html
CC-MAIN-2015-14
refinedweb
192
73.37
Hangman is a paper and pencil guessing game for two or more players. One player thinks of a word, phrase or sentence and the other(s) tries to guess it by suggesting letters or numbers, within a certain number of guesses.ize or numbers that appears in the word, thereby completing the word, before the diagram is completed. The above image shows an example game of Hangman in progress. The underlined letters appear in the word in their correct places, while the crossed-out letters do not appear, and each crossed-out letter corresponds to one part of the drawing. In this case, the secret word is “hangman”. Approach to solve the game In this game, we set a secret word. The guesser first has to input his name, and then, will be asked to guess any alphabet. If the random word contains that alphabet, it will be shown as the output (with correct placement) else the program will ask you to guess another alphabet. Guesser will be given length_of_word+2 turns (can be changed accordingly) to guess the complete word. If the guesser guesses all the letters in the word within the number of turns then he wins the game else loses the game. def play_hangman(): name = input("What is your name? ") print(f"Hello {name}, Time to play hangman!") print("Start guessing...") print("HINT: word is the name of a fruit\n") # here we set the secret word word = "apple" # creates an variable with an empty value guesses = "" # determine the number of turns turns = len(word) + 2 # the game :-)") # exit the script break # ask the user go guess a character guess = input("Guess a character: ") # set the players guess to guesses guesses += guess # if the guess is not found in the secret word if guess not in word: # turns counter decreases with 1 turns -= 1 # print wrong print("Wrong guess") # how many turns are left print(f"You have {turns} more guesses") # if the turns are equal to zero if turns == 0: # print "You Loose" print("You lost the game :-(") if __name__ == "__main__": play_hangman() What is your name? Babloo Hello Babloo, Time to play hangman! Start guessing... HINT: word is the name of a fruit _ _ _ _ _ Guess a character: z Wrong guess You have 6 more guesses _ _ _ _ _ Guess a character: a a _ _ _ _ Guess a character: r Wrong guess You have 5 more guesses a _ _ _ _ Guess a character: p a p p _ _ Guess a character: q Wrong guess You have 4 more guesses a p p _ _ Guess a character: p a p p _ _ Guess a character: c Wrong guess You have 3 more guesses a p p _ _ Guess a character: e a p p _ e Guess a character: j Wrong guess You have 2 more guesses a p p _ e Guess a character: l a p p l e You won the game :-)
https://nbviewer.jupyter.org/github/gowrishankarnath/Dr.AIT_Python_Lab_2019/blob/master/Program_10.ipynb
CC-MAIN-2020-40
refinedweb
501
66.1
error LNK1181 opencv_calib3d300d.lib Hi everybody, I am working on a project and trying to get familiar with OpenCV. I have chosen to try and connect it with MS Visual Studio 2013. Here is the code I am trying to run: "#include <opencv\cv.h> //ignore " "#include <opencv\highgui.h> //ignore " using namespace cv; int main(){ IplImage* img = cvLoadImage("C:\\Users\\--\\Desktop\\ocv.png"); cvNamedWindow("Example1", CV_WINDOW_NORMAL); cvShowImage("Example1", img); cvWaitKey(0); cvReleaseImage(&img); cvDestroyWindow("Example1"); return 0; } This is what I have done to connect to the OpenCV libraries: In Properties Linker>Additioinal Dependencies "opencv_ts300d.lib";"opencv_calib3d300d.lib";"opencv_core300d.lib";"opencv_features2d300d.lib"; "opencv_flann";%(AdditionalDependencies) Linker>Input "C:\opencv\build\x86\vc12\lib";"C:\opencv\build\x86\vc12\bin"%(AdditionalLibraryDirectories) Linker>General "C:\opencv\build\x86\vc12\lib";"C:\opencv\build\x86\vc12\bin"%(AdditionalLibraryDirectories) C/C++>Additional Include Directories "C:\opencv\build\include";"C:\opencv\build\include\opencv";"C:\opencv\build\include\opencv2";%(AdditionalIncludeDirectories) VC++ Directories>Include Directories "C:\opencv\build\include";"C:\opencv\build\include\opencv";"C:\opencv\build\include\opencv2";$(IncludePath) VC++ Directories>Library Directories "C:\opencv\build\x86\vc12\bin";"C:\opencv\build\x86\vc12\lib";$(LibraryPath) VC++ Directories>Source Directories "C:\opencv\build\x86\vc12\bin";"C:\opencv\build\x86\vc12\lib";"C:\opencv\build\x86\vc12\staticlib"$(SourcePath) I get a reoccurring error and my program will not compile. Error 1 error LNK1181: cannot open input file 'opencv_calib3d300d.lib' C:\Users\Will\Documents\Visual Studio 2013\Projects\OPEN_CV_TEST\OPEN_CV_TEST\LINK OPEN_CV_TEST I've tried manipulating everything. I've read all the other similar questions and noticed that other people are having this error. I've also read what Microsoft's website says on the issue. Any help would be appreciated very much. Thank you, deltamaster Shouldn't you have: #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> I mean these are the includes I would use doing a C++ project. Also, before someone else points it, you are writing code with the old "C" way of doing it. Now, C++ is privileged and here is a link to a simple tutorial: Thank you for your input. Adding the #includes does not fix the problem. I tried the code in the example-link and that gave me the same error! Thanks Are you sure the library opencv_calib3d300d.lib is actually there in one of the linker include paths? Since it is not complaining about the first library (opencv_ts300d.lib) in the list, I'm just guessing. Besides that, the code your using is very old (and depricated); please stop using it and start using the C++ interface for new projects. If built from source the lib files should be in C:\opencv\install\x86\vc12\lib or wherever install folder would be in your opencv build folder. A simple search for the .lib file in your windows explorer will also lead you there. Thank you ben.seep that fixed my problem! This is what I did in case anybody has this issue: In the staticlibrary folder are all the ...300d files. I made a folder called "replace" in static library. I moved every ...300d file into the folder (just the ones that are added to additional dependencies). Moved the folder to desktop and copied the ...300d files to the library folder. Then it worked. Note: If you don't move the files out of staticlibrary you will get hundreds of errors. An explanation of the reason behind this would be very helpful. @deltamaster what is static library folder? where is it?
https://answers.opencv.org/question/51060/error-lnk1181-opencv_calib3d300dlib/
CC-MAIN-2021-17
refinedweb
588
52.05
Business::IS::PIN - Validate and process Icelandic PIN numbers (Icelandic: kennitölur) # Functional interface use Business::IS::PIN qw(:all); my $kt = '0902862349'; # Yours truly if (valid $kt) { # Extract YYYY-MM-DD my $year = year $kt; my $month = month $kt my $day = day $kt; # ... } # OO interface that doesn't pollute your namespace use Business::IS::PIN; my $kt = Business::IS::PIN->new('0902862349'); if ($kt->valid and $kt->person) { printf "You are a Real Boy(TM) born on %d-%d-%d\n", $kt->year, $kt->month, $kt->day; } elsif ($kt->valid and $kt->company) { warn "Begone, you spawn of capitalism!"; } else { die "EEEK!"; } This module provides an interface for validating the syntax of and extracting information from Icelandic personal identification numbers (Icelandic: kennitala). These are unique 10-digit numbers assigned to all Icelandic citizens, foreign citizens with permanent residence and corporations (albeit with a slightly different format, see below). The National Statistical Institute of Iceland (Icelandic: Hagstofa) - a goverment organization - handles the assignment of these numbers. This module will tell you whether the formatting of a given number is valid, not whether it was actually assigned to someone. For that you need to pay through the nose to the NSIoI, or cleverly leech on someone who is:) None by default, every function in this package except for "new" can be exported individually, :all exports them all. Optional constructor which takes a valid kennitala or a fragment of one as its argument. Returns an object that stringifies to whatever string is provided. If a fragment is provided functions in this package that need information from the omitted part (such as "year") will not work. Takes a 9-10 character kennitala and returns true if its checksum is valid, false otherwise. Takes a the first 8 characters of a kennitala and returns the 9th checksum digit. Returns true if the kennitala belongs to an individual, false otherwise. Returns true if the kennitala belongs to a company, false otherwise. Return the four-digit year part of the kennitala. For this function to work a complete 10-digit number must have been provided. Return the two-digit month part of the kennitala. Return the two-digit day part of the kennitala. The format of an IPIN is relatively simple: DDMMYY-SSDC Where DDMMYY is a two-digit day, month and year, SS is a pseudo-random serial number, D is the check digit computed from preceding part and C stands for the century and is not included when calculating the checksum digit - 8 for 1800s, and 9 and 0 for the 1900s and 2000s respectively. It is customary to place a dash between the first 6 and last 4 digits when formatting the number. To compute the check digit from a given IPIN 0902862349 the following algorithm is used: 0 9 0 2 8 6 2 3 4 9 * 3 2 7 6 5 4 3 2 = 0 + 18 + 0 + 12 + 40 + 24 + 6 + 6 = 106 checkdigit = (11 - 106 % 11) % 11 I.e. each digit 1..8 is multiplied by 3..2, 7..2 respectively and the result of each multiplication added together to get 106. 106 is then used as the divend in a modulo operation with 11 as the divisor to get 7 which is then subtracted from 11 to get 4 - in this case the check digit, if the result had been 11 a second modulo operation 11 % 11 would have left us with 0. Only supports identity numbers assigned between the years 1800-2099. Please resurrect the author when this becomes an issue. Please report any bugs that aren't already listed at to Ævar Arnfjörð Bjarmason <avar@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/dist/Business-IS-PIN/lib/Business/IS/PIN.pm
CC-MAIN-2016-50
refinedweb
629
51.68
Ok, it's been a bit of time since I posted some technical content. I seem to be the only codebetter blogger who has big business aspirations and is launching a real ISV so I've been trying to mix that content into the Codebetter feed for those of you who have similar aspirations. I think it's time to get back to some technical content though. Using SQL Server to manage images (or other files) is a frequently asked question of mine. I have come across several clients in my consulting career where they were simply dumping the files into a physical directory on the webserver. In the end, this is pretty sloppy and difficult to manage especially if for some reason you want to reorganize the data. In this article I will show you the Easy Assets .NET method of handling image uploads. The application allows clients to store images of their assets, mostly for insurance purposes. I had a few goals for this section of the application as follows: Step 1: Configuring SQL Server First thing we must do is set up a SQL Server table to handle the data. SQL Server has a handy image field to handle this type of thing. Here's the table we'll be using in the example: CREATE TABLE [dbo].[AssetImages] ( [AssetImageID] [int] IDENTITY (1, 1) NOT NULL , [AssetID] [int] NOT NULL , [FileData] [image] NOT NULL , [FileName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [FileSize] [bigint] NOT NULL , [ContentType] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Thumbnail] [image] NOT NULL , [LastEditUser] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [LastEditDateTime] [datetime] NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GO The main image will be stored in the FileData field and the thumbnail image will be stored in the Thumbnail field. Step 2: Compressing the image To compress the image, I used the handy tool I mentioned in this post. You simply register the dll, and drag and drop the compressor tool onto the page. The following code uploads an image from the html file upload object, compresses it, and then generates a thumbnail. It uses my domain pattern, like all pages in Easy Assets .NET. Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click Try Dim upfile As HttpPostedFile = UploadFile.PostedFile ' Make sure there's actually content uploaded If upfile.ContentLength <> Nothing Then Dim myData() As Byte Dim stream As New MemoryStream Dim assetImage As New EasyAssets.DAC.AssetImage myData = ImageOptimizer1.Optimize(upfile) assetImage.FileSize = Convert.ToInt32(myData.Length / 1000) Dim i As Integer = InStrRev(upfile.FileName.Trim, "\") If i = 0 Then assetImage.FileName = upfile.FileName.Trim Else assetImage.FileName = Right(upfile.FileName.Trim, Len(upfile.FileName.Trim) - i) End If assetImage.AssetID = Convert.ToInt32(Request.QueryString("AID")) assetImage.FileData = myData assetImage.ContentType = upfile.ContentType Dim thumbnail As Bitmap = CreateThumbNail(New Bitmap(upfile.InputStream, False), 120, 120) thumbnail.Save(stream, ImageFormat.Jpeg) assetImage.Thumbnail = stream.GetBuffer() DomainManager.Save(assetImage) BindDataGrid() End If Catch ex As Exception WriteMessage(ex.Message, True) End Try End Sub Few things to note: Private Function CreateThumbNail(ByVal postedFile As Bitmap, ByVal width As Integer, ByVal height As Integer) As Bitmap Dim bmpOut As System.Drawing.Bitmap Dim Format As ImageFormat = postedFile.RawFormat Dim Ratio As Decimal Dim NewWidth As Integer Dim NewHeight As Integer '*** If the image is smaller than a thumbnail just return it If postedFile.Width < width AndAlso postedFile.Height < height Then Return postedFile End If If (postedFile.Width > postedFile.Height) Then Ratio = Convert.ToDecimal(width / postedFile.Width) NewWidth = width Dim Temp As Decimal = postedFile.Height * Ratio NewHeight = Convert.ToInt32(Temp) Else Ratio = Convert.ToDecimal(height / postedFile.Height) NewHeight = height Dim Temp As Decimal = postedFile.Width * Ratio NewWidth = Convert.ToInt32(Temp) bmpOut = New Bitmap(NewWidth, NewHeight) Dim g As Graphics = Graphics.FromImage(bmpOut) g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic g.FillRectangle(Brushes.White, 0, 0, NewWidth, NewHeight) g.DrawImage(postedFile, 0, 0, NewWidth, NewHeight) postedFile.Dispose() Return bmpOut End Function Step 3: Binding thumbnails to a datagrid Now, by default, you can't really show image data from sql server into a datagrid, so we have to sort of "trick" ASP .NET into inserting an image into the grid. We do this by calling a special aspx page into the template column of the grid. Here's how it works: First, set up the template column of the grid as such: Notice the call to the two pages, on click of the thumbnail I want to show them the full-size version of the photo in a popup window. The thumbnail is bound to a function called "formaturl" that takes the id of the image as a parameter. Let's take a look at this function: Protected Function FormatURL(ByVal imageID As Integer) As String Return ("AssetShowThumb.aspx?id=" & imageID.ToString()) So basically we have told asp.net that the source of this image is the results of the AssetShowThumb.aspx. But what does this page do? Let's take a look: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then Dim assetImg As New EasyAssets.DAC.AssetImage(Convert.ToInt32(Request.QueryString("ID"))) assetImg = DirectCast(DomainManager.Load(assetImg), EasyAssets.DAC.AssetImage) Response.ContentType = "Image/JPEG" Response.BinaryWrite(assetImg.Thumbnail) So all we've done is load the image record, set the content type to jpeg (I force all saves in the above function to be jpegs), and binary write the image data. We end up with a display like this: And an original image (on click of thumb) like this: And oh how I wish this picture, from my hawaii trip, was actually an asset of mine. =) [Advertisement] very useful article thankx to all it will work nice and helpful but can u tell me what is "EasyAssets.DAC.AssetImage" how can i get this pls replay urgently Thanks, I liked the tutorial. keep up the cool work Best Regards Thanks man, you're a star! This code is quality and it works very well :o) Etienne Lambert Another happy programmer. Hi great stuff but the compressing tools are all payed providing just free trial versions :( Khurram Hi, thanks for this article. I am 'porting'it to C3 and have a question: 1. is the source code donwnloadable for the comlpete worling example 2. in the function CreateThumbNail the ratio is calculated as an integer division. this means that for example that the ratio is 0 when the heigth of is 120 and the postedFile.Height = 250. the ratio of zero is giving an exception while creating the new bitmap since one of its dimensions is 0. Can you comment on that? Thanks, Jan hi, fine i need how to show the image from sql in asp.net using c# send a code to happysuresh@hotmail.com Hi, I read your article and the mention of the Bitmap.CreateThumbnail function. It does indeed sometimes distort the images when using this method, however there is a neat trick you can do which doesn;t distort the image. ' Force image to recreate thumbnail so not to distort image fullSizeImg.RotateFlip(Drawing.RotateFlipType.Rotate180FlipNone) If you do tis just before calling the GetThumbnailImage function the thumbnail will not be distorted. Just thought I would mention it. sir, i want to save the image of person in sqlserver and whenever required retrieve it. Im using the GDI and Response.OutputStream to generate the bitmap in aspx page. After doing the above said thing im giving that aspx page as imageURl to ImageButton which is the item of the datalist in another page. By doing this everthing working good and im displaying 20-30 images per page. The problem is that whenever i refresh the browser intially it showing blank page for while and then images are displayed. It woould be appreciable if given suggestions. hi eric, That's such a nice article. i want to do the same thing but it's not working using this code. some error occurs. Can u mail me the working code of the same.(pmjadeja.it@gmail.com) Thanks. Hi Awesome site. Thanks so much for putting it up Eric. Like other that have posted, I would like to retrieve the image from SQL Server. I have clicked on the links but they don't load. Can someone tell me how? Thanks George Sorry, Email is evansgeorge2@hotmail.com Great stuff, but is there a download for this anywhere? I read people asking for code but no one saying they recieved it. Thanks Good write up! Based on some of the feedback it looks like some folks were not able to get this working. I thought I would add a sample with everything in one method for ease. Note: get the Optimizer dll from In Visual Studio 'right click' the tool bar tab and select 'Choose Item' to add the control. Drag and drop this on a page. Create a reference to the resource dll. (right click the projects name and sellect add reference.) This example does not implement the thumbnail piece, this just save an optimized image to the DB and the retrieves it back and displays it. Note I use a stored procedure for saving and I get the scope_identity so I know the ID of the file I just saved. The stored procedure is.. ALTER PROCEDURE dbo.DHQ_InsertImage_sp ( @FileData image, @FileName nvarchar(50), @FileSize bigint, @ContentType nvarchar(50) ) AS INSERT INTO AssetImages(FileData, FileName, FileSize, ContentType) VALUES(@FileData,@FileName,@FileSize,@ContentType) RETURN Scope_Identity() The page code is......; public partial class DHQImage : System.Web.UI.UserControl { SqlCommand cmdGet; SqlConnection connect; SqlDataAdapter adapter; struct fileDetail { public Byte[] FileData; public string FileName; public Int32 FileSize; public string ContentType; public Byte[] Thumbnail; } protected void Page_Load(object sender, EventArgs e) protected void lnkUpImg_Click(object sender, EventArgs e) if (this.FileUpload1.HasFile) { HttpPostedFile pf = this.FileUpload1.PostedFile; if (pf.ContentLength != 0) { fileDetail container = new fileDetail(); container.FileData = this.imgOpt.Optimize(pf); container.FileSize = Convert.ToInt32(container.FileData.Length / 1000); container.FileName = pf.FileName; container.ContentType = pf.ContentType; // cmdSave = new System.Data.SqlClient.SqlCommand(); adapter = new SqlDataAdapter(); connect = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString()); connect.Open(); adapter.InsertCommand = new SqlCommand("DHQ_InsertImage_sp", connect); adapter.InsertCommand.CommandType = CommandType.StoredProcedure; adapter.InsertCommand.Parameters.Add("@FileData", System.Data.SqlDbType.Image); adapter.InsertCommand.Parameters["@FileData"].Value = container.FileData; adapter.InsertCommand.Parameters.Add("@FileName", System.Data.SqlDbType.NVarChar, 50); adapter.InsertCommand.Parameters["@FileName"].Value = container.FileName; adapter.InsertCommand.Parameters.Add("@FileSize", System.Data.SqlDbType.BigInt, 8); adapter.InsertCommand.Parameters["@FileSize"].Value = container.FileSize; adapter.InsertCommand.Parameters.Add("@ContentType", System.Data.SqlDbType.NVarChar, 50); adapter.InsertCommand.Parameters["@ContentType"].Value = container.ContentType; adapter.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int); adapter.InsertCommand.Parameters["@ID"].Direction = ParameterDirection.ReturnValue; //int iresult = adapter.InsertCommand.ExecuteNonQuery(); SqlDataReader read = adapter.InsertCommand.ExecuteReader(CommandBehavior.SingleResult); int resultID = Convert.ToInt32(adapter.InsertCommand.Parameters["@ID"].Value); read.Close(); connect.Close(); cmdGet = new System.Data.SqlClient.SqlCommand(); cmdGet.CommandText = "SELECT FileData FROM AssetImages WHERE AssetImageID = " + resultID + ""; cmdGet.Connection = connect; byte[] GetImg = (byte[])cmdGet.ExecuteScalar(); connect.Dispose(); if (GetImg != null) { Response.ContentType = "image/jpeg"; Response.Expires = 0; Response.Buffer = true; Response.Clear(); Response.BinaryWrite(GetImg); Response.End(); } } } } One last thing.... The connection string is in the Web.Config file within the configuration element. <connectionStrings> <add name="conn" connectionString="Data Source=[Your DB Server];Initial Catalog=[Db Name];Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> That's about it really...you could probably cut and paste this example. After 3 hours of trying to make things happend I gave up It dosen't work for me edd@andrewlauren.com I wish I can download the code for this blog To get the images in SQL server you just declare a Byte array: public Byte[] FileData; After adding the 'Optimizer' dll to your reference and tools, you drag it to the form and change a couple properties. Get the file from the file upload control and validate its length: HttpPostedFile pf = this.FileUpload1.PostedFile; if (pf.ContentLength != 0) Pass the posted file to the optimizer.... FileData = this.imgOpt.Optimize(pf); Get all info you feel you need (like name, file size, content type, etc..) Create your Sql command, connection, command text or stored procedure. Execute to save. The keys are: - Get the file - You pass the file object to the optimizer - You must save the image in Bytes (or convert the size to KB size/1000) and save the Byte stream to a Byte array data type. - This gets saved into a data table field of type image (for Sql server) When you want to display the image again.... - Create an aspx form and place the logic to get and display the image Example: protected void Page_Load(object sender, EventArgs e) int IDImage = Convert.ToInt32(Request.QueryString["ID"]); try if (connect.State != ConnectionState.Open) if (IDImage > 0) cmdGet.CommandText = "SELECT FileData FROM AssetImages WHERE AssetImageID = " + IDImage + ""; GetImg = (byte[])cmdGet.ExecuteScalar(); Response.ContentType = "image/jpeg"; Response.Expires = 0; Response.Buffer = true; Response.Clear(); Response.BinaryWrite(GetImg); //Response.End(); HttpContext.Current.ApplicationInstance.CompleteRequest(); catch (Exception ex) { } finally connect.Close(); NOTE: I made this as trim as I could. Also, I dont use Response.End(); because it causes false errors. Use HttpContext.Current.ApplicationInstance.CompleteRequest() instead. Now....this page will get called from any other page where you want the image to be displayed. You can do this in a Datalist, DataGrid, etc...control or just and asp Image control. Datalist example: <form id="form1" runat="server"> <asp:DataList <ItemTemplate> <asp:Image ID="img" Width="550" ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "AssetImageID")) %>' Runat=server /> </ItemTemplate> </asp:DataList><asp:SqlDataSource</asp:SqlDataSource> </form> You can see this calls the method in the code behind... public string FormatURL(object _id) int num = Convert.ToInt32(_id); return ("~/GetImage.aspx?id=" + _id); ...and GetImage.aspx is the page you created to get and display the image. Note: Create a data source and bind your control. specify the name of the data source and the field in your table to evaluate. (Container.DataItem, "AssetImageID") and my container is using SqlDataSource1 which has a text Sql query. Thats it really...if you just want to throw an Image control on the form then it loojks like this: <asp:Image Code behind... this.Image1.ImageUrl = FormatURL(ParameterImageID); ..and the GetImage.aspx page will get the ID and pass it to the method we have seen above. Now make sure you placed the Optimizer control on your form so it is registered on the page.. <%@ Register Src="DHQImage.ascx" TagName="DHQImage" TagPrefix="uc1" %> Lets see.... The thumbnail piece....not sure why you would go through all that???? I already have the image and I optimized it once. I could change the properties and pass the image through it again to make it much smaller and save both. One as the regular optimized and the other as a really optimized (smaller version). Unless I'm missing something thats what I would do.... Hope this helps There is working code in the easy assets .net source code which is available at The Image Optimizer dll fails to work on hosted accounts. You may get an error "System.Security.SecurityException: That assembly does not allow partially trusted callers." This is because they didn't add "Allow Partially Trusted Callers Attribute (APTC) attribute" to the assembly. I assume this only happens with the free download. Maybe this is not an issue if you want to pay for this "Free" control. -Chuck Eric, my solution works great locally. I noticed when I deploy my site and access the page where I'm using the Image optimizer control I get an err: System.Security.SecurityException: That assembly does not allow partially trusted callers. Is the paid version of this control signed?? Honestly I have no idea whether it is signed. When I wrote this article and used this control back in 2005 it was free. I haven't kept up with future releases. Eric, How did you do your onclick function to allow for the thumbnail image to display the original image? hi am new to this image uploading to sql server. actually i'm in dilemma whether to store my images in sql server or in a file system. My data may contain 200000 records with each images size around 250KB. and it'll grow around 2% per month. I would appreciate your suggestion regd the same. Chary- It depends on the size and power of your database. 200,000 records really isn't all that many in the grand scheme of things. Will you have a process in place to backup and purge old data? Thnx Eric for the reply. Our client insisted to store in filesystem Very impressive code snippet, this has kept me going for hours and I must say I am really enjoying it. Is there a chance you can put some comments in the VB code so that I can dissect it and understand it? I�m trying to understand how you are uploading the thumbnail when you don�t have a connection string! I know your code must work from your other classes but I can�t seem to understand where or how your connection string is used. Kind Regards and thank God for people like you� Can you help me out please? Im moving onto ASP.net c# from Perl and PHP. Starting with the basics I sett up a simple site with content management system. I need to upload images and attach them to pages. (simple enough for me in php and perl!) So after building the content management side (simple add page and modify page scripts) I decided to add a couple of pages which are for adding images and browsing images in the database. I admit I find it hard to read c# at the moment but I picked out a couple of lines from your code and added them to my code...eventually I had this:- byte[] b = (byte[])dt.Rows[0]["data"]; System.Web.UI.WebControls.Image i = new System.Web.UI.WebControls.Image(); Response.OutputStream.Write(b, 0, b.Length); and this outputs an image!!! Whoop! Wahey! Now can I ask you how I store that image in a tempory file so I can call it with <asp:img> image tag and set its size and height? Your help is much appreciated :)) G Thank you very much this article is very useful Hi, beginner here, but.. 1 kilobyte = 1024 bytes, not 1000 bytes Hai developer I have few questions firstly we have to bought the compressor component or its freeware software. Without compressor compnent we cannot compress the photo files is it mandatory to have the component. If you can give the code without compressor component it will be great help. Thanks for the post, I tried the component in my app, it works really good. I can't believe how I was doing without it so far... Thanks a million. Rob hi eric the code is excellent when i tested some , but i got stucked up at one thing that is whats "DomainManager" what is that you are doing in that. Can you please help me out. and one more thing after downloading and using the image optimizer dll i found that it creates a website address over the thumbnail..i need to remove that can you please let me known.. thanks & Regards Ranjeet Kumar hi i am venkat this is my id venkat5054@rediffmail.com can u pls send ur full code.. to my id and alos tell how shall i add the DLL files , when i clickt the link it show some page , tell wat the procedure to get the tool in tat page.. Thanks... Pingback from Reality Me » Do you store images in a database? Pingback from How to have a image column in a datagrid? |
http://codebetter.com/blogs/eric.wise/archive/2005/05/15/63236.aspx
crawl-002
refinedweb
3,312
50.84
Nextjs + Beginner 5 Most Commonly error face is Next.js? Based on my experience, I create a list of comma errors that repeatedly occur in the nextjs. Next.js is an excellent library in the reactjs world. When you use nextjs every day, you face similar problems repeatedly. Even I know to error is raised. But You know I'm a sluggish person. For In this article, I discuss the five most common errors that occur in next js again and again in daily life. I'm also going to solve the mistakes in easy ways. Note This article is for next.js beginner developers. Suppose you are a beginner person. That article serves you. Error List - Missing slash (/) - Class - Link - Image - Global CSS Missing slash (/) You forget slash in element. But most I forget the slash in the link and img element. This error occurs due to the unclosing tag. in reactjs, everything is based on the open and closing tag. When do not close the proper opening tag in reactjs or nextjs? Because every element in react.js is jsx, and every JSX has an opening and closing tag. Then you face this error. Error First example <Head> <title> Home </title> <link rel="icon" href="favicon.ico"></Head> Solution First example solution You add slash(/) end of HTML link element. <Head> <title> Home </title> <link rel="icon" href="favicon.ico" / ></Head> Error Second example <img height="800" width="100%" src=""> Solution Second example solution You add slash(/) end of HTML img element. <img height="800" width="100%" src=""/> Class Sometimes we try to convert an HTML template into reactjs and nextjs. Then every time I forget to convert class to className. This error is related to the dom property; In javascript, the class HTML property converts to className—the className property instance of the HTML class. Error <div class="card"> <h2> Hello World </h2></div> Solution Simple you change HTML class to javascript className property <div className="card"> <h2> Hello World </h2></div> Link In HTML, we use navigation. for navigation we use <a> anchor tag. But nextjs provide a Link component. You do not warp around the link component into the anchor tag. You face similar errors or warning in run lint and build command in next.js. Error <div className="card"> <h2> link href error </h2> <a href="/about">About us </a></div> Solution Simple you warp HTML <a> to nextjs Link component. <div className="card"> <h2> link href error </h2> <Link href="/about"> <a>About us </a> </Link></div> Image In nextjs, we do not use the image component for the image. For images, we use HTML img element. So that reason we face a warning in nextjs. Most of the time, issues are automatically detected by IDE (vscode) or secondly when we run the lint configuration and nextjs build command in nextjs. Then face image issue. Image component warning is a big issue when converting the reactjs app into nextjs. On the website, the major role of the image is to represent the website. But in nextjs, nextjs does not use the img element or tag. If you use img in nextjs, you need to use the image component. Error or warning <div className="card"> <h2> Image error </h2> <img alt=" random here" height="800" width="100%" src="" /></div> Solution Simple you change HTML <img> element to nextjs Imagecomponent. <div className="card"> <h2> Image error </h2> <Image alt=" random here" height="350" width="600" src="" /></div> Global CSS In nextjs, you do not import global files on every page. If you do that, you face a failed compile error in nextjs. Error import Image from "next/image"; import "../global.css";export default function IndexPage() {return ( <div className="card"> <h2> Image error </h2> <Image alt=" random here" height="350" width="600" src="" /> </div>);} Solution Always Import global CSS file inside _app.js file. import "../global.css";function MyApp({ Component, pageProps }) { return <Component {...pageProps} />;}export default MyApp; Previous Articles In which case do we need to update reactjs to nextjs? Why do we need to update reactjs to nextjs? medium.com How Many Hooks are Present in React? The hook is a way to write less and cleaner code in React. javascript.plainenglish.io Conclusion I discuss those common problems which in mind now. But there is also another problem you also face in daily life. But I provide a basic idea about that. If you encounter any other issues, let me know in the comment section. So everyone sees that.. Rajdeep Singh This website I created was for beginner people to understand the basic concept of programming. Mainly cover a topic. officialrajdeepsingh. dev Read More content at Nextjs. Sign up for a free newsletter and join the nextjs community on medium.
https://medium.com/nextjs/5-most-commonly-error-face-is-next-js-223eab955b83?source=post_internal_links---------6----------------------------
CC-MAIN-2022-27
refinedweb
796
59.09
markusthoemmes commented on a change in pull request #4582: Action container log collection does not wait for sentinel on developer error URL: ########## File path: core/invoker/src/main/scala/org/apache/openwhisk/core/containerpool/docker/DockerContainer.scala ########## @@ -257,17 +257,43 @@ class DockerContainer(protected val id: ContainerId, * previous activations that have to be skipped. For this reason, a starting position * is kept and updated upon each invocation. * - * If asked, check for sentinel markers - but exclude the identified markers from - * the result returned from this method. + * There are two possible modes controlled by parameter waitForSentinel: * - * Only parses and returns as much logs as fit in the passed log limit. + * 1. Wait for sentinel: tail container log file until two sentinel markers show up. Complete + * once two sentinel markers have been identified, regardless whether more + * data could be read from container log file. + * A log file reading error is reported if sentinels cannot be found. + * Managed action runtimes use the the sentinels to mark the end of + * an individual activation. + * + * 2. Do not wait for sentinel: read container log file up to its end. Stop reading once the end + * has been reached. Complete once two sentinel markers have been + * identified, regardless whether more data could be read from + * container log file. + * No log file reading error is reported if sentinels cannot be found. + * Blackbox actions do not necessarily produce marker sentinels properly, + * so this mode is used for all blackbox actions. + * In addition, this mode can / should be used in error situations with + * managed action runtimes where sentinel markers may be missing or + * arrive too late - Example: action exceeds time or memory limit during + * init or run. + * + * The result returned from this method does never contain any log sentinel markers. These are always + * filtered - regardless of the specified waitForSentinel mode. + * + * Only parses and returns as much logs as fit in the passed log limit. Stops log collection with an error + * if processing takes too long or time gaps between processing individual log lines are too long. * * @param limit the limit to apply to the log size * @param waitForSentinel determines if the processor should wait for a sentinel to appear - * * @return a vector of Strings with log lines in our own JSON format */ def logs(limit: ByteSize, waitForSentinel: Boolean)(implicit transid: TransactionId): Source[ByteString, Any] = { + // Define a time limit for collecting and processing the logs of a single activation. + // If this time limit is exceeded, log processing is stopped and declared unsuccessful. + // Allow 2 seconds per MB log limit, with a minimum of 10 seconds. + val logProcessingTimeout = limit.toMB.toInt.max(5) * 2.seconds Review comment: This is somewhat arbitrary and might need some tweaking. Can you run this code through a loadtest to determine we don't hit this overall timeout under load too
http://mail-archives.apache.org/mod_mbox/openwhisk-issues/201908.mbox/%3C156567891252.14553.13578607224978634656.gitbox@gitbox.apache.org%3E
CC-MAIN-2019-47
refinedweb
462
53.71
In this last post of this series, I test the performance of Bluemix & MongoDB against concurrent queries and deletes to the cloud based app with Mongo DB, with auto-scaling on. Before I started these series of tests I moved the Overload policy a couple of notches higher and made it scale out if memory utilization > 75% for 120 secs and < 30% for 120 secs (from the earlier 55% memory utilization) as shown below. The code for bluemixMongo app can be forked from Devops at bluemixMongo or can be cloned from GitHub at bluemix-mongo-autoscale. The multi-mechanize scripts can be downloaded from GitHub at multi-mechanize Before starting the testing I checked the current number of documents inserted by the concurrent inserts (see Bend it like Bluemix., MongoDB using Auto-scaling – Part 2). The total number as determined by checking the logs was 1380 Sure enough with the scaling policy change after 2 minutes the number of instanced dropped from 3 to 2 1. Querying the bluemixMongo app with Multi-mechanize The Multi-mechanize Python script used for querying the bluemixMongo app simply invokes the app’s userlist URL (resp=br.open(“”) v_user.py def run(self): # create a Browser instance br = mechanize.Browser() # don"t bother with robots.txt br.set_handle_robots(False) # start the timer start_timer = time.time() #print("Display userlist") # Display 5 random documents resp=br.open("") assert("Example Mongo Page" in resp.get_data()) # stop the timer latency = time.time() - start_timer self.custom_timers["Userlist"] = latency r = random.uniform(1, 2) time.sleep(r) self.custom_timers['Example_Timer'] = r The configuration setup for this script creates 2 sets of 10 concurrent threads config.cfg run_time = 300 rampup = 0 results_ts_interval = 10 progress_bar = on console_logging = off xml_report = off [user_group-1] threads = 10 script = v_user.py [user_group-2] threads = 10 script = v_user.py The corresponding userlist.js for querying the app is shown below. Here the query is constructed by creating a ‘RegularExpression’ with a random Firstname, consisting of a random letter and a random number. Also the query is also limited to 5 documents. function(callback) { // Display a random set of 5 records based on a regular expression made with random letter, number + ".*"; // Limit the display to 5 documents var results = collection.find({"FirstName": new RegExp(val)}).limit(5).toArray(function(err, items){ if(err) { console.log(err + " Error getting items for display"); } else { res.render('userlist', { "userlist" : items }); // end res.render } //end else db.close(); // Ensure that the open connection is closed }); // end toArray function callback(null, 'two'); } 2. Running the userlist query The following screenshot shows the userlist query being executed concurrently with Multi-mechanize. Note that the number of instances also drops down to 1 3. Deleting documents with Multi-mechanize The multi-mechanize script for deleting a document is shown below. This script calls the URL with resp = br.open(“”). No values are required to be entered into the form and the ‘submit’ is simulated. v_user.py def run(self): # create a Browser instance br = mechanize.Browser() # don"t bother with robots.txt br.set_handle_robots(False) br.addheaders = [("User-agent", "Mozilla/5.0Compatible")] # start the timer start_timer = time.time() # submit the request resp = br.open("") #resp = br.open("") resp.read() # stop the timer latency = time.time() - start_timer # store the custom timer self.custom_timers["Load_Front_Page"] = latency # think-time time.sleep(2) # select first (zero-based) form on page br.select_form(nr=0) # set form field br.form["firstname"] = "" br.form["lastname"] = "" br.form["mobile"] = "" # start the timer start_timer = time.time() # submit the form resp = br.submit() resp.read() print("Removed") # stop the timer latency = time.time() - start_timer # store the custom timer self.custom_timers["Delete"] = latency # think-time time.sleep(2) config.cfg The config file is set to start 2 sets of 10 concurrent threads and execute for 300 secs [global] run_time = 300 rampup = 0 results_ts_interval = 10 progress_bar = on console_logging = off xml_report = off [user_group-1] threads = 10 script = v_user.py [user_group-2] threads = 10 script = v_user.py ; deleteuser.js This Node.js script does a findOne() document and does a remove with the ‘justOne’ set to true collection.findOne(function(err, item) { // Delete just a single record collection.remove(item, {justOne:true},(function (err, doc) { if (err) { // If it failed, return error res.send("There was a problem removing the information to the database."); } else { // If it worked redirect to userlist res.location("userlist"); // And forward to success page res.redirect("userlist"); } })); }); collection.find().toArray(function(err, items) { console.log("Length =----------------" + items.length); db.close(); }); callback(null, 'two'); 4. Running the deleteuser multimechanize script The output of the script executing and the reduction of the number of instances because of the change in the memory utilization policy is shown 5. Multi-mechanize As mentioned in the previous posts The multi-mechanize commands are executed as follows To create a new project multimech-newproject.exe userlist This will create 2 folders a) results b) test_scripts and the file c) config.cfg. The v_user.py needs to be updated as required To run the script multimech-run.exe userlist The details of the response times for the query is shown below . More details on latency and throughput for the queries and the deletes are included in the results folder of multi-mechanize 6. Autoscaling The details of the auto-scaling service is shown below a. Scaling Metric Statistics 7. Monitoring and Analytics (M & A) The output from M & A is shown below a. Performance Monitoring b. Log Analysis output The log analysis give a detailed report on the calls made to the app, the console log output and other useful information The series of the 3 posts Bend it like Bluemix, MongoDB with auto-scaling demonstrated the ability of the cloud to expand and shrink based on the load on the cloud.An important requirement for Cloud Architects is design applications that can scale horizontally without impacting the performance while keeping the costs optimum. The real challenge to auto-scaling is the need to make the application really distributed as opposed to the monolithic architectures we are generally used to. I hope to write another post on creating simple distributed application later. Hasta la Vista! Also see 1. Bend it like Bluemix, MongoDB with autoscaling – Part 1 2. Bend it like Bluemix, MongoDB with autoscaling – Part 2
https://gigadom.in/category/node-express/
CC-MAIN-2020-16
refinedweb
1,048
51.65
Created on 2010-02-22 21:58 by eric.smith, last changed 2014-03-20 00:54 by hct. This issue is now closed. Background: format(obj, fmt) eventually calls object.__format__(obj, fmt) if obj (or one of its bases) does not implement __format__. The behavior of object.__format__ is basically: def __format__(self, fmt): return str(self).__format__(fmt) So the caller of format() thought they were passing in a format string specific to obj, but it is interpreted as a format string for str. This is not correct, or at least confusing. The format string is supposed to be type specific. However in this case the object is being changed (to type str), but the format string which was to be applied to its original type is now being passed to str. This is an actual problem that occurred in the migration from 3.0 -> 3.1 and from 2.6 -> 2.7 with complex. In the earlier versions, complex did not have a __format__ method, but it does in the latter versions. So this code: >>> format(1+1j, '10s') '(1+1j) ' worked in 2.6 and 3.0, but gives an error in 2.7 and 3.1: >>> format(1+1j, '10s') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 's' for object of type 'complex' Proposal: object.__format__ should give an error if a non-empty format string is specified. In 2.7 and 3.2 make this a PendingDeprecationWarning, in 3.3 make it a DeprecationWarning, and in 3.4 make it an error. Modify the documentation to make this behavior clear, and let the user know that if they want this behavior they should say: format(str(obj), '10s') or the equivalent: "{0!s:10}".format(obj) That is, the conversion to str should be explicit. Proposed patch attached. I need to add tests and docs. issue7994-0.diff is against trunk. This version of the patch adds support for classic classes and adds tests. Documentation still needs to be written. Again, this diff is against trunk. If anyone wants to review this, in particular the tests that exercise PendingDeprecationWarning, that would be great. Patch with Misc/NEWS. The patch looks reasonable. I built on it with the following changes: 1. Added some extra test cases to cover Unicode format strings, since the code was changed to handle these as well. 2. Changed test_builtin.py by s/m[0].message.message/str(w[0].message)/, since BaseException.message was deprecated in 2.6. I also have the following general comments: 1. PEP 3101 explicitly defines the string conversion for object.__format__. What is the rationale behind this? Should we find out before making this change? 2. I don't think the comments in 'abstract.c' and 'typeobject.c' explaining that the warning will eventually become an error are needed. I think it would be better to open separate issues for these migration steps as they can be tracked easier and will be more visible. 3. test_unicode, test_str have cases that trigger the added warning. Should they be altered now or when (if) this becomes an error? I haven't looked at the patch, but: Thanks for the the additional tests. Missing unicode was definitely a mistake. str(w[0].message) is an improvement. The PEP is out of date in many respects. I think it's best to note that in the PEP and continue to keep the documentation up-to-date. This issue already applies to 3.3, but my plan is to remove that and create a new issue when I close this one. But I'd still like to leave the comments in place. I'm aware of the existing tests which trigger the warning. I think they should probably be removed, although I haven't really spent much time thinking about it. Meador: Your patch (-3) looks identical to mine (-2), unless I'm making some mistake. Could you check? I'd like to get this applied in the next few days, before 2.7b1. Thanks! Hi Eric, (-2) and (-3) are different. The changes that I made, however, are pretty minor. Also, they are all in 'test_builtin.py'. Committed in trunk in r79596. I'll leave this open until I port to py3k, check the old tests for this usage, and create the issue to make it a DeprecationWarning. This should be merged before 3.2 beta. now the PendingDeprecationWarnings are checked in the test suite, with r84772 (for 2.7). Manually merged to py3k in r84790. I'll leave this open until I create the 3.3 issue to change it to a DeprecationWarning. See issue 9856 for changing this to a DeprecationWarning in 3.3. New changeset f56b98143792 by R David Murray in branch 'default': whatsnew: object.__format__ raises TypeError on non-empty string. just found out about this change in the latest official stable release and it's breaking my code all over the place. something like "{:s}".format( self.pc ) used to work in 3.3.4 and prior releases now raise exception rather then return a string 'None' when self.pc was never update to not None (was initialized to None during object init). this means I have to manually go and change every single line that expects smooth formatting to a check to see if the variable is still a 'NoneType'. should we just create a format for None, alias string format to repr/str on classes without format implementation or put more thought into this I think the best we could do is have None.__format__ be: def __format__(self, fmt): return str(self).__format__(fmt) Or its logical equivalent. But this seems more like papering over a bug, instead of actually fixing a problem. My suggestion is to use: "{!s}".format(None) That is: if you want to format a string, then explicitly force the argument to be a string. I don't think None should be special and be auto-converted to a string. I use lots of complicated format such as the following "{:{:s}{:d}s}".format( self.pcs,self.format_align, self.max_length ) it looks like the way to do it from now on will be "{!s:{:s}{:d}}".format( self.pcs,self.format_align, self.max_length ) Or: "{:{:s}{:d}s}".format(str(self.pcs), self.format_align, self.max_length) You're trying to apply the string format specifier (the stuff after the first colon through the final "s", as expanded) to an object that's not always a string: sometimes it's None. So you need to use one of the two supported ways to convert it to a string. Either str() or !s. str.format() is very much dependent on the types of its arguments: the format specifier needs to be understood by the object being formatted. Similarly, you couldn't pass in a datetime and expect that to work, either. unlike NoneType, datetime doesn't throw exception. is returning the format specifier the intended behaviour of this fix? >>> import datetime >>> a=datetime.datetime(1999,7,7) >>> str(a) '1999-07-07 00:00:00' >>> "{:s}".format(a) 's' >>> "{:7s}".format(a) '7s' >>> "{!s}".format(a) '1999-07-07 00:00:00' >>> Yes. It is not returning the format specifier, it is filling in the strftime template "s" from the datetime...which equals "s", since it consists of just that constant string. Try {:%Y-%m-%d}, for example. Which, by the way, has been the behavior all along, it is not something affected by this fix, because datetime *does* have a __format__ method. None does have __format__, but it raises exception >>> dir(None) ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> None.__format__ <built-in method __format__ of NoneType object at 0x50BB2760> That's not an exception, you've not actually called the function. >>> None.__format__('') 'None' David is correct. It's often easiest to think about the builtin format() instead of str.format(). Notice below that the format specifier has to make sense for the object being formatted: >>> import datetime >>> now = datetime.datetime.now() >>> format('somestring', '.12s') 'somestring ' # "works", but not what you want because it calls now.strftime('.12s'): >>> format(now, '.12s') '.12s' # better: >>> format(now, '%Y-%m-%d') # better '2014-03-19' # int doesn't know what '.12s' format spec means: >>> format(3, '.12s') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 's' for object of type 'int' # None doesn't have an __format__, so object.__format__ rejects it: >>> format(None, '.12s') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: non-empty format string passed to object.__format__ # just like a random class doesn't have an __format__: >>> class F: pass ... >>> format(F(), '.12s') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: non-empty format string passed to object.__format__ Tangentially related: The best you can do here, given your use case, is to argue that None needs an __format__ that understands str's format specifiers, because you like to mix str and None. But maybe someone else likes to mix int and None. Maybe None should understand int's format specifiers, and not str's: >>> format(42000, ',d') '42,000' >>> format('42000', ',d') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 'd' for object of type 'str' Why would "format(None, '.12s')" make any more sense than "format(None, ',d')"? Since we can't guess, we chose an error. NoneType is a subclass of object. >>> class Foo(object): ... pass ... >>> f = Foo() >>> f.__format__ <built-in method __format__ of Foo object at 0xb71543b4> ie: the exception is being raised by object.__format__, as provided for by this issue. BreamoreBoy: This is basically the definition of object.__format__: def __format__(self, specifier): if len(specifier) == 0: return str(self) raise TypeError('non-empty format string passed to object.__format__') Which is why it works for an empty specifier. As a reminder, the point of raising this type error is described in the first message posted in this bug. This caused us an actual problem when we implemented complex.__format__, and I don't see object.__format__ changing. Implementing NoneType.__format__ and having it understand some string specifiers would be possible, but I'm against it, for reasons I hope I've made clear. As to why None.__format__ appears to be implemented, it's the same as this: >>> class Foo: pass ... >>> Foo().__format__ <built-in method __format__ of Foo object at 0xb74e6a4c> That's really object.__format__, bound to a Foo instance. I think was confused as I forgot that I was doing str.format where {} being format of str. confusion cleared
http://bugs.python.org/issue7994
CC-MAIN-2017-09
refinedweb
1,810
68.57
09 March 2010 22:32 [Source: ICIS news] HOUSTON (ICIS news)--Colombia's sole polyethylene (PE) producer, Ecopetrol, increased prices of low density polyethylene (LDPE) by as much as 3.6% effective on Tuesday as part of a weekly adjustment, the producer said. Prices are revised every week in ?xml:namespace> Currency fluctuations are also considered for the price moves, in addition to raw materials and polymer prices in benchmark markets. The Colombian currency has made some gains against the dollar of late, and this has made imports more competitive in the country. The price of bagged LDPE material was set at Colombian pesos (Ps) 3,960/kg, equivalent to $2,097/tonne (€1,531/tonne). The price of bulk LDPE material was set at Ps3,710/kg. These prices are for cash transactions and for material delivered at The price for large-volume LDPE buyers, which receive a discount, was pegged by local sources at Ps3,335/kg. Ecopetrol produces only LDPE in its production plants. Other grades of PE are imported. ($1 = €0.73) For more on polyethylene
http://www.icis.com/Articles/2010/03/09/9341323/colombias-ecopetrol-hikes-ldpe-prices-up-to-3.6.html
CC-MAIN-2013-48
refinedweb
180
64.91
The libxml2 library implements XML namespaces: <mydoc xmlns=""> <elem1>...</elem1> <elem2>...</elem2> </mydoc>, "" is a good namespace scheme. "" ns field pointing to an xmlNs structure detailing the namespace prefix and its URI. ns @@Interfaces@@ xmlNodePtr node; if(!strncmp(node->name,"mytag",5) && node->ns && !strcmp(node->ns->href,"")) { ... } xmlns="http://...." should not break validity even on less flexible parsers. Using namespaces to mix and differentiate content coming from multiple DTDs will certainly break current validation schemes. To check such documents one needs to use schema-validation, which is supported in libxml2 as well. See relagx-ng and w3c-schema. xmlns="http://...." Daniel Veillard
https://opensource.apple.com/source/libxml2/libxml2-21.3/libxml2/doc/namespaces.html
CC-MAIN-2017-43
refinedweb
103
51.95