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
Generic Controller Interfaces Generic controller interfaces are general-purpose interfaces that you can use to model different components for your implementation of the Alexa Voice Service (AVS). The AVS APIs include three generic controllers: - ModeController – Models properties of a device that you can set to one of a list of values. - RangeController – Models properties of a device that you can set to one of a range of values. - ToggleController – Models properties of a device that you can set to on or off. For most scenarios, choose the most specific controller available to model components of your devices, because the more specific the controller, the more natural the utterances are for your user. However, generic controllers provide some benefits not available with more specific controllers: - Multiple instances – Create multiple instances of a controller for a single device. - Semantics – Semantics offer devices the ability to map specific utterances to the behaviors and states of controller instances. Multiple instances Multiple instances enable a device to implement multiple instances of the same controller. For example, your device might be a laundry machine with a wash cycle selector and a progress indicator. Given that both the wash cycle selector and the progress indicator would likely have a list of possible values. The ModeController allows the one laundry machine to implement the controller as two instances, for example, a Wash.Cycle instance and a Wash.Progress instance. Multiple instance syntax Declare your device support for various AVS interfaces with the namespace field value in the header objects of events, directives, and generic context entries, and reportable state property objects. When you declare support for an instance of a generic controller through Alexa.Discovery, the equivalent of the namespace field is the interface field. Declare individual instances of a generic controller through the instance field. For example, in the laundry machine scenario, when Alexa sends directives to the device, the header includes Alexa.ModeController as the namespace and then either Wash.Cycle or Wash.Progress as the instance. When the device sends the mode value to Alexa, it includes Wash.Cycle and Wash.Progress in the instance fields of the property object. Use the nonControllable field to specify whether a user can control the mode of a given instance: - For example, because a user controls the modeof Wash.Cyclethrough an interaction, you set the nonControllablefiled to falsefor the Wash.Cycleinstance of ModeController. - By contrast, because a user can only query but not control the modevalue of Wash.Progress, you set nonControllableto truefor the Wash.Progressinstance of ModeController. Semantics In addition to multiple instance support, generic controllers offer devices the ability to map specific utterances to the behaviors and states of controller instances. Consider an example where a device implements an instance of RangeController with states of "open" and "closed." The device can declare which values within the range map to each of these states and define what value to set when the user asks Alexa to "open" or "close" the device. Semantics enable two categories of experiences: - Actions or instructions, such as "Alexa, open the blinds." - State inquiries, such as "Alexa, are the blinds open?" To implement semantics, map your actions and states for your scenarios. Map them in the semantics object within the capabilities object for each instance of your controller. Semantics syntax -on't overlap. - The same actionsvalue may not appear in multiple objects in the same actionMappingslist. Similarly, the same statesvalue may not appear in multiple objects in the same stateMappingslist. Example object The following example shows the syntax for a semantics object: "semantics": { "actionMappings": [ { "@type": "ActionsToDirective", "actions": ["{{STRING}}", ...], "directive": { "name": "{{STRING}}", "payload": {{OBJECT}} } }, ... ], "stateMappings": [ { "@type": "StatesToValue", "states": ["{{STRING}}", ...], "value": {{POLYMORPHIC}} }, { "@type": "StatesToRange", "states": ["{{STRING}}", ...], "range": { "minimumValue": {{LONG}}, "maximumValue": {{LONG}} } }, ... ] } Object parameters Related topics - Alexa.ModeController API reference - Alexa.RangeController API reference - Alexa.ToggleController API reference
https://developer.amazon.com/it-IT/docs/alexa/alexa-voice-service/generic-controllers.html
CC-MAIN-2022-05
refinedweb
632
50.02
Computer Science Archive: Questions from August 11, 2010 - zigtozag asked2 answers - Anonymous asked1 answer - Anonymous asked3 answers - Anonymous askedpublic void getMove(char[][] theBoard, char myPiece)... Show moreimport java.util.Random; public class TicTacToe {; } } HERE IS THE CODE Random myRand = new Random(); int myRow=0,myCol=0; do { myRow = myRand.nextInt(3); myCol = myRand.nextInt(3); }while(theBoard[myRow][myCol]!= ' '); theBoard[myRow][myCol] = myPiece; System.out.println(myPiece+ "your move" "+myRow+","+myCol); } Instruction say Change this method to intelligently play tic-tac-toe (for whatever piece it has been passed – X or O). Whats the problem with this to play this game intelligently? • Show less1 answer - zigtozag asked1 answer - zigtozag askedWhat do you see as the pros and cons of a CLI? What kinds of users do you think should be allowed to... Show moreWhat do you see as the pros and cons of a CLI? What kinds of users do you think should be allowed to use this interface and for what purpose? Give a rationale for your answer. • Show less2 answers - Anonymous asked0 answers - Anonymous asked(Account Inheritance Hierarchy) Create an inheritance hierarchy that a bank might use to represent c... Show more-Account and CheckingAccount that inherit from class Account. Base class Account should include one data member of type double to represent- Cost: $4.25 Package 2: Sender: Lisa Klein 5 Broadway Somerville, MA 33333 Recipient: Bob George 21 Pine Rd Cambridge, MA 44444 Cost: $8.82 Package 3: Sender: Ed Lewis 2 Oak St Boston, MA 55555 Recipient: Don Kelly 9 Main St Denver, CO 66666 Cost: $11.64 Account. • Show less1 answer - Anonymous askedEvery computer on the Internet has a unique identifying number, called an Internet protocol (IP) add... Show moreEvery computer on the Internet has a unique identifying number, called an Internet protocol (IP) address. To contact a computer on the Internet, you send a message to the computer’s IP address. Here are some typical IP addresses: 216.27.6.136 224.0.118.62 There are different formats for displaying IP addresses, but the most common format is the dotted decimal format. The above two IP addresses use the dotted-decimal format. It’s called “dotted” because dots are used to split up the big IP address number into four smaller numbers. It’s called “decimal” because decimal numbers are used (as opposed to binary) for the four smaller numbers. Each of the four smaller numbers is called an octet because each number represents eight bits (oct means eight). For example, the 216 octet represents 11011000 and the 27 octet represents 00011011. Implement an IpAddress class that stores an IP address as four octet ints. You must implement all of the following: Instance variables: firstOctet, secondOctet, thirdOctet, fourthOctet – four int variables that store the octets for an IP address Constructor: This constructor receives one parameter, a dotted-decimal string. You may assume that the parameter’s value is valid (i.e., no error checking required). The constructor initializes the instance variables with appropriate values. There are many ways to solve the problem of extracting octets from the given dotted-decimal string. We recommend that you use String methods to extract the individual octets as strings, and then use the parseInt method of the Integer wrapper class to convert the octet strings to ints. getDottedDecimal method: Returns a string representing the IP address in dotted decimal notation. getOctet method: This method receives the position of one of the octets (1, 2, 3, or 4) and returns (as an int) the octet that’s at that position. Provide a driver class that tests your IpAddress class. Your driver class should contain this main method: public static void main(String[] args) { IpAddress ip = new IpAddress("216.27.6.136"); System.out.println(ip.getDottedDecimal()); System.out.println(ip.getOctet(4)); System.out.println(ip.getOctet(1)); System.out.println(ip.getOctet(3)); System.out.println(ip.getOctet(2)); } // end main Using the above main method, your program should generate the following output. Sample output: 216.27.6.136 136 216 6 27 • Show less1 answer - Anonymous askedThe question is : What could be causing the periodic slowdown at New Century Health Clinic? If a pro... More »0 answers - Anonymous asked1. An algorithm divides a problem (having n elements as input ) into four equal parts and solves onl0 answers - Anonymous askedcities listed in the file that hav... Show moreSpecifically, I need to be able to use code that extracts all the cities listed in the file that have the first letter of my specification. my function prototype looks like this "int ShowCities(int count, string name)" my file looks like this Bern, 45, 55 Johannesburg, 87, 102 Seattle, 34, 42 New York, 24, 39 St. Louis, 12, 23 I need a function that when prompted to (F)ind city will display this// "S" is the inputCity: S Seattle (34, 42) 1 record(s) found. • Show less0 answers - Anonymous asked2 answers - Anonymous askedmethod needs to be revis... Show moreThe findWinner method just returns a space (indicating no winner yet). This method needs to be revised to return the winner, or a ‘T’ if the game has ended in a tie. ' '; This si the code: public static char findWinner(final char[][] theBoard) { int i; for(i=0; i<3; i++) /* check rows */ if(theBoard[i][0]==theBoard[i][1] && theBoard[i][0]==theBoard[i][2]) return theBoard[i][0]; for(i=0; i<3; i++) /* check columns */ if(theBoard[0][i]==theBoard[1][i] && theBoard[0][i]==theBoard[2][i]) return theBoard[0][i]; /* test diagonals */ if(theBoard[0][0]==theBoard[1][1] && theBoard[1][1]==theBoard[2][2]) return theBoard[0][0]; if(theBoard[0][2]==theBoard[1][1] && theBoard[1][1]==theBoard[2][0]) return theBoard[0][2]; return ' '; } This is not returning a tie it just returns winner. What we put to return a tie? • Show less2 answers - foreverdeployed asked... Show moreWrite a recursive function to generate a pattern of stars such as the following: * ** *** **** **** *** ** * Also, write a program that prompts the user to enter the number of lines in the pattern and uses the recursive functions to generate the pattern. For example, specifying 4 as the number of lines generates the preceding pattern. • Show less1 answer - Anonymous askedThe assignment: Write a program that grades the written portion of the driver's license exam. The ex... Show moreThe assignment: Write a program that grades the written portion of the driver's license exam. The exam has 20 multiple choice questions (answers input into code already.Your program should store the student's answers for each of 20 questions in an array, the answers in another array. After the student's answers have been entered, the program should display a message indicating whether the student passed or failed the exam (a student must correctly answer 15 of the 20 questions to pass). It should display the total number of correctly answered questions, the total number of incorrectly answered questions, and a list showing the question numbers of the incorrectly answered questions. Input validation: only accept A, B, C or D as answers.Here's my code:#include <iostream> using namespace std; /* This Driver's License Exam program will grade the written portion of the driver's license exam. The program will store the correct answers to 20 multiple choice questions and once the student answers have been entered, grade the exam. */ int main() { // Define variables int count, // counter variable for loops correct=0, // variable to count the number of correct answers input by student inCorrect=0; // stores the amount of incorrectly answered questions const int size = 20; // constant variable for max size (there will be 20 spots in array) char studentAnsw[size]; // studentAnsw array stores student input // store answers to multiple choice questions in storedCorrectAnswer array char storedCorrectAnsw[size] = {'B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D', 'B', 'C', 'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A'}; // Allow student to input answers, store in studentAnsw Array cout << "Please enter your answers to the multiple choice questions by inputting A, B, C, or D. Upper case only." << endl; // if statement for input validation to go into loop must be A B C or D if(studentAnsw[size]!='A'||'B'||'C'||'D') { cout << "Please input A, B, C or D for your answer, all upper case." << endl; cin >> studentAnsw[size]; } if(studentAnsw[size]=='A'||'B'||'C'||'D') { // for loop to match storedCorrectAnswer array against studentAnswer array and tally correct answers for (count=0; count<=size-1; count++) { cout << "Enter the answer for Question " << (count+1) << ": "; cin >> studentAnsw[count]; } if (storedCorrectAnsw[count] == studentAnsw[count]) correct+=1; if (storedCorrectAnsw[count] != studentAnsw[count]) inCorrect+=1; } // Display whether student passed of failed. if(correct>=15) { cout << "Congratulations! You passed the Driver's Exam with " << correct << " out of 20 questions correct." << endl; } else { cout << "Unfortunately you did not pass the exam. You only had " << correct << " out of 20 questions correct." << endl; } // pause system("pause"); return 0; }I'm having 3 problems1) I have a validation statement to ensure that A, B, C, or D is entered but it is not working. 2) I have entered the information into the storedCorrectAnsw array. I have done a for loop to get input into a 2nd array called studentAnsw... this is working fine, getting and storing input. I can output at the end passing of failing test, along with how many questions were correct out of 20. The problem is I can't figure out how to compare the studentAnsw array with the storedCorrectAnsw array and return only the question numbers that were wrong 3) I'm getting a weird error message associated with my studentAnsw array • Show less3 answers - Anonymous askedSuppose in Quicksort we implement the median-of-three routine as follows: find the median of A[Left]... More »0 answers
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2010-august-11
CC-MAIN-2014-23
refinedweb
1,637
53.21
I was fiddling with an incredibly naive Fibonacci number generator and noticed that the go build times for my program were fluctuating wildly with very minor changes to the code. Running go build would take an average of 0.4s when int n was set to 5, and then grow to 0.8s for n=25, and plane out at about 1.75s for n>35. This was the only change made, and I've run loops to time builds ten times for a bunch of values of n. This is the code I used: ----------------------- package main import ( "fmt" "time" ) func fib(n int) int { if n < 1 { return 0 } else if n <= 2 { return 1 } return fib(n - 1) + fib(n - 2) } func main() { start := time.Now() // Magical int that changes build times n := 35 r := fib(n) fmt.Printf("fib(%v) == %v, time: %v\n", n, r, time.Since(start)) } -------------------------- This is the described result of timing builds (going from 5 to 35 midway through): <> After discussions in #go-nuts we figured out that it's the linker (8l.exe) that seems to be the culprit, as 8g takes 0.020s no matter what n is. So, could someone explain this build time growth? I'm running Windows 7 with Go-devel built from source as recent as yesterday. -- Grokbase › Groups › Go › golang-nuts › September 2012
https://grokbase.com/t/gg/golang-nuts/129rkbgs1a/go-nuts-weird-go-build-times-under-windows
CC-MAIN-2021-39
refinedweb
228
83.05
08 October 2010 10:16 [Source: ICIS news] LONDON (ICIS)--Rescue operations have been put in place to try to save a chemical tanker carrying 6,000 tonnes of solvents from sinking off the coast of ?xml:namespace> The YM Uranus, a 120m Malta-registered chemical tanker, hit a Panamanian bulk container 160km off the Its 13 crew members were rescued by helicopter just after the accident. The spokeswoman said the navy was on board the ship to try to save it from sinking and would attempt to tow the vessel back to the coast. She said no chemicals had escaped from the vessel, but added that if the situation worsened, "we cannot say it will never happen". The container ship was heading for Amsterdam from Porto Margher
http://www.icis.com/Articles/2010/10/08/9399675/rescue-operations-in-place-to-save-chems-tanker-from-sinking.html
CC-MAIN-2013-48
refinedweb
128
63.43
Overview¶ {fmt} is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams. boost::formatand loki::SPrintf, and neither felt like the right answer. This does. Format API¶ The format API is similar in spirit to the C printf family of function but is safer, simpler and several times faster than common standard library implementations. The format string syntax is similar to the one used by str.format in Python: fmt::format("The answer is {}.", 42); The fmt::format function returns a string “The answer is 42.”. You can use fmt::memory_buffer to avoid constructing std::string: fmt::memory_buffer out; format_to(out, "For a moment, {} happened.", "nothing"); out.data(); // returns a pointer to the formatted data The fmt::print function performs formatting and writes the result to a stream: fmt::print(stderr, "System error code = {}\n", errno); If you omit the file argument the function will print to stdout: fmt::print("Don't {}\n", "panic"); The format API also supports positional arguments useful for localization: fmt::print("I'd rather be {1} than {0}.", "right", "happy"); You can pass named arguments with fmt::arg: fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.", fmt::arg("name", "World"), fmt::arg("number", 42)); If your compiler supports C++11 user-defined literals, the suffix _a offers an alternative, slightly terser syntax for named arguments: using namespace fmt::literals; fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.", "name"_a="World", "number"_a=42); Safety¶ The library is fully type safe, automatic memory management prevents buffer overflow, errors in format strings are reported using exceptions or at compile time. For example, the code fmt::format("The answer is {:d}", "forty-two"); throws the format_error exception because the argument "forty-two" is a string while the format code d only applies to integers. The code format(FMT_STRING("The answer is {:d}"), "forty-two"); reports a compile-time error on compilers that support relaxed constexpr. See here for details. The following desirable. Compact Binary Code¶ The library produces compact per-call compiled code. For example (godbolt), #include <fmt/core.h> int main() { fmt::print("The answer is {}.", 42); } compiles to just main: # @main sub rsp, 24 mov qword ptr [rsp], 42 mov rcx, rsp mov edi, offset .L.str mov esi, 17 mov edx, 1 call fmt::v7::vprint(fmt::v7::basic_string_view<char>, fmt::v7::format_args) xor eax, eax add rsp, 24 ret .L.str: .asciz "The answer is {}." Portability¶ The library is highly portable and relies only on a small set of C++11 features: - variadic templates - type traits - rvalue references - decltype - trailing return types - deleted functions - alias templates These are available in GCC 4.8, Clang 3.0, MSVC 19.0 (2015) and more recent compiler version. For older compilers use {fmt} version 4.x which is maintained and only requires C++98. The output of all formatting functions is consistent across platforms. For example, fmt::print("{}", std::numeric_limits<double>::infinity()); always prints inf while the output of printf is platform-dependent. Ease of Use¶ {fmt} has a small self-contained code base with the core library consisting of just three header files and no external dependencies. A permissive MIT license allows using the library both in open-source and commercial projects.GitHub Repository
https://fmt.dev/7.1.1/
CC-MAIN-2021-04
refinedweb
550
56.86
Using Pyzor Pyzor is a completely free database and software HashSharingSystem, written by Frank Tobin. . Pyzor Install Hints - Be sure to run "pyzor discover" after you install Pyzor, so that you can download the server to contact. Using Pyzor Site-wide Note permissions advice concerning /etc/mail/spamassassin in RazorSiteWide and add the following to your /etc/mail/spamassassin/local.cf: pyzor_options --homedir /etc/mail/spamassassin - Now put some servers in that dir: pyzor --homedir /etc/mail/spamassassin discover - And finally, restart spamd: /etc/init.d/spamd restart Is it working? You can run SpamAssassin from the command line to figure out if it is using Pyzor. The process is described at RazorHowToTell, but the summary is to run the following from the command line: echo "test" | spamassassin -D pyzor 2>&1 | less This test should return output similar to: ... Oct 6 11:11:46.956 [10904] dbg: pyzor: network tests on, attempting Pyzor Oct 6 11:11:52.055 [10904] dbg: pyzor: pyzor is available: /bin/pyzor Oct 6 11:11:52.056 [10904] dbg: pyzor: opening pipe: /bin/pyzor --homedir /some/dir/.pyzor check < /tmp/.spamassassin10904BmyCb9tmp Oct 6 11:11:52.344 [10904] dbg: pyzor: [10906] finished: exit 1 Oct 6 11:11:52.345 [10904] dbg: pyzor: check failed: no response ... The "check failed: no response" does not indicate a problem, as this test does not pass in an actual properly-formatted email message. If you have an actual message handy, use that for your test; you should see output similar to: ... Oct 6 19:34:05.896 [14864] dbg: pyzor: network tests on, attempting Pyzor Oct 6 19:34:10.940 [14864] dbg: pyzor: pyzor is available: /bin/pyzor Oct 6 19:34:10.942 [14864] dbg: pyzor: opening pipe: /bin/pyzor --homedir /some/dir/.pyzor check < /tmp/.spamassassin14864qX2Rmwtmp Oct 6 19:34:11.248 [14864] dbg: pyzor: [14866] finished: exit 1 Oct 6 19:34:11.248 [14864] dbg: pyzor: got response: public.pyzor.org:24441 (200, 'OK') 0 0 ... Pyzor on Debian If you are using Debian, a pyzor package is available in the stable distribution. Detailed instructions Very detailed instructions on configuring pyzor for a personal Unix account are in SingleUserUnixInstall. Reporting Using SpamAssassin to submit spam is described in ReportingSpam. Pyzor on Windows It is possible to make Pyzor work on Windows with a little extra effort. Download and install ActivePython from. Download and install Pyzor from. You'll need something that can un-bzip2 the files. Installing simply means running the following from the folder you extracted pyzor into: python setup.py build python setup.py install - Create a folder somewhere for the pyzor config files. You can use your spamassassin folder if you like as it only creates a single file called servers. I used c:/python24/etc/pyzor - Create a pyzor.bat in your python folder (c:\python24 by default when I installed it), containing the following line, modified for your python folder path. @c:\python24\python c:/python24/scripts/pyzor --homedir c:/python24/etc/pyzor %1 %2 %3 %4 %5 %6 %7 %8 %9 - Edit /Lib/site-packages/pyzor/client.py with the following changes: - Find signal.signal(signal.SIGALRM, handle_timeout) and put a # in front of it. - Find the section for: def time_call(self, call, varargs=(), kwargs=None): and change it to read like this: def time_call(self, call, varargs=(), kwargs=None): if kwargs is None: kwargs = {} return apply(call, varargs, kwargs) - From a command prompt in the python folder context, run the following where /python/pyzor is the folder you created in the previous step. pyzor discover Now you are ready to configure SpamAssassin to use it. - (This is not necessary in v3.1.7) Edit your /site/lib/mail/spamassassin/Util.pm. Find the "sub helper_app_pipe_open_windows" section and the line that reads if ($stdinfile) { $cmd .= " <'$stdinfile'"; }"and replace it with if ($stdinfile) { $cmd .= " <\"$stdinfile\""; }" because Windows won't pipe a file with a space after the < and single quotes around it. - Edit v310.pre and uncomment the load for the Pyzor plugin. - Edit your local.cf and add configuration lines for pyzor. For example: use_pyzor 1 pyzor_path c:\python24\pyzor.bat pyzor_timeout 10 - That should do it. If you do a spamassassin --lint -D you should see pyzor
http://wiki.apache.org/spamassassin/UsingPyzor?action=diff
CC-MAIN-2013-20
refinedweb
713
60.21
Hello ! I posted a simple template to show how to add 'act_as_whatever' to ActiveRecord. I think this might be useful to others as there are some trickery ruby things in this file. Here is the template : Gaspard Bucher on 10.04.2006 13:57 on 10.04.2006 14:39 Any chance of quick guide to how all that works? on 10.04.2006 15:12 Charlie Bowman wrote: > Any chance of quick guide to how all that works? The beggining is just to set a namespace : module YourSuperName module Acts module Idiot Then there is a module method that we overwrite. This method is called when the module is included into another object ('base' here as it will be ActiveRecord::Base) : def self.included(base) # add all methods from the module "AddActsAsMethod" to the 'base' module base.extend AddActsAsMethod end So we extend the base object with our 'acts_as_idiot' method. This adds 'acts_as_idiot' to the class methods of ActiveRecord::Base. Then we have the 'acts_as_idiot' method itself : def acts_as_idiot # BELONGS_TO HAS_MANY GOES HERE class_eval <<-END include YourSuperName::Acts::Idiot::InstanceMethods END end This method makes the following lines class Myobj < ActiveRecord::Base acts_as_idiot end behave like class Myobj < ActiveRecord::Base include YourSuperName::Acts::Idiot::InstanceMethods end And the last tricky part : module InstanceMethods def self.included(aClass) aClass.extend ClassMethods end This is executed when the instance methods are added to the class. 'Self' here is the Myobj class, so extending it with aClass.extend moduleName will add the methods in the module to the class instead of the object. The very last line ActiveRecord::Base.send :include, YourSuperName::Acts::Idiot is equivalent to class ActiveRecord::Base include YourSuperName::Acts::Idiot end This effectively includes our code into ActiveRecord, making 'acts_as_idiot' available as a class method. I hope these explanations made it clearer... Gaspard on 11.04.2006 14:33 Thank you! That's exactly the explanation I was looking for but haven't found anywhere in any tutorials!
http://www.ruby-forum.com/topic/61600
crawl-002
refinedweb
330
57.37
Arduino Stopwatch 60,023 230 37 Featured Intro: Arduino Stopwatch This Instructable will show you how to make a stop watch out of an Arduino. Step 1: What You Will Need Please buy through these Amazon links as it helps me to keep making these Instructables (A small cut of Amazon's profit from the sale is given to me - It doesn't cost you anything!) You Will Need: - 1x Arduino Uno: -US Link: -UK Link: - 1x LCD Keypad Shield: -US Link: -UK Link: - 1x USB A - B Connector Cable: -US Link: -UK Link: What I Recommend: - Amazon Prime so you can get all your items the next day: -US Link:... -UK Link: - You could attach some of these magnets to attach the stopwatch onto nearly anything metal: -US Link: -UK Link - Arduino For Dummies (very helpful when learning code): -US Link: -UK Link:... or - Arduino Projects For Dummies: -US Link: -UK Link: Step 2: Slot the LCD Display Onto the Arduino This step is very simple just slot the LCD display onto the Arduino. Step 3: Connect and Install the Program Just connect your Arduino to The Computer and install the program. Update - Please use the Modified Stopwatch Program. Step 4: Run Your Stopwatch Now just run your stopwatch. 5 People Made This Project! PYJOURDAN made it! Lintang_Wisesa made it! scratchndent made it! Riscyg made it! AldrinS10 made it! See 1 more that made it 37 Discussions 13 days ago on Introduction I made it thank you, Would you allow me to make a video on YouTube of this working? 9 months ago I made it, thank you very much! 1 year ago thank you very much 3 years ago on Introduction Very cool idea and a great starting point, thanks!!! I did a bit of rewrite to make it more accurate and display the time as it progresses plus other tweaks : /* Standalone Arduino StopWatch By Conor M - 11/05/15 Modified by Elac - 12/05/15 */ // call the necessary libraries #include <SPI.h> #include <LiquidCrystal.h> // these are the pins used on the shield for this sketch LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7); // variables used on more than 1 function need to be declared here unsigned long start, finished, elapsed; boolean r = false; // Variables for button debounce time long lastButtonPressTime = 0; // the last time the button was pressed long debounceDelay = 50; // the debounce time; keep this as low as possible void setup() { lcd.begin(16, 2); // inicialize the lcd (16 chars, 2 lines) // a little introduction :) lcd.setCursor(4, 0); // set the cursor to first character on line 1 - NOT needed (it sets automatically on lcd.begin() lcd.print("Arduino"); lcd.setCursor(3, 1); // set the cursor to 4th character on line 2 lcd.print("StopWatch"); delay(2000); // wait 2 seconds lcd.clear(); // clear the display lcd.print("Press select for"); lcd.setCursor(2, 1); // set the cursor to 3rd character on line 2 lcd.print("Start & Stop"); } void loop() { CheckStartStop(); DisplayResult(); } void CheckStartStop() { int x = analogRead (0); // assign 'x' to the Arduino's AnalogueInputs (Shield's buttons) if (x < 800 && x > 600 ) // if the button is SELECT { if ((millis() - lastButtonPressTime) > debounceDelay) { if (r == false) { lcd.clear(); lcd.setCursor(2, 0); // needed lcd.print("Elapsed Time"); start = millis(); // saves start time to calculate the elapsed time } else if (r == true) { lcd.setCursor(2, 0); // needed lcd.print(" Final Time "); } r = !r; } lastButtonPressTime = millis(); } } void DisplayResult() { if (r == true) { finished = millis(); // saves stop time to calculate the elapsed time // declare variables float h, m, s, ms; unsigned long over; // MATH time!!! elapsed = finished - start; h = int(elapsed / 3600000); over = elapsed % 3600000; m = int(over / 60000); over = over % 60000; s = int(over / 1000); ms = over % 1000; // display the results lcd.setCursor(0, 1); lcd.print(h, 0); // display variable 'h' - the 0 after it is the number of algorithms after a comma (ex: lcd.print(h, 2); would print 0,00 lcd.print("h "); // and the letter 'h' after it lcd.print(m, 0); lcd.print("m "); lcd.print(s, 0); lcd.print("s "); if (h < 10) { lcd.print(ms, 0); lcd.print("ms "); } } } Reply 1 year ago Elac, I only want to count time while the button or another input is present , how would I go about this? 1 year ago I'm struggling to get external buttons to work - I want to add a start and stop but keep getting stuck! Anybody done this with the modified code? :) 1 year ago Welcome to join the group :) 2 years ago how to install the program I don't see anything on my computer after connecting the arduino to it. do we need some software like matlab or something? Reply 2 years ago Make sure you have downloaded the arduino software from 2 years ago I want a coding I want to connect ir sensor to micro servo so that if something pass from front of ir sensor servo rotates at a 90 degree angle and returns to its initial position. I have a ARDUINO UNO for the purpose.... Can anybody do coding for this..PLZ PLZ PLZ THANK YOU... HOPE U REPLY... please reply here -- Reply 2 years ago The code is there for you to use Reply 2 years ago Check out one of my other instructables, how to make an arduino web server, it uses a servo, hope it helps ☺ 2 years ago nice 2 years ago Outstanding. I am using it and am happy to say it works without problem. 2 years ago can somebody give me a version for measuring and displaying seconds,miliseconds and microseconds all on 3 digits each . If yes thanks in advance and contact me at mmedocean@gmail.com 2 years ago works 2 years ago on the line elapsed = finished - start I am getting an error 'start' was not declared in this scope. Any ideas? Reply 2 years ago is your software up to date? 2 years ago can i have the schematic diagram... Reply 2 years ago sorry I don't have a schematic
https://www.instructables.com/id/Arduino-Stopwatch/
CC-MAIN-2018-43
refinedweb
1,008
72.56
Data::Dump::Color - Like Data::Dump, but with color This document describes version 0.23 of Data::Dump::Color (from Perl distribution Data-Dump-Color), released on 2014-10-29. Use it like you would Data::Dump, e.g.: use Data::Dump::Color; dd localtime; This module aims to be a drop-in replacement for Data::Dump. It adds colors to dumps. It also adds various visual aids in the comments, e.g. array/hash index, depth indicator, and so on. For more information, see Data::Dump. This documentation explains what's different between this module and Data::Dump. By default Data::Dump::Color shows array index or hash pair sequence in comments for visual aid, e.g.: [ "this", # [0] "is", # [1] "a", # [2] "5-element", # [3] "array", # [4] { 0 => "with", # .{0} 1 => "an", # .{1} 2 => "extra", # .{2} 3 => "hash", # .{3} 4 => "at", # .{4} 5 => "the", # .{5} 16 => "end", # .{6} }, # [5] ] [] and {} brackets will indicate whether they are indexes to an array or a hash. The dot prefixes will mark depth level. To turn this off, set $INDEX to 0: [ "this", "is", "a", "5-element", "array", { 0 => "with", 1 => "an", 2 => "extra", 3 => "hash", 4 => "at", 5 => "the", 16 => "end", }, ] $Data::Dump::* package variables from Data::Dump, like $Data::Dump::TRY_BASE64, etc are now in the Data::Dump::Color namespace, e.g. $Data::Dump::Color::TRY_BASE64, etc. Additional variables include: Whether to force-enable or disable color. If unset, color output will be determined from $ENV{COLOR} or when in interactive terminal (when -t STDOUT is true). Define colors. Whether to add array/hash index visual aid. Add string length visual aid for hash key/hash value/array element if length is at least this value. If set, then will force color output on or off. By default, will only output color when in interactive terminal. This is consulted when $COLOR is not set. Set $Data::Dump::Color::INDEX to 0. Well, colors is sort of the point of this module. But if you want to turn it off, you can set environment COLOR to 0, or $Data::Dump::Color::COLOR to 0. Fiddle the colors in %Data::Dump::Color::COLORS. There will probably be proper color theme support in the future (based on SHARYANTO::Role::ColorTheme. Data::Dump, JSON::Color,.
http://search.cpan.org/~perlancar/Data-Dump-Color-0.23/lib/Data/Dump/Color.pm
CC-MAIN-2016-07
refinedweb
381
69.58
Hi all, I'd like to understand how does AudioPlaySdRaw works in order to make few mods. I'd be gratefull if somebody had the patience to answer to one couple of questions. In AudioPlaySdRaw.cpp it seems to me that .update is the funcion which takes a bunch of samples (AUDIO_BLOCK_SAMPLES*2) and send them to the Connector: I have two questions:I have two questions:Code:void AudioPlaySdRaw::update(void) { unsigned int i, n; audio_block_t *block; // only update if we're playing if (!playing) return; // allocate the audio blocks to transmit block = allocate(); if (block == NULL) return; if (rawfile.available()) { // we can read more data from the file... n = rawfile.read(block->data, AUDIO_BLOCK_SAMPLES*2); file_offset += n; for (i=n/2; i < AUDIO_BLOCK_SAMPLES; i++) { block->data[i] = 0; } transmit(block); } else { rawfile.close(); #if defined(HAS_KINETIS_SDHC) if (!(SIM_SCGC3 & SIM_SCGC3_SDHC)) AudioStopUsingSPI(); #else AudioStopUsingSPI(); #endif playing = false; } release(block); } 1) why .update function is not used in arduino sketch? 2) why samples are deleted before being sent? Thanks a lot!Thanks a lot!Code:for (i=n/2; i < AUDIO_BLOCK_SAMPLES; i++) { block->data[i] = 0; }
https://forum.pjrc.com/threads/51216-Info-about-AudioPlaySdRaw?s=458c3db356dfd5c1291ff2ad7b34f23d&p=175964&viewfull=1
CC-MAIN-2020-10
refinedweb
185
60.21
CodePlexProject Hosting for Open Source Software Wow is this library every awesome !! So I have some variation in the data coming into my client which uses Json.NET. Is there a way to set some sort of mode to be case insensitive like you can with dictionary keys? using System.Collections.Generic; Dictionary<string, string> list = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); list.Add("A", "Value"); if (list["A"] != null) { Console.WriteLine("A can be A"); } if (list["a"] != null) { Console.WriteLine("a can also be A"); } Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://json.codeplex.com/discussions/77896
CC-MAIN-2017-13
refinedweb
123
68.97
Accessing private members of a .NET class is normally not a good idea, a thing you shouldn’t do. But in some cases it is the best opportunity you have. If you maintain code which wraps some legacy code where the source code is missing. Or when classes are binary serialized and you have to migrate them because the class changed. Accessing private members in .NET isn’t very difficult. A private field or property can be read with the code below. It is implemented as generic extension methods. public static T GetPrivateField<T>(this object obj, string name) { BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = obj.GetType(); FieldInfo field = type.GetField(name, flags); return (T)field.GetValue(obj); } public static T GetPrivateProperty<T>(this object obj, string name) { BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = obj.GetType(); PropertyInfo field = type.GetProperty(name, flags); return (T)field.GetValue(obj, null); } With the Type of the object you can get a Fieldinfo or the PropertyInfo object for a specified field or property. The BindingFlags define in which scope the members will be searched. In this case only instance members (no static) which are private will be found. If you are trying to access public members you will get an error. The value can be read by calling the GetValue method on the info objects. Writing values or even calling private methods is similar. public static void SetPrivateField(this object obj, string name, object value) { BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = obj.GetType(); FieldInfo field = type.GetField(name, flags); field.SetValue(obj, value); } public static void SetPrivateProperty(this object obj, string name, object value) { BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = obj.GetType(); PropertyInfo field = type.GetProperty(name, flags); field.SetValue(obj, value, null); } public static T CallPrivateMethod<T>(this object obj, string name, params object[] param) { BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = obj.GetType(); MethodInfo method = type.GetMethod(name, flags); return (T)method.Invoke(obj, param); } You also work with the info object, but you call the method SetValue. If your parameter object has the wrong type an error occurs. When you want to call a private method, you must use the Invoke method in the MethodInfo class. This method takes all parameters as input which the private method takes. The download below contains the extensions methods of this article and more to access private members of a class. Private Extensions Class (5.06 kb) Fluent NH has something like that for private fields, since NH can map to private fields and those members aren’t accessible through the usual expression-based syntax. Only, they called it "Reveal" Thanks for posting this. i really enjoyed reading this. Admiring the time and effort you put into your weblog and detailed data you provide! I will bookmark your weblog and have my kids test up right here often. Thumbs up! to The best source for replica Piccard watch to fit your style and your most useful products that you can buy is a heart classic familiar styles have been designed as part purpose Below is a list and brief description of composed of a blend of outstanding technology and movement 24 time zones sapphire crystal caseback The watches made in Switzerland will bear the mark different occasions the firms will continue to top GPS wholesale watches he desires to follow interested in their appearance with many people this time hit by the famous electric shock of background of the dial stand out well and add that chronograph patented by Graham The technical celebrities The brand is famous for its its fine With an IWC timepiece on your wrist you are three years Once it does a watch repairmans Ballon Bleu because of the blue bubble decoration That’s incredible! complete the outfit and bring out daughter Miuccia Prada took over sits atop a solid silver tone stainless steel case in the US First and foremost people want to look most daring standards and have managed to produce folding clasp made of stainless steel that matches Thanks for posting this. i really had good time reading this. with a smooth sweeping second hand solid that suits the personality of the person you are characterized by instantaneous change and rapid starter kits You can modify or embellish on these is on the Magnificent Mile in Chicago Illinois considering that the watch was made to celebrate precision mechanics This watch comes with a inventive character of modern Swiss designers and going to an important art gallery collection you bracelet is superior to a faux leather one 7 Again place a sequin on the needle engraved leather strap.Gucci thrift shop to tens of thousands of dollars for a market has to fit the high standards and line of fashion wear for women.The fashionable handbags Most handbags Its a pity you dont have a donate button, i would donate some =) leather handbags available on the Applegate is a Knoxville designer Where can i find your rss? I cant find it
http://www.mbaldinger.com/accessing-private-members/
CC-MAIN-2014-10
refinedweb
841
56.45
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How to process event in Background, which is fired on pressing button ? My problem is when i press button the openerp user interface is blocked, because it is doing some xmlrpc work, as long as work is in not done the openerp ui is blocked. So, my question is - Is there any way to do this work in background even i pressed the button ? I don`t want to use any scheduler or any server actions. Also, I want to take care of repetitive xmlrpc events on pressing button 2-3 times. Please suggest some thing , how to solve this problem ??? I found this at base/res/res_partner.py: def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''): while len(ids): self.pool.get('ir.cron').create(cr, uid, { 'name': 'Send Partner Emails', 'user_id': uid, 'model': 'res.partner', 'function': '_email_send', 'args': repr([ids[:16], email_from, subject, body, on_error]) }) ids = ids[16:] return True The task is added to the cron and executed as soon as possible(i think with a delay of max. a minute) in background. Thanks , I already using cron jobs for doing background work in OpenERP, I think this is the only way to do it. anyways, thanks a lot. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-process-event-in-background-which-is-fired-on-pressing-button-22711
CC-MAIN-2017-34
refinedweb
259
74.39
NAME Devel::Modlist - Perl extension to collect module use information SYNOPSIS perl -d:Modlist script.pl DESCRIPTION. OPTIONS: - stdout By default, the report is printed on the STDERR filehandle. If this option is present, it is sent to STDOUT instead. - cpan Reduce the resulting list of modules by using the data maintained in the local CPAN configuration area. The CPAN module (see CPAN) maintains a very thorough representation of the contents of the archive, on a per-module basis. Using this option means that if there are two or more modules that are parts of the same distribution, only one will be reported (the one with the shortest name). This is useful for generating a minimalist dependancy set that can in turn be fed to the CPAN installcommand to ensure that all needed modules are in fact present. - cpandist This is identical to the option above, with the exception that it causes the reported output to be the CPAN filename rather than the module name in the standard Perl syntax. This can also be fed to the CPAN shell, but it can also be used by other front-ends as a path component in fetching the requisite file from an archive site. Since the name contains the version number, this behaves as though noversion (see below) was also set. If both cpan and cpandist are set, this option (cpandist) takes precedence. If path is also specified, this option again takes precedence. - nocore Suppress the display of those modules that are a part of the Perl core. This is dependant on the Perl private library area not being an exact substring of the site-dependant library. The build process checks this for you prior to install. - noversion Suppress the inclusion of version information with the module names. If a module has defined its version by means of the accepted standard of declaring a variable $VERSIONin the package namespace, Devel::Modlist finds this and includes it in the report by default. Use this option to override that default. - zerodefault Also oriented towards the display of versions, this option tells the report to use a zero ( 0) as the default version if the package has not provided a value. Otherwise, an empty string is displayed (unless noversion is given). - path Display the path and filename of each module instead of the module name. Useful for producing lists for later input to tools such as rpm. - yaml =item yamlheader=NAME =item yamlheaderindent=N =item yamlindent=N =item yamlcomplete =. - yamlheader=NAME. - yamlheaderindent=N Specify the indentation for the section header. By default, the header is flush to the left, an indentation of 0. The value provided specifies the number of space characters printed before the header. - yamlindent=N). - yamlcomplete If this option is present, the output will be a complete YAML document, with a comment identifying the generator and a ---separator. yamlheader may still be set to noneto. - stop Exit before the first actual program line is executed. This provides for fetching the dependancy list without actually running the full program. This has a drawback: if the program uses any of require, eval or other such mechanisms to load libraries after the compilation phase, these will not be reported. CAVEATS. Because Devel::Modlist uses the strict pragma internally (as all modules should), that pragma is always removed from the output to avoid generating a false-positive. AUTHOR Randy J. Ray <rjray@blackperl.com>, using idea and prototype code provided by Tim Bunce <Tim.Bunce@ig.co.uk> LICENSE This module and the code within are released under the terms of the Artistic License 2.0 (). This code may be redistributed under either the Artistic License or the GNU Lesser General Public License (LGPL) version 2.1 ().
https://metacpan.org/pod/Devel::Modlist
CC-MAIN-2015-27
refinedweb
621
54.63
I have to carry out a lot of matrics mulitiplication at same time. It is a part of my own neural network. On matlab, i can do things like this: I can just use the keyword parfor However, when it comes to pytorch, anthing becomes different. I implemented the same code like this: def forward(self, x): """ :param x: train or test with the dimension of [N ,D_in, D_in, num, frame] :return: """ for i in range(x.shape[0]): for j in range(x.shape[4]): for z in range(x.shape[3]): x[i, :, :, z, j] = self.w[:, :, z].mm(x[i, :, :, z, j]) return x It is every slow!! I cannot come up with any idea to accelerate this process. Could you give me a hand? I will appreciate it!
https://discuss.pytorch.org/t/how-to-accelerate-many-matrics-mulitiplication/49284
CC-MAIN-2022-21
refinedweb
132
86.1
Logging Server Side ASP.NET Boilerplate uses Castle Windsor's logging facility. It can work with different logging libraries: Log4Net, NLog, Serilog... etc. Castle provides a common interface for all logger libraries. So, you're independent from specific logging library and can easily change it later if you need. Log4Net is one of the most popular logging libraries for .NET. ASP.NET Boilerplate templates come with Log4Net properly configured and working. But, there is just a single-line of dependency to log4net (as seen in configuration section), so you can change it to your favourite library. Getting The Logger No matter which logging library you choice, the code to write log is same (thanks to Castle's common ILogger interface). First, we should get a Logger object to write logs. Since ASP.NET Boilerplate strongly uses dependency injection, we can easily inject a Logger object using property injection (or constructor injection) pattern. See a sample class that writes a log line: using Castle.Core.Logging; //1: Import Logging namespace public class TaskAppService : ITaskAppService { //2: Getting a logger using property injection public ILogger Logger { get; set; } public TaskAppService() { //3: Do not write logs if no Logger supplied. Logger = NullLogger.Instance; } public void CreateTask(CreateTaskInput input) { //4: Write logs Logger.Info("Creating a new task with description: " + input.Description); //TODO: save task to database... } } First, we imported namespace of Castle's ILogger interface. Second, we defined a public ILogger object named Logger. This is the object we will write logs. Dependency injection system will set (inject) this property after creating TaskAppService object. This is known as property injection pattern. Third, we set Logger to NullLogger.Instance. System will work fine without this line. But this is best practice on property injection pattern. If no one sets the Logger, it will be null and we get an "object reference..." exception when we want to use it. This guaranties that it's not null. So, if no one sets the Logger, it will be NullLogger. This is known as null object pattern. NullLogger actually does nothing, does not write any logs. Thus, our class can work with and without an actual logger. Fourth and the last, we're writing a log text with info level. There are different levels (see configuration section). If we call the CreateTask method and check the log file, we see a log line as like as shown below: INFO 2014-07-13 13:40:23,360 [8 ] SimpleTaskSystem.Tasks.TaskAppService - Creating a new task with description: Remember to drink milk before sleeping! Base Classes With Logger ASP.NET Boilerplate provides base classes for MVC controllers, Web API controllers, Application service classes and more. They declare a Logger property. So, you can directly use this Logger to write logs, no injection needed. Example: public class HomeController : SimpleTaskSystemControllerBase { public ActionResult Index() { Logger.Debug("A sample log message..."); return View(); } } Note that SimpleTaskSystemControllerBase is our application specific base controller that inherits AbpController. Thus, it can directly use Logger. You can also write your own common base class for other classes. Then, you will not have to inject logger every time. Configuration All configuration is done for Log4Net when you create your application from ASP.NET Boilerplate templates. Default configuration's log format is as show below (for each line): - Log level: DEBUG, INFO, WARN, ERROR or FATAL. - Date and time: The time when the log line is written. - Thread number: The thread number that writes the log line. - Logger name: This is generally the class name which writes the log line. - Log text: Actual log text that you write. It's defined in the log4net.config file of the application as shown below: <?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" > <file value="Logs/Logs.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10000KB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" /> </layout> </appender> <root> <appender-ref <level value="DEBUG" /> </root> <logger name="NHibernate"> <level value="WARN" /> </logger> </log4net> Log4Net is highly configurable and strong logging library. You can write logs in different formats and to different targets (text file, database...). You can set minimum log levels (as set for NHibernate in this configuration). You can write diffent loggers to different log files. It can automatically backup and create new log file when it reaches to a specific size (Rolling file adapter with 10000 KB per file in this configuration) and so on... Read it's own confuguration documentation for more. Finally, in the Global.asax file, we declare that we use Log4Net with log4net.config file: public class MvcApplication : AbpWebApplication { protected override void Application_Start(object sender, EventArgs e) { IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseLog4Net().WithConfig("log4net.config")); base.Application_Start(sender, e); } } This is the only code line we directly depend on log4net. Also, only the web project depends on log4net library's nuget package. So, you can easily change to another library without changing your logging code. Abp.Castle.Log4Net Package ABP uses Castle Logging Facility for logging and it does not directly depend on log4net, as declared above. But there is a problem with Castle's Log4Net integration. It does not support the latest log4net. We created a nuget package, Abp.Castle.Log4Net, to solve this issue. After adding this package to our solution, all we should do is to change the code in application start like that: public class MvcApplication : AbpWebApplication { protected override void Application_Start(object sender, EventArgs e) { IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config")); base.Application_Start(sender, e); } } The only difference is that we used "UseAbpLog4Net()" method (defined in Abp.Castle.Logging.Log4Net namespace) instead of "UseLog4Net()". When we use Abp.Castle.Log4Net package, it's not needed to use Castle.Windsor-log4net and Castle.Core-log4net packages. Client Side ASP.NET Boilerplate defines a simple javascript logging API for client side. It logs to browser's console as default. Sample javascript code to write logs: abp.log.warn('a sample log message...'); For more information, see logging API documentation.
http://aspnetboilerplate.com/Pages/Documents/Logging
CC-MAIN-2017-09
refinedweb
1,020
52.36
Tell us what’s happening: So I’m confused to what put in the first part because it’s not clear to my understanding of where the function goes. Is it the first or second area where it’s requesting it to be placed? I wrote handleChange(event) but I don’t know what to put next. I’m stuck as I am a visual learner. Any resources you think that would help me figure it out would be swell. Your code so far class ControlledInput extends React.Component { constructor(props) { super(props); this.state = { input: '' }; // change code below this line // change code above this line } // change code below this line // change code above this line render() { return ( <div> { /* change code below this line */} <input value = {this.state.input}/> { /* change code above this line */} <h4>Controlled Input:</h4> <p>{this.state.input}</p> </div> ); } }; Your browser information: User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36. Link to the challenge:
https://forum.freecodecamp.org/t/create-a-controlled-input-veterans-day/239350
CC-MAIN-2020-50
refinedweb
177
76.82
Red Hat Bugzilla – Bug 29387 rpm-python doesn't work with python 2.0 Last modified: 2007-04-18 12:31:45 EDT The rpm sources contain a directory python, which contains the sources for rpmmodule. This allows python programs to use rpmlib. However, it only works with python 1.5 This was ok for a long time since the development cycle for python was very slow. However, in the last year or so, there has already been version 1.6, 2.0 and now 2.1. The problem is that the paths /usr/lib/python1.5/site-packages and /usr/include/python1.5 are hardcoded in Makefile.am These paths should be determined by a configure script. One way to determine the path for the site-package is something along the lines of: #!/usr/bin/env python import sys,string for path in sys.path: if string.find(path,"site-packages")==len(path)-13: print path print sys.executable (There might be easier ways) greetings, Marco Bosch Red Hat ships with Python 1.5.2, all the usual adornments to the build will happen if/when we convert to Python-2.0 Meanwhile, AFAIK, the changes are very straightforward, although I have no idea whether Python-2.0 "works" as I've never looked.
https://bugzilla.redhat.com/show_bug.cgi?id=29387
CC-MAIN-2017-51
refinedweb
215
79.06
Rigidbody の速度ベクトル In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour. Do not set the velocity of an object every physics step, this will lead to unrealistic physics simulation. A typical usage is where you would change the velocity is when jumping in a first person shooter, because you want an immediate change in velocity. Note: The velocity is world-space. using UnityEngine; using System.Collections; // The velocity in y is 10 units per second. If the GameObject starts at (0,0,0) then // it will reach (0,100,0) units after 10 seconds. public class ExampleClass : MonoBehaviour { public Rigidbody rb; private float t = 0.0f; private bool moving = false; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { if (Input.GetButtonDown("Jump")) { // the cube is going to move upwards in 10 units per second rb.velocity = new Vector3(0, 10, 0); moving = true; Debug.Log("jump"); } if (moving) { // when the cube has moved over 1 second report it's position t = t + Time.deltaTime; if (t > 1.0f) { Debug.Log(gameObject.transform.position.y + " : " + t); t = 0.0f; } } } } Note: A velocity in Unity is units per second. The units are often thought of as metres but could be millimetres or light years. Unity velocity also has the speed in X, Y, and Z defining the direction.
https://docs.unity3d.com/ja/current/ScriptReference/Rigidbody-velocity.html
CC-MAIN-2019-18
refinedweb
223
59.5
BBC micro:bit Bit:Commander - Evasion Game Introduction This is a simple game using the joystick and buzzer of the Bit:Commander. The player controls the position of the bright dot by moving the joystick. The dot is moved according to the absolute position of the joystick. The dimmer dot is the spaceship that chases the player, moving towards them every now and then. The player can move more quickly than the spaceship. A beep is sounded each time the ship moves. If the ship catches the player, the game is over. The ship moves a teeny bit quicker each time. Programming The player position is updated more frequently than the ship. This is achieved by using running_time() instead of sleep to control the timing of the game. The ship movement is calculated each time based on the player position. The player's dot is only redrawn if the position changes. This stops the display flickering that you can get if you update the screen too often. from microbit import * import music def joy2grid(): x = pin1.read_analog() y = 1023 - pin2.read_analog() x = int((x / 1023) * 4 + 0.5) y = int((y / 1023) * 4 + 0.5) return x,y def shipmove(a,b): if a>b: return -1 if a<b: return 1 return 0 def play_game(): px = 2 py = 2 lastx = 2 lasty = 2 shipx = 0 shipy = 0 t = running_time() shiptime = 1000 display.set_pixel(px,py,9) display.set_pixel(shipx,shipy,5) playing = True while playing: px,py = joy2grid() # move player if lastx!=px or lasty!=py: display.set_pixel(lastx,lasty,0) display.set_pixel(px,py,9) if running_time()-t>shiptime: t = running_time() shiptime -= 1 display.set_pixel(shipx,shipy,0) music.pitch(440,100,wait=False) shipx += shipmove(shipx,px) shipy += shipmove(shipy,py) display.set_pixel(shipx,shipy,5) if px == shipx and py == shipy: playing = False music.play(music.WAWAWAWAA) display.show(str((1000-shiptime))) # set followers lastx=px lasty=py sleep(5) play_game() The game is quite playable. The small changes in game speed (shiptime - larger=slower) could be adjusted to make the game more interesing. After a period of time, the game could start speeding up by a larger factor or you could have the speed reset and add a ship.
http://www.multiwingspan.co.uk/micro.php?page=bcchase
CC-MAIN-2019-09
refinedweb
374
67.86
May 14, 2008 04:53 PM|TheDuke|LINK Hi I'm new to asp.net and thanks to time restrictions I've had to jump in at the deep end, any help you can provide is great. I'm developing an Asset Register for one of our clients, a rough over view of the database is as follows. Assets Models Manufacturers Using DynamicData I've built a custom page to display the Assets table and I'd like the gridview to display the manufacturer_name field. I've tried using "Model.Manufacturer" and "Model.Manufacturer.manufacturer_name" for the datafield property with no luck, it doesn't recognise the collumn exists. Is this something that DynamicData has support for, if not can anyone point me in the right direction. Many Thanks Ben linqdatasource ASP.NET Dynamic Data DynamicField Dynamic Data 5-12 Release May 14, 2008 06:32 PM|marcind|LINK Hi Ben, you could do this by adding a custom property to your Asset class: public partial class Asset { public string ManufacturerName { get { return this.Manufacturer.manufacturer_name; } } } May 14, 2008 06:39 PM|sjnaughton|LINK you need to point at the oject name i.e. Manufacturers not manufacturer_id this will cause DynamicData to use the foreign key table if the field name you wish to show in the DropdownList then you will need to attribute it like so: [MetadatatypeAttribute(ManufacturersMetaData)] public class Manufacturers { } public class ManufacturersMetaData { [DisplayColumnAttribute("manufacturer_name")] public object manufacturer_name {get; set;} } See Dynamic Data Attributes on Maíra Wenzel's Blog you will find a list of most of the DynamicData Attributes the on I think you need is DisplayColumnAttribute which "Specifies which column to display (in filters or in foreign key links). By default, Dynamic Data uses the first column of type string that it finds." Hope this helps Dynamic Data Metadata May 14, 2008 06:43 PM|sjnaughton|LINK Hi Marcin your Signiture still shows Check out the latest 4/23 Dynamic Data Preview update. [:D] you should be on 5/12 [;)] Dynamic Data 5-12 Release May 14, 2008 06:56 PM|marcind|LINK Steve: thanks, I've just gotten back from a 2 week vacation and not everything has been updated. should be fixed now. Back to Ben's issue: What I think he is trying to do - and correct me if I'm wrong - is to display an additional column in the Asset's grid view that would display the Asset's Model's Manufacturer's name. This can only be done by having an extra property on the Asset class to represent the extra column. However, I did make a small mistake in my initial response, and it should be: public partial class Asset { public string ManufacturerName { get { return this.Model.Manufacturer.manufacturer_name; } } } May 14, 2008 07:11 PM|sjnaughton|LINK I've ha a re-read of his original question and yes I think your answer is what he is looking for. His problem sounded like one I'd had and just jumped to the wrong conclusion. Oh and your signature correct now [:D] Dynamic Data May 14, 2008 07:15 PM|TheDuke|LINK Thanks for the quick replies, I will give this a try. On a connected issue, I would like to be able to filter a models DropDownList whilst in edit mode using the manufacturers field. I think the best way to do this would be to build a user control with linq-to-sql datasources and the necessary methods to filter a models DropDownList, what I'm not sure on is how to then get the value of the models dropDownList (i.e. model_id) back to the GridView ready for the update. Do I need to get the user control to set a property in the assets class? And lastly on a side note, i remember reading that there were plans to provide an OrderBy attribute to the Dynamic Filters, does anyone know if this has been or can be implented in the new code drop? Many thanks. filters ASP.NET Dynamic Data May 14, 2008 07:23 PM|scothu|LINK You can apply a DisplayColumnAttribute for foreign key tables. This attribute takes SortColumn and SortDecending properties to determine how things are sorted. I know these will be used when editing a row, not sure if these affect the filters as well. Marcin? May 14, 2008 09:44 PM|marcind|LINK Yes, these should work for filters as well. Regarding the cascading dropdown issue it should be doable. I had done this before for filters (something like a car shopping site: first choose make, then model, which filters the list of available cars) but the sample was rough and I do not have it available right now. However, it is a bit tricky as I recall I had to write my own linq queries, and writing something that would be generic enough for all situations is nontrivial. I'll try to get it working again and I will let you know. May 16, 2008 01:01 AM|TheDuke|LINK Marcin I think i've figuured out the cascading drop downs, I'd appreciate input on any improvements you can think of. I used a custom Field Template with 2 linq to sql data sources, source for the control is below. ASCX file <asp:LinqDataSource </asp:LinqDataSource> <asp:LinqDataSource <WhereParameters> <asp:ControlParameter </WhereParameters> </asp:LinqDataSource> <asp:Label <asp:DropDownList <br /> <asp:Label <asp:DropDownList Code behind .cs public partial class DynamicData_FieldTemplates_ManufacturerModel : System.Web.DynamicData.FieldTemplateUserControl { // Set up the original values. protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); object val = FieldValue; // Get the manufactuer_id for the current model AssetRegisterDataContext db = new AssetRegisterDataContext(); var models = from mo in db.Models where mo.model_id == (int)val select mo.Manufacturer.manufacturer_id; // Set the Manufacturer drop down to the value from the model record. manufacturersDropDown.SelectedValue = models.Single().ToString(); // Now set the Model drop down to the value from the database. modelsDropDown.SelectedValue = val.ToString(); } protected override void ExtractValues(IOrderedDictionary dictionary) { dictionary[Column.Name] = modelsDropDown.SelectedValue; } public override Control DataControl { get { return modelsDropDown; } } } May 16, 2008 01:55 AM|marcind|LINK Ben, that looks pretty good. As I mentioned earlier, the one downside is that it is specific to that particular fk/parent relationship. Writing something generic would be more complicated, but I hope to have a sample working soon. 11 replies Last post May 16, 2008 01:55 AM by marcind
http://forums.asp.net/p/1261127/2357958.aspx?Re+Accessing+a+foreign+key+s+table+
CC-MAIN-2014-52
refinedweb
1,068
52.39
My Black Jack code is very basic but is running quite smoothly, however I have run into a speed bump. Thus im here. When I call "Hit" to send me another card in my While loop, for every loop the DECK instantiates the same card. The first 2 drawn and the Hit card are always different but within the While loop (which is set to end when the player says "stay" and doesnt want another card.) the Hit cards remain the same. import random import itertools SUITS = 'cdhs' RANKS = '23456789TJQKA' DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS)) hand = random.sample(DECK, 2) hit = random.sample(DECK, 1) print("Welcome to Jackpot Guesser! ") c = input("Would you like to play Black Jack or play Slots? ") if c == 'Black Jack': print() print("Welcome to Black Jack! Here are the rules: ") print("Black Jack is a game of whit, skill with a bit of Luck. You will start with 2 card and try to achieve a total of 21 points. \n Each cards worth is equal to its number, face cards are worth 10 and the Ace can be 1 or 11 points. You decide. \n You can decide to -Stay- and take the points you have or -Hit- to get another card. If you get 21 its Black Jack and you win. \n If no one gets 21, the highest points win, but if you go over 21 you -Bomb- and lose everything. \n Becarful not to Bomb and goodluck out there! Remember, you got to know when to Hit, when to Stay and when to walk away! \n") print(hand) print() g = 'swag' while g != 'Stay': g = input(("What would you like to do, Stay or Hit: ")) if g == 'Hit': print(hit) elif g == 'Stay': print("Lets see how you did!") else: print("test3") elif c == 'Slots': print("test") else: print("test2") The problem is that you are generating the hit card only once, during the start of the program. Changing your code from if g == 'Hit': print(hit) to something like if g == 'Hit': hit = random.sample(DECK, 1) print(hit) will make it outputs different cards on each hit.
https://codedump.io/share/DwwQg8UOmC9m/1/python-black-jack-game-variant
CC-MAIN-2017-09
refinedweb
364
91.51
Better object-oriented features aren't the only new features of PHP 5. Many extensions have been rewritten to take advantage of PHP 5's new capabilities, and many new extensions have been added to the distribution. The MySQL database is PHP's partner in crime. Many developers power their web sites with MySQL, yet PHP's original MySQL extension dates back to the days of PHP/FI. It's showing its age. In retrospect, some design decisions for the MySQL extension weren't the best solution after all. Also, the latest versions of MySQL, 4.1 and 5.0, introduce many new features, some of which require significant changes to the extension. As a result, PHP 5 comes with a completely new and improved MySQL extension. Dubbed MySQLi, for the MySQL Improved extension, MySQLi offers prepared statements, bound parameters, and SSL connections. It even takes advantage of PHP 5's new object-oriented support to provide an OO interface to MySQL. This extension is covered in Chapter 3. While MySQL is greater than ever, it's actually "too much database" for some jobs. SQLite is an embedded database library that lets you store and query data using an SQL interface without the overhead of installing and running a separate database application. It's the topic of Chapter 4. PHP 5 bundles SQLite, providing developers with a database that's guaranteed to work on all PHP 5 installations. Despite the name, SQLite is a nowhere close to a "lite" database. It supports transactions, subqueries, triggers, and many other advanced database features. Like MySQLi, SQLite also comes with dual procedural and OO interfaces. XML is a key part of web development, so PHP 5 offers a full selection of new XML tools. A major goal of XML in PHP 5 is interoperability among each of the different XML extensions, making them a unified unit instead of individual agents. The new Document Object Model (DOM) extension is leaps and bounds better than PHP 4's experimental version. It also uses new PHP 5 features to comply with the DOM specification, fulfilling the goal of DOM as a language-neutral API for XML. There's also a new Extensible Stylesheet Language Transformations (XSLT) extension that operates on XML documents and DOM objects. You can transform DOM objects using XSLT and receive translated documents from XSLT. You can even pass XML nodes back and forth between XSLT and PHP from within a stylesheet. Perhaps the most innovative part of PHP 5 is the SimpleXML extension. This lightweight interface to XML lets you easily iterate through XML documents without the overhead of DOM or the oddness of XSLT. It's perfect for documents where you know the specification and want to quickly extract data. Chapter 5 covers all these topics, plus the original Simple API for XML (SAX) extension and an XPath extension, used for querying XML documents. If you're new to XML or want a refresher on some of its more difficult parts, such as namespaces, be sure to read Appendix A. Iterators are a completely new PHP 5 feature and the topic of Chapter 6. They allow you to use a foreach loop to cycle through different types of data: directory listings, database results, and even XML documents. SPL?the Standard PHP Library?is a collection of iterators that provide this functionality and also filter, limit, cache, and otherwise modify iterator results. Iterators are an incredibly handy way to abstract away messy details from your code.. Chapter 7 covers exceptions. Streams allow you to place a file interface on reading and writing data using protocol-specific objects known as wrappers. Streams also let you modify the data flowing through them by attaching filters. First introduced in PHP 4.3, streams are an underutilized part of PHP. PHP 5 expands upon the existing streams infrastructure to allow more extensive wrappers, and to let you create filters directly in PHP instead of in C. Chapter 8 demonstrates how to create a shared memory wrapper and two streams, one for encoding HTML entities and another for decoding them. Chapter 9 covers three new pieces of PHP 5: SOAP, Tidy, and the Reflection classes. SOAP is a key component of the fast-growing web services field. This extension lets developers create SOAP clients with or without a Web Services Description Language (WSDL) file, and also implement SOAP servers in PHP. The Tidy extension makes it easy to ensure that your output is valid HTML and XHTML. Its smart parser brings even the most unruly of files into compliance with the latest W3C specifications. Nothing less than complete code introspection is the goal of the Reflection classes. This set of classes lets you examine classes, methods, parameters, and more, to discover object attributes. It is now simple and easy to create PHP class browsers, debuggers, and other tools that rely on gathering details about objects and functions. It's one thing to see each of the individual parts of PHP 5 in isolation; it's another to see them in harmony. Chapter 10 provides you with a small address book application that combines the new PHP 5 features into a complete unit. This chapter pulls together the concepts introduced in the rest of the book and provides you with an example that shows exactly why application development in PHP 5 is so great. Even in a short program, you can take advantage of SQLite, DOM, SimpleXML, iterators, abstract classes, exceptions, and property overloading to create an application that's flexible in many dimensions, yet easy to write and understand. This address book lets you add contact information and search stored records using both a web and command-line interface. The output is completely separated from application logic, and the program uses a simple series of template classes to control its formatting. PHP 5 is such a major update that it's impossible to cover it completely in only 10 chapters. Additionally, some features are so minor, they're only worth mentioning briefly. Appendix B contains all the small changes and fixes that aren't mentioned in the chapters. It's definitely worth a read because, in many ways, it's easiest to be tripped up by minor changes. You know you're on new ground with the mysqli extension, but, unless you read Appendix B, you probably would not know that you can now pass optional parameters by reference, or that strrpos( ) behaves slightly differently than before, or even that the command-line version of PHP has the ability to execute code on every line of input.
http://etutorials.org/Server+Administration/upgrading+php+5/Chapter+1.+Introduction/1.2+What+s+New+in+PHP+5/
CC-MAIN-2018-30
refinedweb
1,100
54.32
Hi, i'm pretty new to programming (as you will see), and i'm having difficulty with this program that takes a string and adds a number (i) to each character's acsii value based on its index in the string (i). For example, the string "aaaaa" would become "abcde". Here's the code: The program successfully complies, but when i enter the string "aaaa", i get the following output:The program successfully complies, but when i enter the string "aaaa", i get the following output:Code: #include <stdio.h> #include <string.h> main() { char *origin; int sLimit = strlen(origin); int i; printf("Enter a string to encode.\n\n"); scanf("%s",origin); for (i=0;i<sLimit;i++) { printf("Value %i: %i\n", i, origin[i]+i); } } Enter a string to encode. aaaa Value 0: 97 Value 1: 98 Segmentation fault Any help would be appreciated!
http://cboard.cprogramming.com/c-programming/133490-trouble-pointers-ascii-values-string-manipulation-printable-thread.html
CC-MAIN-2015-32
refinedweb
147
53.31
Scroll down to the script below, click on any sentence (including terminal blocks!) to jump to that spot in the video! gstreamer0.10-ffmpeg gstreamer0.10-plugins-goodpackages. As we've seen, it's totally possible to configure the Vue instance and put the template in the same file. But... this is going to get crazy as our app grows: can you imagine writing 100 lines of HTML inside this string... or more? Yikes! Fortunately, Vue solves in a unique, and pretty cool way: with single file components. Inside the js/ directory create a new folder called pages/, and then a file called products.vue. We'll talk more about the directory structure we're creating along the way. Notice that .vue extension: these files aren't really JavaScript, they're a custom format invented by Vue. On top, add a <template> tag. Then, copy the h1 HTML from the original file, delete the template variable, and paste here. Next, add a <script> tag. Anything in here is JavaScript and we'll export default an object that will hold our Vue options. Copy the data() function, delete it, and move it here. That's it! I know, the format is a bit strange, but it's super nice to work with. On top, the <template> section allows us to write HTML just like if we were in a Twig template. And below, the <script> tag allows us to set up our data, as well as any of the other options that we'll learn about. This is a fully-functional Vue component. Back in products.js, to use this, first, import it: import App - we could call that variable anything - from './pages/products. Thanks to Encore, we don't need to include the .vue extension. Now, inside of render, instead of worrying about compiling the template and all this boring, crazy-looking code, the App variable already has everything we need. Render it with return h(App). That feels good! Let's try it: move over, refresh and... it still works! From here on out, we're going to do pretty much all our work inside of these .vue files - called single file components. One option that we're going to add to every component is name: set it to Products. We could use any name here: the purpose of this option is to help debugging: if we have an error, Vue will tell us that it came from the Products component. So, always include it, but it doesn't change how our app works. Before we keep working, there are two small changes I want to make to products.js. First, the el option: it tells Vue that it should render into the id="app" element on the page. This works, but you usually see this done in a different way. Remove el and, after the Vue object is created, call .$mount() and pass it #app. I also like this better: we first create this Vue object - which is a template and set of data that's ready to go - and then choose where to mount it on the page. Second, because the render() method only contains a return line, we can shorten it: render set to h => h(App). That's effectively the same: it uses the arrow function to say that render is a function that accepts an h argument and will return h(App). I'm mostly making this change because this is how you'll see Vue apps instantiated on the web. Next, let's get to work inside our single file component: we'll add the HTML markup needed for our product list page and then learn how we can add styles. // } }
https://symfonycasts.com/screencast/vue/single-file-component
CC-MAIN-2020-45
refinedweb
618
82.04
Content-type: text/html #include <sys/types.h> #include <sys/stropt.h> #include <sys/conf.h> ioctl(fd, I_PUSH, "jconv7"); jconv7 is a STREAMS module that is available to be pushed onto a stream. Usually, this module has to be pushed onto a stream between a raw device such as ptem(7M) and terminal line discipline module such as ldterm(7M). jconv7 has to be pushed when you set 7-bit JIS terminal and control Japanese EUC data. It converts up stream for 7-bit JIS code into Japanese EUC and passes high module. It also converts down stream for Japanese EUC into 7-bit JIS code and passes low module. jconv7 processes the following ioctls. JA_SKIOC and JA_GKIOC are specified pointer to the next structure as argument: struct kioc { char ki; char ko; }; JA_SKIOC Change the 3rd character of JIS kanji and ASCII indication escape sequence. JA_GKIOC Return the 3rd character of current JIS kanji and ASCII indication escape sequence. EUC_OXLON Start performing code conversion between 7-bit JIS and Japanese EUC for I/O stream. EUC_OXLOFF Stop performing code conversion between 7-bit JIS and Japanese EUC for I/O stream. jtty(1), setterm(1), stty(1), streamio(7I), jconv8(7M), jconvrs(7M), jconvru(7M),jconvs(7M), jconvu(7M), ldterm(7M), ptem(7M) When you use jconv7 with jconvrs(7M) or jconvru(7M) at once and `raw' is specified by stty(1), code convert function automatically become off without specification by EUC_OXLON / EUC_OXLOFF. By default, character set indication escape sequences as follows. The end character may be changed by JA_SKIOC. • ASCII indication: ESC 2/8 4/10 • Character indication: ESC 2/4 4/2 • Convert with JIS X 0201 Kana: SI/SO jconv7 does not support Kanji code for Information Interchange (secondary kanji set) provided by JIS X 0212-1990. When jconv7 is in use, csh(1) does not work properly for filename additional function.
http://backdrift.org/man/SunOS-5.10/man7m/jconv7.7m.html
CC-MAIN-2016-44
refinedweb
317
55.84
Writing new PulseAudio modules Introduction I want to rewrite the JACK modules from scratch, and in order to do that I need to know how modules work and how to use the PulseAudio APIs. Instead of reading the sources I'd like to have a friendly guide that tells me what to do. Because there isn't such a guide, I'll write it myself as I learn stuff by other means. Hopefully this will be useful for future module writers too. This documentation is for the "master" branch in the git, which will eventually become the 0.9.7 release. After 0.9.7 I think I will keep updating these pages as git changes (the APIs needed to write modules are mostly considered internal and thus unstable), but keeping the information for 0.9.7 users there too. This is a wiki, so please improve this yourself whenever you spot inaccuracies, confusion, bad English or straight lies. Update May 6, 2008: It's been now eight months since this tutorial was last edited. I didn't finish the JACK modules (Lennart made them good enough for the 0.9.7 release), and I didn't finish this tutorial, nor have I been keeping this up to date for the parts that have been written. If you notice something that has changed since 0.9.7, please fix it, or at least add a note about it. Also, I claim no ownership over this tutorial, so if you have more time and motivation than me, feel free to improve it in any way you want. --tanuk What is a module? A module is a shared object file that contains implementations of certain functions. The daemon loads the modules from a predefined directory, which by default is /usr/local/lib/pulse- Compiling to a shared object file This section is here in the case you're like me and don't know anything about the specifics of shared object compilation. This works on my machine: gcc -g -shared -o module-<yourmodule>.so module-<yourmodule>.c Copy the resulting .so file to the modules directory and you're done, you can now load your module by running pacmd and saying "load-module module- Update on July 30 2008: Sometime it is not so straightforward, as your module uses some definitions and variables from other files and libraries. You probably use the PulseAudio configure script and Makefile to build your module. In the case, you may update configure.ac and Makefile.am to add your module support. Here is a code snippet in configure.ac, which adds an optional module abc as an example: ... #### ABC support #### AC_ARG_ENABLE([abc], AC_HELP_STRING([--disable-abc],[Disable optional ABC module support]), [ case "${enableval}" in yes) abc=yes ;; no) abc=no ;; *) AC_MSG_ERROR(bad value ${enableval} for --disable-abc) ;; esac ], [abc=no]) if test "x${abc}" != xno ; then if test "x$HAVE_DBUS" = x1 && test "x$HAVE_GLIB20" = x1 ; then AC_DEFINE([ABC], 1, [Have ABC module.]) ABC=1 else ABC=0 fi else ABC=0 fi AM_CONDITIONAL([ABC], [test "x$ABC" = x1]) ... Here is a code snippet to add abc module to src/Makefile.am ... if ABC modlibexec_LTLIBRARIES += \ libdbus-util.la \ module-abc.la endif ... module_abc_la_SOURCES = modules/module-abc.c module_abc_la_LDFLAGS = -module -avoid-version module_abc_la_LIBADD = $(AM_LIBADD) $(DBUS_LIBS) $(GLIB20_LIBS) libpulsecore.la module_abc_la_CFLAGS = $(AM_CFLAGS) $(DBUS_CFLAGS) $(GLIB20_CFLAGS) ... In configure script and Makefile.am, the module may have some dependencies. You need find the right position to add those codes. -stanley Required functions There is one function that every module must implement, the daemon refuses to load the module if it isn't present. int pa__init(pa_module* m); pa_init is called when the daemon loads the module. Any initialization work is supposed to be done in the pa_init function. Some modules may be such that their purpose becomes fulfilled already during the initialization. However, most modules need to do some cleanup work when they are unloaded, so some kind of "destructor" is almost mandatory too. It is called pa__done. void pa__done(pa_module* m); The return value of pa__init tells the daemon whether the initialization succeeded or not. A negative number means failure and zero or greater means success. If pa__init fails, pa__done won't be called. The pa_module type is defined in [source:branches/lennart/src/pulsecore/module.h pulsecore/module.h] and will be explained later. So the minimal module that the daemon agrees to load is: #include <pulsecore/module.h> int pa__init(pa_module* m) { return 0; } Optional functions There are a few other functions that are loaded from the .so file if they are implemented. const char* pa__get_author(); const char* pa__get_description(); const char* pa__get_usage(); const char* pa__get_version(); These strings give additional information about the module, which may be extracted from the modules by running: pulseaudio --dump-modules --verbose You can do these functions more compactly with macros that are defined in module.h. This example is from module-null-sink.c: PA_MODULE_AUTHOR("Lennart Poettering") PA_MODULE_DESCRIPTION("Clocked NULL sink") PA_MODULE_VERSION(PACKAGE_VERSION) PA_MODULE_USAGE( "format=<sample format> " "channels=<number of channels> " "rate=<sample rate> " "sink_name=<name of sink>" "channel_map=<channel map>" "description=<description for the sink>") Static linking of modules It is sometimes desirable to link modules statically in the daemon binary instead of using dynamic loading. If every module defines its own pa__init, that's a serious problem, because you could use static linking only for one module. PulseAudio uses libtool, which provides magic that allows the same code to be used either dynamically or statically linked without these problems. That requires a small bit of work from you, the module writer. You have to create a header file that you include from the source file. Let's use the module-null-sink as an example again. These are the contents of module-null-sink-symdef.h, copy it to yourself and modify the "null-sink" parts to match your own module's name: #ifndef foomodulenullsinksymdeffoo #define foomodulenullsinksymdeffoo #include <pulsecore/module.h> #define pa__init module_null_sink_LTX_pa__init #define pa__done module_null_sink_LTX_pa__done #define pa__get_author module_null_sink_LTX_pa__get_author #define pa__get_description module_null_sink_LTX_pa__get_description #define pa__get_usage module_null_sink_LTX_pa__get_usage #define pa__get_version module_null_sink_LTX_pa__get_version int pa__init(pa_module*m); void pa__done(pa_module*m); const char* pa__get_author(void); const char* pa__get_description(void); const char* pa__get_usage(void); const char* pa__get_version(void); #endif Of course, this is so mechanical stuff that the file can be very well be given to the computer to generate. The PulseAudio developers use a M4 script to generate the symdef files at build time. Read [source:branches/lennart/src/Makefile.am Makefile.am] (search for "SYMDEF") and [source:branches/lennart/src/modules/module-defs.h.m4 modules/module-defs.h.m4] to see how it is done. State data With the interfaces so far introduced, writing modules isn't a terribly useful activity. Now you can basically make a "Hello world" module, optionally with the advanced feature that it prints "Goodbye world" when the module gets unloaded. Next we'll see how a module can carry its internal state data from pa__init to pa__done. Still not too awesome an ability, but with that you could do for example a module that measures the time how long it takes from loading to unloading, that's almost useful! pa_module has the field userdata. It is a void pointer, of which purpose is to store a pointer to the internal state data of your module. So you allocate some data structure that you want to use for your data in pa__init, then set the pa_module's (that you get as a parameter) userdata field to point to the allocated structure. In pa__done you'll have as a parameter the same pa_module, and there you'll find your internal data. Continuing to the PulseAudio internals Now that you know the very basics of writing a PulseAudio module, we can start to go through the various APIs inside PulseAudio and see what they offer us. You're basically writing a subclass of pa_module, so it would probably be a good starting point to have a look on what the superclass contains. ModuleAPI For getting the module parameters that the user has given, read ModuleArgumentsAPI. The only way to expand your abilities inside PulseAudio is to follow the core pointer in the pa_module structure. Let's go there. CoreAPI You will likely run into situations where you'd want the daemon mainloop execute some code of your own. For achieving that, read MainLoop.
http://freedesktop.org/wiki/Software/PulseAudio/Documentation/Developer/Modules/?action=SyncPages
CC-MAIN-2014-10
refinedweb
1,389
55.34
If it is not server programming, why abandon all kinds of gui editing tools? Mainly want to use less mouse, mouse hand hu.. Tag : vim It has been installed several times without success. Windows?.. Operating environment: Mac The system has not been reloaded. Opening any file will report such an error. The first picture is the report error, and the second picture is the content of the. vimrc file. There are too many lines in line 4… Press V, shift and arrow keys to select several rows, and then press X to delete them. This deletion is not to delete the row selected by the cursor. How to delete the row selected by the cursor in vim (not gvim)? Dd can delete the row where the current cursor is located. To delete .. Both of them have been used for several years. Each time I pick them up, I discard them for at most 1 or 2 months. Go back to windows: ( It is still unclear which is more worth learning.Let’s express our opinions:) The editor of god and the god of editors.If you are a god, .. The Internet said: ctrl+w+Vertical Enlargement (Line Number Increase): ctrl+w-Vertical Shrinkage (Number of Rows Decreased) Among them, shrinking can be used, but expanding cannot be used all the time.Ctrl w (shift =) I didn’t press my four fingers I just want to map these two keys:nnoremap <leader>= <C-W>-Although the reduction can be pressed by hand, the .. Modify several shortcut keys provided by vim Of course, Vim’s strength lies in its ability to customize various functions. Please search the search engine for “Vim Custom Shortcu.. As shown in the figure, I am using this plug-in, and what does another visual mode mean? Press cw to return to normal editing mode VIM introduces Visual mode. To select a paragraph of text, first move the cursor to the beginning of the paragraph, press V in normal mode to enter visual mode, and .. Take this Flip [Left to Right to Left] fork Fork \ Bifurcation \ Fork \ Recut Convert to flip ; Flip [left to right to left] fork; Forks \ Bifurcations \ Forks \ Repetitions I use :%s/^\([ a-zA-Z]\+\)\([\U4E00-\U9FFF ]\+.\+\)\([ a-zA-Z]\+\)\([\U4E00-\U9FFF ]\+.\+\)$/\1; \2 \3; \4/g Now I think Flip [Left to Right to Left] fork Fork .. 1. As the topic description Edit the. vimrc file in the user directory. if there is no new one, write the following: set encoding=utf-8 set fileencodings=utf-8,chinese,latin-1 if has(“win32”) set fileencoding=chinese else set fileencoding=utf-8 endif “Resolve menu misprints source $VIMRUNTIME/delmenu.vim source $VIMRUNTIME/menu.vim “Solving consle Output Scrambling language messages zh_CN.utf-8 Then there is the most important, cmder .. As described in the title, it only appears when html tags are entered.The goal is <svg width=”300″ height=”300″><svg> The result is <svg width=”300″ height=”300″> <svg> Problem solvingThere is a sentence in my vimrctw=2.. For example, when processing a text file with tens of thousands of lines, vim moves the cursor with obvious Caton, but sublime is smooth. What is the internal principle? Can vim be improved? Thank you very much! Vim default enable has too many functions, and many of these functions perform poorly under large files. such ..
https://ddcode.net/tag/vim/
CC-MAIN-2019-30
refinedweb
560
74.29
Project report submitted in partial fulfilment of the requirements For the award of the degree of BACHELOR OF TECHNOLOGY In ELECTRONICS AND COMMUNICATION ENGINEERING By K.Sowjanya(09241A04A6) G.Sowjanya (09241A04A7) M.Sridevi (09241A04B0) K.Sushm a(09241A04B5) Under the guidance of Mr.Y.Sudarshan Reddy (Assistant Professor) Page i VOICE BASED APPLIANCE CONTROL Department of Electronics and Communication Engineering GOKARAJU RANGARAJU INSTI TUTE OF ENGINEERING & TECHNOLOGY, BACHUPALLY, HYDERABAD-72 2013 GOKARAJU RANGARA JU INSTITUTE OF ENGINEERING & TECHNOLOGY Hyderabad, Andhra Pradesh. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING CERTIFICATE This is to certify that the project report entitled “IMPLEMENTATION OF DIRECT DIGI TAL SYTHESIZER AD9850 USING ARDUINO UNO” that is being submitted by k.Sowjanya,G.S owjanya,M.Sridevi,K.sushmaunder the guidance of Mr.Y.Sudarshan Reddy in partial fulfilment for the award of the Degree of Bachelor of Technology in Electronics and Communication Engineering to the Jawaharlal Nehru Technological University i s a record of bonafide work carried out by them under my guidance and supervisio n. The results embodied in this project report have not been submitted to any ot her University or Institute for the award of any graduation degree. Prof Ravi BillaMr.Y.SudarshanExternal Examiner HOD, ECE Dept, GRIET,Hyderabad (I nternal Guide) Asst.Professor,ECEDept, GRIET, Hyderabad Page ii VOICE BASED APPLIANCE CONTROL ACKNOWLEDGEMENT We have immense pleasure in expressing our thanks and deep sense of gratitude to our guide Mr.Y.SudarshanRedddy, Assistant Professor, Department of Electronics and Communication Engineering, G.R.I.E.T for his guidance throughout this projec t. We also express our sincere thanks to Prof. Ravi Billa, Head of the Department, G.R.I.E.Tfor extending his help. We wish to express our profound sense of gratitude to Prof. P. S. Raju, Director , G.R.I.E.Tfor his encouragement, and for all facilities to complete this projec t. Finally we express our sincere gratitude to all the members of faculty and my fr iends who contributed their valuable advice and helped to complete the project s uccessfully. K.Sowjanya G.Sowjanya (09241A04A6) (09241A04A7) M.Sridevi (09241A04B0) K.Sushmasree (09241A04B5) Page iii VOICE BASED APPLIANCE CONTROL ABSTRACT This is a wireless, voice control system. People can control almost all the appl iances at home including lights, fans or even back ground music. Microphone is i nterfaced with voice chip to enable voice based recognition.special characters a re used to control various peripheral devices connected.EasyVR ,The goal of our project is to design real time voice controlled appliances which brings more con venience to people's lives. Hardware: Aurduino Uno Board Triac Shield EasyVR Shield Page iv VOICE BASED APPLIANCE CONTROL Page v . 2 Basic structure of triac……………………………………………… 3. R…………………………………………………………..29 Page vi .2 EasyVR chip…………………………………………………………………………….Triac shield 2.EasyVR Shield 3.VOICE BASED APPLIANCE CONTROL LIST OF FIGURES 1.1 1.Arduino 1.2 ATMEGA 328 pin mapping……………………………………………… 2..1Triac symbol……………………………………………………………………………...1 Arduino board………………………………………………………………………….1 EasyVR module…………………………………………………………………………12 3..7 2. EasyVR Shield -Introdution………………………………………………………………..Introduction to Arduino……………………………………………………………..VOICE BASED APPLIANCE CONTROL Contents: 1.Triac Shield -Triac…………………………………………………… 3.…11 -Features…………………………………………………………………. Page vii .1 2. VOICE BASED APPLIANCE CONTROL Page viii . a USB connection. The Arduino Uno is a microcontroller board based on the ATmega328.1 Arduino Board Page 1 . It contains everything needed to support the microcontroller. simply connect it to a computer with a USB cable or power it with a AC-to-DC ad apter or battery to get started. 6 analog input s. a 16 MHz ceramic resonator. a power jack. a nd a reset button. an ICSP header. It has 14 d igital input/output pins (of which 6 can be used as PWM outputs). Fig 1.VOICE BASED APPLIANCE CONTROL Introduction to Arduino . 5 KB used by bootloader 2 KB (ATmega328) 1 KB (ATmega328) 16 MHz Page 2 . The adapter can be connected by plugging a 2. 6-20V 14 (of which 6 provide PWM output) 6 40 Ma 50 mA 32 KB (ATmega328) of which 0. Extern al (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or batte ry.1mm center-positive plug into t he board's power jack. Leads from a battery can be inserted in the Gnd and Vin p in headers of the POWER connector.VOICE BASED APPLIANCE CONTROL Features of Uno board Microcontroller Operating Voltage ATmega328 5V Input Voltage (recommended) 7-12V Input Voltage (limits) Digital I/O Pins Analog Input Pins DC Current per I/O Pin DC Current for 3.3V Pin Flash Memory SRAM EEP ROM Clock Speed POWER The Arduino Uno can be powered via the USB connection or w ith an external power supply. The power source is selected automatically. 3 Arduino Programming Window Page 3 .2 ATmega Pin Mapping Arduino programming Click on the Arduino executable w hich has the Arduino logo The following screen com Fig 1.VOICE BASED APPLIANCE CONTROL Fig 1. For the sketch to work on your Arduino Uno. From the menu select Uno.VOICE BASED APPLIANCE CONTROL The programs written for Arduino are called sketches. it will be map ped as a serial port.4 Arduino Port selection When you connect your Arduino Uno to the USB port of your laptop. there are two hardware related settings you need to make in th e Arduino IDE – Board Serial Port For selecting the board. select the Device Manager Page 4 . Fig 1. f ollow the following procedure Right click on My Computer Select the Manage option In the pop up screen for Com puter Management. go to the Tools tab and select Board. To know the serial port to which your Arduino is mapped. 5 Checking for connected Port In the Arduino IDE. select the Serial Port a s the port to which the Arduino is mapped.VOICE BASED APPLIANCE CONTROL Expand the Ports item. the Arduino Uno will appear as one of the drop down items Fig 1. Page 5 . } Where setup( ) is the preparation. } void loop() { statements. loop() is the execution. Both functions are required for t he program to work.VOICE BASED APPLIANCE CONTROL The basic structure of the Arduino sketch is fairly simple and has two required functions: void setup() { statements. Page 6 . Because of its bidirectional conduction property. triac is a thr ee terminal.1 Triac symbol Construction of a Triac: As mentioned above. It incorporates two SCRs connected in inverse parallel with a common gate terminal in a single chip devi ce. four layer bidirectional semiconductor device that controls ac power whereas an SCR controls dc power or forward biased half cycles of ac in a load. four layer bilateral semiconductor device. The triac also differs from the SCR in that either a positi ve or negative gate signal triggers it into conduction. „Tri‟-indicates that the device has three terminals and „ac‟ indicates that the dev ice controls alternating current or can conduct in either direction. Unlike the SCR. the triac conducts in either direc tion when turned on. Thus the triac is a thre e terminal. As seen. The gate terminal G makes ohmic contacts with both the N and P materials . Fig 2.VOICE BASED APPLIANCE CONTROL INTRODUCTION TO TRIAC SHIELD Triac shield consists of triac and opto-isolator wh ich are explained below: Construction and Operation: The triac is another three- terminal ac switch that is triggered into conduction when a lowenergy signal is applied to its gate terminal. it has six doped r egions. “Triac” is an abbreviation for three terminal ac swi tch. The arrangement of the triac is shown in figure. This Page 7 . Triacs of 16 kW rating are r eadily available in the market. the triac is widely used in t he field of power electronics for control purposes. Electrical equival ent circuit and schematic symbol are shown in figure. As in case of SCR. (MT1). the smaller the supply voltage at which the triac is turne d on. Cons equently four different possibilities of operation of triacexists. the lar ger the gate current. main terminal 2 (MT2) and gate G.b and figure.VOICE BASED APPLIANCE CONTROL permits trigger pulse of either polarity to start conduction. it has become common practice to specif y all voltages and currents using MT1 as the reference.c respectively . Fig 2. Since the triac is a bilateral device. the term “anode” and ”cathode” has no meaning. Terminal MT2 and gate are positive with respect to terminal MT1 Page 8 . To avoid confusion. here too. and therefore. Triac can conduct current irrespective of the voltage polarity of terminal s MT1 and MT2 with respect to each other and that of gate and terminal MT2. terminals are designated as main terminal 1. They are: 1.2 Basic Structure of Triac Operation and Working of a Triac: Though the tr iac can be turned on without any gate current provided the supply voltage become s equal to the breakover voltage of the triac but the normal way to turn on the triac is by applying a proper gate current. it require s a positive gate trigger.VOICE BASED APPLIANCE CONTROL When terminal MT2 is positive with respect to terminal MT1 current flows through path P1N1-P2-N2. The two junctions P2-N1 and P1 . forced commutation by reverse-biasing cannot be employ ed. for bidirectional control and uniform gate t rigger modes 2 and 3 are preferred. Generally. The triac is now said to be neg atively biased. the current flow path is P2-N1P1-N4. it has replaced S CR by virtue of its bidirectional conductivity. phase control circuits. 4. 2. A posit ive gate with respect to terminal MT1 forward biases the junction P2-N2 and the breakdown occurs as in a normal SCR. Thou gh the triggering mode 1 is more sensitive compared to modes 2 and 3.N4 are f orward biased whereas junction N1-P1 is blocked. trigger mode 4 should be avoided especially in circuits where h igh di/dt may occur. which is usually impracticable. are some of its main applications. current carriers are injected and therefore. Te rminal MT2 is negative but gate is positive with respect to terminal MT1 Though the flow path of current remains the same as in mode 3 but now junction P2-N2 is forward biased. the triac is the most widely used member of t he thyristor family. However. The triac is now said to be positively biased. 3. Terminal MT2 is positive but gate is neg ative with respect to terminal MT1 Though the flow path of current remains the s ame as in mode 1 but now junction P 2-N3 is forward biased and current carriers injected into P2 turn on the triac. Motor speed regulation. in many of control applications. power switches etc. temperat ure control. the triac is turne d on. However.Terminal MT2 and gate are negative with re spect to terminal MT1 When terminal MT2 is negative with respect to terminal MT1 . The sensitivity of triggering modes 2 and 3 is high and in case of marginal triggering capability negative gate pulses should be used. So turn-off is either by current starvation. A negative gate with respect to terminal MT1 injects current car riers by forward biasing junction P2-N3 and thus initiates the conduction. illumination control. Applications of Triac Next to SCR. In fact. liquid level control. the triac is le ss versatile than the SCR when turn-off is considered. Page 9 . Because the triac can con duct in either direction. The two junctions P1-N1 and P2-N2 are forward biased whereas j unction N1 P2 is blocked. The first is the frequency handling capability produced by the limiting dv/dt at which the triac remains blocking when no gate signal is applied. control . This beam travels across a transparent gap and is picked up b y the "receiver. while keeping those circuits or systems electrically isolated from each other. Optoisolators are used in a wide variety of communications." which converts the modulated light or IR back into an electric al signal. and monitoring systems. or laser diode for si gnal transmission. although the input and output amplitudes (signal strengths) often diffe r. also known as an optical coupler or optocoupler. and has the appearance of a n integrated circuit (IC) or a transistor with extra leads. The electrical output waveform is identical to the electrical input w aveform. an optoisolator consists of an l ight-emitting diode (LED). and a photosensor for signal reception. There are two limitations enforced on the use of triac at present state of commercially available devices (200 A and 1. so that the limitation of frequency is at the power level of 50 Hz. In its simplest form.000 PRV). The "transmitter" tak es the electrical signal and converts it into aa beam of modulated visible light or infrared (IR). is a semiconductor device that allows signals to be transferred between circuit s or systems. The optoisolator is enclosed in a single package. This dv/dt val ue is about 20 Vmicros-1 compared with a general figure of 200 Vmicro s-1 for th e SCR. When high frequencies and high dv/dt are involved then the backto-back SCRs cannot be replaced by the triac. The s ame dv/dt limitation means the load to be controlled is preferably a resistive o ne.VOICE BASED APPLIANCE CONTROL or else by ac line commutation. Opto-isolator: An optoisolator. Page 10 . IRED (infrared-emitting diode). Alternatively.) Photodiode opto-isolators Diode opto-isolators employ LEDs as source s of light and silicon photodiodes as sensors. The energy is harvested by draining the charge through an exte rnal high-impedance path. Page 11 . it modu lates the flow of energy from an external source.2%. When the photodiode is reverse-bi ased with an external voltage source. If a transient occurs on the telephon e line (and these are common). Two opto isolators are employed in the analog section of the device: one for upstream sig nals and the other for downstream signals.7 V.3 Optoisolator A common application of an optoisolator is in a specialized modem that allows a computer to be connected to a telephone line without risk o f damage from electrical transients (also called "surges" or "spikes"). The rate of charge is proportional to the intensity o f incoming light. The diode itself does not generate energy. modems that use optoi solators provide superior protection against transients compared with modems inc orporating electrical surge suppressors alone. For this reason. (An electrical surge suppressor s hould be installed between the optoisolator and the telephone line for optimum p rotection. in the absence of external bias the diod e converts the energy of light into electric energy by charging its terminals to a voltage of up to 0. the computer will be unaffected because the optic al gap does not conduct electric current.] This mo de of operation is called photovoltaic mode. incoming light increases the reverse curre nt flowing through the diode. the ratio of current transfer can reach 0.VOICE BASED APPLIANCE CONTROL Fig 2. This mode of operation is call ed photoconductive mode. The EasyVR module can be used with any host with an UAR T interface powered at 3.3V – 5V.VOICE BASED APPLIANCE CONTROL INTRODUCTION TO EASYVR: EasyVR is the second generation version of the successfu l VRbot Module. Some application examples include home automation. It is a multipurpose speech recognition module designed to easil y add versatile. Fig 3. such as voice controlled light switches.1 EasyVR Module Page 12 . or adding “hearing” to the most popular robots on the market. robust and cost effective speech recognition capabilities to vi rtually any application. lock s or beds. such as PIC and Arduino boards. Module can be used with any host with an UART interface (powered at 3 .5V) Simple and robust documented serial protocol to access and program throug h the host board 3 GPIO lines (IO1.VOICE BASED APPLIANCE CONTROL EasyVR Features: A host of built-in Speaker Independent (SI) commands for ready to run basic contr ols. Easy -to-use and simple Graphical User Interface to program Voice Command s and audio. in the followings languages: o English (US) o Italian o German o French o S panish o Japanese Supports up to 32 user-defined Speaker Dependent (SD) triggers or commands as well as VoicePasswords. PWM audio output that supports 8Ω speakers. IO2. SD custom commands can be spoken in ANY l anguage. IO3) that can be controlled by new protoc olcommands. Sound playback of up to 9 minu tes of recorded sounds or speech. Page 13 .3V. 2 EasyVR Chip Page 14 .VOICE BASED APPLIANCE CONTROL Technical specifications Physical dimensions and pin assignment Fig 3. VOICE BASED APPLIANCE CONTROL Page 15 . 3 Serial Data Frame Format Page 16 .VOICE BASED APPLIANCE CONTROL Fig 3. so they are referenced to the internal 3. It could also be connected to an external audio amplifier to drive lower impedance loudspeakers It is possible to connect higher impedance loads such as headphone s. Audio Output The EasyVR audio output interface is capable of directly driving an 8Ω speaker. General Purpose I/O Since the EasyVR communication interface takes two pins of the host controller.2K Operating Voltage 3V Almost flat frequency response in range 100Hz– 20kHz I f you use a microphone with different specifications the recognition accuracy ma y be adversely affected. If you need to interface to circuits using adifferent supply. Some of these are outlined below (here Ionindi cates any one of the three I/O pins of the EasyVR). that can be controlled with the communication protocol.VOICE BASED APPLIANCE CONTROL Microphone The microphone provided with the EasyVR module is an omnidirectional electret co ndenser microphone (Horn EM9745P-382): Sensitivity -38dB (0dB=1V/Pa @1KHz) Load Impe dance 2. provided that you scale down the output power according to the speaker rating s. to get those pins back for basic tasks. No other kind of microphone is supported by the EasyVR. a few spare I/O pins are provided. Page 17 . The exact resistor value depends on the headphone power ratings and the desired output volume (usually in the order of 1 0kΩ). there are a n umber of solutions you can adopt. The three I/O pins IO1–IO3 are connected directly to the embedded microcontroller on t he EasyVR module. such as lighting an LED.0V regulated power sup ply. for example using a series resistor. Bridge mode – You can control the module using a software serial library and conne ct to the module with the EasyVR Commander from your PC.VOICE BASED APPLIANCE CONTROL Quick start for using the module EasyVR on Arduino You can connect the EasyVR module to an Arduino board basically in two ways: 1. since it allows simple communication with both the Arduinomicrocontroller and the PC.4 Bridge Mode Connection Page 18 . All the provided examples for Ardui no manage the bridge mode automaticallywhen the EasyVR Commander requests a conn ection. but you need to change the connections o nce you want to control the module from the microcontroller Bridge mode This is the preferred connection mode. Fig 3. Adapter mode – You can use the Arduino board as a USB/Serial adapter b y holding the microcontroller in reset. with the same pin confi guration 2. Connect the EasyVR module to your Arduino board as outlined before Page 19 . it does not rely on the AVR microcontroller to do any software b ridge between communication pins. Using this method also allows you to download a Sound Table to the EasyVR module. provided you alsoconfigure the module to start in bo ot mode Fig 3. with Reset shorted to GND. soit can be used to check your hardware in cas e of connection problems. you need to remove the short (yellow wire) and move the ETX/ERXco nnection to other pins.5 Adapter Mode Connection This configuration. like the above bridgemode. To use themodule from the Arduino mi crocontroller. The example code uses pin 12 for ETX and pin 13 for ERX. so it should work on all Arduino boards. The latest version of EasyVR Commander (sinc e 3.1) does not rely on thatfeature anymore. Adapter mode This connection scheme has the advantage of working with any Arduino board that has an on-boardUSB/Serial adapter and not needing a spare input pin to enter bri dge mode.VOICE BASED APPLIANCE CONTROL Automatic bridge mode used to be supported only on Arduino boards with a bootloa der implementingEEPROM programming. i s for connection with the EasyVR Commander.x) and Arduino libraries (since 1. Arduino software Follow these few steps to start playing with your EasyVR module and Arduino: 1.1. Also. Connect the /XM pin of J4 on the EasyV R module for boot mode (see Flash Update for a possible circuit) 3.6 EasyVR Library Installation To check everything is working fine: 1. Make sure you activate bridge mode (either manually or automatically) or you use ada pter mode 2. Open the EasyVR Commander and select the Arduino serial port Page 20 . Fig 3. connect an 8Ω speaker to J2 header 3. Open the EasyVR Commander and connect to the Arduino serial port (s ee Getting Started) To download a new sound-table: 1. Power ON aga in the EasyVR module and the Arduino board (reconnect the USB cable) 4. If you want audio output. Make sur e you activate bridge mode (either manually or automatically) or you use adapter mode 5. Connect your Arduino board to your PC via USB . Power OFF the EasyVR modul e (for example removing the USB cable) 2. Connect the sup plied microphone to the MIC (J3) connector 4.VOICE BASED APPLIANCE CONTROL 2. Copy the EasyVR library to your Ar duino “libraries” folder on your PC 5. Fig 3.7 Testing EasyVR Programming on Arduino To test the EasyVR module with your Arduino programming IDE: 1. See comments on top of the sketch for usage details Page 21 . Make sure you di d not activate bridge mode manually 2. Open the example sketch TestEasyVR from y our IDE menu “File” > “Examples” > “EasyVR” 3. While disconnected choose “Update Sound Table” from the “Tools”menu . Upload the sketch and open the “Serial Monitor indow 4.VOICE BASED APPLIANCE CONTROL 6. Page 22 . that willuse the provided libraries .VOICE BASED APPLIANCE CONTROL When the EasyVR Commander is connected. you can also generate a template code fo r Arduino. 8 Pin Structure of EasyVR Shield Page 23 .VOICE BASED APPLIANCE CONTROL Technical specifications Physical dimensions and pin assignment Fig 3. oSW – Software serial mode Page 24 .VOICE BASED APPLIANCE CONTROL Jumper settings J12 – Operating mode This jumper selects the operating mode of the EasyVR Shield a nd it can be placed in one of four positions: oUP – Flash update mode Use it for f irmware updates or to download sound table data to the on-board flash memory fro m theEasyVR Commander. oPC – PC connection mode Use it for direct connection with the EasyVR Command er. In this mode. oHW – Hardware serial mode Use it for controlling the E asyVR module from your Arduino sketch through the hardware serial port(using pin s 0-1). the Arduino controller is heldin reset and only the embedded U SB/Serial adapter is used. The EasyVR module is set in boot m ode. In this mode. the Arduino controller is held in reset and only the embeddedUSB/Serial adapter is used. If you want audio outpu t. that willuse the provided libraries . LEDs A green LED (D6) is connected to IO1 pin and can be controlled by the user‟s progr am to show feedbackduring recognition tasks. you can connect theEasyVR Commander leaving the jumper in the SW position. Connect the supplied microphone to the MIC IN (J 11) connector. Copy the EasyVR library to your Arduino “libraries” folder on your PC 5.VOICE BASED APPLIANCE CONTROL Use it for controlling the EasyVR module from your Arduino sketch through a soft ware serial port(using pins 12-13). either wire an 8Ω speaker into the screw terminals (J10) or connectheadphones t o the 3. for example. you can also generate a template code for Arduino. Page 25 . Connect your Arduino board to your PC via USB. provided that therunning sketch implements bridge mode (see librarie s). Set the jumper (J12) in the SW position 2. Open t he example sketch TestEasyVR from your IDE menu “File” > “Examples” > “EasyVR” 3. You can also connect the EasyVR Commander in this mode. just make sure the monitor window is closed. Upload the sketch and open the “Serial Monitor” window 4. All you need is to write actions for each recognized co mmand. When the EasyVR Commande r is connected.The red LED (D5) lights up when you set the shield t o flash update mode (see Jumper settings). See comments on top of the sketch fo r usage details Keep in mind that if you have a “bridge” code running (all examples do) on Arduino. This LED is on by defa ult after reset or power up. Quick start for using the Shield Follow these few steps to start playing with your EasyVR Shield and Arduino: 1. Insert the EasyVR Shield on top of your Arduino board 2.5mm output jack (J9) 3. To test the Shield with yo ur Arduino programming IDE: 1. 4. 115200 b aud. 10 . with zero or more additional argument bytes. Each co mmand sent on the TX line. Since the EasyVR serial interface also is software-based. respectively on the TX and RX lin es. and 100 ms . That accountsfor slower or fas ter host systems and therefore suitable also for software-based serial communica tion (bitbanging).9 ms. again on the TX and RX lines.VOICE BASED APPLIANCE CONTROL EasyVR Programming Communication Protocol Introduction Communication with the EasyVR module uses a standard UART interface compatible with 3. receives an answer on theRX line in the form of a status byte followed by zero or more a rguments.90 ms.1 s. A typical connection to an MCU-based host: The initial configuration at power on is 9600 baud. chosen among lower-caseletters. accordin g to the powering voltage VCC. to allow the EasyVR to get backlistening to a new character. 1 bit stop. that is initiallyset to 20 ms and can be selected later in t he ranges 0 . a v ery short delay might be needed beforetransmitting a character to the module. No parity. There is a minimum delay before each byte sent out from the EasyVR mod ule to the RX line. which can be divided in two main groups: Command and status characters. 8 bit data. The baud rate can bechanged later to operate in the range 9600 .3-5V TTL/CMOS logical levels. Command arguments or status deta ils. es pecially if the host is very fast. The communication protocol only uses printable ASCII characters. Page 26 . spanning the range of capitalletters. The reply is aborted if any other characteris received and so there is no need to read all the bytes of a reply if not required. using the space ch aracter. andthen check that all devices are properly turne d on and start the EasyVR Commander. Page 27 . EasyVR Commander The EasyVR Commander software can be used to easily configure your EasyVR module connected to yourPC through an adapter board. but the template conta ins all thefunctions or subroutines to handle the speech recognition tasks. or by using the microcontroller h ost board with the provided “bridge” program(available for ROBONOVA controller board . and then go with the “Connect” command.VOICE BASED APPLIANCE CONTROL The communication is host-driven and each byte of the reply to a command has to be acknowledged by thehost to receive additional status data. You can define groups of commands or passwords and generate a basic code template to handle them. Gett ing Started Connect the adapter board or a microcontroller host board with a run ning “bridge” program1 to your PC. Invalid combinations o f commands or arguments are signaled by a specific status byte. Arduino 2009/UNO. It isrequired to ed it the generated code to implement the application logic. Parallax Basic Stamp). Select the serial port to use from the tool bar or the “File” menu. Trigger words are used to start the recognition process Group .where you may add user-defined SD commands Passwor d .9 EasyVR Commander There are four kinds of commands in the software (see Figure 3 and Figure 6): Tri gger .built-in set of SI commands (for instance in Figure 3 above.is a special group where you have the built-in SI trigger word "Robot" an d you may add one user-defined SD trigger word. the Wordset 1 is selected) Page 28 .VOICE BASED APPLIANCE CONTROL Fig 3.a special group for "vocal passwords" (up to five). using Speaker Verificati on (SV) technology Wordset. it reads back al l the user-defined commands andgroups.VOICE BASED APPLIANCE CONTROL Speech Recognition The recognition function of the EasyVR works on a single group at a time. When EasyVR Commander connects to the module. Fig 3. so tha t users need to grouptogether all the commands that they want to be able to use at the same time. there is too much background noise or whe n the second word heard is too different from thefirst one. You can add a new command by first selecting the group in wh ich the command needs to be created andthen using the toolbar icons or the “Edit” me nu. A command should be given a label and then it should be trained twice with t he user's voice: the user will beguided throughout this process (see Figure 4) w hen the "Train Command" action is invoked. Page 29 . command training will be cancelled.10 Training Phases of EasyVR Guided training dialog After clicking on Phas e 1 or Phase 2 buttons. Errors may happen when the user‟s voice is notheard correctly. which are stored into the EasyVR module n on-volatile memory. remember to start speaking only when you see this little window: If any error happens. they have been trained with a similarpronunciation). by using the icon on the toolbar or the “Tools” menu. For example.to make sure the trained commands can be recognized successfully. The selected group of comma nds can also be tested. Page 30 .VOICE BASED APPLIANCE CONTROL Alert dialog in case of conflictThe software will also alert if a command is too similar to an existing one by specifying the index of theconflicting command in the "Conflict" column.e. The current status is displayed in the EasyVR Commander list view where groups t hat already containcommands are highlighted in bold. in the following Figure 6 the command"TEST_ CMD_ONE" sounds too similar to "TEST_CMD_ZERO" (i. VOICE BASED APPLIANCE CONTROL PROJECT PROGRAM: #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino. idx.13).use modified NewSoftS erial #include "WProgram. }. }.h" SoftwareSerialport(12. G1_LIGHTS_OFF = 1.h" #include "SoftwareSe rial.h" NewSoftSerialport(12. #else // Arduino 0022 .h" EasyVReasyvr(port). enum Group1 { G1_LIGHTS_ON = 0.h" #include "NewSoftSerial. Page 31 . #endif #include "EasyVR.13). //Groups and Commands enum Groups { GROUP_1 = 1. int8_t group. EasyVRBridgebridge. group = GROUP_1. port.loop(0.setLanguage(0). easyv r. bridge. } // run normally Serial.OUTPUT). 12.HIGH). di gitalWrite(A5. for (.OUTPUT). 13).check()) { cli()..setPinOutput(EasyVR::IO1. digitalWrite(A4. LOW).detect()) { Serial.HIGH). //<-. Serial.). pinMode(A5.println("EasyVR not detected!").VOICE BASED APPLIANCE CONTROL void setup() { pinMode(A4.begin(9600). Page 32 . } easyvr.begin(9600). // bridge mode? if (bridge.start group (customize) } void action(). easyvr. 1.setTimeout(5).println("EasyVR detected!"). if (!easyvr. if (idx> = 0) { // print debug message uint8_t train = 0.print("Co mmand: "). <-. // LED on (listening) Serial.println(group). LOW). if (idx>= 0) { // built-in trigger (ROBOT) // group = GR OUP_X. easyvr. HIGH).setPinOutput(EasyVR::IO1. do { // can do some processing while waiting for a spoken command } while (!easy vr.getWord().recognize Command(group). easyvr.VOICE BASED APPLIANCE CONTROL void loop() { easyvr.print("Say a command in Group "). Serial. Serial. Page 33 . char name[32].hasFinished()). } idx = easyvr. // LED off idx = easyvr.setPinOutput(EasyVR::IO1.jump to another group X return.getCommand(). } else // errors or timeout { if (easyvr.isTimeout()) Serial. idx.VOICE BASED APPLIANCE CONTROL Serial.").pri nt(" = ").print(idx). int16_t err = easyvr. easyvr. train)) { Serial.print("Error ").println(name).. HEX). Serial. if (err >= 0) { Serial.println(). } } } void action() { switch (group) { case GROUP_1: switch (idx) Page 34 .println("Timed out.getError().. // perform some action action().println(err. name. } else Serial.playSound(0. Serial. try again. if (easyvr.dumpCommand(group. Ea syVR::VOL_FULL). HIGH). digital Write(A5. digitalWrite(A4. } // write your action code here // group = GROUP_X. case G1_LIGHTS_OFF: { Serial.or jump to another grou p X for composite commands break.VOICE BASED APPLIANCE CONTROL { case G1_LIGHTS_ON: {Serial. digitalWrite(A5. <-. digitalWrite(A4.LOW).or jump to another group X for composite commands break. } } Page 35 .println("lights off ").LOW).HIGH). } // write your action code here // group = GROUP_X. } break. <-.println("lights on"). wikipedia.sparkfun.com/products/10963 m/ProductDetails.eu/products /easyvr/ BASED APPLIANCE CONTROL References: VAR-01770 Page 36 .
https://www.scribd.com/document/340066635/195668686-Voice-Based-Appliance-Control
CC-MAIN-2018-51
refinedweb
5,564
59.09
wheels for cycling US $3300-3500 / Set 1 Set (Min. Order) three roll mill and plastic wheel US $3300-3500 / Case 1 Set (Min. Order) 250cc three wheels Racing ATV US $1200-1650 / Unit 1 Unit (Min. Order) 2016 Cool Three Wheels 125/150/250CC Sports Motocycle Water-cooled 3 Wheel Inverted ATV 250CC Trike ATV Wholesale 1 Unit (Min. Order) 200cc 250cc 300cc Three Wheels ATV US $2280-2680 / Piece 8 Pieces (Min. Order) 250cc three wheel atv factory sell directly US $1000-2000 / Piece 2 Pieces (Min. Order) 250cc three wheel motorcycle atv (YH-08) US $1300-1400 / Piece 5 Pieces (Min. Order) three wheel scooter 250cc three wheel atv US $1300-1600 / Piece 30 Pieces (Min. Order) 2015 Popular Three wheel motorcycle Cargo tricycle 250cc atv with cheap price US $900-1500 / Set 1 Set (Min. Order) Australia 250cc three wheel atv US $0-373 / Piece 2 Pieces (Min. Order) 250cc three wheel tricycle atv US $1100-1300 / Piece 1 Piece (Min. Order) 150CC 200CC 250CC three wheels Racing ATV US $1800-2800 / Case 1 Case (Min. Order) 250cc three wheel atv 12 Pieces (Min. Order) CE approved 250cc three wheel atv with aluminum wheel US $1127.34-1281.08 / Piece 1 Piece (Min. Order) Cheap Price Cheap 250cc ATV/sport china atvs/three wheel motorcycle atv US $0-1300 / Piece 5 Pieces (Min. Order) Bode New 250cc Three Wheel ATV US $2450-2750 / Piece 2 Pieces (Min. Order) 250cc three wheels Racing ATV 93A-08 US $1240.0-1240.0 / Units 18 Units (Min. Order) 250cc three wheel ATV 5 Pieces (Min. Order) Hot sale buggy car shineray 250cc three wheel atv For Kids with CE US $230-300 / Piece 50 Pieces (Min. Order) Three Wheel Motorcycle ATV 250cc EEC US $2500-3500 / Unit 2 Units (Min. Order) 250cc Three wheel ATV,250cc EEC ATV(TKA250E-Z) US $1000-1300 / Unit 10 Units (Min. Order) three wheels racing ATV 250CC HL-ATV889 5 Pieces (Min. Order) New Hot Sale 250CC Three Wheel ATV US $1000-1200 / Piece 5 Pieces (Min. Order) 2015 new design 250cc three wheel atv US $700-900 / Piece 10 Pieces (Min. Order) China atv supplier MC-380 250cc three wheel atv US $1200-1700 / Piece 2 Pieces (Min. Order) new bajaj three wheel motorcycle atv US $1560.0-1580.0 / Sets 18 Sets (Min. Order) import 250cc bicycles frames passenger three wheel atv from China US $850-1500 / Unit 38 Units (Min. Order) 250cc atv /motor tricycle/three wheel tricycle US $1-100 / Set 1 Unit (Min. Order) 2015 fashion 250cc three wheel trike ATV with CE for sale US $20-25 / Piece 40 Pieces (Min. Order) China 250cc three wheel motorcycle cheap atv for sale US $900-1200 / Unit 10 Units (Min. Order) 250cc 4-wheel super cool big ATV for adults with CE sales very popular in 2014 US $1-999 / Piece 1 Piece (Min. Order) 2015 new hot sale and heavy loading 250cc three wheel atv US $1565-1600 / Piece 27 Sets (Min. Order) 150cc Air-cooled Air-cooling 250Cc Three Wheel Atv US $650-2000 / Unit 2 Units (Min. Order) China Hot Sale Motorcycle Truck Three Wheel Motorcycle Atv (FH25.1) US $1150-1450 / Unit 15 Units (Min. Order) three wheel passenger tricycle for atv US $1000-2000 / Unit 10 Units (Min. Order) AliSourcePro Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE Do you want to show 250cc three wheel atv or other products of your own company? Display your Products FREE now! Related Category Product Features Supplier Features Supplier Types Recommendation for you related suppliers related Manufactures
http://www.alibaba.com/showroom/250cc-three-wheel-atv.html
CC-MAIN-2016-26
refinedweb
608
84.07
A DirectScrollBar is similar to the "scroll bar" widget commonly used by the user to page through a large document. DirectScrollBar is available beginning in Panda3D 1.1. It consists of a long trough, a thumb that slides along the trough, and a pair of buttons on either side of the trough to scroll one line at a time. A DirectScrollBar can be oriented either vertically or horizontally. The DirectScrollBar is similar in function to DirectSlider, but it is specifically designed for scrolling through a large window. In fact, a pair of DirectScrollBars is used to implement the DirectScrolledFrame, which manages this scrolling functionality automatically. (Because DirectScrolledFrame exists, you will probably not need to create a DirectScrollBar directly, unless you have some custom purpose that requires a scroll bar.) DirectScrollBar has many things in common with DirectSlider. Like DirectSlider, the normal DirectGui parameters such as frameSize, geom, and relief control the look of the trough. You can control the look of the thumb by prefixing each of these parameters with the prefix "thumb_", e.g. thumb_frameSize; similarly, you can control the look of the two scroll buttons by prefixing these with "incButton_" and "decButton_". You can retrieve or set the current position of the thumb with myScrollBar['value']. thumb_frameSize myScrollBar['value'] Here is a small example on how to create the scrollbar: from direct.gui.DirectGui import DirectScrollBar mybar = DirectScrollBar(range=(0, 100), value=50, pageSize=3, orientation= DGG.VERTICAL) mybar.setPos(-1, 0, -0.5) This will give you a scrollbar at the lower left side of the screen. If you want to parent the scrollbar to a determined frame, you add the keyword parent to the set of keyboards like so: mybar = DirectScrollBar(parent=myframe, range=(0,100), value=50, pageSize=3, orientation= DGG.VERTICAL) mybar.setPos(-1, 0, -0.5)
http://www.panda3d.org/manual/index.php/DirectScrollBar
CC-MAIN-2018-39
refinedweb
303
55.74
NAME readdir - read a directory SYNOPSIS #include <sys/types.h> #include <dirent.h> struct dirent *readdir(DIR *dir); DESCRIPTION The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dir. It returns NULL on reaching the end-of-file */ char d_name[256]; /* filename */ }; According to POSIX, the dirent structure contains a field char d_name[] of unspecified size, with at most NAME_MAX characters preceding the terminating null byte. POSIX.1-2001 also documents the field ino_t d_ino as an XSI extension. The other fields are unstandardized, and not present on all systems; see NOTES below for some further details.. stat(2) if further actions depend on the type of the file. If the _BSD_SOURCE feature test macro is defined, then. SEE ALSO read(2), closedir(3), dirfd(3), ftw(3), opendir(3), rewinddir(3), scandir(3), seekdir(3), telldir(3), feature_test_macros(7) COLOPHON This page is part of release 3.01 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. 2008-06-20 READDIR(3)
http://manpages.ubuntu.com/manpages/intrepid/man3/readdir.3.html
CC-MAIN-2014-52
refinedweb
187
56.55
formic 0.9beta8 An implementation of Apache Ant FileSet and Globs Features Formic is a Python implementation of Apache Ant FileSet and Globs including the directory wildcard **. FileSet provides a terse way of specifying a set of files without having to enumerate individual files. It: - Includes files from one or more Ant Globs, then - Optionally excludes files matching further Ant Globs. Ant Globs are a superset of ordinary file system globs. The key differences: - They match whole paths, eg /root/myapp/*.py - ** matches any directory or directories, eg /root/**/*.py matches /root/one/two/my.py - You can match the topmost directory or directories, eg /root/**, or - The parent directory of the file, eg **/parent/*.py, or - Any parent directory, eg **/test/**/*.py This approach is the de-facto standard in several other languages and tools, including Apache Ant and Maven, Ruby (Dir) and Perforce (…). Python has built-in support for simple globs in fnmatcher and glob, but Formic: - Can recursively scan subdirectories - Matches arbitrary directories in the path (eg /1/**/2/**/3/**/*.py). - Has a high level interface: - Specify one or more globs to find files - Globs can be used to exclude files - Ant, and Formic, has a set of default excludes. These are files and directories that, by default, are automatically excluded from all searches. The majority of these are files and directories related to VCS (eg .svn directories). Formic adds __pycache__. - Iterate through all matches in the sub-tree - Is more efficient with many common patterns; it runs relatively faster on large directory trees with large numbers of files. Quickstart Formic can be installed from the Cheeseshop with easy_install or pip: $ easy_install formic Once installed, you can use Formic either from the command line: $ formic -i "*.py" -e "__init__.py" "**/*test*/" "test_*" This will search for files all Python files under the current directory excluding all __init__.py files, any file in directories whose name contains the word ‘test’, and any files that start test_. Or integrated right into your Python 2.7 project: import formic fileset = formic.FileSet(include="**.py", exclude=["**/*test*/**", "test_*"] ) for file_name in fileset: # Do something with file_name ... That’s about it :) About Formic is written and maintained by Andrew Alcock of Aviser LLP, Singapore. - Issue tracker - Source on Atlassian BitBucket Formic is Copyright (C) 2012, Aviser LLP and released under GPLv3. Aviser LLP would be happy to discuss other licensing arrangements; for details, please email the maintainer. - Author: Aviser LLP, Singapore - Documentation: formic package documentation - Bug Tracker: - Keywords: Apache Ant,glob,recurse,FileSet,file utilities,find - License: GPLv3+ - Categories - Package Index Owner: Andrew.Alcock - DOAP record: formic-0.9beta8.xml
https://pypi.python.org/pypi/formic
CC-MAIN-2016-50
refinedweb
438
56.76
I am trying to download an image from the NGA.gov site using python 3 and urllib. The site does not display images in a standard .jpg fashion and i get an error. import urllib.request from bs4 import BeautifulSoup try: with urllib.request.urlopen("") as url: s = url.read() soup = BeautifulSoup(s, 'html.parser') img = soup.find("img") urllib.request.urlretrieve(img,"C:\art.jpg") except Exception as e: print (e) BeautifulSoup is library for html/xml parsing. On this url you receive image already, so what are you trying to parse? This works ok: urllib.request.urlretrieve("" ,"C:\art.jpg")
https://codedump.io/share/R1tSW4e64VOY/1/how-to-download-image-from-site-with-no-clear-extention
CC-MAIN-2016-44
refinedweb
102
55.4
This section provides an overview of what concurrency is, and why a developer might want to use it. It should also mention any large subjects within concurrency, and link out to the related topics. Since the Documentation for concurrency is new, you may need to create initial versions of those related topics. import java.util.stream.IntStream; public class Concurrent { public static void printAndWait(String s) { System.out.println(s); try { Thread.sleep(1000); } catch (Exception e) {} } public static void main(String[] args) { Thread myThread = new Thread() { public void run() { IntStream.range(1,32) .forEach(x -> printAndWait(""+x)); } }; myThread.start(); IntStream.range('a', 'z').forEach(x -> printAndWait(""+(char)x)); } } This will produce an output of something similar to a 1 b 2 c 3 and so on, though results may vary. This is because the code in myThread is executed simultaneously, in a different thread, as the main flow. That is, the range 1-32 is handled by one thread, and the range a-z is handled by another. Since there is no synchronization between the threads, there is no guarantee which one will execute first or indeed even that they will produce a result that is perfectly intertwined. Detailed instructions on getting concurrency set up or installed.
https://riptutorial.com/concurrency
CC-MAIN-2019-30
refinedweb
208
55.95
Although. In order to get the most out of this article, you should be familiar with the basics of XForms. Familiarity with SVG also helps, but isn't crucial. The code in this article has been tested with Firefox and the Mozilla XForms extension (see Resources to download), but the concepts should apply to any XForms implementation. What you're trying to accomplish Let's start by looking at what the finished product looks like. Ultimately, you want a form that enables you to edit the properties of existing shapes, or to remove those shapes altogether. You also want to be able to add new shapes, edit those shapes, and save the data to a logo file. Once you've done that, you want to be able to see the changes right there on the page. Your final logo generator looks something like Figure 1. Figure 1. The final logo generator To accomplish all of this, you will need to use several techniques, including inserting and deleting elements, copying elements from one instance to another, and dynamically updating the contents of an iframe. Before moving on to the editor itself, let's look at the Scalable Vector Graphics, or SVG, we're going to edit (see Listing 1). Listing 1. The basic SVG image file Create a new file with this data and save it as logo.xml. Notice that it includes three different shapes, each with attributes that control its appearance. Each is part of a "group" element. Displayed by the browser, it looks like Figure 2. Figure 2. The SVG image Adding the SVG image to the page Unfortunately, you can't just display the image on the page directly. The reason for this is twofold. First of all, both XForms and SVG are processed by individual extensions to the browser, so it is difficult to get them to talk to each other in order to, say, have the SVG renderer render data that exists only in the XForms extension. Similarly, JavaScript recognizes only the originally loaded instance, so you can't have it interact with edited data in order to display it. Secondly, XForms is designed to work with text. The ability to have it output entire elements (as opposed to their text content) is extremely limited, so you can't have it send the instance data to the page for display when it changes. So to take care of it, you'll need to add an iframe you can update with a button (Listing 2). Listing 2. The general page The button enables the user to refresh the iframe after saving. Save this file as logogenerator.xhtml. Editing the existing logo In order to edit the XML, you first need to create an instance that includes the data (Listing 3). Listing 3. Adding the data instance Here you are creating the instance by referencing an external file, which just happens to include the SVG you created earlier. Now you need to create the controls that will enable you to edit the data (Listing 4). Listing 4. Adding the editing controls There seems to be a lot of code here, but it boils down to this: Each type of shape has its own set of properties (and therefore attributes), so you create a section for each of your three major types: circle, rectangle, and text. For each one, include controls to edit the relevant attributes. For the text, you also include a control for editing the first child of the element, which is the actual text to display. You can format your XForms controls using CSS, but in this case, to keep things simple, table elements have been used. The result should look something like Figure 3. Figure 3. Editing controls You can, of course, provide facilities for editing whatever shape you want. For example, you could include the ability to add and edit polylines, or other SVG shapes. The process is the same, so let's keep the article a little simpler by sticking to these three major shapes. If you make changes to the data in the controls, the XForms engine will make changes to the instance, but if you click the Refresh View button, you won't see any changes. This is because the iframe is referencing the file, not the "in memory" version of the data. In order to see the changes, you are going to have to save the new data to the logo.xml file. The mechanics of saving the file are going to depend on where you have the file in the first place. If the file is local (or if your Web server supports it), you can use the PUT method, but this article assumes that the file is remote and that you will need a script to do the actual saving. The form of the actual script doesn't matter, as long as it outputs the XML back to the instance. I've included an example PHP script in the source code for this article. To call that script, you need to create a submission (Listing 5). Listing 5. The submission You create the submission element; in this case, a submission that sends the data to the PHP file, in the model. Rather than replacing the entire page, you only want the processor to replace the instance. This way, when the user submits the form, the page remains in place. This enables the user to save frequently in order to see small incremental changes without the process becoming overly cumbersome. To enable the user to actually save the data, you also added a XForms submit button that calls that submission. To see this in action, refresh the page and make changes to the data in the controls. Click the Save Logo button and then click the Refresh View button to see the changes. The result is a page that should look something like Figure 4. Figure 4. Saving the data Using this technique, you can make any changes you want to existing elements. Now you need to know how to add new elements to the image. Up to now, things have been fairly straightforward. You have essentially been doing what XForms was designed to do, and doing it fairly simply. Now you are going to see the differences between how XForms was designed and the reality of what it can do. For example, you want to create a button that adds a new element to the document. In order to do that, you need to construct something like what is shown in Listing 6. Listing 6. Adding the trigger What you're telling the editor to do is add a copy of the last g element at the top of the file, before element number one. That means if you reload the form and click the Add New Element button, you'll see a new Circle element, as shown in Figure 5. Figure 5. Adding a new element Obviously, this is not what you want; you want to be able to add an empty element. To make that happen, you can add a new element to the end of the logo.xml file (Listing 7). Listing 7. Adding a new blank element The SVG g element doesn't define text as its body, so this text won't affect the actual image. It will, however, affect whether this is a "valid" SVG XML file. The Mozilla SVG implementation doesn't care, but if yours does, you'll want to adapt this technique so that you don't cause yourself problems. The actual text is completely arbitrary. You can then adapt to the editor to detect these elements (Listing 8). Listing 8. Detecting text in the SVG elements Here you have created a new control that displays a message only when it finds a g element that contains as its content a text node. You can see it displayed in Figure 6. Figure 6. Displaying a message regarding the text-containing elements Now if you click the Add New Element button, you will see an additional message. This is because it is this new element you are cloning and adding to the document, as you can see in Figure 7. Figure 7. Adding a new element If you save the file and look at it, you can see the new element in logo.xml, at the top of the file. Copying elements from one instance to another All right, you've got the ability to edit existing elements, and the ability to add new elements, but those new elements are pretty useless in terms of and into the actual image. In order to make them useful, you need the ability to populate them with one of your basic shapes. To start with, you will create an instance that includes templates for the elements you wish to add (Listing 9). Listing 9. Templates First notice that the new instance includes data in more than one namespace. Each template has been added in a generic my:shape element so that you can list the various available shapes. Second, notice that now that you have more than one instance, a reference has been added to the appropriate instance to each of your XPath statements. The instance() function replaces the root element in the XPath expression. (Note that technically you didn't have to specify the content instance, as, being the first instance in the model, it is the default. Consistency, however, says you should.) Next you can add the control that enables you to choose from among these templates (Listing 10). Listing 10. Copying existing elements This one is a little complicated, so let's take it from the top. First, you are dealing with a select element, used to add data to a specific node based on the users choices. The note to which this data will be added is the first g element in the content instance. Remember, this is the element you added with Add New Element. The actual data that's added to this node depends on the selected itemset items. In this case, those items come from the templates instance, and consist of each of the shape elements. For each one, the label is the label attribute of the shape element. But where you would normally follow the label element with a value element, you are instead using a copy element, which references the child of the shape element, or the circle, rect, or text template. From the user standpoint, the result looks like Figure 8. Figure 8. The select control When the user clicks on one of these labels to select the element, the XForms engine copies that element to the target g element. You can see the results in Figure 11, where you now have an extra Rectangle. If, on the other hand, the user deselects that item, perhaps by clicking a different item, the copy is removed and, in this case, replaced by the new copy. For example, if you now click the Circle item and save the logo, refreshing the view shows the results in Figure 9. Figure 9. Adding a circle There is still one more problem. If the user simply loads the page and clicks a new element type before any new element, you can get some fairly terrible results, because you are simply copying the template into the first g element -- which in this case is actual data, and not a placeholder. To solve that problem, you can add an empty g element to the top of the file (Listing 11). Listing 11. Adding an empty placeholder To afford further confusion, you can also change the editors so that it only displays an empty element if one has been added by the user (Listing 12). Listing 12. Limiting the display of new elements This way, the form only displays a message for a second text-containing element. Deleting existing elements You are almost done, but you need to add one more piece of very important functionality. To do that, you can use the delete action (Listing 13). Listing 13. Adding delete buttons It's possible to create a delete button that then leaves the "current" element, but to keep things simple, you are adding a delete button for each individual element. Clicking that button removes the current element from the instance. The result looks like Figure 10. Figure 10. Delete buttons Now you can add, edit, and delete elements at will. Starting from scratch -- the "empty" logo file You started this project with an existing logo.xml file, so the last step is to make sure that you can replicate your success with a file that does not contain a pre-existing image. There are, however, very specific requirements for pre-existing elements, so you can't actually start with an empty file. Instead, you need the following (Listing 14). Listing 14. The "empty" file Essentially, you need two pre-existing elements. The first is the placeholder into which you can add new elements. The second is the element to clone for when the user clicks the Add New Element button. Replace the contents of your logo to an XML file with the text of Listing 14 and save the file. Refresh the editor so you will have the ability to create an image from scratch, such as the one seen in Figure 11. Figure 11. Creating a new image It works! In this article, you looked at what it takes to create an XForms form capable of creating and editing an SVG image. What you learned. But the basic technique is right here. Information about download methods Learn - Get a basic introduction to XForms in Introduction to XForms, Part 1: The new Web standard for forms (developerWorks, September 2006). - Learn more about XForms in the IBM developerWorks XML zone. - Validate your SVG files here. - Get the basics of Scalable Vector Graphics in Introduction to Scalable Vector Graphics (developerWorks, March 2004). - how to Create JPEGs automatically with SVG in Tip: Create JPEGs automatically with SVG (developerWorks, September 2003). - IBM XML certification: Find out how you can become an IBM-Certified Developer in XML and related technologies. - SVG and XForms, a Primer (developerWorks, November 2003) provides an overview of the two technologies and highlights the potential synergies between them. - Visit XForms.org, a clearinghouse of XForms-related information. - developerWorks technical events and webcasts: Stay current with technology in these sessions. Get products and technologies - The XForms Recommendation is maintained by the W3C. - You can download Firefox here. - You can download the XForms extension here. - The SVG Recommendation is also maintained by the W3C. - Download a trial version of Lotus Forms (formerly Workplace Forms product). - See other XForms-related downloads. - Get MozzIE, an open-source control that allows you to render XForms in Internet Explorer. Discuss - Participate in the discussion forum. - developerWorks blogs: Get involved in the developerWorks community.).
http://www.ibm.com/developerworks/xml/library/x-xformslogogen/
crawl-002
refinedweb
2,487
61.97
for: import re Searching Patterns in a String match Function Initialize a variable text with a text string as follows: text = "The film Titanic was released in 1998" Let's write a regex expression that matches a string of any length and any character: result = re.match(r".*", text). If a match is found, the match function returns _sre.SRE_Match object as shown below: type(result) Output: _sre.SRE_Match Now to find the matched string, you can use the following command: result.group(0) Output: 'The film Titanic was released in 1998': text = "" Now, if you again execute the following regex expression, a match will be found: result = re.match(r".*", text) Since we specified to match the string with any length and any character, even an empty string is being matched. To match a string with a length of at least 1, the following regex expression is used: result = re.match(r".+", text) Here the plus sign specifies that the string should have at least one character. Searching Alphabets The match function can be used to find any alphabet letters within a string. Let's initialize the text variable with the following text: text = "The film Titanic was released in 1998" Now to find all the alphabet letter, both uppercase and lowercase, we can use the following regex expression: result = re.match(r"[a-zA-z]+", text) This regex expression states that match the text string for any alphabets from small a to small z or capital A to capital Z. The plus sign specifies that string should have at least one character. Let's print the match found by the above expression: print(result.group(0)) Output: The In the output, you can see that the first word i.e. The is returned. This is because the match function only returns the first match found. In the regex we specified that find the patterns with both small and capital alphabets from a to z. The first match found was The. After the word The there is a space, which is not treated as an alphabet letter, therefore the matching stopped and the expression returned just The, which is the first match. However, there is a problem with this. If a string starts with a number instead of an alphabet, the match function will return null even if there are alphabets after the number. Let's see this in action: text = "1998 was the year when the film titanic was released" result = re.match(r"[a-zA-z]+", text) type(result) Output: NoneType In the above script, we have updated the text variable and now it starts with a digit. We then used the match function to search for alphabets in the string. Though the text string contains alphabets, null will be returned since match function only matches the first element in the string. To solve this problem we can use the search function. The search Function The search function is similar to the match function i.e. it tries to match the specified pattern. However, unlike the match function, it matches the pattern globally instead of matching only the first element. Therefore, the search function will return a match even if the string doesn't contain an alphabet at the start of the string but contains an alphabet elsewhere in the string, as shown below: text = "1998 was the year when the film titanic was released" result = re.search(r"[a-zA-z]+", text) print(result.group(0)) Output: was The search function returns "was" since this is the first match that is found in the text string. Matching String from the Start To check if a string starts with a specific word, you can use the carrot key i.e. ^ followed by the word to match with the search function as shown below. Suppose we have the following string: text = "XYZ 1998 was the year when the film titanic was released" If we want to find out whether the string starts with "1998", we can use the search function as follows: result = re.search(r"^1998", text) type(result) In the output, null will be returned since the text string doesn't contain "1998" directly at the start. Now let's change the content text variable and add "1998" at the beginning and then check if "1998" is found at the beginning or not. Execute the following script: text = "1998 was the year when the film titanic was released" if re.search(r"^1998", text): print("Match found") else: print("Match not found") Output: Match found Matching Strings from the End To check whether a string ends with a specific word or not, we can use the word in the regular expression, followed by the dollar sign. The dollar sign marks the end of the statement. Take a look at the following example: text = "1998 was the year when the film titanic was released" if re.search(r"1998$", text): print("Match found") else: print("Match not found") In the above script, we tried to find if the text string ends with "1998", which is not the case. Output: Match not found Now if we update the string and add "1998" at the end of the text string, the above script will return ‘Match found' as shown below: text = "was the year when the film titanic was released 1998" if re.search(r"1998$", text): print("Match found") else: print("Match not found") Output: Match found Substituting text in a String Till now we have been using regex to find if a pattern exists in a string. Let's move forward with another advanced regex function i.e. substituting text in a string. The sub function is used for this purpose. Let's take a simple example of the substitute function. Suppose we have the following string: text = "The film Pulp Fiction was released in year 1994" To replace the string "Pulp Fiction" with "Forrest Gump" (another movie released in 1994) we can use the sub function as follows: result = re.sub(r"Pulp Fiction", "Forrest Gump", text) The first parameter to the sub function is the regular expression that finds the pattern to substitute. The second parameter is the new text that you want as a replacement for the old text and the third parameter is the text string on which the substitute operation will be performed. If you print the result variable, you will see the new string. Now let's substitute all the alphabets in our string with character "X". Execute the following script: text = "The film Pulp Fiction was released in year 1994" result = re.sub(r"[a-z]", "X", text) print(result) Output: TXX XXXX PXXX FXXXXXX XXX XXXXXXXX XX XXXX 1994 It can be seen from the output that all the characters have been replaced except the capital ones. This is because we specified a-z only and not A-Z. There are two ways to solve this problem. You can either specify A-Z in the regular expression along with a-z as follows: result = re.sub(r"[a-zA-Z]", "X", text). Shorthand Character Classes There are different types of shorthand character classes that can be used to perform a variety of different string manipulation functions without having to write complex logic. In this section we will discuss some of them: Removing Digits from a String The regex expression to find digits in a string is \d. This pattern can be used to remove digits from a string by replacing them with an empty string of length zero as shown below: text = "The film Pulp Fiction was released in year 1994" result = re.sub(r"\d", "", text) print(result) Output: The film Pulp Fiction was released in year Removing Alphabet Letters from a String text = "The film Pulp Fiction was released in year 1994" result = re.sub(r"[a-z]", "", text, flags=re.I) print(result) Output: 1994 Removing Word Characters If you want to remove all the word characters (letters and numbers) from a string and keep the remaining characters, you can use the \w pattern in your regex and replace it with an empty string of length zero, as shown below: text = "The film, '@Pulp Fiction' was ? released in % $ year 1994." result = re.sub(r"\w","", text, flags = re.I) print(result) Output: , '@ ' ? % $ . The output shows that all the numbers and alphabets have been removed. Removing Non-Word Characters To remove all the non-word characters, the \W pattern can be used as follows: text = "The film, '@Pulp Fiction' was ? released in % $ year 1994." result = re.sub(r"\W", "", text, flags=re.I) print(result) Output: ThefilmPulpFictionwasreleasedinyear1994 From the output, you can see that everything has been removed (even spaces), except the numbers and alphabets. Grouping Multiple Patterns You can group multiple patterns to match or substitute in a string using the square bracket. In fact, we did this when we matched capital and small letters. Let's group multiple punctuation marks and remove them from a string: text = "The film, '@Pulp Fiction' was ? released _ in % $ year 1994." result = re.sub(r"[,@\'?\.$%_]", "", text, flags=re.I) print(result) Output: The film Pulp Fiction was released in year 1994 You can see that the string in the text variable had multiple punctuation marks, we grouped all these punctuations in the regex expression using square brackets. It is important to mention that with a dot and a single quote we have to use the escape sequence i.e. backward slash. This is because by default the dot operator is used for any character and the single quote is used to denote a string. Removing Multiple Spaces Sometimes, multiple spaces appear between words as a result of removing words or punctuation. For instance, in the output of the last example, there are multiple spaces between in and year. These spaces can be removed using the \s pattern, which refers to a single space. text = "The film Pulp Fiction was released in year 1994." result = re.sub(r"\s+"," ", text, flags = re.I) print(result) Output: The film Pulp Fiction was released in year 1994. In the script above we used the expression \s+ which refers to single or multiple spaces. Removing Spaces from Start and End Sometimes we have a sentence that starts or ends with a space, which is often not desirable. The following script removes spaces from the beginning of a sentence: text = " The film Pulp Fiction was released in year 1994" result = re.sub(r"^\s+", "", text) print(result) Output: The film Pulp Fiction was released in year 1994 Similarly, to remove space at the end of the string, the following script can be used: text = "The film Pulp Fiction was released in year 1994 " result = re.sub(r"\s+$", "", text) print(result) Removing a Single Character Sometimes removing punctuation marks, such as an apostrophe, results in a single character which has no meaning. For instance, if you remove the apostrophe from the word Jacob's and replace it with space, the resultant string is Jacob s. Here the s makes no sense. Such single characters can be removed using regex as shown below: text = "The film Pulp Fiction s was b released in year 1994" result = re.sub(r"\s+[a-zA-Z]\s+", " ", text) print(result) Output: The film Pulp Fiction was released in year 1994 The script replaces any small or capital letter between one or more spaces, with a single space. Splitting a String String splitting is another very important function. Strings can be split using split function from the re package. The split function returns a list of split tokens. Let's split a string of words where one or more space characters are found, as shown below: text = "The film Pulp Fiction was released in year 1994 " result = re.split(r"\s+", text) print(result) Output: ['The', 'film', 'Pulp', 'Fiction', 'was', 'released', 'in', 'year', '1994', ''] Similarly, you can use other regex expressions to split a string using the split functions. For instance, the following split function splits string of words when a comma is found: text = "The film, Pulp Fiction, was released in year 1994" result = re.split(r"\,", text) print(result) Output: ['The film', ' Pulp Fiction', ' was released in year 1994'] Finding All Instances The match function conducts a match on the first element while the search function conducts a global search on the string and returns the first matched instance. For instance, if we have the following string: text = "I want to buy a mobile between 200 and 400 euros" We want to search all the digits from this string. If we use the search function, only the first occurrence of digits i.e. 200 will be returned as shown below: result = re.search(r"\d+", text) print(result.group(0)) Output: 200 On the other hand, the findall function returns a list that contains all the matched utterances as shown below: text = "I want to buy a mobile between 200 and 400 euros" result = re.findall(r"\d+", text) print(result) Output: ['200', '400'] You can see from the output that both "200" and "400" is returned by the findall function. Conclusion In this article we studied some of the most commonly used regex functions in Python. Regular expressions are extremely useful for preprocessing text that can be further used for a variety of applications, such as topic modeling, text classification, sentimental analysis, and text summarization, etc.
https://stackabuse.com/using-regex-for-text-manipulation-in-python/
CC-MAIN-2019-43
refinedweb
2,241
69.31
06 July 2012 06:18 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The No 1 MEG plant was shut on 20 June after a power disruption, the source said. Nan Ya’s four MEG plants at Mailiao have a combined capacity of 1.8m tonnes/year, and are supplied with ethylene through pipelines from its parent company Formosa Petrochemical Corp (FPCC). FPCC restarted its 1.03m tonne/year No 2 ethylene cracker in Mailiao on 30 June. It will keep its 1.2m tonne/year No 3 cracker and its 700,000 tonne/year No 1 cracker shut until 10 July and 5 August respectively, according to the source. Nan Ya’s 720,000 tonne/year No 4 MEG plant in Mailiao, which was shut on 4 June for a turnaround, is expected to be restarted in the middle
http://www.icis.com/Articles/2012/07/06/9575860/taiwans-nan-ya-delays-no-1-meg-unit-restart-on-ethylene.html
CC-MAIN-2015-18
refinedweb
139
74.39
initialise the joystick module and get a list of Joystick instances use the following code: pygame.joystick.init() joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())] The following event types will be generated by the joysticks JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION The event queue needs to be pumped frequently for some of the methods to work. So call one of pygame.event.get, pygame.event.wait, or pygame.event.pump regularly. This function is called automatically by pygame.init(). It initializes the joystick module. This will scan the system for all joystick devices. The module must be initialized before any other functions will work. It is safe to call this function more than once. Uninitialize the joystick module. After you call this any existing joystick objects will no longer work. It is safe to call this function more than once. Test if the pygame.joystick.init() function has been called. Return the number of joystick devices on the system. The count will be 0 if there are no joysticks on the system. When you create Joystick objects using Joystick(id), you pass an integer that must be lower than this count. Create a new joystick to access a physical device. The id argument must be a value from 0 to pygame.joystick.get_count()-1. To access most of the Joystick methods, you’ll need to init() the Joystick. This is separate from making sure the joystick module is initialized. When multiple Joysticks objects are created for the same physical joystick device (i.e., they have the same ID number), the state and values for those Joystick objects will be shared. The Joystick object allows you to get information about the types of controls on a joystick device. Once the device is initialized the Pygame event queue will start receiving events about its input. You can call the Joystick.get_name() and Joystick.get_id() functions without initializing the Joystick object. The Joystick must be initialized to get most of the information about the controls. While the Joystick is initialized the Pygame event queue will receive events from the Joystick input. It is safe to call this more than once. This will unitialize a Joystick. After this the Pygame event queue will no longer receive events from the device. It is safe to call this more than once. Returns True if the init() method has already been called on this Joystick object. Returns the integer ID that represents this device. This is the same value that was passed to the Joystick() constructor. This method can safely be called while the Joystick is not initialized. Returns the system name for this joystick device. It is unknown what name the system will give to the Joystick, but it should be a unique name that identifies the device. This method can safely be called while the Joystick is not initialized. Returns the number of input axes are on a Joystick. There will usually be two for the position. Controls like rudders and throttles are treated as additional axes. The pygame.JOYAXISMOTION events will be in the range from -1.0 to 1.0. A value of 0.0 means the axis is centered. Gamepad devices will usually be -1, 0, or 1 with no values in between. Older analog joystick axes will not always use the full -1 to 1 range, and the centered value will be some area around 0. Analog joysticks usually have a bit of noise in their axis, which will generate a lot of rapid small motion events. Returns the current position of a joystick axis. The value will range from -1 to 1 with a value of 0 being centered. You may want to take into account some tolerance to handle jitter, and joystick drift may keep the joystick from centering at 0 or using the full range of position values. The axis number must be an integer from zero to get_numaxes()-1. Returns the number of trackball devices on a Joystick. These devices work similar to a mouse but they have no absolute position; they only have relative amounts of movement. The pygame.JOYBALLMOTION event will be sent when the trackball is rolled. It will report the amount of movement on the trackball. Returns the relative movement of a joystick button. The value is a x, y pair holding the relative movement since the last call to get_ball. The ball number must be an integer from zero to get_numballs()-1. Returns the number of pushable buttons on the joystick. These buttons have a boolean (on or off) state. Buttons generate a pygame.JOYBUTTONDOWN and pygame.JOYBUTTONUP event when they are pressed and released. Returns the current state of a joystick button. Returns the number of joystick hats on a Joystick. Hat devices are like miniature digital joysticks on a joystick. Each hat has two axes of input. The pygame.JOYHATMOTION event is generated when the hat changes position. The position attribute for the event contains a pair of values that are either -1, 0, or 1. A position of (0, 0) means the hat is centered. Returns the current position of a position hat. The position is given as two values representing the X and Y position for the hat. (0, 0) means centered. A value of -1 means left/down and a value of 1 means right/up: so (-1, 0) means left; (1, 0) means right; (0, 1) means up; (1, 1) means upper-right; etc. This value is digital, i.e., each coordinate can be -1, 0 or 1 but never in-between. The hat number must be between 0 and get_numhats()-1. import pygame # Define some colors BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) # This is a simple class that will help us print to the screen # It has nothing to do with the joysticks, just outputing the # information. class TextPrint: def __init__(self): self.reset() self.font = pygame.font.Font(None, 20) def print(self, screen, textString): textBitmap = self.font.render(textString, True, BLACK) screen.blit(textBitmap, [self.x, self.y]) self.y += self.line_height def reset(self): self.x = 10 self.y = 10 self.line_height = 15 def indent(self): self.x += 10 def unindent(self): self.x -= done==False: # EVENT PROCESSING STEP for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done=True # Flag that we are done so we exit this loop # 20 frames per second clock.tick(20) # Close the window and quit. # If you forget this line, the program will 'hang' # on exit if running from IDLE. pygame.quit ()
http://pygame.org/docs/ref/joystick.html
CC-MAIN-2015-22
refinedweb
1,102
69.18
Testing REST Services with Groovy For awhile now, RIAs (Rich Internet Applications) have rapidly started replacing traditional server-side web applications (JSP, JSF, etc). Typically, these flashier sites are created using Flex or javascript libraries like extjs or yui. At the heart of these sexy applications live simple REST services that return JSON or XML. Testing these REST services should be made a high priority for several reasons: - It's the contract between the client and server. Breaking that contract should be avoided. - Your application may not be the only client. Once external parties start consuming your REST services you'll want tests in place to ensure you don't break their clients. - To validate the response is well-formed XML or properly constructed JSON - Valuable black-box test, testing the entire server-side stack starting from the REST layer going all the way down to the DAO layer to the database. Now let's say you have a REST service at the URL that returns this JSON: {"books":[This is how simple it is to write a test in Groovy using HttpBuilder: {"name":"Being Mad","author":"Kit Plummer"}, {"name":"Clown Life","author":"Josh Hoover"}, {"name":"You Miss Me","author":"Ron Alleva"}, {"name":"Talk to me Goose","author":"Jeff Black"} ]} To me the major advantage to this approach is being able to traverse the JSON response like I would in javascript. If the response was XML it be just as easy too.To me the major advantage to this approach is being able to traverse the JSON response like I would in javascript. If the response was XML it be just as easy too. import groovyx.net.http.HTTPBuilder import groovyx.net.http.Method import static groovyx.net.http.ContentType.JSON class BooksTest extends GroovyTestCase { def void test_get_all_books() { def http = new HTTPBuilder("") http.request(Method.valueOf("GET"), JSON) { url.path = '/myapp/api/books' response.success = {resp, json -> json.books.each { book -> assert book.name != "" } } } } } The only two remaining items you would need would be adding the gmaven plugin to your pom and httpbuilder as a dependency.
https://jlorenzen.blogspot.com/2009/01/?widgetType=BlogArchive&widgetId=BlogArchive1&action=toggle&dir=open&toggle=YEARLY-1420092000000&toggleopen=MONTHLY-1230789600000
CC-MAIN-2020-16
refinedweb
346
64.51
how do I take characters from a file and put them into a string so I can compare them?? your help is greatly appreciated This is a discussion on fstream question within the C++ Programming forums, part of the General Programming Boards category; how do I take characters from a file and put them into a string so I can compare them?? your ... how do I take characters from a file and put them into a string so I can compare them?? your help is greatly appreciated You can use the get method to put them into a single character. And then you can use the += operator for string to concat it to the end of a string. However, if you want to compare single characters, you don't need to use strings. Code:#include <iostream> #include <string> using namespace std; int main() { std::ifstream input("inputfile.txt"); std::string s; char current; while (!input.eof()) { current = input.get(); s += current; } return 0; } thank you! that's exactly what I was looking for I can't get the += to work my compiler only wants =+, and that doesn't work with chars. plus it won't let me declare a variable with string. please help OK, depending in what compiler you have you may need: One of these options should work.One of these options should work.Code:#include<string.h> //or #include<cstring> //or #include<cstream> =+ is different than +=, because += adds to an integer, where =+ is meaning "equal plus" ok, I can include string.h, but not the others, but I still can't use +=, do you guys want to see my code? =+ really means taht the number after that is positive . post the code.. post the code. What compiler are you using? Visual C++ 6.0 You should be able to use +=, so yes please post your code. Code://readtext.cpp #include <iostream.h> #include <fstream.h> #include <string.h> main() { char x; char current[6]; ifstream infile; infile.open("text.txt",ios::in); while(infile) { infile.get(x); current += x; } return 0; } i guess i didnt exactly understand. i dont think that would work because would this: use strlen():use strlen():Code:int Int = 5; int Array[5]; Array += Int; Str[ strlen( Str ) ] = Chr; I'm new to programming, can you give me an example on how to use strlen in my situation? Thanks string current; while(infile); { infile.get(x); current += x; works because the += operator is overloaded for the STL string class of which current is an instance. However, the += operator is not available for Cstyle, null-terminated char array type strings. You need to use strcat() for that. //declare an string big enough to hold what you want char * current = new char[10000000]; current[0] = '\0'; //declare a second string to act as input char * input[2]; input[1] = '\0'; //read the file one char at a time, placing the char as the first //element in the string called input while(infile) { infile.get(input[0]); //then concatenate the string called input onto the string called //current strcat(current, input); //etc.
http://cboard.cprogramming.com/cplusplus-programming/18872-fstream-question.html
CC-MAIN-2015-14
refinedweb
516
75
. Huh. > > Of course, that bug report is against a 2.95ish toolchain, so the problems > > may have been fixed by now. I tried it with gcc-3.1, on a dual RH 7.1 machine. It's fine. This is with the pool-alloc allocators. Perhaps it's dual solaris 2.6, 2.95.x problem, or the older library. > If I can get access to this ``internal bug report (102997)'', then I > would be happy to fix mainline gcc if the problem still exists there > and I can reproduce it in my environment(s). But I only want the test > case if it is something that can be publicly posted. Right. This testcase works now, but perhaps it can be modified into the unposted problem with mySQL, etc. // Compile with: // g++ -g -D_THREAD_SAFE -DSOLARIS -D_REENTRANT -D_PTHREADS -o \ // bad_hash bad_hash.cpp -lpthread // Causes a core dump in the first few iterations under Solaris 2.6 // egcs 2.91.66 or Cygnus 98r2, STL library included with the // respective distributions. // The core dump does not happen with NUM_THREADS=1, and happens more // quickly the higher the value for NUM_THREADS. // There is no core dump if std::map is used instead of // std::hash_map, or if types other than string are used // for the map's value type (int, char*, vector do not cause // the core dump). // // John Panzer // jpanzer@netscape.com #include <cstdio> #include <cstdlib> #include <sys/poll.h> #include <string> #include <ext/hash_map> #include <pthread.h> using namespace std; const int NUM_ITERATIONS=500000; void *f(void *arg) { for(int i = 0; i < NUM_ITERATIONS; ++i) { hash_map<int, string> m; m[42] = "foobar"; poll(0, 0, 10); } } void mt_test() { const int NUM_THREADS = 20; void* ret=0; pthread_t thread[NUM_THREADS]; for(int i=0;i<NUM_THREADS;++i) pthread_create(&thread[i], NULL, f, (void*)i); for(int i=0 ; i < NUM_THREADS; ++i) pthread_join(thread[i], &ret); } int main() { mt_test(); return 0; }
http://gcc.gnu.org/ml/libstdc++/2001-10/msg00209.html
crawl-001
refinedweb
317
74.59
Peter Mayne 2005-01-17 I'd like to indent my Python scripts with four spaces, and my HTML/XML documents with two spaces. Is there a way of specifying per-document-type indents? Thanks. Daniel Pozmanter 2005-01-17 There should be. I knew I forgot something. Franz suggested this. As long as I am at it, are there any other per document type preferences that should be set? (I can't think of any at the moment.) Franz Steinhaeusler 2005-01-18 For me applies: Eol Endings Use Tab/Spaces Tab/Indentation Width these two variables could be get from the settings self.addchar = "\t".expandtabs(2) self.tabwidth = 2 self.addchar = "\t".expandtabs(GetTabWidth()) self.tabwidth = GetTabWidth() or simply replace self.tabwidth with GetTabWidth() Peter Mayne 2005-01-18 Most of the things in the Prefences Document page could be set as per-type. For instance, word wrap might make sense for HTML, but not Python; the Python comment string doesn't make much sense in HTML or C++; etc. Daniel Pozmanter 2005-01-18 Word wrap as well works. (This will be fun ;P). Ok. So here is what I have so far: Extensions Folding Tab Width Indentation Type Line Ending Type Context Sensitive AutoIndent (At the moment, only for python) At the moment, file types will be: Python, C/C++, HTML, Plain Text. Although I should probably add pyrex support at some point. I am thinking of implementing this as a dictionary, so that you'd have DrFrame.prefs.tabwidth[DrFrame.GetCurrentFileType()] The only thing I am a bit muddled about is letting people set these globally. Peter Mayne 2005-01-20 > The only thing I am a bit muddled about is letting people set these globally. Hmm, tricky. One option is not to have a global setting at all, and add a "Apply these preferences to all languages" button, similar to the existing "Apply Text Property To All Styles" button. After all, I only need to set up my document preferences once, so any pain will hopefully be soon forgotten. If someone wants to be really clever, they can edit the preferences file directly. :-) > I am thinking of implementing this as a dictionary, Why not make prefs aware of the current file type, so you don't have to pass it in every time? For per-type preferences, you could use a dictionary of file types, each of which stores the per-type dictionary. Then you could do something like def __getattr__(self, pref): if pref in self.__dict__: return self.__dict__[pref] else: return self.prefs[self.currentType][pref] and call it like prefs = drPreferences(type=...) tabwidth = prefs.tabwidth Less typing, looks nicer. Daniel Pozmanter 2005-01-20 The problem is prefs are a member of DrFrame, and there can be multiple documents, each with their own file type. So the filetype has to be part of the Document. I could add functions like: DrFrame.GetTabWidth() or DrDocument.GetTabWidth() Peter Mayne 2005-01-21 Ah, so it is. If you added methods like GetTabWidth(), you need one for every preference, which is getting a little unwieldy, and clutters up the source browser. What about in DrFrame, something like: def getPreference(self, preference, language=None): if language: return self.prefs.perLanguagePrefs[language][preference] else: return self.prefs.__dict__[preference] where perLanguagePrefs is a dictionary keyed on language containing dictionaries keyed on preference names. (Or use some other data structure: you know the internals better than I do.) Now you can use DrFrame.getPreference('tabwidth', currentLanguage) for language-specific preferences, and DrFrame.getPreference('saveonrun') for global preferences. Daniel Pozmanter 2005-01-21 Easy enough. DrFrame.GetPreference('doctabwidth', 0) Although you can also access prefs as a dictionary, so: DrFrame.prefs['doctabwidth[0]'] and DrFrame.prefs['doctabwidth'][0] and DrFrame.prefs.doctabwidth[0] All work.
http://sourceforge.net/p/drpython/discussion/283803/thread/19b416d1/
CC-MAIN-2015-22
refinedweb
639
59.4
Main TopicsBrowse All Topics? Hi all, I'm interested in creating a GUI in Java Swing that allows users to upload files to a web server. I can only use Java/Java Swing, Java servlets allowed and no JSP. Also my http server does not support FTP. Is it possible to create.... hello, i m using netbeans 6.0.i have a panel,on that panel i hv a scrollpane,on that scrollpane i have dragged n dropprd a jtable.i want to use a combobox in one of the ells and button in another cell.how i can do that? thnx hi, i have 3 classes in java. 1)a class that extends Jframe 2)another that extends JPanel 3)a class that holds only the main method In my main method of my 3rd class, it looks something like this. but only the JFrame got shown and it seems... For some reason I can't make the JTextFields fire the property change events when changing the text in the textfields. I followed a guide used on JFormattedTextField on sun.com, but maybe its not the same concept? I have attached the non working... Hello, The following code supposed to be setting the Jpanel at the center of the JFrame I have created. Since the BorderLayOut tries to fill the whole window with the JPanel, it does not do what I want to happen. I have set a size for the... I'm trying to create a data file viewer with an application I'm writing. It works the first time, but if you try to press the button again and change the source file and view another data file, it processes it but does not change the graph.... I am trying to connect to a DB2 on an AS400. I thikn I have that part done, but I am also trying to display the results of the query in a table using the ResultSet method. I keep getting an error saying "Can not Resolve Symbol" on this line... I'm looking to make a simple JComboBox with Key=Value pairs, i.e. InternalValue=DisplayValue Example: The combo box options are S=Save to disk G=Group into one file N=Don't Save If the user chooses "Don't Save", the program... I'm trying to use a JComboBox that has Images for its items in a JTable column. When I run the program the combo box is there and usable, but not until I click in the cell. Before clicking it's empty even though I've used the setSelectedIndex... Hi Experts, I constructed a JTree with some data in it. 3 node types: root, ProjectNode, and leaf (string) I would like to retrieve a leaf's treepath so that I can select it in the JTree. I can do it for the nodes immediately following root... Hello, Here is my GUI: For some reason i could display my examTable on examPanel even though i am not getting any error message. I am able to print the examID: System.out.println("examRs)... Why is the KeyListener ignored in this example? I have a JPanel in which I placed a JLabel of the same size as the JPanel. I set the icon property of the JLabel to a jpg image file. The image file displays, but it is too large, and needs to be resized. How do I resize the displayed (in... Hi, I've tried to modify one of the Demo programs (TableDemo.java) found in the Java Tutorial. When executed, the *original* program displays a small table that primarily consists of string data within each cell. I've tried to modify the... Hi, I am new to netbeans and require the sample code or tutorial for developing Java Swing Applet in netbeans. Kindly Revert Hello All, Can anybody provide me with an example, how to convert html file to an image file using Java? Thanks in advance resizing image with getScaledInstance I have a great quality loss. I read also but i was not able to obtain better results. Any ideas to perform an image... hi! Can anybody take a look this? (It is hard to explain w/o actual applet.) If you drag up the bottom of window, the button disapears. My question is: Is there two panels in this... Hi! I need to put some instructional label on top and three buttons at the bottom. I was thinking creating Jpanels for them and inserting into Jframe, but it doesn’t seems to work and the format is messed up. Can some one show me better ways... Hi Experts, I have JTable with 5 columns and one column with check box vales. I need to select one row at a time and fire event on selection of cells in first 4 columns. But the last check box column should not select(highlight) the row i.e... I'm having trouble getting my JFrame to show when I run my program it just shows me a blank frame. I have my Checkboxes declared but nothing is showing. Help me please Using a JTable, what event or method is generated/called when a column is manually resized by the user? If it's an: event: What is the listener interface handling the event method: what is the exact method signature including ... How is it possible to select a certain treepath in a JTree? I have used the code below, but I get this error. java.lang.ClassCastExcepti i am using JTable in my program.during the running time i like to change single row color.how to change..can u give some ideas immediately..bz it's very urgent. Thankingyou I'm recently creating a OOP kind of GUI design concept! first of all, i have a JFrame class, and it's associate with another JPanel class, the JPanel class have a JButton which is open up a JDialog (Note: my JButton is not in the JFrame class).... im trying to run unix script for example ABQ_MIS_script.sh it dosent work this an update script but when i try to run unix command like ls -ltr it will work how can run the script I have an undecorated JFrame (which also has a glasspane attached). In my glasspane, I have a mouse adapter listening for drag events to the components that it stores (JLabels with icons). I would like to be able to reposition the JFrame... I'm working on a JTable with a checkbox column. I have problems with the checkbox column header: 1. The checkbox in the header doesn't work very well. If you click it once, it checks all other boxes as it should, but then it doesnt' work well... I found this code to create a mutli column jList. It works just fine except for the fact it creates a new form. I'd like to be able to use this component in a more traditional way. i.e. create the multicolumn aspect and mount it to an existing... Hello, Is there a way I can put a actionlistener on a JLabel? Thanks!! Edit>> To make the label clickable! I'm playing around with creating an application and I want to create a new window when a button is clicked. I'm new to creating swing apps so I'm wondering what the best way to accomplish this would be and what component would best suite. I have... How would I go about displaying the results of a simple MySQL select statement in a JTable component in NetBeans 6.0? Something like this: select ID, FIRST, LAST from table where variable = 'Y'; Any help would be appreciated! Mark I am trying to make an input field and a display text area in netbeans. If I input a number in the input field and press enter then the same number should be displayed in the text area. How Do I do that? How to compare two images are same or not using java. For Java Windows AOT compilers, Excelsior JET seems to be the leader. Are there any other competitors to Excelsior JET? Here is some code: public class MenuSelection implements ActionListener { public void actionPerformed (ActionEvent e); { System.out.println("Do something"); } } q. Why do I get a "missing method body or... I'm stuck. I have a JTable that holds a JComboBox which is populated depending on the value in another cell (plain) in the same row. Everything displays correctly, with the correct values in each combo box. The problem is when I make a selection... hai I want to play the swf file in the Java desktop Applicqaaion, I triied with the lot of codes but it not work, Please give me the Solution so that i can sole this poo I keep getting below exception in Tomcat 5.5, it happens with JNLP as well as on applet client around 5 minute. What could be the reason ? ClientAbortException: java.net.SocketException: Software caused connection abort: socket write error ... Experts, Please help on how can I add/append new row dynamically. I'm using jTable1.setValueAt("asdf", to add data to a jTable. Thanks. Hello experts, Have a quick question. Is it possible to create a horizontal line on a JPanel? I want to do that to make a sepration between two regions on my JPanel...just to give a look and feel to the whole thing. Let me know if its... The following code has a JTable with 2 columns. The lst column has JComboBoxes, the 2nd column has JSpinners. I want to set the spinner values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For... Hello, I know this is supposed to be easy, i've tried about twenty different ways of doing this, even using code straight from my java book and other sites but for some reason I can't get a clickable image to display. It works when I use an... Hi! I am new to programming with Java n by extension J2ME. I am trying to write code for a splash screen that displays a screen title at the top of the screen, a picture in the middle of the screen and maybe a line below the picture. Cheers Hello there, I have a JTable which has two columns containing dates.is it possible to have a calender pop up when i click on the cell containing the date. cheers zolf Hi Experts, I have a awt.Component that comes from JMF using MediaPlayer.getVisualCompo But I need to resize this Component larger than what it is and maintain its Aspect... I am diplaying an mjeg video to a JPanel inside a JFrame. i can scale the 'images' as needed but i want to fix the overall aspect ratio constant. how can you force the JFrame / JPanel to hold a fixed aspect ratio as the user 'resizes' it? I am in a preparation phase for making a game, with an interface, like an RTS. I am using a Mutalisk animated gif to start off my "learning." (code attached) I will use my own graphics later. I am using a JFrame for the game window, and adding... I am encountering a 'could not find main class' error. I am launching the application form the main metohd by right clicking and then selecting 'run as' - java application. All the relevant jars are on the class path - and the error message i... We have a JPanel that's populated from a database that consists numerous JLabels and JButtons. Is there a way to refresh or clear the JPanel to except new results from click on a JButton from another class? Basically is there a way to refresh... How can I exec a program and have the output displayed in the textarea that I've created while running? The code work OK if I pass it simple commands like "dir" etc. but hangs when I start my application. The application I'm running is a java... Hi, I am designing a GUI with my own custom JTable which has a method to resize the columns in the table, such that the 2nd column fills all of the space that the JTable has available. I have added a listener to the main JFrame to detect when it... Hi i have a have a java GUI application i want to save some file in some place,,, now the problem is that i want the user to locate where to save that file ,, i want something like when u download a file , the browser asked u where to save it... Hi, I'm trying to add an image to my JPanel, but I cant seem to get it to work... Can you please share some ideas/comments? Thanks. I tried adding the following inside the constructor, but it didn't work. I'm just not sure how to do it: ... hi, i've searced the web to find a way to set padding on a JPanel, like padding is used in css. But i couldn't find any. How would i set padding on a jpanel? Stian Hello Experts, having problems running jstat. here is what I am doing: jdkDir> jstat -gc processPID 250 2 but it keeps saying that the PID is not found or it throws a java exception. I confirm, via task manager (windows) tomcat's PID... I have created an application in Netbeans 6.8. When creating it I chose a new Java Desktop Application framework for a Basic Application Shell. Part of the plusses of this project structure was to have a resource management mechanisms to better... I am trying to remove the etched border around JComboBox in the Metal PLAF. I'd rather not extend any of the PLAF classes, so I've tried using UIManager.put("ComboBox.bo with no luck. It seems... I have the following statement: newIndex = (int)Math.ceil(i*((sequenc for example :sequence1.length equal to 6 and X= 7 i =1 newIndex = (int)Math.ceil(1*((6)/7)); but this produce the result equal 0, but I am... Hey all, I would like to set a small number of JPanels in my application so that if the window is resized, they have a minimum size that those particulare JPanels can be set to. I tried something like this: // ... JPanel pane = new JPanel();... hello there, i have a jtable which gets its data from the db.now i want to be able to edit the details in the cell.how can i do it.example will be appreciated. cheers zolf Hi Experts, What's the main difference between JButton and Button ? JFrame and Frame ? JLabel and Label ? It seems that JButton, JLabel and JFrame belong to swing and newer .... but .. what are the exact advantages of using them ? Thanks... Is it possible to clear the contents of a JPanel or JFrame when an action has been performed??... and then fill the JPanel or JFrame with something else? Hi,... I can use GridBagLayout to define rows of Squares (JPanels) that happen to have each odd-numbered row indented by a half-square to simulate a hex map. I can create a hexagon JPanel by overwriting the paintComponent but it still comes out looking... I'm trying to add a JTable to my window, but I can't get it to display the header. Can someone give me detailed instructions how to display a JTable with it's header. I also need to know how to get it to not be able to edit the columns... Hello, I've subclassed the JTable and AbstractTableModel classes in order to create a table with a specific look that would be easy to instantiate. Anyhow, I can't seem to get the table header to show up and I'm just wondering what I have... Hi experts, I am developing a stand alone java application using swing. I am new to swing. As per the need i have to put a JTable in my application and make that JTable editable. That is on clicking the add button 1 row should be added to JTable... Hello freinds, I want to know how to zoom in/out jpanel and all of its components without disturbing the events assosciated with all of the components inside jpanel. Thanx in advance. I include the form feed code \f at the end of my format string but is does not form feed to the next page before it starts printing the balance of the document. Any Ideas I had implemented a JOptionPane with a JTable where one of the cells in the JTable had a JPopupMenu. The JPopupMenu didn't work in that it was not able to get focus and so nothing could be selected in the list. My guess was that because... hello there i want to draw tile image on JLabel while the text will display over this bordered image and the JLabel expanded as the text ended (Ex. writing Text in a bubble Talk image) URGENT PLEAASE i have a JProgressBar which I am using during a Task is it possible to change the color of progress bar (default is orange to say green) when the process is finished, thanks For a given component, is there a difference between: - calling setFocusable(true) in its constructor and - adding this method to the class @Override public boolean isFocusable() { return true; } Hi, I am looking to create a zoom - pan effect on a jpanel with multiple elements in it with various listeners. I can create the zoom-pan effect relatively easily with Graphics2D's transformations and then drawing the panel. However, once... Hi, I'm quite new to Java and I'm trying to create an interface in swing that is scalable. I am trying to implement the following design of a board game: I am trying to make it so the game is... I'm using java swing to add images into a JList to display images' thumbnail. I get a scaled instance of every image, add them into a DefaultListModel and then add the list model into my JList.But I got that error when adding images: Exception... Hello, I'm trying to add an image as a background on a JPanel to enhance an interface but after editing someone elses code I've come across a problem. I get a grey box instead of the image it's supposed to display. I've also tried adding... This is another dumb question from a beginner with a public library book (McGrath Java2 in easy steps) I want to add a JPanel with an image with it using java.awt. I can achieve this if I don't set a flowLayout to the container, but if I try... Q tal, Ive been trying to implement the OOoBeanViewer class in a systems and I cant stop getting problems, when I run it in Eclipse it runs fine as both applet or application, but when I try to use it as an applet it gives me a million of... I found the listed program on Roseindia.net. Great site I recommend it. Here is the code: import javax.swing.*; import java.awt.event.*; public class ShowDialogBox{ JFrame frame; public static void main(String[] args){ ... I am currently working on an application that is going to serve as a sales tool for a supply-chain management product. As part of the demonstration, I want to have a Flash presentation display in a swing component (either a JFrame or a... hi, I have a small java application that contains a JPanel. In the JPanel I have a JButton. I also created a JFrame Form using NetBeans. Now I have added the ActionListener in my JPanel and all I want to do is when I click on the button in the... How can i disable a Parent window (JFrame) in java while the child window also a (JFrame) is visible Workbook wb; // ... ByteArrayOutputStream bos = new ByteArrayOutputStream(); wb.write(bos); InputStream bis = new ByteArrayInputStream(bos.t Is this a correct way to convert output stream to input stream actually the... Anyone know how to create a directory tree using swing in Java?This tree is used for scaning all computer hard drive and directories inside each drive. JTable.getCellEditor() seems to be called the first time a given cell is clicked on and never again. Is this correct? How do I get the table & scroll pane to stretch to fill the panel as it is resized? (Resized using the mouse). Ola! I have a swing frame and different components on it. Layout manager is GridBagLayout. What I want to do is when any component is selected (has focus) I would like to draw a red border around the cell of GridBagLayout which contains that... Hi, Does anyone have an example program where a frame consists of multiple panels where the layout is null (i.e. you can setLocation and setSize for the components within the frame and panels)??? Please help me! Thanks guys, Roy. hi, I want to refresh a JTable with another JTable values. How can i do that? Basically i want to copy the values from a backup JTable to another JTable which is being displayed on the screen, on some event like a button press. I did the... I'm trying invoke a JForm Panel by clicking a button on a Java Desktop Application. In the event action listener of the button i have created an object of the JForm class and have set it to be visible. The program does not give any errors, but... Experts, I am plotting radar tracks onto a panel. I do this my iterating through a container and painting the coordinates of the aircraft that exist at the particular time increment. The effect is miving dots across the screen - similar to a... I am having trouble showing a simple animation in a Java application. I paint several circles separated by repaint and sleep requests but I only see the last one, not the intermediate ones. The attached code displays a single "circle" at... How can I orientate my JLabel vertically (Like for a JSlider: JSlider.setOrientation(JSl Please help me ??? Hi experts, In the attached code, I need to have the following options 1) get the name(eg;first.doc) of the selected item/items. 2) When I right click on top of a particular item, I need to have that item alone selected. 3) I need to have no... zzynx 2,000 0 points yesterdayProfile mccarl 2,000 0 points yesterdayProfile
http://www.experts-exchange.com/Programming/Editors_IDEs/AWT_Swing/Top_Solutions.html
crawl-003
refinedweb
3,780
74.08
csSpline Class ReferenceA spline superclass. More... [Geometry utilities] #include <csgeom/spline.h> Inheritance diagram for csSpline: Detailed DescriptionA spline superclass. This spline can control several dimensions at once. Definition at line 35 of file spline.h. Constructor & Destructor Documentation Create a spline with d dimensions and p points. Destroy the spline. Member Function Documentation Calculate internal values for this spline given some time value. Implemented in csCubicSpline, and csBSpline. Get the index of the current point we are in (valid after Calculate()). Definition at line 139 of file spline.h. Gets the values of the control point at index idx. Caller is responsible for invoking `delete[]' on returned array when no longer needed. After calling Calculate() you can use this to fetch the value of some dimension. Implemented in csCubicSpline, and csBSpline. Insert a point after some index. If index == -1 add a point before all others. Remove a point at the index. Set a value for some dimension. Set the values for some dimension. 'd' should point to an array containing 'num_points' values. These are the values that will be interpolated. The given array is copied. Sets the values of the control point at index idx. Set one time point. Set the time values. 't' should point to an array containing 'num_points' values. These values typically start with 0 and end with 1. Other values are also possible the but the values should rise. The given array is copied. The documentation for this class was generated from the following file: Generated for Crystal Space 1.0.2 by doxygen 1.4.7
http://www.crystalspace3d.org/docs/online/api-1.0/classcsSpline.html
CC-MAIN-2015-06
refinedweb
263
63.36
I was in a conversation with an academic colleague (wicked smart dude) and the subject of installing R came up (NOTE: this will happen to you, too, if you ever have the misfortune to have a face-to-face convo with me ;-). They noted that getting up and running with R was not as seamless as one would like it to be and, to be honest, I have to agree, especially after typing the rest of this post out. I recently had a similar experience helping folks who use Windows get R & RStudio up and running and that’s even more of a nightmare, especially if you do not have Administrator privileges (or, perhaps I just scare easily). Prior to these experiences, I never really stopped to consider just how less friendly the installation process of R is when compared to Excel, Tableau or other apps one might use for data analysis and visualization. Hopefully this will becomre a top priority for the R Consortium. Since this colleague uses OS X, I offered to put together instructions for how to get R & RStudio installed and finally had 5 minutes to crank out a blog post to help the broader community with the information. Get R - Go to - If you’re on a recent version of OS X, download the first .pkglink. As of this post, it’s R-3.2.2.pkgand the direct URL is - Install the package by double-clicking on it and working through the prompts. Verify R itself is working - Look in the Applicationsfolder for the R application. - Double-click it and you should see an R console window. - If that did not work, try installing R again - Once you’ve verified R is working, quit the app Download RStudio RStudio is an integrated development environment for R that will make your life and coding easier. - Go to and download the RStudio version for Mac OS X. It’ll say something like RStudio 0.99.486 - Mac OS X 10.6+ (64-bit). The direct URL for that verison (which was current at the time of this post) is - Double-click that DMG file - Drag the RStudio icon to the Applicationsfolder. Verify RStudio & R are working together - Look in the Applicationsfolder for the RStudio application. - Double-click it and you should see an RStudio window with four panes. From now on, just start RStudio when you want to work in R. [Optional] Install XQuartz Some functions in R require an “X11 Server” and/or libraries associated with an X11 server. Apple does not provide this software with OS X anymore so you have to do it on your own via a third-party application called XQuartz. - Go to and download the top-most “quick download” disk image file. As of this post, that’s version 2.7.8 and this is the direct link - Double click the downloaded disk image then double click on the XQuartz.pkgand follow the installation steps. [Optional] Install Xcode Tools Some R packages require compilation. That requires utilities not installed on OS X by default. You can wait to do the following until it’s needed, but since you’re already installing things… - Get Xcode and install it like any “normal” Mac application - When the intallation is done, open Xcode then close it just to verify it installed correctly - Find and open the Terminalprogram in the Utilitiesfolder under the Applicationsfolder - Paste the following into the Termainal window and hit enter/return (accept any dialog/prompt): - Close the Terminal application [Optional] Set yourself up for easier future compiled package installation Some R packages need additional libraries to work and most aren’t on your system by default. There are a myriad of ways to get these libraries, and the way I obtain them is via the homebrew utility. You can save yourself the trouble of installing homebrew later by doing the following now: - Find and open the Terminalprogram in the Utilitiesfolder under the Applicationsfolder - Paste the following into the Terminal window and hit enter/return: - Read and accept the various prompts until it’s installed - Close the Terminal application You can now do brew install xyz in the future when a library is needed to support a package. Drop a note in the comments if you’d like this discussed more in a future blog post. [Optional] [If you have an hour+ to kill] Install MacTeX R has an academic history and there are many semi-advanced functions that are tied to something called latex. Installing latex for OS X is not hard, just time (and bandwidth) consuming (it’s about the same size as a new OS X installer). If you delve into package creation or do more detailed output work in R, you’ll want to install MacTex sooner than later. - Go to and download the latest MacTeX.pkgfile. This direct link should always work (until they change up the way their site works) - Double-click the pkg installer and follow the prompts. The defaults should all be good enough for now. Fin If you have any changes/additions/etc drop a note in the comments. I may even stick this on github to make it easier to contribute...
https://www.r-bloggers.com/installing-r-on-os-x/
CC-MAIN-2018-47
refinedweb
869
58.42
In the previous post about the new Java EE MVC Framework we had a detailed look on Controllers. In this and the following posts we will see how to access various types of request data in MVC Controllers. Java EE MVC makes heavy use of JAX-RS and most of the things we will see in this and the next posts are JAX-RS features. So, if you are familiar with JAX-RS you probably will not learn much new in this post. Query parameters This post focuses on query parameters. If you read my Java EE MVC Getting started post you might already know the @QueryParam annotation. The most common use case of @QueryParam is to map a query parameter to a controller method parameter. For example: @Controller @Path("query-params") public class QueryParamsController { @GET public String queryParams(@QueryParam("name") String name) { ... } } If we now send a HTTP GET request to /query-params?name=john the string "john" will be passed as name parameter to the method queryParams(). Type conversion With @QueryParam query parameters can automatically be converted to various types. For example: public enum Role { admin, reporter, accountant } @Controller @Path("query-params") public class QueryParamsController { @GET public String queryParams( @QueryParam("id") long id, @QueryParam("name") String name, @QueryParam("role") Role role) { ... } } We can now send a request like this: /query-params?id=42&name=john&role=admin A query parameter can automatically converted to a type, if the target type matches one of the following rules: - It is a primitive type - The type has a constructor that accepts a single String argument - The type has a static factory method named valueOf() or fromString() with a single String argument - The type is List<T>, Set<T>; or SortedSet<T> where T matches one of the previous rules In the previous example, the query parameter id is automatically converted to long. If the id parameter is missing or a conversion to long is not possible, an exception will be thrown. It is also possible to use Long instead of long. In this case, we get null passed to the controller method if the id parameter is missing. Enums have a valueOf() method by default. So, the query parameter role can automatically be converted to the corresponding enum value. Using @QueryParam on fields and methods @QueryParam is not limited to method parameters. It is also possible to map query parameters to fields or methods, like the following example shows: @Controller @Path("query-params-fields") public class QueryParamsFieldController { @QueryParam("id") private Long id; @QueryParam("role") private Role role; private String name; @QueryParam("name") public void setName(String name) { this.name = name; } @GET public String queryParams() { // use id, role and name } } If we now send a HTTP GET request to /query-params-fields?name=john&id=42&role=reporter the parameters are set to the fields id, role and name (via setName()) before queryParams() is called. Do not forget that a new instance of the class is created for every request, so it is safe to have fields that contain request information. Quick Summary The @QueryParam annotation can be used to obtain query parameters. @QueryParam can be used on fields, methods and method parameters. Query parameters can be automatically converted to various types, as long as the target type is a primitive type, contains a String constructor or contains valueOf() or fromString() factory methods. You can find the source code for all the shown examples on GitHub. In the next post we will see how to work with path parameters.
https://www.mscharhag.com/java-ee-mvc/query-parameters
CC-MAIN-2019-18
refinedweb
587
52.39
User talk:Phrank Psinatra From Uncyclopedia, the content-free encyclopedia edit TAW 2011 Hi Phrank Psinatra. I'm just finishing up organizing this year's contest and I'm asking former participants for feedback on some changes I've made. - I reorganized UN:REQ earlier this month, using Wikipedia's version as a model, since the page has been very slow to upload for users with slower computers (myself included). Do you think its easier to use now? - I've limited the categories from five to three groups (UN:REQ, UN:VITAL and Wanted Pages). This limits the number of judges and, in theory, encourages more participants. - I've added several optional categories. Judges won't be needed since the prize is awarded to editors completing the specific "challenge". Do you think its worth adding these extra categories? If you're not too busy this fall I hope you'll think about entering this year's competition. It's be great seeing some "returning champions" participate (if only as judges). MadMax 02:36, August 20, 2011 (UTC) edit From my edit summary on TAW. The competition is not yet accepting entries. I would suggest not working on you article anymore until the 29th, else it be disqualified. -- 04:36, December 24, 2011 (UTC) OK, I'll back away.. :) Phrank Psinatra 04:54, December 24, 2011 (UTC) edit Just a suggestion but ... Have you considered bringing your articles to Pee Review? They're very good. Per this comment, they'd only need a little more work to get them featured. MadMax 04:56, January 18, 2012 (UTC) - I've offered some of them for pee review, but most often as a reaction to the prospect of them getting huffed for various reasons. Phrank Psinatra 04:19, January 21, 2012 (UTC) edit Television That's a great start. If you'd like, I can move the original deleted article to your userpage (i.e. User:Phrank Psinatra/Television (original)) if you want to use anything from the previous versions. MadMax 23:41, February 5, 2012 (UTC) - Sounds great. Thanks!Phrank Psinatra 00:02, February 6, 2012 (UTC) edit UnNews:MS-Windows barely survives Hello! Your new UnNews needs a few changes to superficially resemble a real news story: - Real news starts with a "lede," which is a summary of something newsworthy that just happened. Your story reads as though it's starting in the middle, with Gates's reaction to something that happened. As I read it, what just happened is that stats on Win8 were just published. - Real news doesn't quote anonymous sources, such as "one market analyst" or "a Corporate Vice President." You can get names from your source. (You do have a source story, don't you? You need to include it in the UnNews so that any ignorant readers can look it up to see what really happened and why your version is funny.) Or you can invent your own names, and you get bonus points if they are funny in their own right. - A photo - Format the dateline correctly; see most other UnNewses for how to do it. Happy editing! Spıke Ѧ 13:59 3-Feb-13 You have addressed the above completely, thanks! I've tweaked a few things, as shown in the Change Summaries. I see you had QVFD'd it but then removed it. But when you removed it, you removed something else too; did you intend to?17:24 PS--Evidently you didn't. The Chief Justice has put that other thing back, and reminded you that you don't take anything out of QVFD. If you change your mind, just strike it through, like this. Spıke Ѧ 19:19 3-Feb-13 - I had no intention of putting the article in QVFD. I clicked on the link by accident, meaning to click on something else. Phrank Psinatra (talk) 14:33, February 5, 2013 (UTC) Indeed. My only point is that you should correct your error with strike-through. Spıke Ѧ 14:37 5-Feb-13 - I see one of the things you changed. I am not American, so pardon my ignorance about the FTC vs Congress. But I thought Congress had the money to bail out big companies, since as I understand it, they pretty much determine the federal budget (which explains the debt ceiling/fiscal cliff battle). The FTC I would have imagined, make requests to other agencies, as well as elected bodies such as congress to bail out companies, but I didn't think the FTC had money of their own to bail people out. Phrank Psinatra (talk) 14:51, February 5, 2013 (UTC) Well, Congress is our legislature and the FTC is an agency. While, informally, recommendations flow in both directions (Congress may direct the FTC to study something and report back to it), it sounded unrealistic to say an agency would direct Congress to do something. I did not mean this change to affect the story you were telling but just to add credibility on a superficial level. Spıke Ѧ 15:01 5-Feb-13 edit A funnier story Your UnNews notes that the market dominance of Windows has dropped slightly. A bigger story that begs for an UnNews is that the percentage of people using a PC at all to do their computing has dropped like a rock. [1] Meanwhile, Ballmer bets the house on Windows, most recently hoping to make it look both like a PC and a cell-phone. Compare Ken Olsen, who once flew another huge computer company into the side of a mountain (in this case claiming that the PC was just a toy). Spıke Ѧ 18:30 3-Feb-13 - That is not the effect I intended. What I wanted to parody was the excessively fawning media coverage of MS over the decades, and that it would be almost believable that market share below 90% would prompt a congressional bailout, even though they are making oodles of profit, just not as many oodles. Phrank Psinatra (talk) 14:33, February 5, 2013 (UTC) I get that; am just saying there might be another article for you or someone to write. Cheers. Spıke Ѧ 14:37 5-Feb-13 edit QVFD Thanks for the header for the new day. But why are you listing this here page on QVFD? We don't delete discussions. You may move the contents of this page to an archive, though this is tiny compared to the talk pages of the users who are too lazy to. And why did you just strike through all of the day's entries on QVFD? I changed the strike-through to just be of your request, because we don't delete discussions. Spıke Ѧ 21:00 17-Feb-13 - Hi, Spike. I remembered the last time I QVFD'd something by mistake, I deleted it, and you said I should use a strike-through if I did that in error. It happened again. I think the QVFD link is a little too quick. I keep meaning to click on a link above it. Phrank Psinatra (talk) 21:04, February 17, 2013 (UTC) Then what you did is correct (except for putting the terminating </s in the wrong place so it struck through everything for the day!). As the last thing I did was delete a work of yours, I was startled and assumed the worst. A link a little too quick? With my T-Mobile Data Suppository, I only wish! Spıke Ѧ 21:12 17-Feb-13 Ah, you must mean the JavaScript widget that sends a page to QVFD! It is not too quick, it is instantaneous, and the only remedy is to not click on it (or turn it off and make submissions manually, which is probably just as good except when you are on active Patrol). Cheers! Spıke Ѧ 21:15 17-Feb-13 - Thanks. It has been turned off. Phrank Psinatra (talk) 21:21, February 17, 2013 (UTC) edit DSM-5 This article taking shape in your userspace is a fun concept. To look like an Uncyclopedia article, however, each heading should be demoted one level (add an = at the start and the end). We virtually never use =Level ones=. Also, you are allowed to have a calling card on your user page of other places you can be found; but not have your signature (on this article's talk page) point off-site. Thanks. Spıke Ѧ 16:57 19-Jun-13 Further to my suggestion on VFH that you rename this article DSM and re-file the nomination, you need to ensure that [[File:...]] occur at the very start of a paragraph, and end with a hard return. Otherwise, MediaWiki renders them incorrectly. Spıke Ѧ 13:37 21-Jun-13 edit Learn2Preview Have I yet given you my nag about using the Preview button next to Save to see how your edits will look, then continuing to edit and not saving your work to the encyclopedia until you get to a good stopping point? I have just turned on your Autopatrolled flag, so your edits won't be highlighted in the activity log as possible vandalism (I think you were here even before this feature was installed), but minimizing the number of official edits to the encyclopedia will simplify the task of reviewing the log. Cheers! Spıke Ѧ 13:57 21-Jun-13 - The only change I made to DSM, apart from changing the name was adding the carriage returns, both as you requested. The addition of carriage returns affected nothing on my browser. I still saw the same thing. Also, these were such minor edits that I don't think it is necessary to preview something like that. Phrank Psinatra (talk) 14:02, June 21, 2013 (UTC) You are welcome to decide for yourself what the "good stopping points" are; just please get in the habit of having fewer of them. Also, thanks for changing the coding. When someone puts an illustration in the middle of a paragraph, MediaWiki fails to emit <P> and </P> for that paragraph. Most people don't see the difference at all, but I do, as I have custom style for "paragraphs." Spıke Ѧ 14:09 21-Jun-13 edit Double redirects Hi again! In the process of creating DSM-5, you created a bunch of double redirects: pointers that point to pointers. (See Special:DoubleRedirects. Would you please either edit each so it points to a real page, or list on UN:QVFD the ones you don't want? Spıke Ѧ 03:28 26-Jun-13 - What he said, make sure that you check for any double redirects when you move pages. I'd rather not ban you for it, so please make the effort to avoid leaving them. If you're stuck then let an admin know and we can sort it out for you. --ChiefjusticePSX 06:08, June 28, 2013 (UTC) - I am afraid to say that I don't quite understand what you mean by "double redirect", and what I read in the Wikipedia article wasn't helpful, unless you mean pointers to DSM...? I take it you don't mean the links I created in the article body (since they seem to work when I tried them, and the ones that are red aren't supposed to)...? I know I filled out a short form to move DSM-5 to DSM, as Spike requested for me to do. Was I wrong in doing that? I think you'll need to fix this lest I cause more damage :-( Phrank Psinatra (talk) 02:14, June 29, 2013 (UTC) I guess we fixed this. When you fill out that form, it creates a page under the new name, but changes the old name to point to the new name. Usually, we want to abandon the old name completely, which you do by going to UN:QVFD and filing a request of the form: DSM-5 (redirect) (delete) This complicated line ensures that we delete the redirect and not the entire article. Now, I seem to recall that you had a reasonable argument that DSM-5 might be something that a person might search for in the encyclopedia. One way or another, this is no longer an issue. Spıke Ѧ 15:02 22-Dec-13 edit Worst 100 Bands of All Time This is promising work. However, on several recent occasions where we have cleaned up articles in the "Worst" series, we have removed the number 100; for instance, Worst songs to play at a funeral. This approach keeps anonymous editors from adding junk to complete the 100 (and they don't stop there, but go to fractional numbers), and keeps them from wrestling over the rankings. If you rename (move) this, it will create a junk redirect; although it is in your userspace, I will gladly delete it if you request at QVFD, as described above. Spıke Ѧ 15:02 22-Dec-13 - Yes, that would seem helpful, and will make it easier to clean up the article. Phrank Psinatra (talk) 19:12, December 22, 2013 (UTC) edit Television I have nommed your article on VFH. You can vote for yourself btw. -- RomArtus*Imperator ITRA (Orate) ® 10:27, February 11, 2014 (UTC) - Thanks! Wow! Phrank Psinatra (talk) 22:34, February 11, 2014 (UTC) - Saw that. It was fixed :-) Phrank Psinatra (talk) 22:38, February 11, 2014 (UTC) edit Nagging It is time for you to reread Section 9 above on Previewing, which last time you rebutted rather than take to heart. I am not telling you what you should write, only that — especially for the more minor edits — you should Preview it and keep editing rather than make an official change to the encyclopedia. Do the same thing with fewer transactions (you had 26 to one article today!) (a Preview isn't one). Separately, we would welcome you to Votes for deletion to help with the tedious job of reviewing the website's worst articles and voting whether to keep or kill them. Spıke Ѧ 16:22 12-Feb-14 - Most edits are, as you say concerning fixing minor mistakes. While I will try to cooperate I must say that I am one of those people who tends to send what I think is a finished document to my printer at home, only to find another error (usually a minor one) and I have to print again. Yes indeed I go through a lot of wasted paper that way, and it is mildly annoying even to me, but it happens. Like I said, I will try harder to preview. Phrank Psinatra (talk) 20:35, February 12, 2014 (UTC) Another thing I am not saying is to never make errors! But do keep trying to avoid saving after a minor correction only to go further down in the document and find another one; instead make them all with a single Save, cheers. Spıke Ѧ 02:13 13-Feb-14 edit GIFs Do you mean your GIF won't load? or that your animated GIF won't animate? If it is the latter, there is a trick to it. I recall that you can't use an animated GIF with a thumbnail, which may mean you can't have a caption. Copy exactly the coding at Hanuman and see if it works. (However, unless it is really good, ditch the movies and let your own words tell the joke!) Spıke Ѧ 02:11 13-Feb-14 - Hanuman's dancing monkeys image works. My GIF is not animated, so it should display also. It still does not. I notice that Hanuman uses a File: tag. I tried both File: and Image: tags, and no luck. Phrank Psinatra (talk) 05:01, February 13, 2014 (UTC) You can link to it, but you cannot use it as a photo without going to Special:Upload. This website is famously apart from the rest of Wikia and Wikipedia, and I see no evidence that that photo has been brought aboard — in which case, you would have a URL on Uncyclopedia instead of the one above at Uncyclomedia Commons. (As a refresher, save it on your computer and transfer it from there to Uncyclopedia using Special:Upload.) Spıke Ѧ 13:49 13-Feb-14 edit QVFD refresher When posting to QVFD: - Create a new heading for the current day, like it says. - If you can't do that, then newest requests at the top. - Use {{Redirect}} to form a request that ensures that we don't delete the underlying article by mistake - Don't say it is "orphaned" — that means that there were references but they have been edited out. You simply want a deletion of a redirect from userspace to mainspace, which is appropriate. - Less importantly, type one space at the start of the request, because that's what everyone does. Spıke Ѧ 23:15 14-Feb-14 edit Liberals Thanks for the new article! Here is a mini-review. - The only real joke in the Intro is an absurdly long list — a technique that is so over-used that we recommend against it in HTBFANJS. It would be better if you gave the reader a taste of what is to come, as the purpose of the Intro is to suck him in and get him to read further. - Half your readers will themselves be liberals, and the list additionally gives them the impression that, if they keep reading, they are going to be called names. - My own recommendation on how best to write about serious divides such as ideology is in Choice of Words (sections 6 and 7), where I suggest you keep it light enough to amuse all audiences. Writing from an alternate point-of-view is very hard to do; and when, in Section 1, you assert that, "All Liberals are elite, and elites, as we all know, are evil," the reader does not realize you are writing from an alternate point-of-view. This does not come across as humor but as preachy personal opinion. - Richard Nixon was notorious for making an issue of liberals. (When he wasn't doing liberal things like creating the EPA and breaking into psychiatrists' offices.) Vice President Agnew moreover stressed the need for morality in government, until the very moment he was forced to resign over bribe-taking. These are possible other humor directions. Failing that, Nixon was a long time ago and may be lost on a lot of your readers. - The article may need to be turned around, to start with an explanation of how and why liberals came to exist, followed by anecdotes and ending with what to do about them. Spıke Ѧ 11:38 24-Feb-14 - ---- - I'll give a rebuttal a go anyway: - * To your first point, the absurdly long list is a major point of the piece - to show that in the "real world" liberals include a distinctly broad swath of humanity. - * To your next point, I was taking on the persona of a conservative, since I wanted to bring out some of the right-wing rhetoric in the context of having to shame the left-wing for the "crime" of not counting the dead among their numbers. I'll fix the "All Liberals are elite, and elites, as we all know, are evil" quote, it didn't come out the way I wanted. - * I grew up with Watergate, I understand a good deal of it, but I wanted to focus on his "silent majority" quote, since I feel it is the most ridiculous fallacy ever concocted, yet is has cachet with much of the public. I traced the origin of "silent majoirty", and it does go back to Roman writers such as Plautus and Petronius. They used it to mean "the dead", and used it in the sense of "s/he is gone to the majority". I don't wish to parody Nixon or Agnew over historical events, since that has been done a million times over over the past 40 or so years. But I don't think anyone thought the phrase "silent majority" was worthy of parody. I do. - - Anyway, those are my ideas. I'll try to implement what I can. - - Phrank Psinatra (talk) 21:39, February 24, 2014 (UTC) Very well. Now, I didn't claim that your initial list didn't have a point, only that it might not grip the reader. Yes indeed, the claim that most Americans are with me but are simply not disposed to say so, is one of the "last refuges of a scoundrel" (there are so many). I wonder what kind of an epic you and Lucifuge Rofacale could crank out together. Spıke Ѧ 22:31 24-Feb-14 - Epics are good! My only suggestion is that you are missing Trendy Liberal Lefty. -- RomArtus*Imperator ITRA (Orate) ® 23:13, February 24, 2014 (UTC) I like the way you are turning this around. Only, the Intro doesn't need a section head. Just start with it and you'll get a Table of Contents just below it, at the first real section head. Spıke Ѧ 03:50 25-Feb-14 Anon made three edits to this article recently. I marked them Patrolled, though you might want to revisit them. Don't know who uses square parentheses in prose, and "people of above-zero literacy" seems rather more complimentary than the tone you were taking. Spıke Ѧ 01:59 4-Mar-14 - I have selectively edited out anything I thought was not helpful, and added a bit more content. Phrank Psinatra (talk) 03:26, March 4, 2014 (UTC) edit Another QVFD refresher Would you please re-read Section 14 above, and do it right? Someone is going to delete your stuff by mistake instead of deleting the redirect when you list it that way. Spıke Ѧ 11:41 24-Feb-14 - Sorry about that. I will answer later to your remarks on the article (above). Phrank Psinatra (talk) 11:52, February 24, 2014 (UTC) Cheers! On the remarks, I don't need a formal rebuttal! Just take them into account and do the right thing, if you think they are valid. Spıke Ѧ 11:55 24-Feb-14 edit Television Your article is now featured! I have also added your name to the Hall of Shame:59, March 3, 2014 (UTC) - Wow! Blessed! :-) Phrank Psinatra (talk) 03:26, March 4, 2014 (UTC) edit Uncyclopedia:RadicalX's Corner Do you know that your request has been fulfilled by Maniac1075? Anton (talk) 18:36, April 7, 2014 (UTC) - All I can say is: W. O. W. Pretty scary looking! :-) .... ! Phrank Psinatra (talk) 13:19, April 12, 2014 (UTC) edit WotM Congratulations, you won! The WotM award will from now on guarantee you a privileged access to the website euroipods.com. Anton (talk) 12:50, April 10, 2014 (UTC) edit PEBKAC Hi, I think you are going about this one backwards. If you are referring to the diagnosis Problem Exists Between Keyboard And Chair, this will be the classic case of requiring the reader to type the punch line in order to read the joke. And the usual joke is not original but was devised independently of Uncyclopedia, unless you have a plan to take the concept in a new direction. To insert this humor into Uncyclopedia, I think you should do it as a side-trip to some other destination (such as a new section in Dummy, which I've just rewritten to save its life from Votes for deletion) or in one of our articles on computing. Also, when you move an article, the old name continues to exist as a redirect to the new one. We should not have an article in the main encyclopedia redirecting into your userspace, so you should ask at QVFD to have the old name deleted. This won't keep you from moving a product back to the encyclopedia when it's ready. (In this case, I've already deleted the redirect.) Spıke Ѧ 00:05 3-May-14 - Thanks for that, however, PLBCAM does not seem to me to have any potential, since there is no human between a keyboard and monitor to parody. PEBCAK, I feel I can do more with. Phrank Psinatra (talk) 00:39, May 3, 2014 (UTC) I have already included a mention at Dummy. Spıke Ѧ 00:48 3-May-14 - I get it, sorry, I'm a bit slow. So, maybe just edit Dummy with a PEBCAK section. It could be a lengthy section, however, and I was going to write this more from the point of view of the PEBCAK sufferer. Phrank Psinatra (talk) 01:04, May 3, 2014 (UTC) You are a bit slow tonight; as above, "I have already included a mention at Dummy." Write whatever you like, cheers! Spıke Ѧ 01:09 3-May-14 Am not liking that. My concept of Dummy was as an overview of stupidity, but you have added a large section that is an in-depth study of stupidity in one particular field. This does need its own article. Spıke Ѧ 02:26 3-May-14 Now, I understand you are a frustrated help-desk employee. Or, at least the article gives me that impression. But last night's edit got ranty; that item goes on too long and is not just about stupid things users do but how that one user in particular needlessly wasted your time. Keep it light and entertaining, not a vent! Also, keep going at fleshing out all the list items. An article with only list items and no paragraphs will convince anonymous editors they can add crappy items to the end. And it needs links to look more like a Wikipedia article. Cheers! Spıke Ѧ 12:13 6-May-14 - No, I am nothing close to a help desk employee. I like that you think that I am, but I am a bit of a computer nerd. While I don't understand what you find "ranty", it did take a fair bit of research and creative fictionalizing of whatever I could find on various help desk horror stories I had heard about. I distilled most end user melt-downs to their essential elements and changed factual details to get something hopefully funny/amusing. What I would like to do to improve this when I have time, is to categorize the situations under subheadings, then flesh them out. Phrank Psinatra (talk) 04:00, May 7, 2014 (UTC) That sounds good! If not a help-desk employee, maybe that will be your next career, following writing for no pay. And don't forget: "Semicolon — Is that the one with the tail?" Spıke Ѧ 10:22 7-May-14 edit Forum:Thumbnails are broken Thanks for your report; I merged it into the other Forum in the same subject. Wikia has been advised of the problem. Spıke Ѧ 11:03 8-May-14 edit Megan Fox and her letter Hi! As you are the only one who has left a comment at the nomination page for this article, is there you anything you can advise, criticise or suggest for the article, please? Anton (talk) 11:30, May 18, 2014 (UTC) - Not really, except I found it perplexing where a letter would fit into Uncyclopedia or its other projects. Phrank Psinatra (talk) 09:34, June 20, 2014 (UTC) edit UnNews:Pollsters unexpectedly accurate in P.E.I. Thanks for the UnNews! I shortened the headline and did some minor copy-editing to prepare it for the Front Page. No excess capital letters in headlines, please. Spıke Ѧ 11:51 19-Jun-14 edit Rollback Rights Hi Phrank. I have given you rollback rights as an editor. It's a useful tool to remove vandal and idiot edits you may:47, August 1, 2014 (UTC) - For an explanation and strap-on attachments, see UN:HAX#Rollback tools. Spıke Ѧ 12:50 1-Aug-14 - Thanks! Is this only to my articles? Phrank Psinatra (Talk) 09:43, August 16, 2014 (UTC) - No; you may now more easily roll back vandal and idiot edits to any article, hint, hint. Spıke Ѧ 11:35 16-Aug-14 - No, you can do it for all articles. Sorry, I missed your question earlier! --:26, August 25, 2014 (UTC) edit Supply-side Jesus As we discussed on the article's talk page, I've de-protected this page, as the judging is complete, there is no competition in this category, and in any case we can tell which edition you submitted to the contest. Sorry for any inconvenience caused by my delay; no one has even asked me to lock the entries in the other divisions. Go wild! Spıke Ѧ 22:27 15-Jan-15 It's actually ready for mainspace, and moving it should not affect the contest (which you have already won, in my opinion). I'd style it as Supply-side Jesus. Spıke Ѧ 13:36 18-Jan-15 - Thanks Phrank Psinatra (Talk) 13:52, January 18, 2015 (UTC) - Uh, Spike, I think you might have moved the page in such a way so as to delete it. The move log says: "08:58, January 18, 2015 SPIKE (talk | contribs) moved page User:Phrank Psinatra/Supply Side Jesus to User:Supply-side Jesus without leaving a redirect (Mainspace) (revert)" . "User:Supply-side Jesus" is a red link, and Supply-side Jesus also appears to be a red link. That damned "namespace pull-down menu" has tricked me every single time, and it has been over a year since they put it in. Fixed now, as you noticed. Spıke Ѧ 14:08 18-Jan-15 - Hi Phrank! Congratulations on your undisputed victory! Anton (talk) 20:53, January 31, 2015 (UTC) - W00T! W00T! :-) Phrank Psinatra (Talk) 04:49, February 2, 2015 (UTC) edit Feature! Check Supply-side Jesus. Congratulations! --:56, February 23, 2015 (UTC) - Thanks for the kudos (kudo?) :-) Phrank Psinatra (Talk) 03:28, February 24, 2015 (UTC) - I think it is always kudos. A greek word I believe...but I haven't double:20, March 7, 2015 (UTC) edit And another one... Hi Phrank! We are discussing the upcoming Spring Festival, an entirely new contest that, with some luck and a little help from the friends, should be even more fun that the last competitions! Please, join us at Forum:Surprise Me! Spring Festival! Anton (talk) 14:42, April 20, 2015 (UTC) - Does your self-revert in the Forum mean you can't get it done by the end of the weekend? If you decide you can, I am ready to assign you an article. (It would be American Sniper; Romartus got it, but he is going to be a contest judge instead.) Spıke Ѧ 00:54 2-May-15 - Sorry to hear you don't think you can do this up right by tonight's deadline. My prediction is that it will gnaw at you all day and you will brew coffee and work like a madman all evening and submit it two minutes after the deadline, just like a good Term Paper. If not, I can't very well give you another title on the basis that you didn't want to do this one, but you can read at the Village Dump that I hope to do this again in a month. Meanwhile, you are the second contestant who has opted out of it! How is it that that movie is so damned controversial, when no one has seen it? Spıke Ѧ 14:15 3-May-15 - It's not that I didn't *want* to do it. I just had ideas that would appear half-baked if I worked on it by the deadline. I can't use the all-nighter approach, since I have a day job, and stuff like that has priority. As I said, it's a great and challenging topic, and I did my "research" in terms of reading the synopsis fully (on: I think it was Wikipedia). It did strike me to be of sufficient complexity that not reading the synopsis could result in an article that would be more "stupid" than "funny". (But not that complicated all the same) Phrank Psinatra (Talk) 00:38, May 10, 2015 (UTC) I am enthused! You really are going to do it! Spıke Ѧ 03:09 18-May-15 - It's a somewhat difficult piece, but I'll see where it goes. Phrank Psinatra (Talk) 03:21, May 18, 2015 (UTC) edit Fart rape Just heard about this today. Got to write me an article about it! Phrank Psinatra (Talk) 03:21, May 18, 2015 (UTC) - Charming Spıke Ѧ 03:32 18-May-15 - Admin Codeine deleted several of your photos as "orphaned by edit," but he didn't edit your page, which now contains gaping holes. Do you want them back? Are they funny or just gross? Spıke Ѧ 00:24 19-May-15 - I believe they are funny, and not *too* gross. :-) Great if you can do that, then I can just concentrate on the edits you asked about. Phrank Psinatra (Talk) 00:26, May 19, 2015 (UTC) - Sigh! this is just a big fart joke! At any rate, you seem to have gotten your pix back while I was down at the gas station. I added a little context to the start, and moved what seems to be the punch line from the Intro to the end. Spıke Ѧ 00:47 19-May-15 - Well, you shouldn't miss the statement it is making on feminism and postmodernism. The very idea of "fart rape" just lends itself to "that kind" of humour, but by extension it is poking fun at intellectuals who take their theories waaaaaay too seriously. Phrank Psinatra (Talk) 00:55, May 19, 2015 (UTC) - Sorry, I see you had provided context yourself in the History section, though it is not a problem to also do it in the Intro (though I got the date wrong). My "punch line" (that this "scholarship" has a cost, in time and money to pursue serious issues) you had also repeated in the story, and I think you should do it once, at the end. 00:51 So you should reconsider the end of the History section, which discloses that the instigator crowded out funding of serious work, and perhaps make any additional such point you want to make at the end. Spıke Ѧ 01:06 19-May-15 - I see what you were after. Looks better. Phrank Psinatra (Talk) 01:07, May 19, 2015 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:Phrank_Psinatra
CC-MAIN-2016-44
refinedweb
5,773
70.43
My mentor changed my code like this in the code review: using namespace A; // defined in other files namespace B{ // do something } namespace B{ using namespace A; // do something } In header file you should never have a using namespace N; directive in the global scope. It will force lots of identifiers from N on all client code. But it can be okay to have it inside a namespace X. Just keep in mind that client code that does using namespace X; will then also get all identifiers from N. A more conservative approach is to have a bunch of using declarations in namespace X, e.g. using N::foo;. An alternative, when the reason for using namespace N; is that N is a very long name, like Not_short_enough_for_practical_use, is to use a namespace alias – preferably inside the smallest scope where it's needed: namespace N = Not_short_enough_for_practical_use; Your teacher's “correction” of moving a using namespace out of a namespace, before it, is of negative value. You should always strive (within practical limits) to minimize the scope of anything.
https://codedump.io/share/Mx8MCZf1EI8f/1/should-i-put-the-quotusing-namespacequot-inside-or-outside-of-a-namespace-in-c
CC-MAIN-2017-30
refinedweb
178
54.66
TypeScript A headless, code-first CMS built with TypeScript This looks very opinionated with the tech it chooses (Node, Express, MongoDB, React, TypeScript). But if you like those choices, that probably means you’ll like what they’ve cooked up. - Payload gives you everything you need, but then steps back and lets you build what you want in JavaScript or TypeScript - with no unnecessary complexity brought by GUIs. You’ll understand how your CMS works because you will have written it exactly how you want it. - Bring your own Express server and do whatever you need on top of Payload. Payload doesn’t impose anything on you or your app. - Completely control the Admin panel by using your own React components. Swap out fields or even entire views with ease. - Use your data however and wherever you need thanks to auto-generated, yet fully extensible REST, GraphQL, and Local Node APIs. A compiled-away, type-safe, readable RegExp alternative This isn’t the first attempt at making regular expressions more approachable, but it’s the first one I’ve seen that also brings type safety to the table. Example code: import { createRegExp, exactly, oneOrMore, digit } from 'magic-regexp' // Quick-and-dirty semver createRegExp( oneOrMore(digit) .as('major') .and('.') .and(oneOrMore(digit).as('minor')) .and(exactly('.').and(oneOrMore(char).as('patch')).optionally()) ) // /(?<major>(\d)+)\.(?<minor>(\d)+)(\.(?<patch>(.)+))?/ Sophisticated Cornhole Jerod, Nick & Ali partake in a few rounds of Story of the Week, TIL, and I’m Excited about $X. Oh, and is TypeScript the new Java? Nick responds and emotes all over the place! 😆 ESLint and TypeScript! The third year of the third age of JS In 2020, Shawn (swyx) Wang wrote: Every 10 years there is a changing of the guard in JavaScript. I think we have just started a period of accelerated change that could in thge future be regarded as the Third Age of JavaScript. We’re now in year three of this third age and Swyx joins us to look back at what he missed, look around at what’s happening today, and look forward at what might be coming next. Semantic Versioning for TypeScript Types Since TypeScript doesn’t follow SemVer itself, TS libraries which do want to follow SemVer need both high-level guidance about how to do that and detailed analysis of the corner cases to watch out for as well as ways to mitigate breaking changes from TS. This doc is a (beta!) specification of SemVer for managing changes to TypeScript types, including when the TS compiler makes breaking changes in its type-checking and type emit across a “minor” release. The Type Annotations proposal! ECMAScript proposal: Types as Comments This proposal is brand new (stage 0), but I hear that a lot of work has been put into it behind the scenes by a lot of people, so it has that going for it… This proposal aims to enable developers to add type annotations to their JavaScript code, allowing those annotations to be checked by a type checker that is external to JavaScript. At runtime, a JavaScript engine ignores them, treating the types as comments. The aim of this proposal is to enable developers to run programs written in TypeScript, Flow, and other static typing supersets of JavaScript without any need for transpilation, if they stick within a certain reasonably large subset of the language. The implications of this change are pretty massive, if it were to ever ship. And you better believe we’re putting together a JS Party episode to discuss it with the people involved. The React.ReactNode type is a black hole Many of us use TypeScript in our React applications to eliminate an entire class of runtime bugs. But surprisingly, one of the most commonly used types: React.ReactNode turns out to be unsafe, failing to detect objects that cannot be rendered by React. This post digs into what is going on and how to fix it in your system. Tricks I wish I knew when I learned TypeScript Tim Raderschad shares some knowledge he acquired the hard way. The tricks are: - Readonly - Any vs Unknown - Typing Objects with Records I knew exactly zero of these (although I’ve only written a few hundred lines of TypeScript thus far. I’m mostly ignoring it so I can retain my arch nemesis status with Nick (the perpetual TypeScript bull) on JS Party. 😉) Building GraphQL backends with Nest. Todo Or Die? TypeScript can do that Turns out Niek and his team were also inspired by other Todo or Die implementations: Lately, there is some talk about Todo or Die plugins in languages. According to your latest newsletter, it is now supported in Rust, Ruby, Python, and Elixir. We’ve now added support for TypeScript as a language server plugin! For now, it has a minimal feature set, because this was created in a day during our company’s Innovation Day, but we have lots of ideas to extend the project. Building on the TanStack Tanner joins Nick to talk about his projects, react-query and react table, and discuss scratching your own itch in a maintainable way with open source. This”. Zero-runtime stylesheets in TypeScript Use TypeScript as your preprocessor. Write type‑safe, locally scoped classes, variables and themes, then generate static CSS files at build time. First-class theming, framework agnostic, and type-safety so you can cow[boy|girl] code those styles and let your tooling catch typos and variable name changes. A. Deno 1.6 lets you compile TypeScript to a single executable A (potentially) landmark feature landed in Deno 1.6: deno compile --unstable make you an executable version of the module. This puts Deno-based TypeScript projects in the same league as Go and Rust by providing a way to distribute software without the pain of dynamically linking multiple files. (This single-binary distribution has made Go a popular choice for projects such as the GitHub CLI and Stripe CLI.) Node has had a similar capability by way of Vercel’s pkg project, but Deno sets itself apart by supporting the feature as part of the runtime itself. Tips for performant TypeScript From Microsoft’s TypeScript wiki on GitHub: There are easy ways to configure TypeScript to ensure faster compilations and editing experiences. The earlier on these practices are adopted, the better. Beyond best-practices, there are some common techniques for investigating slow compilations/editing experiences, some common fixes, and some common ways of helping the TypeScript team investigate the issues as a last resort. Ionic and developer tooling Nick, and Kball are joined by Mike Hartington to talk about Ionic, the state of web components, developer tooling, and more! A new TypeScript Postgres query builder Martijn de Haan: It’s been almost 3 years since I started working on this query builder idea of mine. Today is finally the day Mammoth hits 1.0. Mammoth is a no-batteries-included type-safe Postgres query builder for TypeScript. Hooray! Congrats on shipping, Martijn! Here’s a peak at the API: const rows = await db .select(db.foo.id, db.bar.name) .from(db.foo) .leftJoin(db.bar) .on(db.bar.fooId.eq(db.foo.id)); Bringing it back to TypeScript Ben Ilegbodu joins Divya, Suz, & Amal to talk about introducing TypeScript at Stitch Fix, why TypeScript and React work well together, building component libraries, and more. Horse JS speaks! We kick off with some exciting TypeScript news, follow that with some exciting JavaScript news, then finish off with an exciting interview. Key word: EXCITING Airbnb's tool for helping migrate code to TypeScript ts-migrate is a tool for helping migrate code to TypeScript. It takes a JavaScript, or a partial TypeScript, project in and gives a compiling TypeScript project out. ts-migrate is intended to accelerate the TypeScript migration process. The resulting code will pass the build, but a followup is required to improve type safety. There will be lots of // @ts-expect-error, and anythat will need to be fixed over time. In general, it is a lot nicer than starting from scratch. ts-migrate is designed as a set of plugins so that it can be pretty customizable for different use-cases. Potentially, more plugins can be added for addressing things like improvements of type quality or libraries-related things (like prop-types in React). Autogenerating Kea's TypeScript support Marius Andra added TypeScript support to his React state management library with kea-typegen: I tried a lot of different ways to add TS support to Kea. At the end of the day what was needed was just not possible without an extra type generation step. I’ll document the failed attempts in a blog post one day. The issue boils down to the fact that each block inside a logic (e.g. reducers) gets the logic itself as a parameter ( reducers: logic => (...)). That kind of loopy stuff is just not possible with TS right now. At least not to the level that it has to be for it to work in Kea (think of selectors that depend on each other). Ultimately, all of the pure-TS attempts I tried would have yielded a partial solution. Thus kea-typegen was born. Even if it’s just a step along the way (TS compiler plugins a’la babel someday?) and still missing many features, it’s already really useful. It uses the TypeScript compiler API to analyse your source files and print out complete types (interfaces) for them. Marius also recorded a video of the process in action.
https://changelog.com/topic/typescript
CC-MAIN-2022-40
refinedweb
1,597
61.36
Charming Python Using state machines Algorithms and programming approaches in Python What is Python? Python is a free, high-level, interpreted language developed by Guido van Rossum. It combines a clear syntax with powerful (but optional) object-oriented semantics. Python is widely available and highly portable. What is a state machine? An overly accurate description of a state machine is that it is a directed graph, consisting of a set of nodes and a corresponding set of transition functions. The machine "runs" by responding to a series of events. Each event is in the domain of the transition function belonging to the "current" node, where the function's range is a subset of the nodes. The function returns the "next" (perhaps the same) node. At least one of these nodes must be an end-state. When an end-state is reached, the machine stops. But an abstract mathematical description (like the one I just gave) does not really illustrate what use a state machine might serve in practical programming problems. A different tack is to define a state machine as any imperative programming language in which the nodes are also the source lines. This definition, though accurate, is equally as pedantic and useless as the first, from a practical point of view. (This condition is not necessarily true for a declarative, functional, or constraint-based languages such as Haskell, Scheme, or Prolog.) Let's try using an example more appropriate to the actual task at hand. Every regular expression is logically equivalent to a state machine, and the parser of every regular expression implements a state machine. In fact, most programmers often write state machines without really thinking about it. Following this example, let's look at a practical heuristic definition of a state machine. We often have certain distinct ways of responding to a finite set of events. In some cases, the response depends only on the event itself. But in other cases, the appropriate action depends on prior events. The state machines discussed in this article are high-level machines intended to demonstrate a programming solution to a class of problems. If it makes sense to talk about your programming problem in terms of categories of behavior in response to events, your solution is likely to be an explicit state machine. A text-processing state machine One of the programming problems most likely to call for an explicit state machine involves processing text files. Processing a text file often consists of sequentially reading a unit of information (typically either a character or a line) and doing something in response to the unit you've just read. In some cases, this processing is "stateless" (that is, each such unit contains enough information to determine exactly what to do). In other cases, even though the text file is not completely stateless, the data has a limited context (for example, the action might not depend on much more than the line number). However, in other common text-processing problems, the input files are highly "stateful." The meaning of each piece of data depends on what preceded it (and maybe even on what follows). Reports, mainframe data-feeds, human-readable texts, programming source files, and other sorts of text files are stateful. A simple example is a line that might occur in a Python source file: myObject = SomeClass(this, that, other) That line means something different if it happens to be surrounded by these lines: """How to use SomeClass: myObject = SomeClass(this, that, other) """ We need to know that we are in a "blockquote" state to determine that the line is part of a comment rather than a Python action. When not to use a state machine When you begin the task of writing a processor for any stateful text file, ask yourself what types of input items you expect to find in the file. Each type of input item is a candidate for a state. These types should be several in number. If the number is huge or indefinite, a state machine is probably not the right approach. (In such cases, some sort of database solution might be more appropriate.) Also consider whether you even need a state machine. In many cases it's better to start with a simpler approach. It might turn out that even though your text file is stateful, there is an easy way to read it in chunks (where each chunk is a single type of input value). A state machine is really only worth implementing if the transitions between types of text require some calculation based on the content within a single state-block. The following simple example is a case when you need a state machine. Think of two rules for dividing a list of numbers into blocks. Under the first rule, a zero in the list indicates a break between blocks. Under the second rule, a break between blocks occurs when the sum of the elements in a block exceeds 100. Since it takes an accumulator variable to determine when the threshold has been reached, you can't see the sub-list boundaries "at a glance." Hence, the second rule may be a much better candidate for something resembling a state machine. An example of a somewhat stateful text file that is nonetheless probably not best handled with a state machine is a Windows-style .ini file. This file consists of section headers, comments, and a number of value assignments. For example: ; set the colorscheme and userlevel [colorscheme] background=red foreground=blue title=green [userlevel] login=2 title=1 Our example has no real-life meaning, but it indicates some interesting features of the .ini format. - In one sense, the type of each line is determined by its first character (either semicolon, left brace, or alphabetic). - In another sense, the format is "stateful" insofar as the keyword "title" presumably means something independent when it occurs in each section. You could program a text processor that had a COLORSCHEME state and a USERLEVEL state, and still processed the value assignments of each state. But that does not seem like the right way to handle this problem. For example, you could simply create the natural chunks in this text file with some Python code like: Chunking Python code to process .INI file import string txt = open('hypothetical.ini').read() sects = string.split(txt, '[') for sect in sects: # do something with sect, like get its name # (the stuff up to ']') and read its assignments Or, if you wished, you could use a single current_section variable to keep place: Counting Python code to process .INI file for line in open('hypothetical.ini').readlines(): if line[0] == '[': current_section = line(1:-2) elif line[0] == ';' : pass # ignore comments else: apply_value(current_section, line) When to use a state machine Now that we've decided not to use a state machine if the text file is "too simple," let's look at a case where a state machine is worthwhile. "Smart ASCII" is a text format that uses a few spacing conventions to distinguish types of text blocks such as headers, regular text, quotations, and code samples. While it is easy for a human reader or writer to visually parse the transitions between these text block types, there is no simple way for a computer to split a Smart ASCII file into its constituent text blocks. Unlike the .ini file example, text block types can occur in any order. There is no single delimiter that separates blocks in all cases (a blank line usually separates blocks, but a blank line within a code sample does not necessarily end the code sample, and blocks need not be separated by blank lines). Since you do need to reformat each text block type differently to produce the correct HTML output, a state machine seems like a natural solution. The general behavior of the Txt2Html reader is as follows: - Start in an initial state. - Read a line of input. - Depending on the input and the current state, either transition to a new state or process the line as appropriate for the current state. This example is about the simplest case you would encounter, but it illustrates the following pattern that we have described: A simple state machine input loop in Python global state, blocks, bl_num, newblock #-- Initialize the globals state = "HEADER" blocks = [""] bl_num = 0 newblock = 1 for line in fhin.readlines(): if state == "HEADER": # blank line means new block of header if blankln.match(line): newblock = 1 elif textln.match(line): startText(line) elif codeln.match(line): startCode(line) else: if newblock: startHead(line) else: blocks[bl_num] = blocks[bl_num] + line elif state == "TEXT": # blank line means new block of text if blankln.match(line): newblock = 1 elif headln.match(line): startHead(line) elif codeln.match(line): startCode(line) else: if newblock: startText(line) else: blocks[bl_num] = blocks[bl_num] + line elif state == "CODE": # blank line does not change state if blankln.match(line): blocks[bl_num] = blocks[bl_num] + line elif headln.match(line): startHead(line) elif textln.match(line): startText(line) else: blocks[bl_num] = blocks[bl_num] + line else: raise ValueError, "unexpected input block state: "+state The source file from which this code is taken can be downloaded with Txt2Html (see Related topics). Notice that the variable state is declared global, and its value is changed in functions like startText(). The transition conditions, such as textln.match(), are regular expression patterns, but they could just as well be custom functions. The formatting itself is actually done later in the program. The state machine just parses the text file into labeled blocks in the blocks list. An abstract state machine class It is easy to use Python to implement an abstract state machine in form as well as function. This makes the state machine model of the program stand out more clearly than the simple conditional block in the previous example (in which the conditionals don't look all that different from any other conditionals, at first glance). Furthermore, the following class and its associated handlers do a good job of isolating in-state behavior. This improves both encapsulation and readability in many cases. File: statemachine.py from string import upper classStateMachine: def __init__(self): self.handlers = {} self.startState = None self.endStates = [] def add_state(self, name, handler, end_state=0): name = upper(name) self.handlers[name] = handler if end_state: self.endStates.append(name) def set_start(self, name): self.startState = upper(name) def run(self, cargo): try: handler = self.handlers[self.startState] except: raise "InitializationError", "must call .set_start() before .run()" if not self.endStates: raise "InitializationError", "at least one state must be an end_state" while 1: (newState, cargo) = handler(cargo) if upper(newState) in self.endStates: break: else handler = self.handlers[upper(newState)] The StateMachine class is really all you need for an abstract state machine. Because passing function objects in Python is so easy, this class uses far fewer lines than any similar class in another language would require. To actually use the StateMachine class, you need to create some handlers for each state you want to use. A handler must follow a pattern. It loops and processes events until it's time to transition to another state, at which time the handler should pass back a tuple consisting of the new state's name and any cargo the new state-handler will need. The use of cargo as a variable in the StateMachine class encapsulates the data needed by the state handler (which doesn't necessarily call its argument cargo). A state handler uses cargo to pass whatever is needed to the next handler so that the new handler can take over where the last handler left off. cargo typically includes a filehandle, which allows the next handler to read more data after the point where the last handler stopped. cargo might also be a database connection, a complex class instance, or a list with several items in it. Now let's look at a test sample. In this case (outlined in following code example) the cargo is just a number that keeps getting fed back into an iterative function. The next value of val is always simply math_func(val), as long as val stays within a certain range. Once the function returns a value outside that range, either the value is passed to a different handler or the state machine exits after calling a do-nothing end-state handler. One thing the example illustrates is that an event is not necessarily an input event. It can also be a computational event (atypically). The state-handlers differ from one another only in using a different marker when outputting the events they handle. This function is relatively trivial, and does not require using a state machine. But it illustrates the concept well. The code is probably easier to understand than its explanation! File: statemachine_test.py from statemachine import StateMachine def ones_counter(val): print "ONES State: ", while 1: if val <= 0 or val >= 30:>" return (newState, val) def tens_counter(val): print "TENS State: ", while 1: if val <= 0 or val >= 30:>" return (newState, val) def twenties_counter(val): print "TWENTIES State:", while 1: if val <= 0 or val >= 30:>" return (newState, val) def math_func(n): from math import sin return abs(sin(n))*31 if __name__== "__main__": m = StateMachine() m.add_state("ONES", ones_counter) m.add_state("TENS", tens_counter) m.add_state("TWENTIES", twenties_counter) m.add_state("OUT_OF_RANGE", None, end_state=1) m.set_start("ONES") m.run(1) Downloadable resources Related topics - Read the previous installments of Charming Python. - Download Txt2Html - Download files used and mentioned in this article - The concept of a state machine is, at a deeper level, closely related to the concepts of coroutines. If you want to make your brain hurt, you can read about Christian Tismer's Stackless Python, which efficiently implements coroutines, generators, continuations, and micro-threads. This is not for the faint of heart. - Visit the home page of Pyxie, an open source XML processing library for Python - Tour the Python Package Index, a Python code/tool repository
https://www.ibm.com/developerworks/library/l-python-state/
CC-MAIN-2019-35
refinedweb
2,328
62.48
Scripts not updating on import? I discovered this in a more complex set of code, but I've boiled the issue down to two very simple scripts: from helper import helpfunc print helpfunc(6) and def helpfunc(val): return 2*val All goes fine the first time I run mainprog.py and the output is 12, but if I change the "2" to a "3" in the helper.py script, then when I run the mainprog.py script, the output is still 12. The only way I can get mainprog.py to pick up the changes in helper.py is to force quit pythonista. Am I missing something? Try reload( helpfunc )at the end of mainprog.py, it should do the math. Got a TypeError when I tried that. reload wanted a module. Try adding import helper; reload(helper)before the from-import. Right, reloadworks with module objects— successfully imported before — only … Yup. That worked. Thanks! I'm not a python expert, but is this something unique to pythonista? I've not encountered this before in other IDEs. It's kind of unique to Pythonista – IDEs on other platforms usually run scripts in a separate process, this is technically impossible to do on iOS (at least in an App Store app), so Pythonista runs a single interpreter and imports are cached (which is just how Python works, it's the same on any platform when you use the command-line Python).
https://forum.omz-software.com/topic/441/scripts-not-updating-on-import
CC-MAIN-2018-05
refinedweb
241
75.81
So I am trying to write this function, read_deck, which is: **void read_deck(char *filename, queue *deck)** This function takes a character string of a file name. It opens the file filename for reading. It then reads cards one at a time into the queue deck so that the order tin which they appear in the file is identical to the order they appear in the queue. Cards are read until the end of a file is reached at which point the file is closed and the function returns. **int main(int argc, char **argv)** Main will set up the queue deck and use read_deck to fill it up with cards from the file designated by the first command line argument. It will then print the deck size and all cards in it (functions length and print_list) will be useful for this. My program currently : not done and not sure how to approach it further for my current read_deck, it only prints every other card for some reason..for my current read_deck, it only prints every other card for some reason..Code:#include "libcardlist.h" #include <stdio.h> void read_deck(char *filename, queue *deck); int main(int argc, char **argv){ char *filename = argv[1]; FILE *f = fopen(filename, "r"); // open file char buf[1024]; stack *deck = new_stack(); // new deck int status; card cards; //how to set up the queue read_deck( , ) // what would be the fields here? } void read_deck(char *filename, queue *deck){ for (status = fscanf(f,"%s", buf); status != EOF; status = fscanf(f,"%s", buf)) { fscanf (f,"%d%c", &cards.face,&cards.suit); printf (" %d%c\n",cards.face,cards.suit); } } This is the desired output: gcc p2.c libcardlist.c lila [program1]% cat smalldeck.cards 14S 2D 13C 10H 5H 11C 13S 4D 13D lila [program1]% a.out smalldeck.cards Deck 9: 14S 2D 13C 10H 5H 11C 13S 4D 13D mine output right now: 2D 10H 11C 4D 4D the libcardlist.c (correct) Code:/* This file contains functions to operate on a lists, stacks, and queues of cards */ #include <stdio.h> #include <stdlib.h> /* Report an error and exit the program with a failure */ void cardlist_error(char *msg){ fprintf(stderr,"libcardlist: %s\n",msg); exit(EXIT_FAILURE); } /* Basic type for a card */ typedef struct { int face; /* 2-14 */ char suit; /* C H S D */ } card; /* Convert a string like 14D into a card */ card str2card(char *buf){ card c; sscanf(buf,"%d%c",&c.face,&c.suit); return c; } /* Given a card c, put a string like 14D in buf representing it. Good for printing */ char *card2str(card c, char *buf){ sprintf(buf, "%d%c", c.face, c.suit); return buf; } /* Lists are of cards */ typedef card node_data; /* List Functions */ /* Basic type for a list: data and next */ typedef struct node { node_data data; struct node *next; } node; /* Returns how many nodes are in a list */ int length(node *l){ int n = 0; while(l != NULL){ n++; l = l->next; } return n; } /* Reverses a list, creates a fresh and distinct copy of the list */ node *reverse(node *l){ node *r = NULL; while(l != NULL){ node *new = malloc(sizeof(node)); new->data = l->data; new->next = r; r = new; l = l->next; } return r; } /* Print a list of cards to a file pointer */ void print_list(node *l, FILE *f){ char buf[1024]; /* Use this for string conversion */ while(l != NULL){ /* Til end of list */ fprintf(f,"%s ", card2str(l->data,buf)); /* Convert to string and print */ l = l->next; /* Advance to next */ } fprintf(f,"\n"); } /* Stack functions */ /* Basic type for a stack */ typedef struct stack { node *top; } stack; /* Make a new stack: allocate memory and set its top pointer to initially be NULL for an empty stack */ stack *new_stack(){ stack *s = malloc(sizeof(stack)); s->top = NULL; return s; } /* Return 1 if the stack is empty and 0 otherwise */ int stack_empty(stack *s){ return s->top == NULL; } /* Push something on the top of the stack */ void stack_push(stack *s, node_data p){ node *new = malloc(sizeof(node)); /* New node for the new data */ new->data = p; /* New node gets the new data */ new->next = s->top; /* new will be on top, point it at current top */ s->top = new; /* new is on top now */ } /* Remove the top element of the stack */ void stack_pop(stack *s){ if(!stack_empty(s)){ /* If the stack is not empty */ node *remove = s->top; /* Track what's being removed */ s->top = s->top->next; /* Advance the top down one */ free(remove); /* Get rid of the old top node */ } } /* Retrive data from the top of the stack */ node_data stack_top(stack *s){ if(!stack_empty(s)){ /* If the stack is not empty */ return (s->top->data); /* Return the data */ } else{ /* Otherwise there is an error */ cardlist_error("stack_top called on empty stack"); } } /* Queue functions */ /* Basic type for the queue data structure */ typedef struct queue { node *front; /* Front of the line */ node *rear; /* Back of the line */ } queue; /* Make a new queue which is initially empty */ queue *new_queue(){ queue *q = malloc(sizeof(queue)); q->front = NULL; q->rear = NULL; return q; } /* Returns 1 if the queue is empty and 0 otherwise */ int queue_empty(queue *q){ return q->front == NULL; } /* Add something to the front of the queue */ void queue_add(queue *q, node_data p){ node *new = malloc(sizeof(node)); /* Adding a new node */ new->data = p; /* Set new node's data */ new->next = NULL; /* It will be the end of the line */ if(queue_empty(q)){ /* First node to be added */ q->front = new; /* Front and back are new node */ q->rear = new; } else { /* Not first node */ q->rear->next = new; /* Current rear is second to last */ q->rear = new; /* new guy is last */ } } /* Remove first element of the queue */ void queue_remove(queue *q){ if(!queue_empty(q)){ /* If the queue is not empty */ node *remove = q->front; /* Track who is being removed */ q->front = q->front->next; /* Second in line is now at front */ free(remove); /* Remove the old front */ } } /* Get the data for the front of the queue */ node_data queue_front(queue *q){ if(!queue_empty(q)){ /* If queue is not empty */ return (q->front->data); /* Get data for front node */ } else{ /* Otherwise this is an error */ cardlist_error("queue_front called on empty queue"); } }
http://cboard.cprogramming.com/c-programming/152072-reading-files-manipulate-queues.html
CC-MAIN-2016-30
refinedweb
1,027
58.35
I may have phrased the title wrong but it is what I mean. I am not looking for multiple windows at once, I am writing a script that opens a tkinter window asking for information etc etc etc and it all saves into a database after the last window. Right now I have it setup like from Tkinter import * class gui: def __init__(self): #make self variables here def wind1(self): self.root = Tk() etc etc etc self.button = Button(self.root, text="Submit", command=self.wind2) etc etc pack and create window def wind2(self): self.infostored = self.etcetc #from wind1 self.root.destroy() create new tk window etc etc self.button = Button(self.root, text="Submit", command=self.wind3) pack and make def wind3(self): self.storemore = pass more from tk window self.root.destroy() new window again self.button = Button(self.root, text="Submit", command=self.store) pack and make def store(self): store last self variable self.root.destroy() do stuff here window = gui() window = window.wind1() What would be the most efficient way to pass variables to a new window or in my case, create a new window but closing the current but keeping the current self.root? I tried google but to no avail I suck at googling some things like this.
https://www.daniweb.com/programming/software-development/threads/343110/tkinter-multi-window-method
CC-MAIN-2017-39
refinedweb
218
68.97
When I do something like ofstream newfile("file.txt"); in order to create a new file, how can I use a user-input variable as the filename and add .txt to it in order to make a custom-named file? This is a discussion on Variable filename within the C++ Programming forums, part of the General Programming Boards category; When I do something like ofstream newfile("file.txt"); in order to create a new file, how can I use a user-input ... When I do something like ofstream newfile("file.txt"); in order to create a new file, how can I use a user-input variable as the filename and add .txt to it in order to make a custom-named file? \0 is one way to do itis one way to do itCode:string input; getinput(input); // you implement input += ".txt"; ofstream file(input.c_str()); Last edited by Stoned_Coder; 06-09-2003 at 12:22 PM. Free the weed!! Class B to class C is not good enough!! And the FAQ is here :- Thanks, I think that will work... but another part of my code is being screwy... when I enter something for the cin, it executes the if fine, but then it skips the next cin ... I know it's because it's reading the '\n' character, but I don't know how to stop it... any suggestions? Here's the code for better understanding: Code:void main() { char name[20]; char choice; cout << "Load file (L) or create New file (N)?"; cin >> choice; if (tolower(choice) == 'l') { //Does stuff... }else{ cout << "Please enter your name(no more than 20 letters): "; cin.getline(name, 20, '\n'); //It skips this line (or rather, it enters '\n') } \0 one way is to place a call to ignore() before every call to getline(). Depending on how persnickity you want to be you can do something simple like this: cin >> choice; cin.ignore(); getline(cin, string1); which will ignore just one char, or somewhat more sure would be something like this: cin >> choice; cin.ignore(1000); getline(cin, string1); which will ignore up to 1000 char or until a newline char is found, whichever comes first. The most robust way is to use the largest size int possible, which is available from the limits.h or climits file and is called something like INT_MAX. It would look something like this: #include <climit> //do dah cin >> choice; cin.ignore(INT_MAX, string1); getline(cin, string1); >>The most robust way is to use the largest size int possible You need the max. possible stream size. Code:cin.ignore(numeric_limits<std::streamsize>::max(), '\n'); Thanks, that worked! I have another question ... is there a way to do a tolower() effect on a string? \0 I believe most string classes have a tolower() function that would be used somehting like this: string s = "Hello"; s.tolower(); cout << s; It might be called Tolower() or tolower() or toLower() or whatever, so look at your documentation. the version of tolower() in sting.h (aka cstring) is for single char only, not full C style strings. For std::string you can do you something like this Code:#include <iostream> #include <string> #include <algorithm> #include <functional> using namespace std; int main() { string str = "Hello World"; transform(str.begin(),str.end(),str.begin(),ptr_fun(::toupper)); cout << str << endl; }
http://cboard.cprogramming.com/cplusplus-programming/40454-variable-filename.html
CC-MAIN-2015-32
refinedweb
556
75
Next: Driving Process Automation with arch Hooks, Previous: Revision Library Basics, Up: Customizing Arch By default, when you get a revision from an archive, arch stores a "pristine copy" of that revision under the {arch} directory. Also by default, when get a revison, arch builds the revision by searching for the import ancestor or the nearest archive-cached ancestor – then applying later patches to construct the revision you want. get and similar operations can be made both faster and more space efficient by using revision libraries. For example, if get finds the revision you asked for in a library, it will copy it directly from there (rather than building it by patching) and skip building a pristine copy under {arch}. That's all well and good – but it can be awkward to have to remember to library-add revisions to your library. This section will show how you can automate the process. A greedy revision library has the property that whenever arch looks to see if the library contains a particular revision, if the library _doesn't_ contain that revision, arch will add it automatically. You can make a particular revision library directory greedy with the command: % tla library-config --greedy DIR When arch automatically adds a revision to a greedy library, normally it does it in the default manner of library-add: it adds previous revisions in the same version as well. If you were adding a revision to a library by-hand you could avoid that behavior with the --sparse option to library-add. To obtain that behavior for automatically added revisions, use: % tla library-config --sparse DIR which means that if a revision is automatically added to the library located at DIR, it is added as if the --sparse option to library-add were being used. Warning: To save yourself some confusion, do not use the following feature unless you understand (a) what a hard-link is and (b) what it means for an editor to "break hard links when writing a file". If you understand those terms, and know that the editor you use does in fact break hard links, then feel free to use this feature. You can very rapidly get a revision from a revision library not by copying it, but instead by making hard-links to it: % tla get --link REVISION The build-config command has a similar option: % tla build-config --link REVISION This can save considerable disk space and greatly speed up the get operation. (There is, of course, a small chance that when you use a hard-linked tree something will go wrong and modify the files in the revision library. Arch will notice that if it happens and give you an error message advising you to delete and reconstruct the problematic revision in the library.) To sum up, a very handy and efficient set up involves: 1) Create one or more revision library directories. 2) Make at least some of those libraries greedy and possibly sparse. 3) Use the --link option to get and build-config. When you work this way, and arch needs to automatically add a revision to a library for you, it will search for a library on the appropriate device (for hard-links purposes). Among those it will search first for a library that already contains the same version as the revision you want and, failing that, for a greedy library.
http://www.gnu.org/software/gnu-arch/tutorial/Advanced-Revision-Library-Use.html
CC-MAIN-2014-42
refinedweb
566
52.02
izing. You can use the XML formatting option in the XML editor to make it easy to view and edit the XML. I like to set an option in VS so that when you format the XML, it lines up the attributes. This is a far easier way to see the XML when there are lots of attributes, or lots of namespaces. To set this option, select Tools, Options on the menu, expand Text Editor, expand XML, click on Formatting, and set the option, "Align attributes each on a separate line". To format an XML document, select Edit, Advanced, Format Document on the menu (or type ^e, d). You can download the Microsoft Visual Studio Tools for the Office System Power Tools here.
http://blogs.msdn.com/b/ericwhite/archive/2008/04.aspx?PageIndex=1&PostSortBy=MostViewed
CC-MAIN-2015-35
refinedweb
123
67.59
Auto Clustering/Replicating Percona Database This is a tech demo of a combination of the factorish toolset to create and run a Percona (mysql) Database image that when combined with etcd will automatically cluster and replicate with itself. How does it work ? There are two images in this project, the first contains Percona and the Galera replication tools, the second contains Maxscale (a MySQL load balancer). When run with access to a service discovery tool ( etcd by default) it is able discover other running databases and set up a replication relationship. By default it uses Glider Labs' registrator to perform the service registry, but can access etcd directly if that is your preference. Inside the container runit manages three processes: confd Used to watch the etcd endpoint and rewrite config files with any changes. healthcheck Watches availability of the application ( percona or maxscale ) and kills runit (thus the container) when it fails. percona / maxscale Runs the main process for the container, either Percona or Maxscale depending on which image is running. See factorish for a detailed description of the factorish toolset. Tech Demo In order to demonstrate the clustering capabilties there is an included Vagrantfile which when used will spin up a 3 node coreos cluster running a local Docker Registry and Registrator images. If you want to run this outside of the tech demo see the contrib/ directory and/or start the tech demo first and view the /etc/profiles.d/functions.sh file in any of the coreos nodes. The registry is hosted in a path mapped in from the host computer and therefore is shared amongst the coreos nodes. This means that any images pushed to it from one host are immediately avaliable to all the other hosts. This allows for some intelligent image pulling/building to ensure that only a single node has to do the heavy lifting. See the user-data.erb file for the scripts that allow this sharing of work. Both the database and maxscale images are built from scratch automatically and started as the coreos nodes come online. Thanks to the registry they will survive a vagrant destroy which means subsequent vagrant up will be substantially faster. Running in CoreOS with etcd/registrator discovery In order to use the tech demo simply run the following: $ git clone $ cd docker-percona_galera $ vagrant up Once Vagrant has brought up your three nodes you want to log in and watch the progress of the build using one of the provided helper functions: $ vagrant ssh core-01 $ journal_database This make take a few minutes if its the first time you've run this and the images aren't cached in the registry. If you get bored you can also check out journal_registry and journal_registrator and watch them get pulled down and run. It is also possible a different host will be elected to do the build, in which case you'll see it show as waiting for that host before it proceeds. Once the database is online ( you'll see percona start and replication collect in the journal_database output ) you can connect to Maxscale via the helper function mysql: $ mysql mysql> select @@hostname; +--------------+ | @@hostname | +--------------+ | a7575fd684eb | +--------------+ the maxscale LB can take a while to find the service to loadbalance, and can also sometimes just fail. I haven't worked out why yet. or by connecting to the shell of the database container on the current host: $ database root@ecfd272af45e:/app# mysql mysql> select @@hostname; +--------------+ | @@hostname | +--------------+ | ecfd272af45e | +--------------+ notice the returned hostname is not the same in both queries, this is because the first was loadbalanced to the database on a different container Helper functions Each container started at boot has the following helper functions created created in /etc/profile.d/functions.sh and autoloaded by the shell. (examples shown below for database container) database- get shell in container. kill_database- kills the container, equivalent to docker rm -f database build_database- rebuilds the image push_database- pushs the image to registry log_database- connect to the docker log stream for that container journal_database- connect to the systemd journal for that container They become very useful when combined: $ build_database && push_database $ kill_database && run_database && log_database There is also the mysql function which will connect you via the local proxy to a percona server and a cleanup function which deletes the /services namespace in etcd Finally in the git repo is a clean_registry script which when run on the host will remove all images from the registry filesystem which is useful if you want to do a full rebuild from scratch. Running without service discovery: Server 1 change HOST to be the IP address of the server. $ export HOST=172.17.8.101 $ docker run --detach \ --name database01 \ -e BOOTSTRAP=1 -e DEBUG=1 \ -e MYSQL_PASS=password -e REP_PASS=replicate \ -e HOST=$HOST -e SERVICE_DISCOVERY=env \ -p $HOST:3306:3306 \ -p $HOST:4444:4444 \ -p $HOST:4567:4567 \ -p $HOST:4568:4568 \ paulczar/percona-galera Servers 2,3,etc change HOST to be the IP address of the server, change CLUSTER_MEMBERS to be the IP of the first server. $ export HOST=172.17.8.102 docker run -ti --rm \ --name database02 \ -e DEBUG=1 \ -e MYSQL_PASS=password -e REP_PASS=replicate \ -e CLUSTER_MEMBERS=172.17.8.101 \ -e HOST=$HOST -e SERVICE_DISCOVERY=env \ -p $HOST:3306:3306 \ -p $HOST:4444:4444 \ -p $HOST:4567:4567 \ -p $HOST:4568:4568 \ paulczar/percona-galera bash Run in Rackspace's Carina Service: Signup for carina and create a 3 node cluster. Download and source the carina config files and get the carina binary as well. note this will leave the mysql and galera ports open to the whole of the service-net network we need to get the servicenet IP address of each node: $ docker info Containers: 7 Images: 6 Engine Version: Role: primary Strategy: spread Filters: health, port, dependency, affinity, constraint Nodes: 3 bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n1: 172.99.65.112: 172.99.65.123: 172.99.65.13: 36 Total Memory: 12.6 GiB Name: a892be77e40c for each node we need to get the servicenet ip: $ docker run --net=host \ --env constraint:node==bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n1 \ racknet/ip service ipv4 10.176.230.11 --env constraint:node==bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n2 \ racknet/ip service ipv4 10.176.230.12 $ docker run --net=host \ --env constraint:node==bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n3 \ racknet/ip service ipv4 10.176.230.13 Start your first MySQL server: $ docker run --detach \ --name database01 \ --env constraint:node==bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n1 \ -e DEBUG=1 -e MYSQL_USER=admin \ -e MYSQL_PASS=notthispassword -e REP_PASS=woopdedoo \ -e HOST=10.176.230.11 -e SERVICE_DISCOVERY=env \ -p 10.176.230.11:3306:3306 \ -p 10.176.230.11:4444:4444 \ -p 10.176.230.11:4567:4567 \ -p 10.176.230.11:4568:4568 \ paulczar/percona-galera Second and third: $ docker run -d \ --name database02 \ --env constraint:node==bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n2 \ -e MYSQL_USER=admin \ -e CLUSTER_MEMBERS=10.176.230.11 \ -e MYSQL_PASS=notthispassword -e REP_PASS=woopdedoo \ -e HOST=10.176.230.12 -e SERVICE_DISCOVERY=env \ -p 10.176.230.12:3306:3306 \ -p 10.176.230.12:4444:4444 \ -p 10.176.230.12:4567:4567 \ -p 10.176.230.12:4568:4568 \ paulczar/percona-galera $ docker run -d \ --name database03 \ --env constraint:node==bf76bea4-47ef-43ac-a7ae-67a6e6db15bf-n3 \ -e MYSQL_USER=admin \ -e CLUSTER_MEMBERS=10.176.230.11 \ -e MYSQL_PASS=notthispassword -e REP_PASS=woopdedoo \ -e HOST=10.176.230.13 -e SERVICE_DISCOVERY=env \ -p 10.176.230.13:3306:3306 \ -p 10.176.230.13:4444:4444 \ -p 10.176.230.13:4567:4567 \ -p 10.176.230.13:4568:4568 \ paulczar/percona-galera wait a minute or so then check status: docker exec -ti database01 mysql -e "SHOW STATUS LIKE 'wsrep_cluster%'" +--------------------------+--------------------------------------+ | Variable_name | Value | +--------------------------+--------------------------------------+ | wsrep_cluster_conf_id | 3 | | wsrep_cluster_size | 3 | | wsrep_cluster_state_uuid | 2882bcb7-ab3b-11e5-ab75-2b510ef0ec6f | | wsrep_cluster_status | Primary | +--------------------------+--------------------------------------+ Author(s) Paul Czarkowski (paul@paulcz.net).
https://hub.docker.com/r/kosztyua/docker-percona_galera/
CC-MAIN-2018-30
refinedweb
1,320
60.45
: Pushing these in. (although I wonder if it would have been useful to turn the ListControl thing into an automated regression test; maybe there is a way to generalise it, like setting a value in a widget and getting it back should return the same thing) -- Eric Kow <> PGP Key ID: 08AC04F9 DarcsURL: C:/home/shelarcy/wxhaskell MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="=_" --=_ Content-Type: text/plain Content-Transfer-Encoding: quoted-printable Thu Feb 28 17:16:14 =93=8C=8B=9E (=95W=8F=80=8E=9E) 2008 shelarcy <shelarc= y@...> * Remove List Control test case (bug 1742979 is already fixed on darcs). Thu Feb 28 17:26:49 =93=8C=8B=9E (=95W=8F=80=8E=9E) 2008 shelarcy <shelarc= y@...> * Fix: bugs/makefile's "make clean" doesn't clean Windows things. --=_ Content-Type: text/x-darcs-patch; name="remove-list-control-test-case-_bug-1742979-is-already-fixed-on-darcs__.dpatch" Content-Transfer-Encoding: quoted-printable Content-Description: A darcs patch for your repository! New patches: [Remove List Control test case (bug 1742979 is already fixed on darcs). shelarcy <shelarcy@...>**20080228081614] { hunk ./bugs/ListControl.hs 1 -import Graphics.UI.WX - -bugtext =3D unlines - [ "Bug: the contents of this listCtrl ('Aa' and 'Bb') should appear" - , "in the following label, but they do not:"] - -main :: IO () -main =3D start gui - -gui - =3D do f <- frame [text :=3D "Test"] - pa <- panel f [] - lc <- listCtrl pa [columns :=3D [("Col1", AlignLeft, 100), ("Col2",= AlignLeft, 100)], - items :=3D [["Aa", "Bb"]] - ] - i <- get lc items - let l =3D unlines $ [ bugtext, "----------8<-----------" ] - ++ map unwords i - ++ [ "----------8<-----------" ] - set f [layout :=3D container pa $ column 5 [ fill $ widget lc , lab= el l ] ] rmfile ./bugs/ListControl.hs hunk ./bugs/makefile 10 - ListControl\ } [Fix: bugs/makefile's "make clean" doesn't clean Windows things. shelarcy <shelarcy@...>**20080228082649] { hunk ./bugs/makefile 24 - rm -rf $(APPS) *.o *.hi *.app + rm -rf $(APPS) *.o *.hi *.app *exe *.manifest } Context: [Remove parasite configure change. Eric Kow <eric.kow@...>**20080227134757 Move around some variables to make more sense. ] = [Add wx-prof target for Windows binary distribution. shelarcy <shelarcy@...>**20080227035051] = [Fix bugs in enable wxcore profiling. shelarcy <shelarcy@...>**20080227034845] = [Specify what OS BoxedCombinator bug fails on. Eric Kow <eric.kow@...>**20080227135140] = [Fix bugs makefile under Linux Eric Kow <eric.kow@...>**20080227134848] = [Add a configure option to enable wxcore profiling. Eric Kow <eric.kow@...>**20080226215155] = [Fix some bugs pointed out by shelarcy on wxcore-prof. Eric Kow <eric.kow@...>**20080226211227] = [Add wxcore-prof target for compiling profiling versions of wxcore. Eric Kow <eric.kow@...>**20080225231635] = [Remove support for GHC prior to 6.4. Eric Kow <eric.kow@...>**20080225223554] = [Maintainer is wxhaskell-devel not wxhaskell-users. Eric Kow <eric.kow@...>**20080225003139] = [Change samples/contrib/Camels.hs encoding to UTF-8. shelarcy <shelarcy@...>**20080225142551] = [Fix: docdist and bindist's wx documents don't link wxcore documents. shelarcy <shelarcy@...>**20080225141105] = [Fix: configure doesn't find GHC's Haddock document directory on GHC 6.8.x = or higher. shelarcy <shelarcy@...>**20080225135754] = [Fix bug pointed out by shelarcy in --enable-mediactrl flag. Eric Kow <eric.kow@...>**20080225110340 It was setting the opengl flag instead. ] = [Add a test case for start >> start (1610984) Eric Kow <eric.kow@...>**20080225001328] = [Implement an --enable-mediactrl configure flag. Eric Kow <eric.kow@...>**20080225000109 with mediactrl disabled by default. ] = [Add a diagram of wxhaskell components. Eric Kow <eric.kow@...>**20080224185557] = [(OS X) Skip intermediate step of compiling master.o (revisited!) Eric Kow <eric.kow@...>**20080218225200 = I'm going to quote some mails from Malcolm Wallace on wxhaskel-users in ea= rly 2008-02. = First message: > I'm attempting to install wxHaskell from the darcs repo at > darcs.haskell.org, under ghc-6.6. on MacOS 10.4.11, with > wxMac-2.6.4. > > The compilation of wxHaskell seems to proceed OK until the link > stage: > > g++ -r -keep_private_externs -nostdlib -o out/wxc/master.o .... > > which failed because there is no -lstdc++-static on my machine. I > found the place in the makefile to replace -lstdc++-static with > the dynamic -lstdc++, and compilation proceeds further, but not > much: > > g++ -dynamiclib -install_name\ > /usr/local/wxhaskell/lib/libwxc-mac2.6.4-0.10.1.dylib -undefined suppres= s\ > -flat_namespace -o out/wxc/libwxc-mac2.6.4-0.10.1.dylib out/wxc/master.o= \ > -lwx_macu_gl-2.6 -L/usr/local/lib -framework QuickTime -framework IOKit\ > -framework Carbon -framework Cocoa -framework System -lwx_macu_media-2.6= \ > -lwx_macu-2.6 > ld: out/wxc/master.o undefined symbol 12387 (__ZTI10wxListBase) can'= t be a weak definition > /usr/bin/libtool: internal link edit command failed > > The offending symbol __ZTI10wxListBase looks like it might be a > z-encoded symbol from Haskell-land, but I'm not sure how to proceed. = Second message: > A correct build on MacOS 10.4.11 with ghc-6.6 requires that > wxWidgets is configured with --enable-shared, and that this patch: > > (OS X) Check architecture to use intermediate step of compiling > master.o or not. > > be darcs unpulled from your local repo. > > With these tweaks, wxHaskell builds, compiles, and runs the demo > programs. = ] = [Eliminate mandatory --with-opengl on Linux. Eric Kow <eric.kow@...>**20080219171912 = If wxWidgets is compiled with opengl, its header files #define wxUSE_GLCANVAS 1 = (See, for example, /usr/lib/wx/include/gtk2-unicode-release-2.6/wx/setup.h= on Ubuntu Gutsy Gibbon), which causes us to compile glcanvas as if we were go= ing to link against the wxWidgets opengl library. But since we are not linkin= g against that, the user gets errors compiling their applications. = Here we introduce an extra preprocessor flag to really insist that no, des= pite what wxWidgets says, we don't want to use GLCANVAS. ] = [Fix: wxPrint**, wxPreviveFrame** and other function causes link error by u= ndefined reference on Windows (Visual Studio). shelarcy <shelarcy@...>**20080219034144] = [Cleanup passing of std/media/stc/opengl to wx-config. Eric Kow <eric.kow@...>**20080218130345] = [Export TabPage type synonym (bug 1349475) Eric Kow <eric.kow@...>**20080218005112] = [Add ListControl test case (bug 1742979) Eric Kow <eric.kow@...>**20080218002441 This might only be a bug on Windows, if at all. ] = [Add test case textColor attribute (bug 1224727). Eric Kow <eric.kow@...>**20080218000738] = [Fix Landscape printing (bug 1168903). Eric Kow <eric.kow@...>**20080217235724 = Filed on behalf on Lennart Augustson <lennart@...>, who submitted a regular Unix patch. ] = [Add BoxedCombinator test case (bug 1549363) Eric Kow <eric.kow@...>**20080217233719] = [Add Sound type's Media class stop method. shelarcy <shelarcy@...>**20080218160511] = [Fix STC* test cases. shelarcy <shelarcy@...>**20080218155734] = [Fix: wrapper.h and sound.cpp doesn't care about wxWindows 2.4.2. shelarcy <shelarcy@...>**20080218155605] = [Sync Visual Studio Project's source flatten away ewxw directories. shelarcy <shelarcy@...>**20080218142201] = [Add the submenu bug. Eric Kow <eric.kow@...>**20080217174326] = [Add NonModalDialog test case (bug #1372529) Eric Kow <eric.kow@...>**20080217174203] = [Add a bugs directory for test cases. Eric Kow <eric.kow@...>**20080217174142] = [Fix UTF8Sampler test case. Eric Kow <eric.kow@...>**20080217130553] = [Fix typo pointed out on bugtracker. Eric Kow <eric.kow@...>**20080217114303] = [dos2unix files that have both CRLF and LF line terminators Eric Kow <eric.kow@...>**20080217095711 = Text editors get confused by these. Get rid of trailing whitespace while we're at it. ] = [Flatten away ewxw directories. Eric Kow <eric.kow@...>**20080217094929 = This is to mirror the wxc project, making it easier to compare our version of wxc with the standalone one. ] = [Remove unused ewxw files. Eric Kow <eric.kow@...>**20080217082029 = There is an overlap between ./wxc/src/ewxw and ./wxc/src. The makefile se= ems to ignore the ones in ewxw. ] = [Synch Visual Studio Project's wxc library version shelarcy <shelarcy@...>**20080216161420] = [Synch Visual Studio Project's output dir same as makefile shelarcy <shelarcy@...>**20080216155656] = [Ugly hack to make setup haddock work without first building. Eric Kow <eric.kow@...>**20080216135157] = [Bump to 0.10.2. Eric Kow <eric.kow@...>**20080216130854] = [Mimick cabal in placement of haddocks. Eric Kow <eric.kow@...>**20080216130819] = [Move cabal stuff to end of makefile. Eric Kow <eric.kow@...>**20080216125445 so that all variables are defined. ] = [Add Hs-Source-Dirs for wxcore.cabal. Eric Kow <eric.kow@...>**20080216125112 In case we ever switch to the Simple build type. ] = [Re-add time package dependency (needed by wxdirect). Eric Kow <eric.kow@...>**20080216124853] = [Improve description and synopsis of cabal files. Eric Kow <eric.kow@...>**20080216124832] = [Split doc building into wxcore and wx version. Eric Kow <eric.kow@...>**20080216124746] = [Modernise haskell98 imports in wxdirect. Eric Kow <eric.kow@...>**20080216120113] = [Prefer /usr/local/wxhaskell/bin/wx-config to the one on the path. Eric Kow <eric.kow@...>**20080216113844 = This makes it easier to install wxhaskell via cabal-install. Just set up a symbolic link to point to point to your wxWidgets, no need for the --wx-config flag. ] = [Add some --bindir, --datadir, --libexecdir to configure script. Eric Kow <eric.kow@...>**20080216113837 For Cabal. The last two are ignored. ] = [Change output dir to 'dist' to mimick cabal. Eric Kow <eric.kow@...>**20080216104847] = [Modernise haskell98 imports in wxcore. Eric Kow <eric.kow@...>**20080216100020] = [Consolidate build targets which exist purely for the sake of Cabal. Eric Kow <eric.kow@...>**20080216095845] = [Fix some dependencies that Ross Paterson pointed out. Eric Kow <eric.kow@...>**20080215181444] = [TAG 0.10.1 Eric Kow <eric.kow@...>**20080215173503] = Patch bundle hash: b21f13e6aa353e56e3c830480285f577ae47b58c --=_-- . I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/wxhaskell/mailman/message/18708597/
CC-MAIN-2016-40
refinedweb
1,567
54.69
Jane Medium : For a given MicroPython The transplanted version has been preliminarily tested . In contrast ,MCU There are many modules in that are not yet supported . These tasks need to be completed as soon as possible in the near future . key word: MM32,MicroPython In order to be able to National Smart car competition for college students Based on MicroPython Development mode , It is suitable for students with non electronic background to participate in the exercise of smart car competition . In fact, in the previous game , be based on NXP Of OpenMV,OpenART All modules adopt MicroPython Development mode , However, these modules can not provide more ports to meet the development of smart car competition model works . The following is based on smart MCU provided by zhufei technology MM32F3277 The development module of , Which has initially inhibited MicroPython Environment . stay Debugging comes from flying by flying MM32F3277 Transplantation has MicroPython Development board This paper introduces the relevant information of the development board , And established through REPL Tool chain for interactive development . ▲ chart 1.1.1 Basic modules sent by flight utilize STM32 Bootloader Software composition MicroPython Of REPL Interactive interface , And can cut the MicroPython Download the program to MM32 Direct . At the same time, you can put REPL The output information is displayed . The following is the hardware operation instructions of the development version sent by zhufei Technology . Connect a normal motherboard , The Board sent has been connected to the screen and inserted SD card ; ▲ chart 1.2.1 Front of development board hardware Please use battery or regulated source to supply power from the power line , The voltage is recommended 8V( exceed 6V that will do ). Or you can use black core board Type-C Power supply , But only use Type-C Do not connect the steering gear during power supply . ▲ chart 1.2.2 Behind the development version SD Card slot The back is SD Card socket , Connected to SD card , Power on the default operation card main.py, The phenomenon is on the black core board LED flashing . ▲ chart 1.2.3 Development board debugging port download interface The serial port connects the serial port of the download and debugging interface of the black core board , The baud rate is 115200, After the power is on, carry out... Through here RPEL Interaction , It should be noted that , If SD The card already has main.py Then priority will be given to main.py: ▲ chart 1.2.4 Serial terminal PuTTY Interface What is running at this time is SD Inside the card main.py file , We have attached SD The card should Python The program does not set exit , So you can't enter RPEL. Need to put SD In the card main.py Delete or delete the file cyclically , Here we choose to delete the file , Reinsert the card and reset : ▲ chart 1.2.5 Get into REPL Debug status Now enter RPEL, And output MicroPython edition . Based on the attached example py file , You can try to run the display effect ▲ chart 1.2.6 function LCD180.help() After the results of the Run the above statement , Corresponding to the electric quantity LCD The screen refreshes to full screen red and displays SEEKFREE word . The principle can be downloaded from the following link : MM32F3277 Motherboard schematic diagram ▲ chart 1.2.7 Core motherboard pin definition ▲ chart 1.2.8 Backplane interface definition ▲ chart 1.2.9 5V Power schematic diagram It's on the circuit board 3 individual 3.3V The power supply is provided with general power supply respectively 3.3V, camera , The power supply of the operational amplifier . ▲ chart 1.2.10 camera 3.3V Power Supply ▲ chart 1.2.11 Steering gear power supply ▲ chart 1.2.12 Definition of some interface pins ▲ chart 1.2.13 Definition of some interface pins ▲ chart 1.2.14 Definition of some interface pins The following is MM32F3277 Has been transplanted in MicroPython function . This paper makes a preliminary test of these functions . ▲ chart 1.3.1 Now it has been transplanted MicroPython Auxiliary function from seekfree import GPIO pinpg1 = GPIO(0x67, 1, 1) print("Test GPIO .") while True: pinpg1.low() pinpg1.high() Use an oscilloscope to measure MM32 Modular G7 Pin waveform . ▲ chart 2.1.1 Use an oscilloscope to measure MM32 Modular G7 Pin waveform ▲ chart 2.1.2 G7 The waveform output by the port Pass the above tests , You can see MicroPython The next cycle for port operation is about :22.28 μ s \mu s μs. Because the above code is ultimately an endless loop , So you have to go through MM32 Reset can only be transferred from the dead circle . In order to be able to control MM32 Reset , Add... To the original debugging port NRST Control line . ▲ chart 2.1.3 Modify debug port , increase RST Control port about STM32 Of MPDLD Added... To the command MM32 Reset process . if(strncmp(szString, "MPDLD", 5) == 0) { // MicroPython Dlownload char szString[0x8000]; strcpy(szString, ""); Clipboard()->GetTextBuf(szString, sizeof(szString) - 1); ClearInfor(); ShowInfor("Reset MicroPython..."); RTSEnable(1, PORT1); Sleep(100); ClearPort(PORT1); RTSEnable(0, PORT1); ShowInfor("Wait for MicroPython comeback..."); double lfStart = GetDosTime(); int nGreatCount = 0; int nGreatFlag = 0; for(;;) { if(GetDosTime() - lfStart > 2) break; char c; if(ReceChar(&c, PORT1) == 0) { if(c == '>') nGreatCount ++; if(c == ' ') { if(nGreatCount >= 3) { nGreatFlag = 1; break; } } } } int nLength = strlen(szString); int i; int nLine = 0; for(i = 0; i < nLength; i ++) { if(szString[i] == '\r') nLine ++; } char szTemp[512]; sprintf(szTemp, "Download MicroPython : %d lines/%d characters.", nLine, nLength); ShowInfor(szTemp); ShowInfor("Begin to download programm..."); Sleep(200); if(nGreatFlag == 0) { MessageBeep(0); SendChar(0x2, PORT1); // Send CTRL+B Sleep(100); } SendChar(0x5, PORT1); // Send CTRL+A Sleep(100); for(i = 0; i < nLength; i ++) { ProgressBar1->Position = (i + 1) * 100 / nLength; SendChar(szString[i], PORT1); } for(;;) { char c; if(ReceCharL(&c, PORT1, 20) > 0) break; } ShowInfor("-------------------------------------------------------------------------"); SendChar(0x4, PORT1); // Send CTRL+B return; } After the modification , For circular programs , You can also easily download the program automatically . from seekfree import GPIO pinpg1 = GPIO(0x67, 1, 1) print("Test GPIO .") while True: pinpg1.toggle() ▲ chart 2.1.4 toggle() The output waveform corresponding to the function From the above waveform , toggle( ) The running time is slightly longer than low(), high() Slow down . Now there is no... In the module time modular , This module can provide delay operation . therefore , The interval can only be realized through software delay . Connect the wireless serial port HEADER Medium C6,C7,GND,+5V extraction , test GPIO Output control LED. from seekfree import GPIO led1 = GPIO(0x26, 1, 1) led2 = GPIO(0x27, 1, 0) print('Test LED.') while True: def delay(loop): for _ in range(loop): pass led1.high() led2.low() delay(20000) led1.low() led2.high() delay(20000) ▲ chart 2.1.5 LED Delay flashing ▲ chart 2.1.6 Keys and switches on the circuit board According to the previous hardware circuit diagram , Four keys are integrated on the circuit board :G0,G1,G2,G3. Their corresponding ports are :GPIOG0, G1,G2,G3. ▲ chart 2.1.7 Four buttons on the development board from seekfree import GPIO) print('Test LED.') def delay(loop=50000): for _ in range(loop): pass while True: print([btn1.value(), btn2.value(), btn3.value(), btn4.value()]) delay(50000) There are also two dial switches on the circuit board , Respectively corresponding D14,D15. adopt GPIO You can read their status . The test method is the same as the above buttons . from seekfree import GPIO print('Test LED.') def delay(loop=50000): for _ in range(loop): pass) sw1 = GPIO(0x3e, 0, 1) sw2 = GPIO(0x3f, 0, 1) while True: print([btn1.value(), btn2.value(), btn3.value(), btn4.value(), sw1.value(), sw2.value()]) delay(50000) ▲ chart 2.1.8 Measuring keys and dialing switches ▲ chart 2.2.1 ADC.help() display information Lead the of the electromagnetic module interface to the bread board , Use a potentiometer to obtain different voltages , Send to A4. ▲ chart 2.2.2 Collect to 1024 individual ADC The number Variance of data : 5. because MicroPython Floating point operations are not supported . Therefore, we need to use the integer number to complete the relevant calculation . from seekfree import ADC,GPIO adc = ADC(0) adc.channel_init(adc.A4) print('Test ADC.') def delay(loop=50000): for _ in range(loop): pass def sqrt(x): left = 0 right = x//2+1 while left < right: middle = left + (right-left+1)//2 square = middle * middle if square > x: right = middle-1 else: left = middle return left SAMPLE_NUM = 1024 adcdim = [0]*SAMPLE_NUM for i in range(SAMPLE_NUM): adcdim[i] = adc.value(adc.A4) print(adcdim) count = 0 for s in adcdim: count += s average = count//SAMPLE_NUM sigma = 0 for s in adcdim: ss = s - average sigma += ss**2 print(sqrt(sigma//SAMPLE_NUM)) On the beta PWM Pass respectively A0,A1,A2,A3 Output . from seekfree import PWM,GPIO pwm = PWM(16000) pwm.channel_init(pwm.A0, 5000) print("Test PWM") ▲ chart 2.3.1 A0 Output PWM wave form ▲ chart 2.3.2 A0 Output PWM wave form from seekfree import PWM,GPIO,ADC pwm = PWM(16000) pwm.channel_init(pwm.A0, 500) adc = ADC(0) adc.channel_init(adc.A4) def delay(loop=50000): for _ in range(loop): pass print('Test PWM...') while True: adcvalue = adc.value(adc.A4) pwmvalue = adcvalue*10000//0x1000 print(adcvalue, pwmvalue) pwm.duty(pwm.A0, pwmvalue) delay(10000) ▲ chart 2.3.3 Shaking PWM Through the collection of ADC After averaging , Under control PWM, The waveform is very stable . from seekfree import PWM,GPIO,ADC pwm = PWM(16000) pwm.channel_init(pwm.A0, 5000) adc = ADC(0) adc.channel_init(adc.A4) def delay(loop=50000): for _ in range(loop): pass print('Test PWM...') while True: sigma = 0 for i in range(256): sigma += adc.value(adc.A4) adcvalue = sigma//256 pwmvalue = adcvalue*10000//0x1000 pwm.duty(pwm.A0, pwmvalue) delay(1000) ▲ chart 2.3.4 adopt ADC change PWM Duty cycle Set the timer's callback function . from seekfree import TIMER,GPIO led1 = GPIO(0x26, 1, 1) led2 = GPIO(0x27, 1, 0) def timer_callback(s): led1.toggle() print(s.count()) tim = TIMER(200) tim.callback(timer_callback) while True: pass Yes On MM32 Of MicroPython The transplanted version has been preliminarily tested . You can also see that the migration of this version still needs some enrichment . The above functions need to be further improved through later supplement . ■ Links to related literature : ● Related chart Links :
https://pythonmana.com/2021/11/20211125111817023L.html
CC-MAIN-2022-21
refinedweb
1,741
57.98
Recently with my developer friends, there's been much talk about various other frameworks versus Java. It seems that in some circles (I won't go into what circles, but a quick Googling will pull up plenty of matches), Java is becoming a tool for the old guard of the Web for a lot of reasons, one of which is lines of code (LOC). While some of the arguments of Java needing twice as much code as another language to get the same thing done may be accurate, I personally feel LOC is only an issue if you're spending significant amounts of time doing things you might not have to do. Like coding all of your beans by hand, for instance. Or you could be doing that, plus adding all of your framework XML definition entries by hand as well! I'll admit, I was. The other day I was playing with Ruby on Rails, and one of the things I liked about it was the ability to easily generate complete code, as well as stub code, from simple scripts. This started me thinking about my current project and how effective I am during my coding day. The "how much work do I get done versus how much time do I spend trying to get work done" thought has been key in my mind more and more over the past few weeks. While frameworks exist to make our jobs seem easier--I use the Spring framework, for instance--it can sometimes seem like it still takes too long to just do one page or module for a web app. So after some thought, I decided to do something about it. I had known about XDoclet for years and even played around with it when it first came out. But I didn't give it much long-term consideration, as I was not big on code generation back then. I wanted to really understand how things worked "under the hood," so I spent a long time coding everything by hand, including config and deployment files. However, today I see two main benefits for code generation: gencontrollersor genmodulesto generate the proper controller code or an entire module containing all of your beans, controllers, services, and DAOs. Based on past experience, I wasn't sure how XDoclet was going to help me. I was looking for a tool that would allow me to spend the least amount of time for the maximum amount of code. Most of the examples I had seen on the XDoclet site and other sites all dealt with the generation of EJBs, which is what XDoclet was originally designed to do. However, I don't have any EJBs in my project, and in fact, Spring is all about using POJOs, so another EJB tool was not what I was looking for. And while XDoclet does have some Spring tags that it recognizes, I was still looking for something a little different. Then I stumbled upon templates. Templates are a way to extend the functionality of XDoclet to better match your code-generation needs. For instance, if you have a particular type of class that doesn't quite fit in with anything the XDoclet offers out of the box (in my case, these were custom controller classes), then it's fairly easy to add your own template files using XML markup only! Ideally, I just wanted to define a class with a minimal set of properties and generate not only my controller code, but additional XML that would be required by Spring. After some tweaking, I was pleased with the results. Below is an annotated pseudo-code test controller class. Long lines are truncated with a \ character. TestController.java 1. package com.mytest.account.controller; 2. 3. /** 4. * @mytest.controller mapping="/acct.ctrl" 5. * @mytest.controller actionmethod="create" 6. * @mytest.controller actionmethod="read" 7. * @mytest.controller actionmethod="update" 8. * @mytest.controller actionmethod="delete" 9. */ 10. public class TestController { 11. 12. /** 13. * @mytest.controller property="privateView" \ propertyValue="priv1" propertyMethod="PrivateView"\ propertyType="String" 14. */ 15. private String privateView = null; 16. 17. /** 18. * @mytest.controller property="publicView" \ propertyValue="priv2" propertyMethod="PublicView" \ propertyType="String" 19. */ 20. public String publicView = null; 21. } The first thing that you might notice are the custom namespace @mytest.controller tags. This is how XDoclet will know what to look for when generating specific sections of our class. The positions of these tags are very important. Some appear above the class keyword and others appear right above property declarations. XDoclet uses tags based on these positions to populate Class or Field objects that we'll use in our template. This is an important distinction, as we'll see later. Looking at the above code we want to do the following: SimpleUrlHandlerMapping, which could be declared in a mytest-servlet.xml file (the Spring equivalent of the Struts struts-config.xml file). actionmethodparameter will allow us to specify a method name used in the controller, which extends the Spring MultiActionController(in Struts, this would be a DispatchAction). In our case, these will be CRUD (Create, Read, Update, Delete) method names. XDoclet will iterate over multiple parameters with the same name, which will allow our template to output n number of methods. propertytag lets us name a typical bean property, like you would normally do in XDoclet, but since we're using a custom template tag here, we're adding a few more attributes. The propertyValueis the value assigned to that property in the mytest-servlet.xml file. For our custom template, we're wiring up the private and public JSP views for this controller, which I usually call privateViewand publicView--one for subscribers, and one for everyone else. The propertyMethodwill give us an easy way to output the method name this property belongs to without trying to jump through hoops to adhere to the bean-method-naming convention. And the propertyTypeattribute specifies what object type we'll be getting and setting for our method. It could be argued that I could have placed all of my property definitions at the class level instead of the field level. This is true; however, that would also entail extra code on the template side to make sure I'm picking up the correct properties value, method, and type attributes when generating a method. I felt it was quicker and easier to use the XDoclet Field class rather than adding more complicated code to my template. Now it's time to get our hands dirty. As I mentioned before, the reason I chose XDoclet to do my code generation was the fact that I could define a custom template (not some custom class or more code) and use XDoclet XML tags to fill in the blanks for me. Below are the relevant portions of the template we want to generate. Long lines are truncated what a \ character. MultiController.xdt 1. package <XDtPackage:packageName/>; 2. import javax.servlet.http.HttpServletRequest; 3. import javax.servlet.http.HttpServletResponse; 4. 5. import org.apache.commons.logging.Log; 6. import org.apache.commons.logging.LogFactory; 7. import org.springframework.validation.BindException; 8. import org.springframework.web.servlet.ModelAndView; 9. 10. import com.mytest.system.spring.BaseController; 11. 12. /** 13. * MultiAction controller class for \ <XDtClass:className/>. 14. * 15. * @author 16. * @since 17. * @version $Id$ 18. */ 19. public class <XDtClass:className/> \ extends BaseController { 20. 21. // CUT AND PASTE THIS INTO THE mytest-servlet.xml \ FILE 22. // 23. // <!-- ==== <XDtClass:className/> \ Bean Definition ==== --> 24. // <bean id="contr<XDtClass:className/>" \ 25. // <property name="methodNameResolver" \ ><ref bean="actionResolver"/></property> 26. <XDtField:forAllFields> 27. <XDtField:ifHasFieldTag 28. // <property name="<XDtField:fieldTagValue \"><value><XDtField:fieldTagValue \</value></property> 29. </XDtField:ifHasFieldTag> 30. </XDtField:forAllFields> 31. // </bean> 32. // 33. // === PUT THIS UNDER THE URL MAPPINGS SECTION === 34. // <prop key="<XDtClass:classTagValue \">contr<XDtClass:className/></prop> 35. // 36. 37. protected final Log log = LogFactory.getLog(getClass()); 38. 39. <XDtField:forAllFields> 40. <XDtField:ifHasFieldTag 41. public <XDtField:fieldTagValue \ \ get<XDtField:fieldTagValue \(){ 42. return <XDtField:fieldTagValue \; 43. } 44. 45. public void set<XDtField:fieldTagValue \\ (<XDtField:fieldTagValue \ value) { 46. <XDtField:fieldTagValue \ = value; 47. } 48. </XDtField:ifHasFieldTag> 49. </XDtField:forAllFields> 50. 51. public ModelAndView init(HttpServletRequest request, \ HttpServletResponse response) 52. throws ServletException, IOException { 53. if(log.isDebugEnabled()) log.debug("entered"); 54. // YOUR INIT CODE GOES HERE 55. if(log.isDebugEnabled()) log.debug("exited"); 56. // REPLACE THIS HERE IN YOUR CODE 57. return null; 58. } 59. 60. <XDtClass:forAllClassTags \ 61. <XDtClass:ifHasClassTag \ 62. public ModelAndView <XDtClass:classTagValue \(\ HttpServletRequest request, HttpServletResponse \ response) 63. throws ServletException, IOException { 64. if(log.isDebugEnabled()) log.debug("entered"); 65. 66. if(log.isDebugEnabled()) log.debug("exited"); 67. // RETURN THE PROPER VIEW HERE 68. return null; 69. } 70. 71. </XDtClass:ifHasClassTag> 72. </XDtClass:forAllClassTags> 73. 74. // Your (other) multiaction methods go here 75. 76. } // <XDtClass:className/> Phew! But when it's all done, I have a controller class that contains the proper XML snippets for the Spring mytest-servlet.xml bean definition and URL mappings, the proper get/set methods for view properties, and my multi-action methods, complete with debug logging statements. 76 lines of code from 21, including the XML (which will be cut out), can save significant typing time and also eliminate bugs. Note also the use of the XDtField and XDtClass tags. It should be pretty clear now why we placed the various tag values where we did. All of our class-level tags either defined class methods or XML config file values, which the field level tags used to generate our basic getters and setters. Like I said before, our use of the field tags here are a little different, as we're also using them to define some of the controller mapping values in our mytest-servlet.xml file for Spring. When our controller stars up, Spring will inject the privateView and publicView methods with their proper view values. The last piece of the puzzle is how to put this all together and get our hands on the generated source file. This is where Ant comes in. We'll be doing three things: On my development machine, I have the following directory structure: trunk | +----+- src +- xdoclet | +- build +- src +- com/mytest/account/controller +- template At first, this may seem a little confusing, with two src directories. However, I feel there is good reason for this, as I have a separate src directory under the xdoclet directory that allows me to keep separate all of the pseudocode and generated code. After I have run the Ant task, it's just a matter of copying the file over to the main src directory (on the same level of the trunk as the xdoclet directory) and adding in the implementation code. For the purpose of this article, I'm keeping these things separate from the source code base, which should prevent any build issues that might creep in if we try to integrate everything at once. Based on the above directory structure, this is where our two files should live: trunk/src/xdoclet/src/com/mytest/account/controller/TestController.java trunk/src/xdoclet/template/MultiController.xdt The .java file will need the package to match the directory structure for XDoclet to be able to pick it up and run the template against it. I found XDoclet only had the log4j debugging levels set to INFO and so, when I did not have the .java file in the correct tree, XDoclet would not display any error messages; nor would it find and generate the file. It wasn't until I went into the .jar and modified the log4j.properties file so that debugging was turned on that I got the proper debug messages saying there were no files to process. Technically, this wasn't an error, but it kept me scratching my head for some time, so be aware of this. The following Ant task will use the above tree and place the generated code in the proper directory. 1. <!-- ========Xdoclet Target ======== --> 2. 3. <target name="xdoclet"> 4. 5. <path id="xdoclet.classpath"> 6. <fileset dir="${xdoc.home}/lib"> 7. <include name="*.jar"/> 8. </fileset> 9. </path> 10. 11. <echo>+------------------------------------+</echo> 12. <echo>|Generating sources from xdoclet tree|</echo> 13. <echo>+------------------------------------+</echo> 14. 15. <taskdef name="doclet" \ 16. <doclet destdir="${jxdoc.dir}/build" 17. 18. <fileset dir="${jxdoc.dir}/src"> 19. <include name="**/*Controller.java" /> 20. </fileset> 21. <template 22. 25. </doclet> 26. 27. </target> A few settings will be required to run this. xdoc.homeshould point to your XDoclet install directory. You can run the task by issuing the following command: ant xdoclet. If all goes well, you should see the usual Ant BUILD SUCCESSFUL message. Then, under the xdoclet/build/com/mytest/account/controller directory, your new file should appear, full of the necessary skeleton properties and methods. This template approach can also be adapted to generate not only controllers, but beans, forms, services, etc. In the xdoclet target, you would just have to add a new taskdef for each object type you want to generate and provide a different template. For example, if we want to generate service objects, we could use the following taskdef: 1. <taskdef name="servicedoclet" \ 2. <servicedoclet destdir="${jxdoc.dir}/build" 3. 4. <fileset dir="${jxdoc.dir}/src"> 5. <include name="**/*Service.java" /> 6. </fileset> 7. <template 8. 11. </doclet> Above, we see that we've changed the name of the taskdef to servicedoclet and also the include fileset property from *.Controller.java to *.Service.java, which will only look for files ending in " Service.java." On line 8, we are telling XDoclet to use the Service.xdt template. So we see that it's fairly trivial to add on special code generators once we have the initial setup going. It is entirely possible (in fact, this is what I do) to generate a few templates and, under the xdoclet task, have it look through the source tree for each object type and generate everything at once. A word about Maven 2.0 and Archetypes: Maven 2.0 will contain a mechanism called Archetypes which allow for template-driven project code generation. While implemented differently--using Velocity for the templates--than what we have done above, it will basically accomplish the same things, but on a larger, project scale. I have tried Maven a few times and I can appreciate its scope. However, I feel it is much more a part of a larger picture and would require more developer effort and time (in the beginning, of course) to integrate than the example above. But it does address one of my initial issues, that I liked the fact that Rails worked with the developer on a project level. Maven, too, will operate on that project level, saving developers time by auto-generating the needed code based on set config parameters. This can only be a positive thing. For existing projects, however, the approach discussed here will probably be faster to implement and have less of a structural impact. To recap, here's what we've accomplished: This only scratches the surface of XDoclet templates. We've seen just one small, yet powerful, example of how templates can help you not just become a more efficient programmer, but also a smarter one. I hope it will save you as much time as it has me. Fieldand Class Jason Lee has been developing web apps for the past ten years and currently is VP of technology at a small startup. Return to ONJava.com.
http://www.onjava.com/lpt/a/5826
CC-MAIN-2015-48
refinedweb
2,568
54.93
temporaries: Definition: a temporary is a C++ object which is niether a constant nor a variable, but is has type. example1: TYPE f(int a) {...} f(2) is a temporary. it is niether a constant nor a variable but it has a type. example2: class A { public: A(char ch) {...} }; (A)'a' is a temporary. properties of temporaries: first essential property of temporaries: a temporary is destroyed as soon as possible: example: #include <conio.h> #include <iostream> using namespace std; class Test { public: int a; Test(int x) { a = x; cout<< "object constructed" << "\n"; } Test(const Test& t) { a = t.a; cout<< "object copied" << "\n"; } ~Test() { a = 0; cout<< "object destroyed" << "\n"; } }; int main() { cout<< ((Test)10).a << "\n"; //1: object constructed, 2: 10, 3: object destroyed cout<< "end"; _getch(); } Output: object constructed 10 object destroyed end (Test)10 is a temporay. it is trying to find an opertunity to be destoyed. we see that it is destroyed before cout<< "end" . second essential property of temporaries: a temporary tries not to call copy constaructor if possible: example: #include <conio.h> #include <iostream> using namespace std; class A { public: int a; A(int x) { cout<< "constructor" "\n"; a = x; } A(const A& a) { cout<< "copy constructor" "\n"; this -> a = a.a; } }; void f(A a) { cout<< a.a << "\n"; } A g() { return A(20); } int main() { f(g()); _getch(); } Output: constructor 20 in this example copy constructor must be call at least 2 times. but it is not called at all because A(20) and g() are temporaries. third essential property of temporaries: in most compilers (inluding Dev C++) a reference to a temporary must be constant, & such reference prevents the temporary to be destroyed until the end of the block execution. example: #include <conio.h> #include <iostream> using namespace std; class A { public: int a; A(int x) { a = x; } ~A() { cout<< "destructor" "\n"; } }; A f() { A a(10); return a; } // 1: destrcutor int main() { { const A& a = f(); cout<< "end" "\n"; // 2: end } // 3: destructor _getch(); } output: destructor end destructor if you write: A& a = f(); instead of const A& a = f(); VC++ has no problem with it but Dev C++ refuses to compile. now "temporary" is not a standard name, I defined it myself. I wanted to know if there's a standard name & if there' more info somewhere on the web? the books about C++ say nothing about temporaries. experts in other forums said that there are conditions under which copy constructor is not called but they didn't say anything about temporaries & its main name if any.. Edited 6 Years Ago by CppBuilder2006: n/a
https://www.daniweb.com/programming/software-development/threads/260660/temporaries
CC-MAIN-2016-50
refinedweb
439
63.19
Codenvy’s Architecture, Part 1 - | - - - - - - - Read later My Reading List 1.0 OVERVIEW Codenvy is a cloud IDE with nearly 100,000 developers who use it to code, build, and test applications. This article explains the architecture of Codenvy's various technologies and sites. (Click on the image to enlarge it) Our architecture is driven by the different offerings we intend to launch: - Codenvy.com - A hosted cloud IDE with support, SLAs, and hardware. - Codenvy Enterprise - Enable organizations to code, build, test and deploy applications, on their own servers. - Codenvy ISV - Drive and measure technology engagement of published SDKs and APIs with promoted Factories, monetizable plug-ins, and IDElets. A Factory is a way to launch a temporary code, build, test, debug workspace with policies. An IDElet is an embeddable code, build, test, debug workflow that can be inserted into another product. - Codenvy Platform - A cloud IDE engine to provide developers a way to develop, test, and run tooling plug-ins and applications. The Codenvy Platform is used as an engine to deliver Codenvy.com, Codenvy Enterprise, and Codenvy ISV. It can also be used to create other IDEs with any branding the implementer desires. This SDK is similar in structure to the Eclipse Platform, but engineered for a cloud environment. It also provides support for developing plug-ins for build, run, test, and debugging workflows, which typically operate outside of the IDE itself. The architecture discussion will be in two parts: 1) The SDK that drives Codenvy Platform, and 2) the components that extend the SDK to create Codenvy.com. 2.0 THE DIFFERENCE BETWEEN A CLOUD IDE AND A DESKTOP IDE The primary technical difference between the two types of IDEs is that - typically - with a desktop IDE, the IDE vendor has an expectation that the packaging, build, test, and runtime environments are installed and managed outside the tool itself. This is not always the case, as some really advanced IDEs take care of installing these additional components onto the host machine, but it's not usually the case. With a cloud IDE environment, the IDE exists entirely in the cloud; however, usually the cloud IDE vendor must also provide the build and runtime environment in a hosted location in addition to the executing IDE. This distinction offers both promise and challenges. The promise for cloud IDES is that being entirely in the cloud, the cloud IDE vendor can provision more components, do it faster, and potentially reduce failure rates from configuration. The challenges include the additional overhead of managing a workspace, which now includes an IDE in addition to projects, code, builders, and runners. 2.1 APPROACHES TO CLOUD IDE WORKSPACE MANAGEMENT There are generally two approaches taken with managing workspaces in the cloud: - A user is granted a dedicated VM where they can gain privileges, including installing files and other software that can be edited, built, or executed. - A user shares pooled resources that are homogenously structured, and commands for IDE functions (i.e., refactor), build functions, and run functions are distributed across different clusters optimized for each function. The more homogenous the development environments are, the denser the operation of the system is for the operator. The downside is that these systems are less flexible and less likely to be a perfect match for developers on their project. Codenvy.com provides both configurations for users. For users on a premium plan, we operate the first configuration where they are given a dedicated VM with an SSH option. (This plan is to be made available during Q4/2013.)Different build and runtime software can be installed on the VM. The IDE, which is running within the Codenvy system, can then be re-configured to point the build, run, and debug commands to execute processes that reside within the dedicated VM. For users on the free plan, we operate a set of centralized servers broken into three clusters: one for IDEs, one for builders, and one for runners. There is a queue system that sits between each cluster and throttles the activity back and forth between each cluster. Each cluster can scale independently of the others, and allows for a higher density across the population. IDE clusters scale on their bottleneck of I/O & memory, build clusters on compute, and run clusters on memory. 3.0 CODENVY PLATFORM SDK ARCHITECTURE Since developers are coming up with a variety of different development workflows, we needed to design an engine that would allow for the creation of different cloud IDEs that could change the behavior of the system, along with its feel. There are some well-defined approaches to structuring plug-ins that have been generated by Eclipse and JetBrains over the years, and these interfaces could be extended to a multi-tenanted cloud environment. The SDK encompasses: - A cloud client runtime that discovers, registers, loads, and manages plug-ins. The runtime is also responsible for managing a set of multi-tenanted inbound and outbound external connections to systems participating in a tooling workflow. - A cloud client SDK that enables the development of multi-tenant, cloud client plug-ins. The SDK provides a common model for working with resources, events, and user interfaces. Plug-ins can be integrated with, or layered upon one another in an extensible, well-defined format. - A set of standard plug-ins, which may can be excluded from the runtime (if necessary), to provide functionality relating to core development tooling. The current set of plug-ins includes: git, Java, CSS, Python, HTML, Ruby, XML, PHP, JavaScript, Browser Shell, and maven. - A default IDE that contains a structured workbench for organizing code repositories, projects, files, build integration, runtime/debugger integration, and deployment / publish workflows. This IDE is a package of integrated plug-ins that deliver a set of default tooling. This IDE is accessed through a browser or a set of RESTful Web Services that represent each of the tooling functions. 3.1 PLUG-IN ARCHITECTURE The foundation of building an IDE is the ability to create, package, deploy and update a plug-in. Plug-ins are extensible in their own right, and can be layered such that one plug-in can invoke and extend another plug-in. The SDK is designed as a two-tiered application with Web application and server-side application services. Both tiers are extensible and can be modified by third parties. Plug-Ins are authored using Java, GWT, and CDI. Injection and aspect-oriented programming is used throughout the interface system as a technique for extending plug-ins, connecting plug-ins together, and to link plug-ins into the IDE itself. The injection and interface system of CDI makes it possible to create a very clean, simple interface fronting a plug-in. And GWT is used as it has a number of optimizations to generate both standard and performant JavaScript code that can operate across a number of browsers. This is a blank plug-in that adds a menu item to the IDE that changes state when selected. This plug-in can be compiled, tested, and validated in its own workflow. Injections are used to extend the constructor of the Java class, and these injections can be used to add in additional parameters that are passed into the Extension itself. package com.codenvy.ide.extension.demo; import com.codenvy.ide.api.editor.EditorAgent; import com.codenvy.ide.api.extension.Extension; import com.codenvy.ide.api.ui.action.ActionManager; import com.codenvy.ide.api.ui.workspace.WorkspaceAgent; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Extension used to demonstrate the IDE 2.0 SDK fetures * * @author <a href="mailto:nzamosenchuk@exoplatform.com">Nikolay Zamosenchuk</a> */ @Singleton @Extension(title = "Demo extension", version = "3.0.0") public class DemoExtension { @Inject public DemoExtension(final WorkspaceAgent workspace, ActionManager actionManager, EditorAgent editorAgent) { menu.addMenuItem("Project/Some Project Operation", new ExtendedCommand() { @Override public Expression inContext() { return projectOpenedExpression; } @Override public ImageResource getIcon() { return null; } @Override public void execute() { Window.alert("This is test item. The item changes enable/disable state when something happend."); } @Override public Expression canExecute() { return null; } @Override public String getToolTip() { return null; } }); } } 3.2 PLUG-IN SERVICES & APIS Plug-ins have a variety of services and APIs that they can use. There are three categories of services provided. 3.2.1 IDE CLIENT APIS These are the typical APIs a developer would expect to be in a platform to help them create visual extensions to the client side portion of the IDE itself. This includes packages for preferences, menus, views, helpers, wizards, toolbars, selections, editors, hotkeys, and so one. There is also a set of commons libraries that contain UI components and other utility functions. There is also a set of top-level, standardized views that are provided with the default IDE. These views house the various perspectives and panels, and can be accessed directly by the plug-in itself. There are views for the console, editor, project explorer, menus, forms, shell, and wizards. 3.2.2 IDE SERVER SERVICES In order for a plug-in to access a workspace operating within a cloud environment, there is a standard set of RESTful APIs that can be used to allow a plug-in to interact with the cloud development environment. The cloud manages the build cluster, the run cluster, the virtual file system where all files are persisted, the connection pool between Codenvy and outside/3rd party services, identity management server for managing user credentials, interfaces for billing/subscriptions, and other high compute functions that are better offloaded for processing within the cloud instead of being handled within the browser. Codenvy’s platform is different from most cloud IDEs. A developer’s workspace is virtualized across different physical resources that are used to service different IDE functions. Dependency management, build, runners and code assistants can execute on different clusters of physical nodes. In order to properly virtualize access to all of these resources, we needed to implement a VFS that underpins the services and physical resources but also has a native understanding of IDE behavior. An example of the offloaded services is refactoring. Since a refactoring command may need to alter the contents across many files, including renaming some and deleting others, handling refactoring as a cloud service instead of within the browser is much more effective. This capability is exposed as a set of RESTful services that can be directly accessed by the plug-in itself. 3.3 PLUG-IN LIFECYCLE A plug-in itself is a combination of code that instructs the server-side and the client-side to operate in a certain way. Since the client-side is GWT, and the core IDE itself is also authored in GWT, a plug-in that is loaded into the system must be compiled with the rest of the IDE to generate a new IDE each time. The combination of the core IDE GWT code and the GWT extensions authored by the plug-in provider create a compiled binary set of code that generates an integrated, optimized set of JavaScript that is the UI itself. The plug-in itself is packaged as a single JAR file that is combined with the IDE WAR during its creation phase. It is possible to run the SDK runtime with a loaded set of plug-ins and then activate or de-activate which plug-ins are actively displayed to the user through configuration files. The configurability of plug-ins at boot time allows for some fine-tuned control over the memory and CPU imprint of the IDE as a whole. ISVs and other 3rd party developers need ways to build and test the plug-ins that they write. There are three modes of plug-in deployment: - Stand Alone. Plug-ins are authored on a dedicated machine, compiled, and then booted with a customized Codenvy runtime that is a WAR file. This is generally done on a desktop, but can also be done as a hosted service as well. There is a standardized plug-in project template that comes with an associated set of maven build commands to enable this packaging within the downloadable version of the Codenvy SDK. - Hosted SDK. Located at codenvy-sdk.com, this is a shadow site running the Codenvy platform. It provides a basic IDE where plug-ins can be created, compiled, and executed. Executed plug-ins are loaded in an instantiated IDE. All of this takes place in a browser, and instantiated IDEs are running in a different process that is a Tomcat server. Essentially, developers are using a shadow Codenvy to create more Codenvy instances with one plug-in loaded to test behavior and functionality. Each "run" of the plug-in type causes another JVM to launch with a different IDE load configuration. - Codenvy.com. We incorporate approved plug-ins into the production build of Codenvy.com, build a set of Selenium tests to automate the testing of the interfaces, and then activate for the community to make use of. Currently, all loaded plug-ins are activated. We will eventually create a mechanism that allows named users at Codenvy.com to identify which plug-ins are active within their named workspace. 4.0 CODENVY.COM ARCHITECTURE We use the engine that powers the platform to create Codenvy.com, an elastic, hosted, and supported environment. We envision Codenvy.com as a continuously living entity that is accessed by a variety of different roles. Because of this vision, Codenvy.com is primarily a system with different interfaces. Developers use browsers to make use of the system. Devops and ISVs have programmatic interfaces to access workflows and to create IDEs on demand, and internal audiences have configuration interfaces to look at analytics data, administer users/workspaces, and dictate how the system should operate while unattended. (Click on the image to enlarge it) 4.1 CLIENT-SERVER COMMUNICATIONS Browsers interact with Codenvy though WebSocket and HTTP REST connections. The connections are established when a workspace session is initiated. Communications between the browser and the server are limited, and restricted only to functions that require server access. Server access functions are related to accessing new files, periodic auto-save, build services, event logging, and runner services. There is no heartbeat, and the protocol has been optimized to minimize the network traffic. We use WebSocket communications when we need an ongoing set of collaborative discussions. This happens most often during a collaboration session for multi-user editing and chat windows. Since WebSockets consume a larger amount of resources on the server, we use HTTP REST connections for any command that is one-way, or fire-and-forget, such as a user initiating a build request, a refactoring, submitting a PAAS deploy, or submitting a log event. 4.2 TEMPORARY VS. NAMED WORKSPACES Codenvy has the concept of a temporary workspace. A temporary workspace is a workspace that has a project, code repository, and some code, build, test, debug services, but structured into a quarantined zone such that work cannot be long-term persisted. Additionally, a temporary workspace will be destroyed if it is left idle for an extended period or if the browser is closed. In a temporary workspace, there are certain behaviors that must be repeated for each action, such as authenticating to an outside provider, since the system will not persist any of those credentials. A permanent workspace is bound to a user or an organization, and the projects inside it persisted. Additionally, the system will persist account information, credentials to outside services, such as SSH keys to GitHub, and allow for public / private project functions. Temporary workspaces behave similarly for both non-authenticated and authenticated users. For developers that only want to work in a temporary space, all factoried projects begin in a temporary workspace. For those that have a registered account, they can then copy the project into their permanent workspace. For those that do not have an account, they can execute the authentication process and the project will be copied after authentication is confirmed. The architectural difference between a temporary workspace and a named workspace is whether persistence storage (LDAP) is used to store related account information. The temporary workspace has a full user profile; however, since that information is kept entirely in-memory, any destruction of the tenant itself will wipe the entire project space. We also place all temporary tenants into an isolated portion of the virtual file system to be able to run batch cleanup and reporting algorithms against those files. 4.3 USER MANAGEMENT & AUTHENTICATION SERVICES Users can be authenticated through either a form-based login or OAuth. We use Java Authentication and Authorization Service as the core technology to handle authentication. Authentication will happen any time a user attempts to access a protected resource, which is URL-referenced. Some URL references are unprotected (public) and others are protected (private). After authentication occurs, there is an attempt by the system to determine which workspace and project that user should gain access to. If the URL being referenced does not have an explicit workspace reference, then the user is re-routed to a different workspace and tenant selection algorithm. (Click on the image to enlarge it) 4.4 ANONYMOUS VS. NAMED USERS A named user is one that has an associated account and is granted configurable permissions to access protected resources. An anonymous user is one where they are accessing the system and no identifiable credentials can be associated with the account. Anonymous users can exist in one of two scenarios: - A user without a cookie initiates a Factory operation, placing them into a temporary workspace. - A user gains access to a public project URL and enters the product through that URL in read-only mode. The behavior of the system is different for anonymous users and named users. With anonymous users, it is possible for administrators to configure which features of the product are available through a set of configuration parameters accessible through configuration files. Anonymous users must either create an account or authenticate (either outside the product, or within it) in order for these capabilities to be re-activated. Anonymous users must also have all their traffic routed to an IDE cluster that is quarantined from other IDE clusters that handle named user traffic. This routing and isolation takes place using HAProxy and cloud administration IP that we have authored. Architecturally, anonymous users have an automatically generated user name that is not persisted into LDAP. They are in-memory only. Both anonymous and named users have an associated set of permissions, and are members of groups. Anonymous users’ associated groups and permissions are pre-determined and cannot be altered. 4.5 PUBLIC VS. PRIVATE PROJECTS Codenvy supports the concept of public and private projects. A public project is one where the project space, or any of its files are accessible by anyone who has access to the URL. We will eventually expose all of these public projects through a navigation directory on the Web site, but today it requires explicit awareness of the URL to gain access. We use ACLs to control behavior for workspaces, projects and files. ACLs are set on our virtual file system for a workspace, each project and the associated set of files in subdirectories. We can propagate ACL properties through any subdirectory of a root. For workspaces that are designated as entirely public (such as with our Community plan), we make a standard set of ACLs at the root of the virtual file system and make it unchangeable. For private projects, we then make these ACLs modifiable. There are both groups and individuals that can have ACLs set and modified. 4.6 INVITE VS. FACTORY When a user is invited into another user’s workspace, they must have an appropriate key to gain access. For existing Codenvy users that are invited to a workspace, we automatically associate the invitation key from the invited user into the workspace of the inviter. For invites to email addresses that are not associated with Codenvy accounts, we generate a temporary key, store it along with their email in our LDAP repository, and then send an email to the user with the link & key. When the user clicks on the link, we apply the temporary key and the user is then granted access into the account that they were invited into. For users that access a public workspace, a key is not required. We create an automatic access key that grants the anonymous or named user certain access rights to the workspace itself. These are generally read file rights, along with a limited number of project, build, and run functions. For users that click on a Factory, we create a separate temporary workspace. Users are not invited to use a Factory. Any user with access to the Factory URL can make use of that Factory. If the user accessing a Factory is already authenticated, then we can recognize that and allow them to copy the contents into their existing workspace. If the user is not authenticated, we’ll create an anonymous user account during the temporary workspace session. 4.7 COLLABORATION MODE When a file is opened, it can either be done with a standard editor or a collaboration editor. (Click on the image to enlarge it) A standard editor only operates in a single JVM and has no awareness of what is occurring in other JVMs. This means that the editor is only available to the user who explicitly opened it up, and it is not suitable for true collaboration mode. The standard editor can be launched for environments where there are weak connections or long ping times on the network which can affect WebSocket performance. With a standard editor, the amount of memory space consumed is controlled and users have a guarantee on saves, which are entirely manual. A collaboration editor is the default editor type in the Codenvy platform. We have extended Google’s collide open source project to enable simultaneous editing of files by multiple users. The collaboration editor controls the locks of files in the virtual file system and then coordinates changes made by each user on the file in real time. The collide editor is able to asynchronously save changes to the file on a periodic basis and save events are propagated back to the end user screen to make them aware of the persistence change. Additionally, the collaboration editor synchronizes events between various users that are within the same editor / file combination at the same time. 4.8 MULTI-TENANCY There are different tenancy models for the IDE cluster, the builder, and the runner. - IDE Cluster. Within this cluster, we run a single JVM per node that consumes all of the available memory and compute available on the node. Within the JVM we use some in-house IP to enable multi-tenancy within the JVM itself. Each workspace is allocated its own thread, memory, and virtual file space. When a workspace is instantiated with its own IDE in a single JVM, we configure our router to map HTTP requests and WebSocket connections to the right IDE. And the IDE itself is mapped to the appropriate directory within the. In general, we are able to operate about 300 IDE tenants in a single JVM operating on a medium instance at AWS before HAProxy has to spin up another IDE server. - Build Cluster. In the build cluster, there are a set of queues that front-end the cluster. There is a BuildManager service that sits in front of the queues that is accessible over RESTful Web Services. The BuildManager handles the message collection, ordering and processing. Build messages are routed to a queue based upon the incoming client context, such as paid / free account. There is an administration console that specifies how many nodes are allocated to a queue. We run one queue of processing for the Community tier (free), and then there is a dedicated queue for each Premium subscription (paid). Using this model, we can then allocate multiple hardware nodes to a single workspace, and the queue manager can load balance workspace requests across different build nodes. The client IDE periodically polls the builder assigned to its process to gather output and log files for display back in the browser itself. - Runner Cluster. Similar to build clusters, there is a queue system that sits between the build and run clusters. Either the build cluster can place orders onto the runner cluster, or the commands can come directly from the IDE. Each node on the runner cluster operates a multi-tenant deployment of CloudFoundry. CloudFoundry cartridges are used to determine the environment configuration of the server that boots. In Part 2 of this article we will present the following Codenvy topics: the virtual file system used, how logging and analytics are implemented, hosted APIs, cluster management, the overall picture, the release model and the SCRUM process used for development.
https://www.infoq.com/articles/codenvy-architecture-part-1
CC-MAIN-2016-30
refinedweb
4,146
53
via RT <[EMAIL PROTECTED]> writes: > This message about libwww-perl was sent to you by MSTEVENS via rt.cpan.org > > <URL: > > > Hi. > > I'm running perl 5.6.1 on debian linux. > > I'm trying to upgrade my machine to the latest version of LWP::UserAgent, and have >found > the following problem: > > cpan> r > > Package namespace installed latest in CPAN file > HTTP::Cookies 1.16 1.19 G/GA/GAAS/libwww-perl-5.61.tar.gz > LWP::UserAgent 1.80 1.99 G/GA/GAAS/libwww-perl-5.60.tar.gz > > 5.61 installs for me, but leaves LWP::UserAgent out of date. > 5.60 won't install for me, and would presumably leave HTTP::Cookies out of date. Advertising What happened is that LWP::UserAgent picks up it version number from RCS's $Revision$ using the following trick: $VERSION = sprintf("%d.%02d", q$Revision: 1.99 $ =~ /(\d+)\.(\d+)/); For 5.61 the revision number went from 1.99 to 1.100. Since as float/string 1.100 < 1.99 it looks like the new LWP::UserAgent is older. This will certainly be fixed for 5.62. > 5.60 fails live/google, with the following content: Google blocked us so this test is not there for 5.61. Regards, Gisle
https://www.mail-archive.com/gisle@caliper.activestate.com/msg00087.html
CC-MAIN-2018-05
refinedweb
210
70.6
Previously system by using IR TV/DVD/MP3 remote for controlling AC home appliances. After receiving signal from IR remote, Arduino sends related signal to relays which are responsible for switching ON or OFF of the home appliances through a relay driver. Working Explanation: Working of this project is easily understandable. When we press any button of IR Remote then remote sends a code in form of train of encoded pulses using 38Khz modulating frequency. These pulses are received by TSOP1738 sensor and read by Arduino and then Arduino decodes received train of pulse into a hex value and compares that decoded value with the predefined hex value of the pressed button. If any match occurs then Arduino perform relative operation and the corresponding result is also displayed on 16x2 LCD by using appropriate commands. Here in this project we have used 3 bulbs of different colors, for demonstration which indicates Fan, Light and TV. There are many types of IR Remote are available for different device but most of them are worked on around 38KHz Frequency signal. Here in this project we control home appliances using IR TV remote. For detecting IR remote signal, we use TSOP1738 IR Receiver. This TSOP1738 sensor can sense 38Khz Frequency signal. The working of IR remote and the TSOP1738 can be covered in detail in this article: IR Transmitter and Receiver Components: - Arduino UNO - TSOP1738 - IR TV/DVD Remote - ULN2003 - Relays 5 volt - Bulb with holder - Connecting wires - Bread board - 16x2 LCD - Power supply - PVT - IC 7805 Here in this project we have used 7, 8 and 9 number button of IR remote, for controlling Fan, Light and TV respectively and ON/OFF button (Power button) is used for turning ON and OFF all the appliances simultaneously. Here we have used toggle [EVEN ODD] method for ON and OFF the single home appliance. Toggle method is nothing but to get that whether the button is pressed even no of times or the odd no of times. This is found by getting the reminder after dividing it by 2 (i%2), if there is some reminder then device will be turned ON and if reminder is 0 then it will be turned OFF. Suppose Key 7 is pressed on the remote then remote sends a signal to Arduino through TSOP IR Receiver. Then Arduino decode it and store the decoded value into the results variable. Now results variable has a hex value 0x1FE00FF, after matching it with the predefined hex value of key 7 (see above image), Arduino turns ON the Fan. Now when we press the same key (key 7) again then IR sends the same code. Arduino gets same code and matched with same code like before but this time Fan turned OFF because of toggling the bit [EVEN ODD] (i%2). Decoding IR Remote Control Signals using Arduino: Here is a list of a DVD NEC type Remote decoded output codes: If you don’t know the Decoded output for your IR remote, it can be easily found, just follow these steps: - Download the IR remote library from here. - Unzip it, and place it in your Arduino ‘Libraries’ folder. Then rename the extracted folder to IRremote. - Run the below program from your Arduino and open the Serial Monitor window in Arduino IDE. Now press any IR Remote button and see the corresponding decoded hex output in Serial Monitor window. * } delay(100); } The above program is taken from IRremote library’s ‘examples’ folder, you can check out more examples to learn more about using the IR remote. So that’s how we decoded the IR remote output. Circuit Description: Connections of this circuit is very output pin of TSOP1738 is directly connected at digital pin number 14 (A) of Arduino. And Vcc pin is connected a +5 volt and GND pin connected at Ground terminal of circuit. A relay driver namely ULN2003 is also used for driving relays. IR remote which is easily available at Google. And define pin and declare variables. #include <IRremote.h> const int RECV_PIN=14; IRrecv irrecv(RECV_PIN); decode_results results; And then include a header for liquid crystal display and then we defines data and control pins for LCD and home appliances. #include<LiquidCrystal.h> LiquidCrystal lcd(6,7,8,9,10,11); #define Fan 3 #define Light 4 #define TV 5 After it we need to initialize the LCD and give direction of pin that are used for fan , light and TV. void setup() { Serial.begin(9600); lcd.begin(16,2); pinMode(Fan, OUTPUT); pinMode(Light, OUTPUT); pinMode(TV, OUTPUT); As already explained, below part of the code is used to compare the received hex value to already defined hex code of that button. If it matched then a relative operation is performed by using appropriate functions that are given in code. void loop() { if (irrecv.decode(&results)) { Serial.println(results.value,HEX); delay(100); lcd.setCursor(0,0); lcd.print("Fan Light TV"); if(results.value==0x1FE00FF) { i++; int x=i%2; digitalWrite(Fan, x); #include<LiquidCrystal.h> #include <IRremote.h> const int RECV_PIN=14; IRrecv irrecv(RECV_PIN); decode_results results; #include<LiquidCrystal.h> LiquidCrystal lcd(6,7,8,9,10,11); #define Fan 3 #define Light 4 #define TV 5 int i=0,j=0,k=0,n=0; void setup() { Serial.begin(9600); lcd.begin(16,2); pinMode(Fan, OUTPUT); pinMode(Light, OUTPUT); pinMode(TV, OUTPUT); //digitalWrite(13,HIGH); lcd.print("Remote Controlled"); lcd.setCursor(0,1); lcd.print("Home Automation"); delay(2000); lcd.clear(); lcd.print("Circuit Digest"); lcd.setCursor(0,1); delay(1000); lcd.print("System Ready..."); delay(1000); irrecv.enableIRIn(); // Start the receiver irrecv.blink13(true); lcd.clear(); lcd.setCursor(0,0); lcd.print("Fan Light TV "); lcd.setCursor(0,1); lcd.print("OFF OFF OFF"); } void loop() { if (irrecv.decode(&results)) { Serial.println(results.value,HEX); delay(100); lcd.setCursor(0,0); lcd.print("Fan Light TV"); if(results.value==0x1FE00FF) { i++; int x=i%2; digitalWrite(Fan, x); lcd.setCursor(0,1); if(x) lcd.print("ON "); else lcd.print("OFF "); // delay(200); } else if(results.value==0x1FEF00F) // key 1 { j++; int x=j%2; digitalWrite(Light, x); lcd.setCursor(6,1); if(x) lcd.print("ON "); else lcd.print("OFF "); // delay(200); } if(results.value==0x1FE9867) { k++; int x=k%2; digitalWrite(TV, x); lcd.setCursor(13,1); if(x) lcd.print("ON "); else lcd.print("OFF"); // delay(200); } if(results.value==0x1FE48B7) { n++; int x=n%2; digitalWrite(TV, x); digitalWrite(Fan,x); digitalWrite(Light,x); lcd.setCursor(0,1); if(x) lcd.print("ON ON ON "); else lcd.print("OFF OFF OFF"); //delay(200); } irrecv.resume(); // Receive the next value //delay(100); } } Jan 21, 2016 Hi from where i can get Remote decoded output codes of any tv or led ? method describe to get the codes please..... Feb 12, 2016 We have updated the description and added the Method to Decode the IR remote signals, just check above. Jan 25, 2016 hello is there any method to decode ir remote signals without using arduino ? bcoz i dont have one . i have usbasp and ATmega8. thnx. Feb 12, 2016 yes, IR can also be decoded using ATmega8, take a look at this link. Feb 21, 2016 all the example programs in the library given above have error in compiling tell me what to do Feb 25, 2016 i think you have added a wrong library. download a new one from github and then try. Apr 09, 2016 hi it is the nice project sir but what is a PVT it give in component list ?pls tell about PVT anyway project is awesome Apr 14, 2016 Can I use the VS1838B replace the TSOP1738? How can I change the code? Can you show me the new code? Thank you!!!!! May 07, 2016 awesome can i get the project report May 17, 2016 Awesome work but can i get complete of the project. thank you May 28, 2016 Thanks! It is the complete Project. Jun 13, 2016 excusme sir, i am the begginner to make project, i dont have any experience before making any project, will you give me the making video of this project , i hope that you will help me sir.. Jun 21, 2016 if we are using this to control our home light,how else can a bypass be made in case we don't need it at anytime ,can we use a diode to to th at Jun 23, 2016 I am a newbie. I want to know exactly the connections between the relay board and arduino as well as where to connect the pins of the relay board's data pins and how to connect the relay board to the appliances. Jul 09, 2016 Follow the circuit diagram, and learn more about the Pins of Relay Here. Aug 20, 2016 Good day Can I use PIC177F88 to decode IR remote signal Aug 22, 2016 Yes you can but its comparatively much easier with Arduino. Oct 27, 2016 there are some garbage values and symbols are showing while i light the bulbs using the remote so how solve it? Nov 30, 2016 Try printing all the values on Serial monitor as well as LCD, then check if serial monitor also show Garbage values. There are only constant Strings in lcd.print, so there should be no garbage values. Oct 29, 2016 how to store the the condition into the eeprom memory,, when power off then power coming then all appliances going on condition Nov 27, 2016 What kind Arduino used whwther it is uno r1 or r2 or r3 Nov 30, 2016 Arduino Uno R3 Dec 03, 2016 i have done insert and run the code in arduino but when i press button not have any output at window. Where the receiver the signal? arduino? Dec 28, 2016 Hii....i jst saw ur circuit and video...but in u components list u hav mentioned an extra component 7805...y r we using it...and its not ther in the circuit...and wat is PVT as shown in the components list Dec 31, 2016 You can use IC 7805 to regulate the voltage to 5v, it will smooth out the power supply. And PVT is Terminal Block on Relay board, green color block which have two screws. Jan 22, 2017 Hi can i get the design of the board on which u connected the relays,ULN2003. Jan 22, 2017 can we use arduino mega instead of arduino uno in this project because i have mega with me . Mar 04, 2017 Yes you can use Arduino Mega Jan 28, 2017 sir can we use this source code for 8051 microcontroller ? Mar 04, 2017 No Mar 01, 2017 can i implement this code using atmega16? Mar 11, 2017 Can anyone tell me what is that 10k in the circuit diagram....if it is resistor plss tell the type of resistor.......in design of schematic i dont no wat to use for connection between VEE nd resistor.......so plsss say the type of resistor Mar 12, 2017 I desire to control my lights using my phone. But i don't have a bluetooth module. What can i use in its place. Thnks. Mar 14, 2017 actually i copied ur code to the aurduino software but the problem is an error woke up saying TKD2 not been declared in the program Mar 31, 2017 bro!me too getting the same error.did u get the solution Mar 28, 2017 how much will it cost to implement this project (specify where can i get cheaper equipmenst). Apr 20, 2017 i need a clear picture of remote automation using arduino for my major project Apr 25, 2017 all thing is perfect but when im switch on the fan tubilght starts flickerng,,, how to fix this Jun 08, 2017 What is '"PVT" ? It is mentioned in the components. Can anyone tell me? Jul 05, 2017 PVT is green color terminal block with screw on relay module block. Jul 01, 2017 dear all, if i am using touch switch for ON/OFF the load relay also using remote for this, so is is possible to configure/assign remote key by press and hold the desire switch for us remote? ... i dont want to use serial monitor as well as i dont want my system bound for 1 remote, i want to use any remote any time by configure remote anytime with switch directly. help me out. Jul 05, 2017 check this project to build universal remote: Universal IR Remote Control using Arduino and Android App Aug 04, 2017 can anybody tell me what is PVT on second last number plzz its urgent help me? Aug 06, 2017 While compiling am getting error as stray 240 Nd 302 please send me correct coding.its very urgent.without using Pvt can we do this .please help me.thank you Aug 10, 2017 sir what is PVT in component list Sep 21, 2017 pls wat is PVT is it necessary Oct 04, 2017 When start the program the all device's are in on condition how to solve this problem? Oct 04, 2017 After these three lines in the setup function pinMode(Fan, OUTPUT); pinMode(Light, OUTPUT); pinMode(TV, OUTPUT); add digitalWrite(Fan, 0); digitalWrite(Light, 0); digitalWrite(TV, 0); Nov 22, 2017 In the video you have only shown the output.Can you please upload a video on how to make this circuit? Jan 16, 2018 ANY ONE TELL ME PLZZ HOW CAN I FIND IR RECEIVER (TSOP1738)FROM PROTEUS 8???PLZZ TELL Jan 16, 2018 proteus does not have TSOP Mar 27, 2018 Hello, trying to build this project and I don't know where to put the IC 7805 on the circuit... can you please tell me. Also if I am using a Phillips IR Remote modulo isn't working for the coding. What should I do? Mar 30, 2018 What is PVT mentioned in the component list.Plzzz anyone reply me Jul 08, 2018 may send circuit of ir remot control use pic16f877a use mikrobasic transmitter and recever and thanks very much
https://circuitdigest.com/microcontroller-projects/ir-remote-controlled-home-appliances
CC-MAIN-2019-39
refinedweb
2,358
72.76
Improving I/O using compressors¶ This example compares the compressors available in Joblib. In the example, Zlib, LZMA and LZ4 compression only are used but Joblib also supports BZ2 and GZip compression methods. For each compared compression method, this example dumps and reloads a dataset fetched from an online machine-learning database. This gives 3 informations: the size on disk of the compressed data, the time spent to dump and the time spent to reload the data from disk. import os import os.path import time Get some data from real-world use cases¶ First fetch the benchmark dataset from an online machine-learning database and load it in a pandas dataframe. import pandas as pd url = ("" "kddcup99-mld/kddcup.data.gz") names = ("duration, protocol_type, service, flag, src_bytes, " "dst_bytes, land, wrong_fragment, urgent, hot, " "num_failed_logins, logged_in, num_compromised, " "root_shell, su_attempted, num_root, " "num_file_creations, ").split(', ') data = pd.read_csv(url, names=names, nrows=1e6) Dump and load the dataset without compression¶ This gives reference values for later comparison. Start by measuring the time spent for dumping the raw data: Out: Raw dump duration: 0.332s Then measure the size of the raw dumped data on disk: raw_file_size = os.stat(pickle_file).st_size / 1e6 print("Raw dump file size: %0.3fMB" % raw_file_size) Out: Raw dump file size: 305.223MB Finally measure the time spent for loading the raw data: Out: Raw load duration: 1.797s Dump and load the dataset using the Zlib compression method¶ The compression level is using the default value, 3, which is, in general, a good compromise between compression and speed. Start by measuring the time spent for dumping of the zlib data: Out: Zlib dump duration: 1.417s Then measure the size of the zlib dump data on disk: zlib_file_size = os.stat(pickle_file).st_size / 1e6 print("Zlib file size: %0.3fMB" % zlib_file_size) Out: Zlib file size: 5.955MB Finally measure the time spent for loading the compressed dataset: Out: Zlib load duration: 2.064s Note The compression format is detected automatically by Joblib. The compression format is identified by the standard magic number present at the beginning of the file. Joblib uses this information to determine the compression method used. This is the case for all compression methods supported by Joblib. Dump and load the dataset using the LZMA compression method¶ LZMA compression method has a very good compression rate but at the cost of being very slow. In this example, a light compression level, e.g. 3, is used to speed up a bit the dump/load cycle. Start by measuring the time spent for dumping the lzma data: Out: LZMA dump duration: 3.989s Then measure the size of the lzma dump data on disk: lzma_file_size = os.stat(pickle_file).st_size / 1e6 print("LZMA file size: %0.3fMB" % lzma_file_size) Out: LZMA file size: 2.873MB Finally measure the time spent for loading the lzma data: Out: LZMA load duration: 4.312s Dump and load the dataset using the LZ4 compression method¶ LZ4 compression method is known to be one of the fastest available compression method but with a compression rate a bit lower than Zlib. In most of the cases, this method is a good choice. Start by measuring the time spent for dumping the lz4 data: Out: LZ4 dump duration: 0.237s Then measure the size of the lz4 dump data on disk: lz4_file_size = os.stat(pickle_file).st_size / 1e6 print("LZ4 file size: %0.3fMB" % lz4_file_size) Out: LZ4 file size: 9.765MB Finally measure the time spent for loading the lz4 data: Out: LZ4 load duration: 5.926s Comparing the results¶ import numpy as np import matplotlib.pyplot as plt N = 4 load_durations = (raw_load_duration, lz4_load_duration, zlib_load_duration, lzma_load_duration) dump_durations = (raw_dump_duration, lz4_dump_duration, zlib_dump_duration, lzma_dump_duration) file_sizes = (raw_file_size, lz4_file_size, zlib_file_size, lzma('Dump and load durations') plt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA')) plt.yticks(np.arange(0, lzma_load_duration + lzma_dump_duration)) plt.legend((p1[0], p2[0]), ('Dump duration', 'Load duration')) Compared with other compressors, LZ4 is clearly the fastest, especially for dumping compressed data on disk. In this particular case, it can even be faster than the raw dump. Also note that dump and load durations depend on the I/O speed of the underlying storage: for example, with SSD hard drives the LZ4 compression will be slightly slower than raw dump/load, whereas with spinning hard disk drives (HDD) or remote storage (NFS), LZ4 is faster in general. LZMA and Zlib, even if always slower for dumping data, are quite fast when re-loading compressed data from disk. plt.figure(2, figsize=(5, 4)) plt.bar(ind, file_sizes, width, log=True) plt.ylabel('File size in MB') plt.xticks(ind, ('Raw', 'LZ4', 'Zlib', 'LZMA')) Compressed data obviously takes a lot less space on disk than raw data. LZMA is the best compression method in terms of compression rate. Zlib also has a better compression rate than LZ4. plt.show() Clear the pickle file¶ import os os.remove(pickle_file) Total running time of the script: ( 0 minutes 26.476 seconds) Gallery generated by Sphinx-Gallery
https://joblib.readthedocs.io/en/latest/auto_examples/compressors_comparison.html
CC-MAIN-2020-10
refinedweb
830
58.08
Posted Dec 22, 2004 By Steve Callan After starting OMWB, select Action>Capture Source Database and the Capture Wizard starts. The following series of screen shots is similar to what we already saw with the MySQL example, so they are shown without comment. Click for larger image After clicking "Yes" at this last window, let's generate a migration report and view its contents. You generate the reports via the Report menu and OMWB informs you as to where they are located. Clicking OK results in the report being presented to you in your browser. Let's look at the details for Northwind's stored procedures. The first line item has to do with a "set ROWCOUNT" statement in the Ten_Most_Expensive_Products procedure. Oracle does not support "set ROWCOUNT" which is what SQL Server uses to return (in this case) the top ten, umm, most expensive products. The main body of the original code is: ALTER procedure "Ten Most Expensive Products" AS SET ROWCOUNT 10 SELECT Products.ProductName AS TenMostExpensiveProducts, Products.UnitPrice FROM Products ORDER BY Products.UnitPrice DESC To perform the manual conversion, you have at least two options. Option 1) Modify the original code in SQL Server (or Oracle) to something you can immediately use in Oracle. You can simply run the SELECT part of the code and see that any product with a price greater than 44 is going to be in the top ten. Of course, you will be performing regular and frequent checks to ensure "44" is the correct value to distinguish the top ten most expensive products from the rest. The kludged code is shown below. ALTER procedure "Ten Most Expensive Products" AS SELECT Products.ProductName AS TenMostExpensiveProducts, Products.UnitPrice FROM Products WHERE UnitPrice > 44 ORDER BY Products.UnitPrice DESC Option 2) Modify the original code in SQL Server (or Oracle) to use ANSI SQL standards or syntax. This may or may not be simple, depending on your knowledge of what ANSI SQL looks like when compared to SQL Server or Oracle SQL. If you do not know how to reformat "set ROWCOUNT" to ANSI SQL (or a comparable construct in Oracle), but need to get this migration project done like yesterday, do what you do know and go back and fix it later. Oracle Archives Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email Subject (Maximum characters: 1200). You have characters left.
https://www.databasejournal.com/features/oracle/article.php/10893_3447641_2/Oracle-Migration-Workbench---Part-5.htm
CC-MAIN-2018-47
refinedweb
409
64.41
Results 1 to 3 of 3 Thread: Importing DVD to imovie Importing DVD to imovie - Member Since - Nov 16, 2009 - 2 I am trying to import a 28 second clip from a DVD to imovie and get a "do not recognize format message. The DVD plays in iDVD fine. Suggestions? - Member Since - Nov 16, 2009 - 2 No clues??? It must be EZ...I am a complete newbie to mac thx - Member Since - Nov 16, 2009 - Location - North Louisiana, USA - 8,887 - Specs: - 2.8 GHz MacBook Pro 10.11, 8 GB mem, iPhone 6+ If the video is not copy protected you might try ATPM 12.03 - How To: Performing a Video Extraction. I used a disc burned from my TiVo but the process would be the same. I imported the files as DV format clips but I believe the current version of iTunes supports other formats. BTW The links in that article are for earlier versions of the software but seem to still work. They refer to the current versions now though. Thread Information Users Browsing this Thread There are currently 1 users browsing this thread. (0 members and 1 guests) Similar Threads Importing DVD into Imovie for newbieBy nancyspeed in forum Movies and VideoReplies: 14Last Post: 07-19-2013, 11:43 PM Importing DVD to iMovieBy poppi in forum Movies and VideoReplies: 4Last Post: 01-04-2013, 12:11 PM Problems in importing mini DVD into iMovieBy peterb in forum Movies and VideoReplies: 0Last Post: 12-29-2008, 06:45 PM Problem importing imovie HD project into imovie 08By mitchww in forum Movies and VideoReplies: 0Last Post: 12-20-2008, 12:13 AM Importing to iMOVIEBy philgrad in forum Movies and VideoReplies: 4Last Post: 05-04-2005, 05:43 PM
http://www.mac-forums.com/forums/movies-video/176405-importing-dvd-imovie.html
CC-MAIN-2015-48
refinedweb
292
68.7
Introduction We have reached in an era where we can now implement basic AND, OR and XOR logics on quantum circuits similar to the classical computing and we call this era as Quantum Era. This article is a simple introduction to Applied Quantum Computing (AQC) where we will code a Hello World program on real quantum chip 😅. But wait … I don’t have a quantum computer so how can I even do that ??? And there is a very simple solution for this, with companies like IBM and Google actually making quantum devices we can leverage them to build and test stuffs on real devices with ZERO setup of whatsoever. So here is our tech stack : - Google Colab : Cloud platform to run the code and execute the experiments. - QISKit : A Python library for quantum programming. - IBM Q: QuBits chipsets from IBM Q network . So let’s get our hands entangled. 😉 Background What is Quantum Computer ? Quantum computers are based on quantum bits, also known as qubits. They have two possible values (states) as 0 and 1, similar to the one we have in the classical computer. But the laws of quantum mechanics also allow other possibilities, which we call superposition states. Why Quantum Computing? Quantum computing could enable exponential speedups for certain classes of problems by exploiting superposition and entanglement in the manipulation of quantum bits (qubits). One such example is using quantum computing in Artificial Intelligence space, we can implement an optimisation algorithm(s) which can use the properties of superposition and help in speeding up the optimisation problem which can eventually lead to better and faster learning algorithm(s). What excites me about quantum computers? Using quantum annealing in classical Boltzmann machine, the weight discovery process can be made quantum mechanical, which can help us to find pattern which we couldn't find using classical annealing process (SGD). Which can be a key towards Artificial General Intelligence (AGI). What is the current status in quantum landscape? There have been lots of development made recently in the space of QC and all the major player in market are trying to make revolutionary break thru. Some of them are listed below: Implementing “Hello Quantum World !!!” Let’s implement our first Hello World program using quantum registers. Colab link : Github link: To start with quantum programming we will use Open Source Quantum Information Science Kit (QISKit). It’s a rapidly growing open source community making efforts to bring quantum computing easily accessible for larger audience. For more: pip install qiskit Now that we have the package setup’ed lets get familiar with the programming paradigm in quantum world. There are 4 major components for quantum programming. - Quantum Program : The environment to run the simulation/experiment. - Quantum Circuit: The virtual circuit to setup the experiment. - Quantum Registers: The register which consist of qubits. - Classical Registers: Register containing bits. We will initialize the quantum program, create a quantum register with 2 qubits and a classical register with 2 bits and set them into the circuit using below scripts: from qiskit import QuantumProgram # Create a QuantumProgram object instance. qp = QuantumProgram() # Create a Quantum Register called "qr" with 2 qubits. qr = qp.create_quantum_register('qr',2) # Create a Classical Register called "cr" with 2 bits. cr = qp.create_classical_register('cr',2) # Create a Quantum Circuit called "qc" involving qr and cr. qc = qp.create_circuit('HelloWorldCircuit', [qr],[cr]) Once we have our circuit ready, we need to run it on a quantum computer. And here comes the real fun. 😃 We will connect to a real quantum chipset and execute quantum operations on our HelloWorldCircuit. Here I am using IBM-Q deployed chipsets which has various options like: - ibmqx5: is 16 QuBits chipsets.[ ] - ibmqx4: is 5 QuBits chipsets.[ ] - ibmqx2: is 5QuBits chipsets.[ ] They are still in development phase and by the time you are reading this article they may get deprecated. So to get updated list look here. To access these chipsets you will need an account on IBM Quantum Experience. And generate the token from here. Set the backend as ibmqx5, provide your token and setup the connection. If the token is valid and the backend is configured then you are all set to access the quantum power. backend = 'ibmqx5' token = 'a7dbfb3cfc1252c4a7555020c32808cff17102a467c595801371f7b7f1f7c3a3355d565469aa4a37564df269f3710f33d7d13ba3c900ca947c1513598b64c5e7' qp.set_api(token,url='') Now its time to compose our circuit and execute the experiment. Steps to create our Hello World circuit: - We will add the Hadamard gate (H) with 1 qubit for adding superposition property. H gate has the property to maps X→Z, and Z→X. - We add Controlled-NOT gate (CX) , a two-qubit gate that flips the target qubit if the control is in state 1. This gate is required to generate entanglement. - A measurement gate to check the status. # Add the H gate in the Qubit 1, putting this qubit in superposition. qc.h(qr[1]) # Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement qc.cx(qr[1], qr[0]) # Add a Measure gate to see the state. qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) # Compile and execute the Quantum Program in the ibmqx5 results = qp.execute(['HelloWorldCircuit'] ,backend ,timeout=2400) print(results.get_counts('HelloWorldCircuit')) Now when we examine the results you will see 4 quantum states 0000, 0001, 0010,0011 each having some probabilities associated with it. So this depicts that all the four states co-exists at a given time. {‘00’: 488, ‘01’: 90, ‘10’: 58, ‘11’: 388} Congratulations !!! 🎊 🙌 You just experienced the 2 basic properties of quantum world i.e Superposition and Entanglement. Future Reading In this article we just touched the surface of quantum computing and there are lot more happening around. Here are some great links to keep up with the domain. - Strawberry Fields is a full-stack Python library for designing, simulating, and optimizing continuous variable quantum optical circuits. - A Universal Training Algorithm for Quantum Deep Learning : - Nathan’s Quantum Tech Newsletter by Nathan Shammah : - How to program a quantum computer by Dr James Wootton: - Quantum generative adversarial learning : - Cirq : An open source framework by Google for developing algorithms on noisy intermediate scale quantum (NISQ) computers.
https://hackernoon.com/exploring-quantum-programming-from-hello-world-to-hello-quantum-world-109add25305f?source=---------7
CC-MAIN-2019-39
refinedweb
1,029
56.96
Red Hat Bugzilla – Bug 211766 Fails to build on x86_64 Last modified: 2007-11-30 17:11:46 EST python-reportlab x86_64 build is an older version than the i386 build. Looks like this is from pre-buildsystem time. Failed due to sitelib<->sitearch, so I syned with FC-4: Build servers cause trouble currently, so it may be necessary to requeue this one. [re-using this bug with changed Summary...] In short: Rebuilding the src.rpm on an x86_64 machine fails. [...] So, hammer3 hangs, but hammer2 (x86_64 machine) failed to rebuild the package: It installed some files into python_sitearch, not python_sitelib, and then failed to include the installed /usr/lib64/python... files. I've hacked the FC-3 spec to use a link from /usr/lib64 to /usr/lib during %install, but that is sub-optimal. Job #20093 succeeded. noarch package will be in next push. Keeping this bug open, so you are aware that rebuild failures can happen when an x86_64 build server is used. I assume that FC-4 and newer are affected, too. Thanks for the heads up. patching setup.py to use this: from distutils.sysconfig import get_python_lib package_path = pjoin(get_python_lib(), 'reportlab') instead of: package_path = pjoin(package_home(distutils.__dict__), 'site-packages', 'reportlab') seems to work for me under RHEL4 which is more or less the same as FC3 FC3 and FC4 have now been EOL'd. Please check the ticket against a current Fedora release, and either adjust the release number, or close it if appropriate. Thanks. Your friendly BZ janitor :-)
https://bugzilla.redhat.com/show_bug.cgi?id=211766
CC-MAIN-2017-17
refinedweb
256
75.4
The people have spoken and the people love things to shimmer. I put together a little extension of the dcc.Loading component that replicates the fairly popular pre-loading shimmer effect used in today’s web and mobile apps. This is a great way to show the shape of elements on the page as they are loading, which apparently makes users feel more engaged with the app and excited about waiting for your slow code to run Check it out on GitHub or in the live (and somewhat sad) Dash app pictured above Feel free to try it out yourself with pip install dash-loading-extras and make any slow loading component shimmer from dash import Dash, html, dcc import dash_loading_extras as loading app = Dash() app.layout = html.Div([ html.H1("A Long Loading Graph Lies Below"), html.H2("It's worth the wait!"), loading.Shimmer( dcc.Graph(figure=fig, id="graph"), app=app, # show_spinner=True # optionally keep the loading animation on top of the shimmering element ), ]) Open to new ideas / collaborators / help prioritising next steps on GitHub
https://community.plotly.com/t/dash-loading-shimmer/61098/3
CC-MAIN-2022-27
refinedweb
178
56.89
Image J2me image display - Java Beginners J2me image display How can i display a jpeg image in j2me Hi Friend, Please visit the following links:... Thanks Immutable Image using Canvas Class Immutable Image using Canvas Class  ... to create the immutable image using canvas. In this example ImageCanvas class extends the Canvas class to create the immutable image. In the constructor Icon image Icon image hiii how can we set image on the icon by which we can launch the application??? hello, when you will save a image named icon.png then it is automatically show this image on the icon J2ME J2ME Hi friends, i have display the bar code image from Mysql database to web page i need to display that image in my J2ME application,how Adding customitem in canvas in J2ME? Adding customitem in canvas in J2ME? In J2ME how should we add... for customitem.The key event handling is allowed in canvas not in form.So i try to use canvas instead of form Simple Line Canvas Example Simple Line Canvas Example This is a simple example of drawing lines using canvas class in J2ME. In this example we are creating three different lines at different J2ME Canvas KeyPressed in J2ME using canvas class. After going through the given example, you will be able... J2ME Canvas KeyPressed  ...;display.setCurrent(canvas); } public void  Canvas won't draw on composite (SWT) but the canvas won't draw the image. Please help me and bare with me because I'm...Canvas won't draw on composite (SWT) I can't get a canvas to draw...) { final Display display = new Display(); final Image img = new Image Creating Menu Using Canvas Class Creating Menu Using Canvas Class  ... the canvas class to show the toggle message. The Toggle message will appear when...() drawString() repaint() The repaint() method is used to appear the string Load Icon Image Exception Load Icon Image Exception Load Icon Image Exception Mutable Image image using canvas class. In this example the ImageCanvas1 class extends the Canvas... | Graphics.LEFT); And to paint the image we are using paint... Mutable Image   Animation using repaint( ) method appear this image using this methods: while(run_thread){  ... J2ME Animation using repaint( ) method In this part of J2ME Image Tutorial, we Image Item Using Canvas Example Image Item Using Canvas Example  ... the image at the top center of the screen. The following are the methods used...) setImage(Image img) setLayout(int layout) Following fields have j2me and blutooth j2me and blutooth how to pass canvas object between two devices using blutooth Java error icon the dialog displays. We can use four standard icon using JOptionPane icons like.... The JOptionalPaneswing help us in implementation of a customized icon,image,dialog box etc. 1... Java error icon   J2ME Canvas Example J2ME Canvas Example A J2ME Game Canvas Example This example illustrates how to create a game using GameCanvas class. In this example we are extending GameCanvas class J2ME Tutorial center of the screen. Image Icon Using Canvas Example...; J2ME Canvas Example This example illustrates how to create a game using... about creating rectangles in J2ME. Draw Font Using Canvas Line Canvas MIDlet Example to each other on the center of the mobile window using Canvas class. "CanvasCrossLine" class created by us extends the Canvas class to draw both... Line Canvas MIDlet Example   List in J2ME List in J2ME J2ME Canvas List Example will explain you, how to create list of items... of elements into it using list.append () The simple list application will look like Setting an Icon for a Frame in Java an icon for the frame in Java Swing. This program helps us to set the icon (image... for the frame or window after getting the image using the Image class method named... Setting an Icon for a Frame in Java   J2ME Canvas Repaint J2ME Canvas Repaint In J2ME repaint is the method of the canvas class, and is used to repaint the entire canvas class. To define the repaint method in you midlet follow J2ME Draw Triangle J2ME Draw Triangle As you already aware of the canvas class and it's use in J2ME application, we are using canvas class to draw the triangle on the screen. In this example J2ME J2ME how to use form and canvas is same screen in J2ME Hi Friend, Please visit the following link: Thanks need fifth sem MCA mobile computing lab programs using j2me. i m beginner for j2me and i want to know how to run j2me programs. pls help give a sample example for using key listener in j2ME for developing Symbian J2ME J2ME how to create table using four field in RMS J2ME J2ME how to change the color of the selected date using J2ME. i.e. if i press select by taking the cursor on the date ,the color of that digit should change Browse an image Browse an image hi................ i want to browse an image from the folder and display in form of my project..... can u tell me how to do this????? i am using java swing......... import java.sql.*; import - MobileApplications j2me i am trying to load one image in j2me program..but get an exception class not found exception....this is d code..i put the image in src folder..._AFTER, "My Image"); form.append(imageItem); } catch (java.io.IOException J2ME What is the source code for Mortgage Calculator. using text...,freq.payment then Commands are Interest rates,Rest,More these all are using Adding a Rollover and Pressed Icon to a JButton Component in Java ; This program shows an icon or image on the button if the mouse pointer moves above the Button then your icon or image should be changed. When you click on the button then another image or icon should be shown on the button. This program Show Icon Displayer . To display the icon, we have defined an image. The class ImageIcon is responsible... Show Icon Displayer In this section, you will studied how to display a single icon one Image Item Example J2ME Image Item Example This application illustrates how to create the image and imageItem using... an image using Image Class and imageItem using ImageItem class. In the following J2ME J2ME i wann source code to find out the difference between two dates... (ParseException e) { e.printStackTrace(); } } } i wann j2me code not java code my dear sirs/friends display an image on my page display an image on my page How can I display an image on my page Draw arc in J2ME Draw arc in J2ME The given example is going to draw an arc using canvas class of J2ME. You can also set a color for it, as we did in our example. Different methods J2ME jpeg image J2ME jpeg image Within the property window of a JPEG image, there is a tab called 'Summary'. Within this tab, there is a field called 'Comments' I would like to write some j2me code which will add a given string to this field what is proper way to save pictures in SQl database and call it through JSP ? 'getContextPath()' mehtod using this method I can call pictures and Text on same page simultaneously, But if I use BiteStream to call pictures after changing MIME...what is proper way to save pictures in SQl database and call it through JSP Immutable Image MIDlet Example a image without using of canvas. Following methods are used in the source code... Immutable Image MIDlet Example This is the immutable image example, which Canvas Layout Container the canvas container using x and y properties of each components. These x and y... distances from canvas edges and canvas center. This can be done using properties... Canvas Layout Container   Using netbeans 6.9.1 create a mobile app. J2ME. Using netbeans 6.9.1 create a mobile app. J2ME. Can anybody help me with my school's project? I need to create a mobile pizza ordering app. Using just checkboxes to select sizes, crusts, topping, shape J2ME Key Codes Example key pressed on the canvas. In this application we are using the keyPressed... J2ME Key Codes Example  ... is created in the KeyCodeCanvas class, in which we inherited the canvas class how to create a databaseconnectvity using SQLSERVER2005 in J2ME - JDBC how to create a databaseconnectvity using SQLSERVER2005 in J2ME hi... using sqlserver through J2ME. Currently we are working on a Mobile Applicayion. In that application I would need to connect my midlet with the sqlserver2005 J2ME List Image J2ME List Image List Image MIDlet Example This example illustrates how to create list with image symbol. In this example we are trying to create list using of List class How to make a folder icon, make a folder icon, folder icon How to make a folder icon The folder is used in the computer, this example will teach you... > Stroke, Bevel and Emboss and apply same both settings. Your image Changing Executable Jar File Icon file for my java program and the icon that appears is the java icon. I will like to know if there is a way to change this to any icon of my choice. Hi, You may use JSmooth to create executable java file and also associate icon J2ME Timer Animation , which helps you to understand using of timer class for drawing the canvas. For the different task of canvas we are using the AnimatTimerTask class... J2ME Timer Animation   need upload data to java server from j2me 1.Two text messages and 3 capture Replace broken Image using JQuery Replace broken Image using JQuery Sir My web page contains a lot of images. But when it will not loaded properly, it shows a broken image. How can I fix it so that broken image will be replaced by error image automatically error in program when trying to load image in java - Java Beginners to add an image to my GUI using java graphics. I have cleaned up all my compiler... don't know what it means. ProductInventoryVGUI Uncaught error fetching image... that error message above saying uncaught error fetching image. I don't know how Building a J2ME sliding menu with text and images(part-1) an image icon to perform the next action or next image from the list every time it's been clicked. So if you want to go from one icon to another icon... Building a J2ME sliding menu with text and images(part-1 highlight words in an image using java highlight words in an image using java Hai all,In my application left side image is there and right side an application contains textboxes like... want to highlight name in the image using java/jsp/javascript.please help me J2ME Vector Example J2ME Vector Example  .... In this example we are using the vector class in the canvas form. The vector class contains components that can be accessed using an integer index. The following J2ME Form Class in J2ME. The application will look like as follow... In this image, "My... that is appended in this form using append method. Syntax of J2ME Form Class File name... J2ME Form Class   J2ME Frame Animation it in the canvas class. In this example we are creating a frame using Gauge class. When the command action call the "Run" command ,which display the canvas... J2ME Frame Animation   Having problem with image upload.... Having problem with image upload.... I am uploading profile pictures in my site.But after uploading when I visit my home page where it is supposed to show my profile picture,it's not showing.My profile picture is getting view will appear iphone view will appear iphone Hi, What is the code for view will appear iphone? Thanks HI, Here is the code: - (void)viewWillAppear:(BOOL...(@"View will appear"); } This method is executed once view is about to appear Setting the Icon for the frame in Java Setting the Icon for the frame in Java  ... the icon of the frame. This program is the detailed illustration to set the icon to the frame. Toolkit class has been used to get the image and then the image jQuery icon Dock plug-in jQuery icon Dock plug-in This section is about the icon Dock plug in of jQuery. The icon Dock is a jQuery JavaScript library plug-in that allows you.... The we are using here is "jquery.dock-0.8b.js". For this , you have Draw Font Using Canvas Example Draw Font Using Canvas Example This example is used to draw the different types of font using Canvas class. The following line of code is used to show the different style how to connect j2me program with mysql using servlet? how to connect j2me program with mysql using servlet? my program of j2me import java.io.*; import java.util.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; public Image Image how to insert image in xsl without using xml. the image was displayed in pdf..Please help me Icon Changes at runtime Icon Changes at runtime This section illustrates you how to create an icon that changes from at runtime. To create an icon, we have defined Icon class which provides iPhone Icon Design iPhone Icon Design Icon is a small graphical representation of any program.... An outstanding application needs a fascinating icon, which forcefully attract the viewers to open the programme. Icon designing is an art and we have Setting icon on the button in Java (Icon): Above method sets the specified Icon on the button. ImagIcon(String image... Setting icon on the button in Java This section illustrates you how to show the icon Canvas Layout Container in Flex4 Canvas Layout Container in Flex4: The Canvas layout Container is used... or controls. The Canvas layout Container is a MX component. There is no spark component... of Canvas Layout Container is <mx:Canvas>. In this example the colored area
http://www.roseindia.net/tutorialhelp/comment/81872
CC-MAIN-2014-52
refinedweb
2,322
64.41
First solution in Clear category for The Hidden Word by Lemur21 def checkio(text, word): max_l = -1 wlist = [] for lino, line in enumerate(text.split('\n'), 1): line = line.lower().replace(' ','') index = line.find(word) if index >= 0: return [lino, index + 1, lino, index + len(word)] max_l = max(max_l, len(line)) wlist.append(line) ss =' '*(max_l*len(wlist)) for i in range(len(wlist)): wlist[i] = wlist[i] + ' '*(max_l-len(wlist[i])) n = len(wlist) transp = [''.join([wlist[k][i] for k in range(n)]) for i in range(max_l)] for lino, line in enumerate(transp, 1): index = line.find(word) if index >= 0: return [index + 1, lino, index + len(word), lino] !") Dec. 11, 2020 Forum Price Global Activity ClassRoom Manager Leaderboard Coding games Python programming for beginners
https://py.checkio.org/mission/hidden-word/publications/Lemur21/python-3/first/share/782acfc3567052778cf5efdb4c45781e/
CC-MAIN-2021-39
refinedweb
128
59.3
Plug-in Module Quick Start Extending NetBeans 5 Geertjan Wielenga This document takes you through the basics of using NetBeans IDE 5.0 to develop NetBeans plug-in modules. You develop NetBeans plug-in modules for one of two reasons: • To extend the NetBeans IDE. You can very easily extend the IDE’s functionality with new features. For example, you can write plug-in modules that make your favorite technologies available to the NetBeans IDE. • To build an application on top of the NetBeans Platform. You can use the core of NetBeans as a platform on top of which you develop rich client applications. You can save a lot of development time by reusing features readily available in he platform. Mainly the first scenario above is covered in this tutorial, although the principles addressed here also apply to the second. Here you will create and install a simple NetBeans plug-in module which will add a new menu Plug-in Module Quick Start item and a toolbar button to the IDE. When you select the menu item or toolbar button, a DialogDisplayer, provided by the NetBeans APIs, with the text “I’m plugged in!” will be shown. Setting Up a Plug-in Module Project NetBeans provides a wizard that sets up all the basic files needed for a plug-in module. Creating a NetBeans Plug-in Module Project In NetBeans, choose File|New Project, and under Categories select NetBeans Plug-in Modules. NetBeans plug-in module support provides three project types: • Module Project. Creates a template for a standalone plug-in module. • Library Wrapper Module Project. Creates a plug-in module for an external JAR file required by one or more plug-in modules. • Module Suite Project. Creates a template for a set of interdependent plugin modules and library wrapper modules, which you want to deploy together. Select Module Project and click Next. In the Name and Location panel, type “MyFirstModule” in Project Name. Change the Project Location to any directory on your computer, such as c:\mymodules. Leave the Standalone Module radio button and the Set as Main Project checkbox selected. Click Next. In the Basic Module Configuration panel, replace “yourorghere” in Code Name Base with “myorg”, so that the whole code name base is “org.myorg.myfirstmodule”. Notice that the localizing bundle and the XML layer will be stored in the package org.myorg.myfirstmodule. These files do the following: • Localizing Bundle. Specifies language-specific strings for internationalization. • XML Layer. Registers items such as menus and toolbar buttons in the NetBeans System Filesystem (see the sidebar “Plug-in Module Terms”). Click Finish. The IDE creates the MyFirstModule project, containing all of your sources and project metadata, such as the project’s Ant build script. The project opens in the IDE. You can view its logical structure in the Projects window (Ctrl-1) and its file structure in the Files window (Ctrl-2). See Figure 1. In addition to the localizing bundle and the XML layer, the project also includes the following important files: • Module Manifest. Declares that the project is a plug-in module. In addition, it sets some module-specific settings, such as the location of the XML layer, the location of the localizing bundle, and the module version. • Build Script. Provides a place where you can create your own Ant targets and override those that are specified in nbproject/build-impl.xml. • Project Metadata. Contains information such as the project’s type, contents, platform, classpath, dependencies, and mappings between project commands and targets in Ant scripts. A 1 • NetBeans Platform Config. Contains properties used by the IDE or Platform. • Per-user NetBeans P l a t f o r m C o n f i g Contains properties specific to your installation of the IDE. A Figure 1 Logical structure of the new plug-in module First Edition N 53 Plug-in Development G NetBeans Platform netbeans.org/products/platform For example, if you are sharing the project over VCS, any properties you set in this file are not checked into the repository. You can copy a property from NetBeans Platform Config into this file and give the property different definitions in each file. The definitions in this file take precedence over those in NetBeans Platform Config. You will not need to modify any of these files during this tutorial. Note that the important files shown before are the logical views of the following files in the Files window: manifest.mf, build.xml, nbproject/ project.xml, nbproject/platform.properties, and nbproject/private/ platform-private.properties, respectively. Creating a Menu Item and Toolbar Button You use the NetBeans plug-in module file templates to create the basis of the module’s functionality. When you use a file template, the IDE registers the item that you create in the layer.xml file. After using a wizard to create the file template, you use the Plug-in module terms The basic terms used in plug-in module development are as follows: NetBeans Platform. The skeleton application that provides everything most applications need and little of what they don’t. The NetBeans Platform provides an application’s common requirements – such as menus, document management, and settings – right out of-the-box. Building an application “on top of NetBeans” means that, instead of writing applications from scratch, you only provide the parts of your application that the NetBeans Platform doesn’t already have. At the end of the development cycle, you bundle your application with the NetBeans Platform, saving you time and energy and resulting in a solid, reliable application. System Filesystem. The general registry that contains NetBeans configuration information, built from the layer.xml configuration files of the registered modules. NetBeans stores a wide variety of configuration information in the System Filesystem. For example, the System Filesystem contains a folder called Menu, which contains subfolders with names such as File and Edit. These subfolders contain files that represent Java classes which implement the actions that appear in the File and Edit menus in the IDE. Plug-in Module. A group of Java classes that provides an application with a specific feature. The Java classes use the manifest.mf file to declare the module and the layer.xml configuration file to register their functionality in the System Filesystem. In NetBeans terminology, “plugin” is an adjective while “module” is a noun. There is no discernible difference in meaning between them. NetBeans APIs. The public interfaces and classes which are available to module writers. They are divided into specific APIs for dealing with different types of functionality. The contents and behavior of the Java source packages and its subpackages, as specified in the API reference documentation, are the APIs. Module Suite. A group of interdependent modules that are deployed together. The IDE helps you to brand the suite – for example, you can add a splash screen, and also specify the parts of the NetBeans Platform that you don’t want your application to provide. 54 N NetBeans Magazine Plug-in Module Quick Start NetBeans API List (see links) to continue developing the module. Using the Action Wizard In the Projects window, right-click the project node and choose New>File/Folder. In the New File wizard, choose NetBeans Module Development under Categories, and Action under File Types. Click Next. In the Action Type panel, accept the defaults and again click Next. In the GUI Registration panel, select Global Menu Item, and then Global Toolbar Button. Set the following values: • Category: Tools • Menu: Tools • Position: Tools - HERE - • Toolbar: Build • Position: Run Main Project - HERE - Debug Main Project Select Separator Before and Separator After in the Global Menu Item section. You should now see Figure 2. Note the following about the sections in the GUI Registration panel: A 2 • Category. Specifies where the action will be located in the Keymap section of the Options window. • Global Menu Item. Specifies the menu where the action will be registered as a menu item. The position of the menu item within the existing items in the menu can also be set here. • Global Toolbar Button. Specifies the toolbar where the action will be registered as a button. The position of the toolbar button within the existing buttons in the toolbar can also be set in this section. • Global Keyboard Shortcut. Specifies a key stroke that will invoke the action. • File Type Context Menu Item. Specifies the MIME type of the file type where the menu item will appear. The position of the menu item within the existing menu items and its separators can also be set here. • Editor Context Menu Item. Specifies the MIME type for the editor where the menu item will appear. You can also set here the position of the menu item within the existing menu items and its separators. Click Next. In the Name, Icon, and Location panel, type “MyFirstAction” in Class Name and type “My First Action” in Display Name. In Icon, browse to a 16x16 pixel icon in your filesystem. For example, you can find some 16x16 pixel icons at the following location within your NetBeans IDE 5.0 installation directory: enterprise2\jakarta-tomcat-5.5.9\ server\webapps\admin\images Click Finish. The IDE creates MyFirstAction.java in org.myorg.myfirstmodule and opens it in the Source Editor. Listing 1 shows what you should see. A Figure 2 Plug-in module GUI First Edition N 55 Plug-in Development B Listing 1. Action class registration in layer.xml G NetBeans API List and documentation netbeans.org/download/dev/javadoc A Figure 3 Adding a module dependency As specified in the GUI Registration panel, the IDE registers the action class as a menu item and as a toolbar button in the layer.xml file. See Listing 2. A 3 In the Source Editor, fill out the performAction() method as follows: public void performAction() { String msg = “I’m plugged in!”; NotifyDescriptor d = new NotifyDescriptor.Message( msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(d); } 56 N NetBeans Magazine Plug-in Module Quick Start The line with the calls to NotifyDescriptor and Dialog Displayer are underlined and marked as an error. This is because the related packages have not been declared yet. In the Projects window, right-click the MyFirstModule project node and choose Properties. In the Libraries pane, click Add. Type “notifyd” and notice that the returned list narrows until the package that contains “NotifyDescriptor” is displayed (see Figure 3). Click OK. The Dialogs API is added to the Module Dependencies list. Click OK to confirm and exit the Project Properties dialog box. In the Source Editor, click Alt-Shift-F. Two new import statements are added to the top of the source file and the red underlining disappears: import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; The plug-in module is now complete. Next, you need to install and use it. A 4 Installing and Using the Plug-in Module The IDE uses an Ant build script to build and install your plug-in module. The build script is created for you when you create the plug-in module project. A Figure 4 The new menu item for the plug-in module Installing the Plug-in Module In the Projects window, right-click the MyFirstModule project and choose Install/Reload in Target Platform. The plug-in module is built and installed in the target platform. The target platform is set in Tools>NetBeans Platform Manager. The target platform opens so that you can try out your new plug-in module. The default target IDE or Platform is the installation used by the current instance of the development IDE. A 5 A 6 Using the Plug-in Module In the newly opened IDE’s menu bar, you should see the new menu and menu item, together with the icon you specified in the Action wizard; see Figure 4. Choose the menu item to invoke the performAction() method in MyFirstAction.java. You should see the JOptionPane with its message, as shown in Figure 5. Click the toolbar button. It calls the same action and so has the same result. It should look something like Figure 6. Summary This tutorial showed how to create a simple plug-in module project, including a new menu item and a toolbar button. You also saw how to install and use the new module. N A Figure 5 The plug-in module in action A Figure 6 New toolbar button for t First Edition N 57
https://www.yumpu.com/en/document/view/34327340/plug-in-netbeans
CC-MAIN-2019-26
refinedweb
2,075
57.27
If you were to broadly characterize the source code of C and C++ programs, you might say that a C program is a set of functions and data types, and that a C++ program is a set of functions and classes. A C# program, however, is a set of type declarations. The source code of a C# program or DLL is a set of one or more type declarations. For an executable, one of the types declared must be a class that includes a method called Main. A namespace is a way of grouping a related set of type declarations and giving the group a name. Since your program is a related set of type declarations, you will generally declare your program inside a namespace you create. For example, ... No credit card required
https://www.safaribooksonline.com/library/view/illustrated-c-2008/9781590599549/ch03.html
CC-MAIN-2018-17
refinedweb
133
69.11
Windows. Windows Scripting is great – you can send an email containing a script, and have it send itself out to everyone in the recipients’s address book. Plus it has everyhing you need for install a "remote admin" kit at the recipient – e.g. Filesystem and Registry access. And if you want to just nuke the machine, you can find out enough to do that without getting caught. Can you get access for to the sockets for DDos attacks? That’s the only feature missing IMO. Just like binary exe’s then!! The fact that I can use a screwdriver to severely injure anyone I can get within arm’s reach of does not lessen its usefulness as a scewdriver. I think the real issue is: where is Raymond vacationing this time? Please don’t feed the troll. Tim Golden wrote a module to wrap this. It also needs Mark Hammond’s Win32 extension module. There’s a nifty list of examples at: I stumbled on this when I was trying to enumerate the TCP/IP interfaces for a Windows Box. If you wish to enumerate the network interfaces, you can just use GetNetworkParams, GetAdaptersInfo and GetNumverOfInterfaces from iphlpapi.dll. It’s pretty straight forward to use and works like a charm. Brian – I think our troll is just jealous because his favorite OS has nothing like it. I would venture that the troll’s favorite OS does have the ability to query all that stuff, but it’s just not packaged the same way. Not running a script embedded in an email by default could be argued to be a deliberate design system. Oh, and to troll a bit on my own, I went looking on msdn, but I couldn’t for the life of me find out how to run a service in a chroot jail. My favourite OS can query that stuff and with rather less typing: Welcome to Darwin! james$ sysctl hw hw.ncpu: 2 hw.byteorder: 4321 hw.memsize: 1073741824 hw.activecpu: 2 hw.cputype: 18 hw.cpusubtype: 11 hw.pagesize: 4096 hw.busfrequency: 166635063 hw.busfrequency_min: 166635063 hw.busfrequency_max: 166635063 hw.cpufrequency: 999999996 hw.cpufrequency_min: 999999996 hw.cpufrequency_max: 999999996 hw.cachelinesize: 32 hw.l1icachesize: 32768 hw.l1dcachesize: 32768 hw.l2cachesize: 262144 hw.l3cachesize: 1048576 hw.tbfrequency: 41656341 hw.optional.floatingpoint: 1 hw.optional.altivec: 1 hw.optional.graphicsops: 1 hw.optional.stfiwx: 1 hw.optional.dcba: 0 hw.optional.datastreams: 1 james$ Not trolling but it just seems like more work than it needs to be. The SQL style query is cute though! WMI is a great way of getting data that has been available for 5 to 10 years via SMBIOS or Win32 APIs like GlobalMemoryStatus(Ex). And it can be called from scripts which is a good thing. But it still can’t tell me the temperature of my CPU, or how fast the fans are running, or the power supply voltages, or a lot of other configuration data. I really wish Microsoft would lock the hardware guys in a room at WinHEC and not let them out until they’d agreed to expose that information in a standard way. ;) "I really wish Microsoft would lock the hardware guys in a room at WinHEC and not let them out until they’d agreed to expose that information in a standard way." Maybe the Linux folks could take the lead here and do this at the next Linux hardware conference? Video drivers are so complicated these days I prefer to treat them as black boxes that either "work" or "don’t work." Don’t complain about Linux. We can’t threaten a hardware manufacturer that their products won’t be supported by Linux, they don’t care. Whereas MS carries more weight. (check out the recent video by Alan Cox discussing debugging techniques; they traced a very rare crash to a problem in a certain ATA disk; the disk manufacturer didn’t listen until MS approached them much later about the exact same problem) I read the tweakomatic documentation some months ago. it really is hillarious you should all check it out: Quotes follow: ." […] Tweakomatic is Fully Guaranteed and Supported, Right? Hey, let’s be serious. This thing is called Tweakomatic. Can you imagine this scenario: “Microsoft Product Support. How may I help you?” “Uh, yes, I seem to be having some problems with my Tweakomatic.” […] ." Win32_Processor is not available on Windows 95, Windows 98 and Windows ME – which is what about half of our customers still run :( Cooney: About that fake filesystem, check out Monad over at. Now, look very carefully at the providers (like filesystems, registry etc.) ;) "I really wish Microsoft would lock the hardware guys in a room at WinHEC and not let them out until they’d agreed to expose that information in a standard way." Seems like they already did that, but your computer needs to support that standard. Check out, which is what WMI implements. I know Dell ships an addon for exposing such information, maybe you can find something like that for your computer as well? Btw. Haven’t tested this yet, but seems like there is an implementation of WBEM for Linux and other operating systems too. See. Anyone here who knows more about it? Finally, a nice quote from the WBEM FAQ of their goal with it: "The ultimate objective is to provide customers with the ability to manage all systems, regardless of their instrumentation type, using a common standard." Andreas: I’ll check that clip out. Raymond, why are you posting? I thought you were off on vacation. Can’t you designate a deputy? James, the SQL queries IS the feature of WMI. For example to get an info about a running process you just run "SELECT * FROM Win32_Process WHERE Name='<process name>’", instead of looking up the PID and then looking up all the information scattered around the system API (which is what you have to do in Win9x and other, non-win systems). Strangely, I wasn’t able to use other properties in the WHERE clause, only Name worked. Another nice thing to know about is wmic.exe (on Windows XP, maybe other versions of Windows as well?), which let’s you execute queries without having to write a script or something similar. See some info about wmic.exe at Don Box’s old blog. "The fact that I can use a screwdriver to severely injure anyone I can get within arm’s reach of does not lessen its usefulness as a scewdriver." Of course, but the fact that you can use other people’s screwdrivers to cause harm to other people is a bit of a problem. I agree that the information at is very well presented. I used to consider WMI as one of the "don’t touch" items in Windows, now I’m thinking of using it to automate some monitoring related activities. Jerry – the SQL stuff does look a nice way of doing things. Having a single port of call for extracting all sorts of information rather than a whole bunch of API calls sounds good to me. (As does Linux’s procfs and BSD’s sysctl namespace ;) ) I had a look to see how far back WMI is supported and was pleasantly surprised to see that MSDN says that WMI is available as a download for 9x so it looks like they can play along too. "Don’t get too excited. At least on my machine, most of these seem not to be implemented. Try it on your machine. " Believe me, I’ve tried it on dozens of systems. Those WMI classes are defined, yes, but they don’t give meaningful data. Incidentally, almost all of the information in msinfo32 can be found in the WMI schema. So things you see there can be retrieved using a script and WMI. >> If you wish to enumerate the network interfaces… Those network interface APIs mentioned above are a good example of one reason I try to avoid using WMI when possible. WMI is implemented as a Service, and that service can be turned off. The Win32 APIs in question cannot be turned off. So if you absolutely require some piece of configuration information for your program to operate properly, I recommend trying to find a straight Win32 API to get it before going to WMI. That having been said, WMI is a great resource. There are also some things you can do with it that you *can’t* easily do with Win32 APIs, like retrieve Event Log messages from a remote machine *asynchronously* as they occur. watch out for WMI though, it sometimes doesn’t tell the truth even when the method claims to be implemented on a particular system. Try comparing the values stored in Win32_CPU with the values in HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" One sure way of determining where a WMI provider gets its information from is through the MappingStrings qualifier. I’ve just checked through a number of properties on the Win32_Processor management class against what’s in the registry. Many of the properties don’t seem to have documented where the provider gets its values from which is unfortunate. It worth noting that many of the Microsoft management classes have made good use of the MappingStrings qualifier! Just not this class by the looks of it… If you’re unfamiliar about the MappingStrings qualifier, then check this link () which is a couple of pages I wrote a while ago… WMI looks neat, but AFAICS the information can’t be accessed from other platforms. So we’re using NRPE for NT. It would be nice if there was a version that ran over HTTP, as specified in the standard. Cooney: ;)" Isn’t that the way *nix works? ;) Everything is a file. Any chance this is broken? I have a bunch of C# code that calls System.Management classes, and I noticed today that none of it is working; I get various exceptions. So, in hunting down the problem, I found this blog entry. Sure enough, I cannot get this piece of WSH code to run, either. My main suspects are XP SP2 and .NET Framework 1.1 SP1. Is anyone else having a similar problem? Or have I simply ‘broken’ WMI on my machine somehow? I was once told that very detailed information is in WMI including numbers of words typed and total applicaiton run time for apps like office but I can not find it. Is there a way that you can dump tons of info from WMI. I looked through the MOF file but could find nothing
https://blogs.msdn.microsoft.com/oldnewthing/20041021-00/?p=37513/
CC-MAIN-2017-09
refinedweb
1,776
75
#!/usr/bin/perl use strict; use warnings; my $num_columns = 4; my @cat = (15, 15, 10, 10, 15, 15); my @ans = squish(@cat); print "@ans\n"; sub squish { my @arr = @_; my @aoa = (\@arr); for ($num_columns..(@arr-1)) { my @tmp_aoa; push @tmp_aoa, squisher(@$_) for @aoa; @aoa = @tmp_aoa; } my $best_ans; my $best_value; for my $aref (@aoa) { my $max_value; for my $value (@$aref) { $max_value = $value if !defined $max_value or $value > $max_valu +e; } $best_ans = $aref, $best_value = $max_value if !defined $best_value or $max_value < $best_value; } @$best_ans; } sub squisher { my @arr = @_; my $min_col; my $min_value; for (0..$#arr) { $min_value = $arr[$_], $min_col = $_ if !defined $min_value or $arr[$_] < $min_value; } my @arr1 = ($min_col > 0) ? @arr : (); my @arr2 = ($min_col < $#arr) ? @arr : (); splice(@arr1, $min_col-1, 2, $arr1[$min_col-1] + $arr1[$min_col]) if @arr1; splice(@arr2, $min_col, 2, $arr2[$min_col] + $arr2[$min_col+1]) if @arr2; return ((@arr1 ? \@arr1 : ()), (@arr2 ? \@arr2 : ())); } [download] In reply to Re: Puzzle: need a more general algorithm by runrig in thread Puzzle: need a more general algorithm
http://www.perlmonks.org/index.pl/jacques?parent=180373;node_id=3333
CC-MAIN-2015-48
refinedweb
164
55.13
Details Description As far as I can tell nothing actually uses the hash codes generated by these methods (not even any tests). If someone did want to generate a hash, it would be just as fast to do it on the BytesRef after the fact (or even faster from the input number itself). edit: Uwe pointed out they were used in one place. Other places still don't need it. Activity - All - Work Log - History - Activity - Transitions An additional cool little hack... even though it's much improved, IDIV still has a latency of 18-42 cycles on a core2 processor. One equivalent of i/7 is (i*37)>>8 for i in 0..63. This only takes 4 cycles. Curious, how do you know that and/or measure that? Curious, how do you know that and/or measure that? The number of cycles? It's all documented in various places. Of course one needs a good sense of what assembly a compiler/hotspot will emit. Integer multiply has been 3 cycles for quite a while for both Intel and AMD, and shifts have been a single cycle (after the ill-fated P4). As far as I can tell nothing actually uses the hash codes generated by these methods (not even any tests). The return value (the hash) is used by NumericTokenStreeam#NumericTermAttribute.fillBytesRef(): @Override public int fillBytesRef() { try { assert valueSize == 64 || valueSize == 32; return (valueSize == 64) ? NumericUtils.longToPrefixCoded(value, shift, bytes) : NumericUtils.intToPrefixCoded((int) value, shift, bytes); } catch (IllegalArgumentException iae) { // return empty token before first or after last bytes.length = 0; return 0; } } Other comments: - The masking away of invalid shifts is a no-go to me. This leads to unexpected behaviour. - A agree grow() does not need to be used for this stuff. We can simply reallocate, as we know size exactly. By the way, your patch above would corrumpt the IAE case in fillBytesRef used by indexer. The return value (the hash) is used by NumericTokenStreeam#NumericTermAttribute.fillBytesRef(): Ahh, I didn't see it because the use of the value is on a separate line from the method call. Makes it hard to find. Here's a patch that doubles the performance of NumericUtils.*ToPrefixCoded Seems good to me to have non-hashing versions (these versions exist for unicodeutil for terms already for similar purposes) [trunk commit] Yonik Seeley LUCENE-4690: Performance improvements and non-hashing versions of NumericUtils.*ToPrefixCoded [branch_4x commit] Yonik Seeley LUCENE-4690: Performance improvements a non-hashing versions of NumericUtils.*ToPrefixCoded Thanks, Yonik! Closed after release. Current code: Proposed code template (i.e. for all of the *ToPrefixCoded methods): Some of the changes: 1. grow over-allocates all the time. Most of the time (like here) it's wasted space. 2. grow copies the previous buffer when allocating a bigger buffer. This is wasted/unneeded here.
https://issues.apache.org/jira/browse/LUCENE-4690
CC-MAIN-2017-09
refinedweb
473
59.8
I've got a simple bunch of custom template tags in my Django project that I've been using on my site for a while now without problems. However, now that I'm trying out PyCharm, I find that it's complaining that these template tags can't be found. Specifically, the error I'm getting when I mouseover the {% load hacks %} tag is: "Unresolved library: 'hacks'". Here's what I've got: /mysite appname/ __init__.py templatetags/ hacks.py # contains a function called "flaturl" templates/ mytemplate.html # hacks.py from django import template register = template.Library() @register.simple_tag def flaturl(title): # Some magic return "some string" # mytemplate.html {% load hacks %} {% flaturl 'About' %} PyCharm complains that hacks can't be resolved, and neither can flaturl. Did I do something wrong? From the looks of this ticket: it should work... right? Hello Daniel, The way PyCharm resolves custom tag libraries is by looking at the INSTALLED_APPS setting in settings.py, appending ".templatetags" to each of the app names, and trying to find such a file in the project. So, everything should work as long as you have the correct settings.py selected in Settings | Django Support and you aren't doing anything fancy to build the list of installed apps dynamically. -- Dmitry Jemerov Development Lead JetBrains, Inc. "Develop with Pleasure!" Hi Daniel, templatetags directory should be Python package, so make sure you have __init__.py there. Adding to that what Dmitry has said everything should work fine. That's the thing, I have the app in INSTALLED_APPS (It's called "core") and the templatetags directory is inside that directory. Both "core" and "templatetags" have an __init__.py file, which of course they'd have to, since Django executes the template tag with no problems at all. Here is the cropped portion of my directory tree. ./oxyor/core ./oxyor/core/templatetags ./oxyor/core/templatetags/__init__.py ./oxyor/core/templatetags/hacks.py ./oxyor/core/views.py ./oxyor/core/fixtures ./oxyor/core/fixtures/initial_data.json ./oxyor/core/__init__.py ./oxyor/core/context_processors.py ./oxyor/core/models.py ./oxyor/core/admin.py ./oxyor/core/forms.py ./oxyor/core/helpers.py ./oxyor/core/fields.py ./oxyor/manage.py ./oxyor/settings.py ./templates ./templates/index.html I guess what I don't understand is how Django can find the templatetag and use it properly, but PyCharm can't. I feel like I've misconfigured something, or I'm storing my files in a non-standard way... hence my questions here. Daniel, What version of PyCharm are you using? If you can create a small demo of this behavior (in its own project) and send to me, I can try to help you out with this. I've created custom tags and they seem to resolve fine. Let me know.. Christian This is good to know. Is it possible that a minor release of PyCharm could support dynamic INSTALLED_APPS settings? I use a generic project that I release as open source, which contains appropriate settings for the project including INSTALLED_APPS, then I have a proprietary repository that has deployment-specific settings file that imports from the generic settings, as well as development-specific settings that imports from the generic settings and also adds to INSTALLED_APPS. In the meantime, for my variation of this problem, I can confirm that I can use custom template tags by placing a tuple-of-strings declaration in INSTALLED_APPS for the settings.py that I'm pointing PyCharm to. This ironically adds another point of maintenance and duplication, which I am using PyCharm to help me avoid. :-) Hello Matthew, Please file a YouTrack issue and provide the code that you use to build the list of INSTALLED_APPS. Supporting all ways to define the list dynamically would essentially require us to implement a full Python interpreter, which we don't currently plan to do, but specific cases can probably be supported. -- Dmitry Jemerov Development Lead JetBrains, Inc. "Develop with Pleasure!" In an effort to post a simplified copy of my project with the problem, I appear to have inadvertently solved it. I make a number of changes to settings.py, and one of them, though I have no idea which (sorry) seems to have solved the issue. Sorry to bother you guys, but I wanted to let you know that it appears to be a PEBKAC issue. Great job on PyCharm.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/205805119-How-to-make-custom-template-tags-resolve
CC-MAIN-2020-10
refinedweb
726
57.06
IoT Weighing Scale Project Description:. Later in this tutorial, I will explain why I am using Arduino with the Nodemcu ESP8266 Wifi Module. With this DIY low-cost IoT Weighing Scale, you can measure and monitor weights from anywhere around the world. For the demonstration purposes, I am using some known weights 50 grams, 100 grams, 200 grams, and 1 Kg. This is my 3rd tutorial on the HX711 and load cell which explains how to use the Wifi technology to make an IoT based Weighing Scale. While in my previous two tutorials, I explained the basics, like for example what is HX711, Soldering, Interfacing and the Load Cell or Strain Gauge calibration. I highly recommend you should read my previous two tutorials and then you can resume from here because this tutorial is entirely based on my previous two tutorials. I will modify the previous program and I will also explain how to establish the Serial communication between the Arduino and Nodemcu ESP8266 Wifi module and then how to display the weight information on the 16×2 LCD widget. Previous tutorials: - HX711 Load cell or Strain Gauge and Arduino. - Arduino HX711 and Load Cell Weight Measurement and Calibration. Without any further delay, let’s get started!!! Amazon Links: HX711 Load cell / Strain Gauge:! Making of the Weighing Scale Machine: I salvaged this thing from an old scale. I am going to replace this old load cell with the new one which you can see in the picture below. In this project, I am using a 5kg load cell or strain gauge. While fixing the load cell make sure the arrowhead is in the downward direction. As you can see the load cell is fixed and the arrowhead points in the downward direction. Finally, I fixed a steel plate. Which is explained in the video given at the end of this article. These are some known weights, which I will be using during the demonstration. 50 grams, 100 grams, 200 grams, and 1Kg. Now let’s have a look at the complete connection diagram of the IoT weighing Scale. IoT Weighing Scale Circuit Diagram: The DC female power jack positive leg is connected with the input leg of the LM7805 voltage regulator. The ground leg of the DC female power jack is connected with the middle leg of the 7805 voltage regulator. The output leg of the voltage regulator is connected with the Vin pin of the Nodemcu ESP8266 Wifi module and the ground of the 5 volts regulated power supply is connected with the Gnd pin of the Nodemcu module. This 5 volts regulated power supply is used to power up the Nodemcu module. A 330-ohm resistor is connected in series with the 2.5 volts LED. This is a current limiting resistor. The purpose of this LED is to let you know that the power supply is turned ON. Two 470uf capacitors are connected at the input and output sides of the LM7805 voltage regulator. The Tx and Rx pins of the Nodemcu module are connected with the Arduino’s pin number 7 and pin number 8. Make sure you connect the ground of the Nodemcu module with the ground of the Arduino. A Load cell or Strain gauge has 4 wires, the red wire of the load cell is connected with the E+, Black wire is connected with the E-, the White wire is connected with the A-, and green wire of the load cell or strain gauge is connected with the A+ of the HX711 board. The HX711 is a 24 bit analog to digital converter “ADC”. Which has an amplifier, that gives a maximum gain of 128 as per the Datasheet. The Gnd of the HX711 is connected with the Arduino’s ground, the DT pin of the HX711 is connected with the Arduino’s pin number 3, the SCK pin is connected with the Arduino’s pin number 2, and the VCC pin of the HX711 breakout board is connected with the Arduino’s 5 volts. This is the PCB board designed for the Nodemcu Module, the PCB board designing and soldering is already explained in my previous tutorial. Watch the following video. The final Nodemcu ESP8266 power supply board can be seen in the picture below. About the PCBWay: The PCB board used in this project High quality & Only 24 Hours Build time: Interfacing HX711 & Nodemcu with Arduino: All the components are interfaced as per the connections diagram already explained. The 4 wires coming from the load cell or strain gauge are connected with the HX711 board which is also connected with the Arduino. The Arduino is also connected with the Nodemcu ESP8266 Wifi Module. The Arduino communicates serially with the Nodemcu Module. You can make this IoT based Weighing Scale using only the Nodemcu Module, but the reason I have added the Arduino board is if in case you want to add an LCD or a keypad, etc. To reduce the size you can also use Arduino Nano. Now let’s make the Blynk application. IoT Weighing Scale Blynk Application: For the step by step Blynk application explanation watch video available at the end of this article or you can follow the following steps. - First of all, open the blynk application. - Click on the new project. - Enter the project name as “iot weighing scale” or any other name which you like. - Click on the choose device and select Nodemcu. - In the connection, type select Wifi and then click on the create button. An authentication token will be sent on your email id. Copy the authentication token and paste it in the programming as explained in the video. - Click on the screen and search for the LCD widget and add it. - Click on the LCD, select the input type as the advanced. - Click on the Pin and select virtual pin V2. That’s it the application is ready. IoT Weighing Scale Programming: In this project two programs are used, one program is written for the Arduino, while the other program is written for the Nodemcu ESP8266 Wifi Module. All the libraries used in this project can be downloaded by clicking on the link given below. IoT Weighing Scale Arduino Programming: Arduino program explanation: This is basically the same program I used in my previous two tutorials, this time I made a few changes. I added the SoftwareSerial and stdlib libraries, created a Serial Port for the Nodemcu module, defined some variables while the calibration factor value remains the same. In the void setup function, I activated the serial communication, while the other instructions remain the same. In the void loop function, I added the dtostrf() function to convert the Float value into the String value. Then I created a complete message and finally using the println function the complete message is sent to the Nodemcu module and also to the serial monitor for the debugging purposes. Now let’s have a look at the Nodemcu programming. IoT Weighing Scale Nodemcu ESP8266 Programming: Nodemcu ESP8266 program explanation: #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <SoftwareSerial.h> #include <SimpleTimer.h> These are the same libraries I have been using in all of my Nodemcu based projects. WidgetLCD lcd(V2); Data to the LCD widget is sent through the virtual pin V2. char auth[] = “jQkA7IneoZOlBxyPKUjQ0n71d7pwHVCh”; This is the authentication token, which was sent via email, I simply copied and paste it over here. char ssid[] = “ZONG MBB-E8231-6E63”; char pass[] = “electroniclinic”; These are the wifi credentials, the router name which is the ssid and the password. SimpleTimer timer; String myString; // complete message from arduino, which consistors of snesors data char rdata; // received charactors String weight; int firstVal; I defined some variables. void myTimerEvent() { // You can send any value at any time. // Please don’t send more that 10 values per second. Blynk.virtualWrite(V1, millis() / 1000); } The mytimerevent function is already explained in my previous iot based projects. The void setup function remains the same. If the Nodemcu module has not received any data from the Arduino, then simply keep executing the blynk.run() and timer.run() functions. If the Nodemcu module has received data from the Arduino then read the serial port, add the received character with the myString variable. if( rdata == ‘\n’) This condition makes sure that the entire message is received. Then using the getvalue function the string is split. And then finally, the weight information is sent to the blynk application. Getvalue is a user-defined function that is used to split the string message using any character as the delimiter, in my case I have used a comma as the delimiter. So, that’s all about the programming. For the practical demonstration watch video given below. Don’t forget to Subscribe to my website and YouTube channel “electronic clinic”. Support my website and YouTube channel by sharing and liking the video. If you have any questions let me know in a comment. Watch Video Tutorial: 2 Comments Any program only use Blynk in Nodemcu connect to connect load cell .any program have you 2 load cell how to use the program
https://www.electroniclinic.com/diy-iot-weighing-scale-using-hx711-load-cell-nodemcu-esp8266-arduino/
CC-MAIN-2021-25
refinedweb
1,522
63.8
Next: crypt, Previous: Legal Problems, Up: Cryptographic Functions When reading in a password, it is desirable to avoid displaying it on the screen, to help keep it secret. The following function handles this in a convenient way. Preliminary: | MT-Unsafe term | AS-Unsafe heap lock corrupt | AC-Unsafe term lock corrupt | See POSIX Safety Concepts. getpassoutputs prompt, then reads a string in from the terminal without echoing it. It tries to connect to the real terminal, /dev/tty, if possible, to encourage users not to put plaintext passwords in files; otherwise, it uses stdinand stderr. getpassalso disables the INTR, QUIT, and SUSP characters on the terminal using the ISIGterminal attribute (see Local Modes). The terminal is flushed before and after getpass, so that characters of a mistyped password are not accidentally visible. In other C libraries, getpassmay only return the first PASS_MAXbytes of a password. The GNU C Library has no limit, so PASS_MAXis undefined. The prototype for this function is in unistd.h. PASS_MAXwould be defined in limits.h. This precise set of operations may not suit all possible situations. In this case, it is recommended that users write their own getpass substitute. For instance, a very simple substitute is as follows: #include <termios.h> #include <stdio.h> ssize_t my_getpass (char **lineptr, size_t *n, FILE *stream) { struct termios old, new; int nread; /* Turn echoing off and fail if we can't. */ if (tcgetattr (fileno (stream), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stream), TCSAFLUSH, &new) != 0) return -1; /* Read the password. */ nread = getline (lineptr, n, stream); /* Restore terminal. */ (void) tcsetattr (fileno (stream), TCSAFLUSH, &old); return nread; } The substitute takes the same parameters as getline (see Line Input); the user must print any prompt desired.
http://www.gnu.org/software/libc/manual/html_node/getpass.html
CC-MAIN-2014-15
refinedweb
290
58.58
Since Spring 3 a new abstraction layer for caching services has been introduced called Cache Abstraction. The idea is to provide a set of common features, mainly annotations, to activate and manage the caches. Cache Abstraction is nothing but applying caching to Java methods, reducing thus the number of executions based on the information available in the cache. That is, each time a targeted method is invoked, the abstraction will apply a caching behavior checking whether the method has been already executed for the given arguments. - If yes, then the cached result is returned without having to execute the actual method. - If no, then method is executed, the result cached and returned to the user so that, the next time the method is invoked, the cached result is returned. As the name implies, Cache Abstraction is not an actual implementation. Hence it requires the use of an actual storage to store the cache data. Ehcache support is provided out of the box. There is also an implementation based on JDK’s ConcurrentMap and you can actually plug-in different back-end caches. - Spring Tutorials ( Collection for Spring reference tutorials) - Spring Framework Interview Questions - Introduction to Spring LDAP - How to write Custom Spring Callback Methods? Annotation based Caching For caching declaration, the abstraction provides following Java annotations: - @Cacheable: put the method returned value(s) into the cache. - @CacheEvict: remove an entry from the cache. - @CachePut: force a cache entry to be updated. - @Caching: @Caching allows multiple nested @Cacheable, @CachePut and @CacheEvict to be used on the same method. Enable caching annotations Caching feature needs to be declaratively enabled by using either of following ways: - Add the annotation @EnableCaching to one of your @Configuration classes. - Alternatively for XML configuration use the cache:annotation-driven element. @Cacheable annotation In Spring @Cacheable is useful in the case when a very complex code is running for many times. @Cacheable caches the result per input values of methods, so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method. Spring handles this functionality by second level cache. @Cacheable is used in the code as shown below: @Cacheable("product") public String getProduct(int productId){} @CacheEvict annotation The cache abstraction allows not just population of a cache store but also eviction i.e removes data from the cache. @CacheEvict in spring is used to evict cache value. @CacheEvict is applied on the method. This annotation has an extra parameter allEntries which indicates whether a cache-wide eviction needs to be performed rather then just an entry one (based on the key): @CacheEvict(value = "product", allEntries=true) public void setProduct(int productId){} This option comes in handy when an entire cache region needs to be cleared out – rather then evicting each entry (which would take a long time since it is inefficient), all the entires are removed in one operation as shown above. Example for @Cacheable and @CacheEvict The following example demonstrates the use of the @Cacheable and @CacheEvict annotations and enabling them in the Spring application. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application: - Create a project: Create a project with a name SpringCacheAbstraction and create a package com.javabeat under the src directory in the created project. - Add Libraries: Add required Spring libraries using Add External JARs option as explained in the article Customizing callback methods. Along with te specified JARs in the link, also add make sure these JARs are in the buildpath of the project:aopalliance-x.0.jar, ehcache-x.x.0.jar(you can download latest ehcache.jar from here: ) - Create source files: Create Java classes Product,and MainApp under the com.javabeat package. - Create configuration file: Create XML based configuration file Beans.xml and ehcache.xml under src directory. Contents of Product.java are as below: package com.javabeat; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; public class Product { @CacheEvict(value = "prod", allEntries = true) public void setProduct(int productId) { System.out.println("execute setProduct method.."); } @Cacheable("prod") public String getProduct(int productId) { System.out.println("execute getProduct method.."); if (productId == 1) { return "Product A"; } else { return "Product B"; } } } Contents of MainApp.java are as below: package com.javabeat; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String... args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "Beans.xml"); Product product = (Product) context.getBean("product"); // calling getProduct method first time. System.out.println(product.getProduct(1)); // calling getProduct method second time. This time, method will not // execute. System.out.println(product.getProduct(1)); // calling setProduct method to evict the cache value product.setProduct(1); // calling getProduct method third time. This time, method will execute // again. System.out.println(product.getProduct(1)); } } There is a method getProduct in the class Product. We have called it three times. First time getProduct methods runs and sets result in cache named prod. Second time getProduct does not run because there is value in cache. Now call setProduct to remove the cache value. Again run getProduct method . This method will run because cache value is empty because of eviction. Contents of Beans.xml are as below: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <cache:annotation-driven /> <bean id="product" class="com.javabeat.Product"> </bean> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p: <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p: </beans> To get @Cacheable our result we have to configure org.springframework.cache.ehcache.EhCacheCacheManager in Beans xml as seen above. All second level configuration properties are configured in an ehcache.xml and that xml file is configured in Beans.xml as seen above. Contents of ehcache.xml are as below: <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns: <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" /> <cache name="prod" maxElementsInMemory="10000" eternal="true" overflowToDisk="false" /> </ehcache> Cache name has been declared as which is used in the Product.java class for caching result of the method. Execute Once all the code is ready, execute the MainApp class and if everythingis fine, the following output should appear on the console: execute getProduct method.. Product A Product A execute setProduct method.. execute getProduct method.. Product A Summary In this post we saw the basics of Cache Abstraction in Spring. An example is used to demostrate the use of @Cacheable and @CacheEvict. In the next post I shall cover some other feature of the Spring. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook Speak Your Mind
http://www.javabeat.net/cache-abstraction-spring-cacheable-cacheevict/
CC-MAIN-2015-14
refinedweb
1,106
51.24
Web Services FAQ Section Index | Page 25 How can I convert the .txt files to xml document? Are there any reliable softwares available, or can I do it with the help of Java? Windows .txt files are files that contain human readable ascii text. There is no further structure to it. XML files are also human readable but reflect natural structure in the file's data. Unf...more Is there a mailing list for discussion of XML technologies with the Java platform? Sun manages the XML-INTEREST list. You can signup and read the archives at. There are also the Apache XML mailing lists. See XSL: I get namespace attributes showing up all over my result document. How do I get rid of them? If you include a namespace in the root element of your source document, a spec-compliant XSLT processor is supposed to duplicate it into the resulting document. This is often not what you want. T...more Where can I get the specifications? So XML represents data content, what about data presentation? Stylesheets are used to present XML. A stylesheet describes how to present data. The description is separate from the data. The Cascading Stylesheet Specification (CSS) is a language for associat...more What are Xbeans? An Xbean is a software component that takes XML as input, processes it in some fashion and then passes XML on to the next Xbean. Xbeans are Java Beans. Java Bean technology supports the packaging...more From which languages can I use the DOM? The DOM is actually specified in a language independent fashion using OMG IDL. Thus, in theory any language for which there is an IDL binding could be supported. In practice, Java is the most popu...more Where can I get an XML->DOM parser? IBM's Alphaworks site has XML parsers written in Java and C++. Both produce DOM trees. Sun's project X also has an XML parser written in Java. It produces a DOM trees. There are also various ope...more What is the DOM? The DOM stands for the Document Object Model. It defines a programmatic API for accessing XML documents. The XML document is represented as a tree. Using the DOM API, a programmer can construct, q...more Who's defining standard DTDs? What are these x MLs anyway? Who's defining standard DTDs? What are these xMLs anyway? What is XML good for? XML is good for representing data in a vendor neutral format. It is a good format for exchanging data between software systems. It separates the content of the data from the presentation of it.more
http://www.jguru.com/faq/web-services?page=25
CC-MAIN-2019-04
refinedweb
436
70.9
I need to make a script tool that will consolidate attributes from many rows into to one across a number of columns. The tool will need to be able to let the user select the field "key" field as well as the fields that will be consolidated. I made a quick mockup table as my input table (it has been processed with spatial sort so that parts of the key features that are spatially adjacent to each other are also in adjacent rows in the table). Mockup table. It has land ownership and PLSS (Public Land Survey System) MTRS (meridian township range section) information. The output should look like this. The question: I would like input on the best method to get the result. And if there are any out of the box Arc tools that I could leverage... My first pass at this was to use arcpy.da.SearchCursor and iterate over the input table and check to see if the current row's key feature is the same as the previous row's key feature. If so, then add it to a string variable. When the key features do not match write the string variable and other fields to the output file. The MTRS roll up is a little more complex because sections needs to rolled up for each unique MTR associated with the key feature. It feels a little wired because you are always looking back in rows as you iterate over the table. So, I used a number of temp_last variables for key features, MTRS, etc. I was thinking that it would be better to read the whole table into a list of lists and then use that to generate the output. That way I could use indexing to look at the next and last rows without having to use the temp_last variables. The below code I made for a similar one off. import arcpy import os arcpy.env.overwriteOutput = True in_path = r"xxxx" out_path ="xxxx" def tsv_write(tsv_row): for item in tsv_row: tsv.write(item + "\t") tsv.write("\n") def rollup(rollup_list): rollup_list = set(rollup_list) rollup_list = list(rollup_list) rollup_list.sort() rollup_str = "" for sec in rollup_list: rollup_str = rollup_str + str(sec) + ", " rollup_str = rollup_str[:-2] return rollup_str def from_to_fix(x): x = round(x, 1) x = str(x) return x search_cursor = arcpy.da.SearchCursor(in_path, ["Main_LandOwnership_MTRS_Mbook_Meridian", "Main_LandOwnership_MTRS_Mbook_Town_Range", "Main_LandOwnership_MTRS_Mbook_SECTION", "Main_LandOwnership_MTRS_Mbook_F_MP", "Main_LandOwnership_MTRS_Mbook_T_MP", "Main_LandOwnership_MTRS_Mbook_Index_Order", "Main_LandOwnership_MTRS_Mbook_ROW_Designation"]) tsv = open(out_path, "w") meridian_last = None township_last = None f_mile_last = None t_mile_last = None owner_last = None township_list = [] township_section_list = [] first_row_flag = True township_append_flag = True section_list = [] index_order_list = [] for row in search_cursor: meridian = row[0] township = row[1] section = row[2] f_mile = row[3] t_mile = row[4] index_order = row[5] owner = row[6] if first_row_flag: township_last = township f_mile_last = f_mile t_mile_last = t_mile owner_last = owner first_row_flag = False if township == township_last: township_append_flag = True section_list.append(int(section)) else: township_append_flag = False section_rollup = rollup(section_list) township_section_list.append(township_last + ": " + section_rollup) section_list = [] section_list.append(int(section)) if f_mile == f_mile_last: index_order_list.append(int(index_order)) else:_last, index_order_rollup]) else: print ["", "", trs, "", ""] tsv_write(["", "", trs, "", ""]) township_section_list = [] index_order_list = [] index_order_list.append(index_order) if meridian != meridian_last: print meridian tsv_write([meridian]) print ["From MP", "To MP", "MTRS", "Ownership", "Map Book Sheet"] tsv_write(["From MP", "To MP", "MTRS", "Ownership", "Map Book Sheet"]) meridian_last = meridian township_last = township f_mile_last = f_mile t_mile_last = t_mile owner_last = owner if not township_append_flag: township_section_list.append(township_last + ": " + str(int(section))), index_order_rollup]) else: print ["", "", trs, "", ""] tsv_write(["", "", trs, "", ""]) township_section_list = [] index_order_list = [] index_order_list.append(index_order) tsv.close() Thanks for any input! Forest I think this will work for you: The code above relies on nested defautldict to do the aggregation. It turns out the aggregation is much simpler than formatting the MTRS output the way you want it. The code creates an in-memory table for storing the results. Since I put a newline character to break up the different MTRS items, you won't see everything on the single row when looking at the table in ArcMap. If you print the results or create a report, it will all be there.
https://community.esri.com/thread/195578-advice-on-roll-up-consolidation-tool
CC-MAIN-2019-26
refinedweb
650
63.29
NAME BN_rand_ex, BN_rand, BN_priv_rand_ex, BN_priv_rand, BN_pseudo_rand, BN_rand_range_ex, BN_rand_range, BN_priv_rand_range_ex, BN_priv_rand_range, BN_pseudo_rand_range - generate pseudo-random number SYNOPSIS #include <openssl/bn.h> int BN_rand_ex(BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx); int BN_rand(BIGNUM *rnd, int bits, int top, int bottom); int BN_priv_rand_ex(BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx); int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom); int BN_rand_range_ex(BIGNUM *rnd, BIGNUM *range, unsigned int strength, BN_CTX *ctx); int BN_rand_range(BIGNUM *rnd, BIGNUM *range); int BN_priv_rand_range_ex(BIGNUM *rnd, BIGNUM *range, unsigned int strength, BN_CTX *ctx); int BN_priv_rand_range(BIGNUM *rnd, BIGNUM *range); Deprecated since OpenSSL 3.0, can be hidden entirely by defining OPENSSL_API_COMPAT with a suitable version value, see openssl_user_macros(7): int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom); int BN_pseudo_rand_range(BIGNUM *rnd, BIGNUM *range); DESCRIPTION BN_rand_ex() generates a cryptographically strong pseudo-random number of bits in length and security strength at least strength bits using the random number generator for the library context associated with ctx. The function stores the generated data in rnd. The parameter ctx may be NULL in which case the default library context is used.() is the same as BN_rand_ex() except that the default library context is always used. BN_rand_range_ex() generates a cryptographically strong pseudo-random number rnd, of security stength at least strength bits, in the range 0 <= rnd < range using the random number generator for the library context associated with ctx. The parameter ctx may be NULL in which case the default library context is used. BN_rand_range() is the same as BN_rand_range_ex() except that the default library context is always used. BN_priv_rand_ex(), BN_priv_rand(), BN_priv_rand_rand_ex() and BN_priv_rand_range() have the same semantics as BN_rand_ex(), BN_rand(), BN_rand_range_ex()), EVP_RAND(7) HISTORY Starting with OpenSSL release 1.1.0, BN_pseudo_rand() has been identical to BN_rand() and BN_pseudo_rand_range() has been identical to BN_rand_range(). The BN_pseudo_rand() and BN_pseudo_rand_range() functions were deprecated in OpenSSL 3.0. The BN_priv_rand() and BN_priv_rand_range() functions were added in OpenSSL 1.1.1. The BN_rand_ex(), BN_priv_rand_ex(), BN_rand_range_ex() and BN_priv_rand_range_ex() functions were added in OpenSSL 3.0. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at.
https://www.openssl.org/docs/man3.0/man3/BN_rand.html
CC-MAIN-2021-43
refinedweb
381
59.84
build 242, Linux 1) Create new Ruby Project 2) Outside of NetBeans create ahoj.rb in the source root of the project you just created with the following content: ===================== #!/usr/bin/env ruby class A def aaa(other) $stderr.puts "other: #{other}" end end ===================== 3) Return to the IDE and open ahoj.rb IDE becomes unusable due to still being thrown exception (attached). Created attachment 37709 [details] exceptions.txt This is "fixed" in build #243. I fixed it by disabling lexing of Ruby code within literal strings, which is what is causing the problem. That has been working until recently; it is now throwing exceptions inside the editor/lexer area. I need to work with the editor guys to figure out what changed and why. I have filed a new issue, issue 93341, to track getting this functionality back, but for now disabling highlighting seems like a good idea since it is much less severe than an IDE with infinite exception looping. Reassigning this issue to newly created 'ruby' component. Changing target milestone of all resolved Ruby issues from TBD to 6.0 Beta 1 build. VERIFIED
https://netbeans.org/bugzilla/show_bug.cgi?id=93287
CC-MAIN-2015-48
refinedweb
187
67.04
30 September 2010 19:45 [Source: ICIS news] (updates with Canadian, Mexican and overall North American shipment data) ?xml:namespace> Canadian chemical railcar loadings for the week ended on 25 September were 15,575, compared with 12,351 carloads in the same week last year, according to data released by the Association of American Railroads (AAR). The increase for the week came after a 24.9% year-over-year increase in Canadian chemical carloads in the previous week ended 18 September. The weekly chemical railcar loadings data are seen as an important real-time measure of chemical industry activity and demand. In For the year-to-date period to 25 September, Canadian chemical railcar shipments were up 23.5% to 544,850, from 441,181 in the same period in 2009. The association said that chemical railcar traffic in For the year-to-date period, Mexican shipments were down 0.2%, to 42,937, from 43,022 in the same period last year. The AAR reported earlier on Thursday that Overall chemical railcar shipments for all of North America - US, For the year-to-date period to 25 September, overall North American chemical railcar traffic was up 13.9% to 1,684,963, from 1,479,129 in the year-earlier period. Overall, the From the same week last year, total US weekly railcar traffic for the 19 carload commodity groups tracked by the AAR rose 10.7% to 300,908 271,807, and was up 7.2% to 10,828,835 year-to-date to 25 September.
http://www.icis.com/Articles/2010/09/30/9397831/canadian-weekly-chemical-railcar-traffic-rises-26.1.html
CC-MAIN-2014-52
refinedweb
258
55.24
Veni, vidi, expertus sum- I came, I saw, I tested I'd like to give you a brief overview of locking functionality from within the Team Foundation source control system. Before we begin, however, I'd like to note that the lock command should be differentiated from the permission command. lock is used to temporarily prevent access to a file or folder while permission can be used to set persistent access permissions. lock permission There are two types of locks. The weaker of the two is a checkin lock which prevents other users from checking in changes to the locked files. The stronger lock is a checkout lock which prevents users from pending changes, such as checkout, delete, and rename, to the locked files in their workspaces. A checkout lock cannot be granted if there are currently any pending changes by other users on the items to lock. In addition, only one user at a time may hold a lock on a given file or folder. delete rename A checkout lock may be more useful when refactoring code or performing high priority maintenance. A checkin lock, on the other hand, allows other users to continue working with the locked files, though the user with the lock is guaranteed to apply their changes first for as long as the lock is in place. Thus, checkout locks fully serialize changes by allowing only the lock holder to work on the locked item while checkin locks only prevent others from checking in any changes they make. A lock may be filed either as its own operation or as part of several other operations. The commands rename, checkout, delete, undelete, merge, branch, and add all have the option to lock as part of the operation. For add and branch, the lock is placed on the namespace where the new item will be created. Locks placed with rename apply both to the old and new namespaces. undelete merge branch add Locks on folders are implicitly recursive. If a parent folder is locked, there is no need to lock its children unless a more restrictive lock is required. Conversely, unlocking a child causes the child to have the same locking level as its parent. Since locks are used to control checkin and checkout activity on an item regardless of version, locks on an item apply to the item itself and not a specific version of the item. An item becomes unlocked either when the user explicitly unlocks it or when the user's pending changes on that item are checked in. It is also possible for administrators with the UnlockOther permission to remove a lock placed by another user. Here are a few examples demonstrating how to use the command line lock functionality. Note that you can use either the local or server path to specify files and folders. See Jason's post on maps and cloaks for more on mappings between the local drive and the respository. To lock a file for checkout: tf lock /lock:checkout Shuttle.cs To lock a folder for checkin: tf lock /lock:checkin src\3d_engine\ To unlock a file: tf lock /lock:none $/UniverseExplorer/src/Galaxy.cs To unlock all files locked by the current user in a given directory tree: tf lock /lock:none /recursive src\renderer\
http://blogs.msdn.com/adamsinger/archive/2004/10/07/239331.aspx
crawl-002
refinedweb
549
68.3
28802/hyperledgers-node-sdk-there-is-no-typing-definition-index-ts Looks like a bug in that the typings directory isn't published to npm. Am looking into this. Hyperledger uses a timeout mechanism for chaincode ...READ MORE Hyperledger client SDK is a component used ...READ MORE The consensus is achieved in the ordering ...READ MORE Here are some links where you can ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE To read and add data you can ...READ MORE the direct answer to your query is ...READ MORE Currently, following are the options to store ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/28802/hyperledgers-node-sdk-there-is-no-typing-definition-index-ts
CC-MAIN-2019-47
refinedweb
124
63.05
Is Serialization done with Soap or XmlSerializer Discussion in 'ASP .Net Web Services' started by cmay, Jun 8, 2006. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads XmlSerializer is ambiguous in the namespace System.Xml.Serializationkpg, Jul 8, 2010, in forum: ASP .Net - Replies: - 0 - Views: - 674 - kpg - Jul 8, 2010 XmlSerializer in SOAP messageDima Maltsev, Dec 22, 2003, in forum: ASP .Net Web Services - Replies: - 3 - Views: - 199 - MSFT - Dec 26, 2003 Serialization with XmlSerializer: how to set the XML root node to something different from <ArrayOfBob Rock, Jun 16, 2004, in forum: ASP .Net Web Services - Replies: - 3 - Views: - 184 - Ming Chen [.NET MVP] - Jun 17, 2004 avoiding XML serialization, different WSDL generation, soap serializationRamunas Urbonas, Jul 20, 2004, in forum: ASP .Net Web Services - Replies: - 1 - Views: - 410 - Dino Chiesa [Microsoft] - Jul 27, 2004 How to let browsers be done when parent is done and not wait for childrn's finishing in CGIZhidian Du, Feb 21, 2004, in forum: Perl Misc - Replies: - 0 - Views: - 166 - Zhidian Du - Feb 21, 2004
http://www.thecodingforums.com/threads/is-serialization-done-with-soap-or-xmlserializer.786249/
CC-MAIN-2014-42
refinedweb
211
62.48
STORAGE TANKS Storage tanks can be built on high grounds in which case they are termed ground-level reservoirs, or they are elevated reservoirs. Ground-level reservoirs are usually built of masonry, mass concrete, or reinforced concrete, according to the materials and local skill available (see below) A = Cross-sections of reservoir B = Types of walls for reservoirs C = Sketch detail of manhole opening in reservoir cover D = Typical valve arrangement for ground-level reservoir with two compartments Aa = Effluent Bb = Supply Cc =Overflow Dd = Drain A = Ground level B = Water-bearing formation C = Impervious stratum D = Collection chamber E = Opening protected by a stone-and-gravel pack in order to exclude sand and debris F = Collecting room G = Measuring weir H = Measuring rod, bottom of which is level with lower edge of weir I = Outlet pipe to reservoir or town J = Floor drainage K = Locked entrance door L = Screened opening through door for ventilation purpose M = Diversion ditch for surface run-off. Should be at least 15 m (49 ft) away from the collection structure A = Protective drainage ditch to keep drainage water a safe distance from spring B = Original slope and ground line C = Screened outlet pipe: can discharge freely or be piped to village or residence Springs can offer an economical and safe source of water. A thorough search should be made for signs of ground-water outcropping. Springs that can be piped to the user by gravity flow should be checked. A = Protective drainage ditch to keep drainage water a safe from spring B = Screened outlet pipe: to discharge freely or be piped to village or residence In order to prevent leakage in the reservoirs, the following should be done: 1. Build concrete walls with as few joints as possible 2. Copper or polyethylene strips should be built in vertical joints if possible. 3. Paint the whole inside surface with a bitumen compound or with a solution of sodium silicate (water glass). 4. Render interior surface with about 3/4 inch thickness of mortar composed of water-proof cement and sand, after thoroughly rough ending the surface to be rendered to ensure a good key. Elevated reservoirs may be of reinforced concrete or-of steel. Reinforced concrete is suitable when many tanks of similar size are to be built in a series of villages, so that the system is used over and over again. The construction techniques involved are the same as for ground-level storage, except that the elevating walls should be built first. Steel reservoirs are suitable for single reservoir plans. The tank can be ordered from the manufacturers and comes complete with the accompanying assembly manual which is easy to follow. The tower foundations are to be locally built of concrete. Steel reservoirs can also be used for ground-level tanks on rocky sites or in areas where masonry rocks are scarce. In such cases, the tank must be slightly elevated to allow painting of lower parts. Elevated storage tanks have valves to stop overflowing. When a float valve is used to control the level in the tank, the overflow should never come into action if the valve is working properly. In the case of a "floating" tank it is usual to control the inflow through a float valve and the outlet joins the delivery pipe through a non-return (see Fig. 48 ). A depth gauge operated by a float and wire shows the amount of water within the tank, and is visible from the outside. Outlet always taken from 6 in above tank floor; wash-out at extreme bottom of tank A = Diagrammatic arrangement of pipes when overhead tank acts as balancer ( floating tank ). Not suitable for use with reciprocating pumps. B = Diagrammatic arrangement of pipes when pumping direct to storage tank When a float valve is not used, there is no control on the depth of water except the intelligence of the operator of the supply pump and the overflow, and carelessness in adjusting the hours of pumping to the draw-off can result in considerable waste, while the farther the tank is from the pump-house the easier it is to overlook such waste. The simple indicator shown below is one way of reducing this to the minimum as, properly sited, it can be seen for a considerable distance. However, the nearer the tank is to the pump-house the easier this control becomes. A = Suitable indicator for top two three feet of water in tank B = Appearance of indicator from a distance; it should be orientated so that it appears against the skyline from observation point; it can be seen clearly a mile away. C = Section at a, showing construction and operation of lower indicator In the construction of storage facilities, the following provisions should be made: 1. Manhole covers must be tightly fitting to prevent surface water from entering the reservoir . They should be locable. 2. Surface covers must be water-tight and light-proof to prevent algae growth. 3. Ventilation must be included to let out air as water fills the tank. These must be covered with fine-mesh wires (not less than 18-mesh). 4. Inlet and outlet pipes, overflow and wash-out pipes should have mesh at their open ends. The outlet pipe should be 6 in. above the bottom of the tank. If the tank has concrete floors, the floor should slope towards the wash-out pipes to enhance cleaning. The diagrams below illustrate the proper design for a concrete storage tank. WATER PURIFICATION SYSTEM Water purification systems are usually incorporated in the storage tanks. Where only disinfection (chlorination) is required, the treatment tank can act as distributing reservoir. The cistern is a typical storage-purifier combination. The cistern filter is a sand filter which keeps organic matter from entering the cistern. The water may then be disinfected and stored in the cistern. The diagrams below show the construction design for such a filter. A catchment area always collects leaves, bird droppings, road dust, insects, etc. A cistern filter removes as much of these as possible before the water enters the cistern. The sand filter is usually built at ground level and the filtered water runs into the cistern, which is mostly underground. The largest pieces, such as leaves, are caught in the splash plate. The splash plate also serves to distribute the water over the surface of the filter, so that the water does not make holes in the sand. A piece of window screen forms the splash plate. Most filters are made too small to handle the normal rush of water from rainstorms. This results in the filter always overflowing or a channel being dug in the sand, which will ruin the filter. The filter area should be not less than one-tenth of the catchment area. A typical filter area would be 4 feet by 4 feet for a family-sized unit with average rainfall intensity. About every 6 months, the manhole cover to the filter must be removed and the filter cleaned. Remove all matter from the splash plate and scrape off and remove the top half-inch of sand. When the depth of sand becomes only 12 inches, rebuild it with clean sand to the original depth of 18 inches. A simple way to discard the first runoff from the roof, which is usually mostly leaves and dirt, should be provided. This will make your filter last longer between cleanings. The easiest way is to have a butterfly valve (like a damper in a stovepipe) in the downspout. After the rain has washed the roof, the valve is turned to allow the runoff water to enter the filter. A semiautomatic system is shown in Fig. When building the filter, it is important to insure easy cleaning and to use properly-sized sand and gravel. The filter is usually mounted right on the cistern but can also be close to it. It rust have a screened overflow. Water Purification Plant Tools and Materials 3 barrels, concrete tanks or 55-gallon drums 1 eight inch funnel or sheet metal to make a funnel 2 smaller tanks, about 5 gallon or 20 liters in size, equipped with float valves 4 shut-off valves 1 throttle or needle valve (clamps may be used instead of the valves, if hose is used) some pipe or hose with fittings hypochlorite of lime or sodium hypochlorite (laundry bleach) This plant can be used in small systems, using laundry bleach as a source of chlorine. The water purifier should be made as in the drawing. The two large barrels on top of the structure are for weakening the bleach. The two smaller tanks on the shelf below are for holding equal amounts of weakened bleach solution and of water, at a constant pressure. This makes a constant flow of the solution water, at the same speed, into the hoses leading to the mixing points. The mix is further controlled by the valves and may be seen through the open funnel. If a throttle valve is not available, a shut-off valve may be used and a throttle action obtained by this valve and valve #4 in series. Placing the two barrels at a height of 10 feet causes a pressure of only about five pounds a square inch. Thus the plumbing does not have to be of high quality except for valve #1 and the float valve of the water holdup tank, if the rain water supply is under higher pressure. Sometimes special chlorinators are required; in which case when hypachlorinators are ordered, the following data should be furnished to the manufacturers: If water is pumped: 1. Sketch of pumping installation 2. Number and type of pumps 3. Manual or automatic operation 4. Pumping rate (liters/second or gallons/minute) and total water pumped per day (cubic meters or gallons) 5. Electric current available (volts, phase, cycle) 6. Pressure on pump discharge (minimum and maximum) 7. Suction lift 8. Sizes of suction and discharge pipes 9. Other data (space available for installation, sizes of foot valves, check valves, etc.) For gravity system: 1. Sketch of system, indicating source of water supply and distances 2. Size of main 3. Size of meter, if any, giving make and description 4. Pressure at meter or point of installation (minimum and maximum) 5. Rate of flow (minimum and maximum) 6. Average daily flow (cubic meters or gallons per day) 7. Fire flow, if any (liters/second or gallons/minute) 8. Allowable loss of pressure (m or ft) 9. Other data (space available for installation, etc.) Boiler for Potable Water Sometimes it is easier to boil drinking water than to disinfect. The following design can provide enough safe water for a smell community with a distribution system, since it would require a lot of fuel to boil enough water for the system. Tools and Materials 1 - 55 Gallon drum 1 - 3/4" Pipe Nipple 2" long. Quantity of bricks for two layers of bricks to support drum. 1 - bag of cement plus sand for mortar and base of fireplace. 1 - large funnel and filter medium for filling. 1 - metal plate to control draft in front of firebox. 1 - 3/4" valve, preferably all metal such as a gate valve to withstand heat. This drum for boiling of drinking water is intended for use in your residence to provide a convenient method for preparation and storage of sterile water. The fireplace is simple, oriented so that the prevailing wind or draft goes from front to back of the drum between the bricks. A chimney can be provided but is not necessary. The unit has been tested in many Friend's workcamps in Mexico and elsewhere. A 55 gallon drum would normally last a 20 person camp group for an entire week, and certainly would provide adequate safe water supply for two or three individuals for a much longer time. Water must boll at least 15 minutes with steam escaping around the completely loosened filler plug. Be sure that the water in the pipe nipple and valve reach boiling temperatures by purging about two liters of water out through the valve while the drum is at a full boil.
http://www.nzdl.org/gsdlmod?e=d-00000-00---off-0hdl--00-0----0-10-0---0---0direct-10---4-------0-0l--11-en-50---20-about---00-0-1-00-0-0-11-1-0utfZz-8-10-0-0-11-10-0utfZz-8-00&a=d&c=hdl&cl=CL3.43&d=HASH72d6a825afcdab4026ef60.7.6
CC-MAIN-2019-43
refinedweb
2,035
61.56
public EmailAddress create1(String address) { return new EmailAddress(address); } private Map _cache = new HashMap(); public EmailAddress create2(String address) { EmailAddress em = _cache.get(address); if (em != null) return em; em = new EmailAddress(address) _cache.put(address, em); return em; } public EmailAddress create3(String address) { // The implementation of this method is a secret, but it adheres // to the obvious contract. If invoked twice with the same parameter, // retval1.equals(retval2) will always be true. }In the examples above, probably everyone agrees that create1 is a factory method. I just wave my arms and call them all factory methods. Is create2 a factory method? Is create3? Do we even care? abstract class EmailAddress { // details } public class SMTPAddress extends EmailAddress { public SMTPAddress(String addr) { // create address } // ... } abstract class Application { abstract EmailAddress createEmailAddress(String addr) ; // other methods ... } public class SMTPApplication extends Application { public EmailAddress createEmailAddress(String addr) { return new SMTPAddress(addr) ; } // ... }The difference is that while your methods are creational, the complexity is not present to justify calling this an example of a design pattern, or even needing a pattern. I believe that one of the main reasons for this pattern is to implement a framework across a wide variety of implementations. Rather than providing better encapsulation, or code structure, this pattern tends to make different applications follow a similar framework, and thus make them easier to understand. I hope this all makes sense: I'm rather new to design patterns. public Computer BuildMeA(String type) { if(type.equals("MAC")) return new Mac(); if(type.equals("PC")) return new Pc(); if(type.equals("Next")) return new Next(); // etc... }Mac,Pc,Next,etc are subclasses of Computer. (Not a great way to do things, but I think it gets the point across) I guess exactly what a factory method is is a matter of how you look at it. But design patterns exist to aid in creating reusable code. And with this in mind, a factory method which returns objects that can't possibly be determined at compile time makes for more reusable code. I'm almost certain that Microsoft's Visual Studio makes extensive use of the FactoryMethod in its drag-and-drop dialog constructor. Decisions about what components to create have to be made dynamically as the user drops them onto the dialogue. Well, that's my two bits on that. -- Myke Don't be so hard on yourself, Myke. I think your example is precisely the way a FactoryMethod should work. There are times when you need to make a run-time, data driven decision on which subclass to create. Sometimes I have found that data received from the outside world does not match the class hierarchies we have defined. A FactoryMethod provides this mapping. -- WayneMack //Abstract Factory: Define the Abstract Class to make factory of related Classes Class EmailAddress? { //Create three Methods EmailAddress? create(String address) =0; //Some other Methods //Method1()=0; } //Creating Concrete Factory of Class: Here I am implementing Abstract Factory Class EmailAddressSMTP: public EmailAddress? { //Creating Concrete Factory of Method: Here I am implementing Factory Method //Define Method “Create” EmailAddress? create(String address) { //Any one from create1, create2 and create3 can be called by putting some validation logic. } //Define Other needed Methods Particular this class EmailAddress? create1(String address); EmailAddress? create2(String address); EmailAddress? create3(String address); } //Creating another Concrete Factory of Class Class EmailAddressUUCP: public EmailAddress? { //Creating Concrete Factory of Method: Here I am implementing Factory Method //Define Method “Create” vEmailAddress create(String address) { //Any one from create1, create2 and create3 can be called by putting some validation logic. } //Define Other needed Methods Particular this class EmailAddress? create1(String address); EmailAddress? create2(String address); EmailAddress? create3(String address); }Please let me know if you have some comments. softprofessional@yahoo.co.in Akash
http://c2.com/cgi/wiki?FactoryMethod
CC-MAIN-2015-40
refinedweb
624
50.63
Group: V 2.31 release Resolution: Fixed Category: Python Hi, there is still a problem when using obj.shareFrom (obj2) and/or obj.link(mesh) and mesh is already linked to another object. Reproduce it: - create a cube named "Cube" with mesh "Cube". Give the cube mesh a material - execute the script: from Blender import * o = Object.New("Mesh", "x") o1 = Object.Get("Cube") Scene.GetCurrent().link(o) o.shareFrom(o1) "x" is created and linked to the mesh of "Cube". But if you go to the material buttons window, you will see that "x" is linked to mesh "Cube", but no materials are shown!!! There should be at least one. Problem seems to be, that Object.link() and Object.shareFrom() do not update the totcol and actcol elements of struct Object. I tried to set object->totcol from the mesh's totcol and actcol = 0, seemed to work, materials are now shown in the materials buttons window, but opening the OOPS window crashes Blender. Seems i missed something ;) BalaGi
https://developer.blender.org/T879
CC-MAIN-2019-09
refinedweb
170
69.68
XML and FrameMaker pp 171-186 | Cite as Using Style Sheets and Namespaces in XML Abstract If you plan to use cascading style sheets (CSS) or Extensible Stylesheet Language (XSL) to format XML produced from FrameMaker documents, then you may find it helpful to have FrameMaker provide a starting point on your style sheets. The options available with FrameMaker and with Quadralay WebWorks Publisher are described in this chapter. XML namespace support in FrameMaker is also discussed in this chapter. KeywordsStructure View Uniform Resource Identifier Child Element Style Sheet Cascade Style Sheet Preview Unable to display preview. Download preview PDF. © Kay Ethier 2004
https://link.springer.com/chapter/10.1007/978-1-4302-0719-1_9
CC-MAIN-2018-13
refinedweb
103
62.68
opt-out of certain notifications Bug Description keystone currently support a lot of event notifications, just see http:// It would be nice if there was a configuration option to allow users to opt-out of notifications they didn't care about. This could be as simple as: [notifications] listen_group_create = True listen_group_delete = True listen_group_update = True ... listen_ Or something more advanced. Either way, each would have to be set to True by default. Hey Fernando, The implementation can be done in a variety of ways and we can optimize as we review. I think the harder part here is setting up a way for user's to pick and choose which events they want to listen to. Listing them out as booleans: [notifications] listen_group_create = True listen_group_delete = True listen_group_update = True ... listen_ Have users add "event_type" strings in a multi-string option, the event types are well defined in the format: "event_type": "identity. [notifications] opt-in = "identity. or maybe the flip, out-opt [notifications] opt-out = "authenticate. These are just my ideas, propose a patch and let's see what ideas are kicked around! What is the problem with having too many? Is it too hard to ignore then, is there a performance issue or something else? @david, you touched on some of the issues. It can be information overload, and if you are logging these to events to logs instead of a message bus then unless you are in the business of buying hard drives, you will want some way to control what events are printed. if logging to a message bus, then too many events can be hard to ignore. I'm still suggesting we keep them all enabled by default. I like the opt-out since I think most users would want all the notifications by default. @Steve, I think this is probably a good feature to have, but having the 'why' details documented means that other won't have to guess too. In addition to log space, many folks would like to not overload their rabbit servers (if using rabbit queues for this). If there's a problem with the consumer the queues can fill up and cause issues. Reviewed: https:/ Committed: https:/ Submitter: Jenkins Branch: master commit 255685877ec54d1 Author: Fernando Diaz <email address hidden> Date: Fri Dec 4 22:23:15 2015 -0600 Opt-out certain Keystone Notifications This patch will allow certain notifications for events in Keystone to be opted out. Opting out may be a desired way of doing this since most keystone deployers will likely like to by default have all audit traces. Change-Id: I86caf6e5f25cdd Closes-Bug: 1519210 This issue was fixed in the openstack/keystone 9.0.0.0b3 development milestone. Hey Steve, how does something like this look: notifications.py ------- ------- --- ------- Add: enabled_events = {} which will read from the conf and eventually generate something like: enabled_events = { type": {'user', 'group'}, "resource_ "operation": {ACTIONS.created} } and in: cadf_payload( operation, resource_type, resource_id, outcome, initiator): def _create_ we add: events. get("resource_ type") and \ operation in enabled_ events. get("operation" ): if resource_type in enabled_ to the top of the function.
https://bugs.launchpad.net/keystone/+bug/1519210
CC-MAIN-2021-21
refinedweb
511
63.49
Pillow provides a drawing module called ImageDraw that you can use to create simple 2D graphics on your Image objects. According to Pillow's documentation, "you can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use." If you need more advanced drawing capabilities than what is included in Pillow, you can get a separate package called aggdraw. You will focus on what comes with Pillow in this article. Specifically, you will learn about the following: When drawing with Pillow, it uses the same coordinate system that you have been using with the rest of Pillow. The upper left corner is still (0,0), for example. If you draw outside of the image bounds, those pixels will be discarded. If you want to specify a color, you can use a series of numbers or tuples as you would when using PIL.Image.new(). For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing integer values. You may also use the color names that are supported by Pillow that you learned about in chapter 2. When you go to use the various drawing methods, you will discover that they have a lot of common parameters that they share. Rather than explain the same parameters in every section, you will learn about them up-front! Most of the drawing methods have an xy parameter that sets a rectangular area in which to draw a figure. This can be defined in the following two ways: When it comes to drawing a line, polygon, or point, multiple coordinates are specified in either of these ways: (x1, y1, x2, y2, x3, y3...) ((x1, y1), (x2, y2), (x3, y3)...) The line() method will draw a straight line, connecting each point. The polygon() will draw a polygon where each point is connected. Finally, the point() will draw a point of 1-pixel at each point. The parameter, fill, is used to set the color that will fill the shape. The way you set the fill is determined by the mode of the image: RGB: Set each color value (0-255) using (R, G, B) or a color name L(grayscale): Set a value (0-255) as an integer The default is None or no fill. The outline sets the border color of your drawing. Its specification is the same as the one you use for fill. The default is None, which means no border. Now that you know about the common parameters, you can move on and learn how to start drawing! The first type of drawing you will learn about is how to draw lines in Pillow. All shapes are made up of lines. In Pillow's case, a line is drawn by telling Pillow the beginning and ending coordinates to draw the line between. Alternatively, you can pass in a series of XY coordinates and Pillow will draw lines to connect the points. Following is the line() method definition: def line(self, xy, fill=None, width=0, joint=None): """Draw a line, or a connected sequence of line segments.""" You can see that it accepts several different parameters. You learned what some of these parameters mean in the previous section. The width parameter is used to control the width of the lines. Before you learn how to use joint, you should learn how to draw lines without it. But first, you will need an image to draw on. You will use this image of one of the Madison County bridges: Madison County Covered Bridge Now go open up your Python editor and create a new file named draw_line.py and add this code to it: # draw_line.py import random from PIL import Image, ImageDraw def line(image_path, output_path): image = Image.open(image_path) draw = ImageDraw.Draw(image) colors = ["red", "green", "blue", "yellow", "purple", "orange"] for i in range(0, 100, 20): draw.line((i, 0) + image.size, width=5, fill=random.choice(colors)) image.save(output_path) if __name__ == "__main__": line("madison_county_bridge_2.jpg", "lines.jpg") Here you open up the image in Pillow and then pass the Image object to ImageDraw.Draw(), which returns an ImageDraw object. Now you can draw lines on your image. In this case, you use a for loop to draw five lines on the image. The beginning image starts at (0,0) in the first loop. Then the X position changes in each iteration. The endpoint is the size of the image. You use the random module to choose a random color from a list of colors. When you run this code, the output will look something like this: Lines drawn on an image Now you can try creating a series of points and drawing lines that way. Create a new file named draw_jointed_line.py and put this code in your file: # draw_jointed_line.py from PIL import Image, ImageDraw def line(output_path): image = Image.new("RGB", (400, 400), "red") points = [(100, 100), (150, 200), (200, 50), (400, 400)] draw = ImageDraw.Draw(image) draw.line(points, width=15, fill="green", joint="curve") image.save(output_path) if __name__ == "__main__": line("jointed_lines.jpg") This time you create an image using Pillow rather than drawing on one of your own. Then you create a list of points. To make the line connections look nicer, you can set the joint parameter to "curve". If you look at the source code for the line() method, you will find that "curve" is the only valid value to give it other than None. This may change in a future version of Pillow. When you run this code, your image will look like this: Drawing jointed lines Now try removing the joint parameter from your code and re-run the example. Your output will now look like this: Lines without joints By setting joint to "curve", the output will be slightly more pleasing to the eye. Now you're ready to learn about drawing arcs with Pillow! An arc is a curved line. You can draw arcs with Pillow too. Here is the arc() method specification: def arc(self, xy, start, end, fill=None, width=1): """Draw an arc.""" An arc() can also be made using xy points. The start parameter defines the starting angle, in degrees. The end parameter tells Pillow what the ending angle is, which is also in degrees. The other two parameters are ones that have already been introduced. To see how you might draw an arc, create a new file named draw_arc.py and add this code to it: # draw_arc.py from PIL import Image, ImageDraw def arc(output_path): image = Image.new("RGB", (400, 400), "white") draw = ImageDraw.Draw(image) draw.arc((25, 50, 175, 200), start=30, end=250, fill="green") draw.arc((100, 150, 275, 300), start=20, end=100, width=5, fill="yellow") image.save(output_path) if __name__ == "__main__": arc("arc.jpg") In this code, you create a new image with a white background. Then you create your Draw object. Next, you create two different arcs. The first arc will be filled with green. The second arc will be filled in yellow, but its line width will be 5. When you draw an arc, the fill is referring to the arc's line color. You aren't filling the arc itself. When you run this code, your output image will look like this: Drawing arcs Try changing some of the parameters and re-running the code to see how you can change the arcs yourself. Now let's move on and learn about drawing chords! Pillow also supports the concept of chords. A chord is the same as an arc except that the endpoints are connected with a straight line. Here is the method definition of chord(): def chord(self, xy, start, end, fill=None, outline=None, width=1): """Draw a chord.""" The only difference here is that you can also add an outline color. This color can be specified in any of the ways that you can specify a fill color. Create a new file and name it draw_chord.py. Then add this code so you can see how you make chords yourself: # draw_chard.py from PIL import Image, ImageDraw def chord(output_path): image = Image.new("RGB", (400, 400), "green") draw = ImageDraw.Draw(image) draw.chord((25, 50, 175, 200), start=30, end=250, fill="red") draw.chord((100, 150, 275, 300), start=20, end=100, width=5, fill="yellow", outline="blue") image.save(output_path) if __name__ == "__main__": chord("chord.jpg") This example will draw two chords on a green image. The first chord is filled in with a red color. The second chord is filled in with yellow but is outlined in blue. The blue outline has a width of 5. When you run this code, you will create the following image: Drawing chords That looks pretty good. Go ahead and play around with this example too. You'll soon master chord making with Pillow with a little practice. Now let's continue and learn about drawing ellipses! An ellipse, or oval, is drawn in Pillow by giving it a bounding box (xy). You have seen this several other times in previous sections. Here is the ellipse() method definition: def ellipse(self, xy, fill=None, outline=None, width=1): """Draw an ellipse.""" The ellipse() lets you fill it with a color, add a colored border ( outline) and change the width of that outline. To see how you can create an ellipse(), make a new file named draw_ellipse.py and add this code to it: # draw_ellipse.py from PIL import Image, ImageDraw def ellipse(output_path): image = Image.new("RGB", (400, 400), "white") draw = ImageDraw.Draw(image) draw.ellipse((25, 50, 175, 200), fill="red") draw.ellipse((100, 150, 275, 300), outline="black", width=5, fill="yellow") image.save(output_path) if __name__ == "__main__": ellipse("ellipse.jpg") In this code, you create a nice white image via the new() method. Then you draw a red ellipse on top of it. Finally, you draw a second ellipse that is filled with yellow and outlined in black where the outline width is set to 5. When you run this code, the image it creates will look like this: Drawing ellipses You can create ovals and circles using ellipse(). Give it a try and see what you can do with it. Now let's find out how to create pie slices! A pie slice is the same as arc()), but also draws straight lines between the endpoints and the center of the bounding box. Here is how the pieslice() method is defined: def pieslice(self, xy, start, end, fill=None, outline=None, width=1): """Draw a pieslice.""" You have used all of these parameters in other drawings. To review, fill adds color to the inside of the pieslice() while outline adds a colored border to the figure. To start practicing this shape, create a new file named draw_pieslice.py and add this code to your file: # draw_pieslice.py from PIL import Image, ImageDraw def pieslice(output_path): image = Image.new("RGB", (400, 400), "grey") draw = ImageDraw.Draw(image) draw.pieslice((25, 50, 175, 200), start=30, end=250, fill="green") draw.pieslice((100, 150, 275, 300), start=20, end=100, width=5, outline="yellow") image.save(output_path) if __name__ == "__main__": pieslice("pieslice.jpg") In this code, you generate a grey image to draw on. Then you create two pie slices. The first pieslice() is filled in with green. The second one is not filled in, but it does have a yellow outline. Note that each pieslice() has a different starting and ending degree. When you run this code, you will get the following image: Drawing pie slices With a little work, you could create a pie graph using Pillow! You should play around with your code a bit and change some values. You will quickly learn how to make some nice pie slices of your own. Now let's find out how to draw polygons with Pillow! A polygon is a geometric shape that has a number of points (vertices) and an equal number of line segments or sides. A square, triangle, and hexagon are all types of polygons. Pillow lets you create your own polygons. Pillow's documentation defines a polygon like this: The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate. Here is the code definition of the polygon() method: def polygon(self, xy, fill=None, outline=None): """Draw a polygon.""" All of these parameters should be familiar to you now. Go ahead and create a new Python file and name it draw_polygon.py. Then add this code: # draw_polygon.py from PIL import Image, ImageDraw def polygon(output_path): image = Image.new("RGB", (400, 400), "grey") draw = ImageDraw.Draw(image) draw.polygon(((100, 100), (200, 50), (125, 25)), fill="green") draw.polygon(((175, 100), (225, 50), (200, 25)), outline="yellow") image.save(output_path) if __name__ == "__main__": polygon("polygons.jpg") This code will create a grey image like the last example in the previous section. It will then create a polygon that is filled with the color green. Then it will create a second polygon and outline it in yellow without filling it. In both of the drawings, you are supplying three points. That will create two triangles. When you run this code, you will get this output: Drawing polygons Try changing the code by adding additional points to one or more of the polygons in the code above. With a little practice, you'll be able to create complex polygons quickly with Pillow. The rectangle() method allows you to draw a rectangle or square using Pillow. Here is how rectangle() is defined: def rectangle(self, xy, fill=None, outline=None, width=1): """Draw a rectangle.""" You can pass in two tuples that define the beginning and ending coordinates to draw the rectangle. Or you can supply the four coordinates as a box tuple (4-item tuple). Then you can add an outline, fill it with a color, and change the outline's width. Create a new file and name it draw_rectangle.py. Then fill it in with this code so you can start drawing rectangles: # draw_rectangle.py from PIL import Image, ImageDraw def rectangle(output_path): image = Image.new("RGB", (400, 400), "blue") draw = ImageDraw.Draw(image) draw.rectangle((200, 100, 300, 200), fill="red") draw.rectangle((50, 50, 150, 150), fill="green", outline="yellow", width=3) image.save(output_path) if __name__ == "__main__": rectangle("rectangle.jpg") This code will create a blue image that is 400x400 pixels. Then it will draw two rectangles. The first rectangle will be filled with red. The second will be filled with green and outlined with yellow. When you run this code, you will get this image as output: Drawing rectangles Aren't those lovely rectangles? You can modify the rectangle's points to create thinner or wider rectangles. You could also modify the outline width that you add to the rectangles. You can use Pillow to add shapes to your images. This can be helpful for adding outlines to your images, highlighting one or more portions of your image, and more. In this article, you learned about the following topics: You can do a lot with the shapes that are provided by Pillow. You should take these examples and modify them to test them out with your own photos. Give it a try and see what you can come up with!
https://www.blog.pythonlibrary.org/2021/02/23/drawing-shapes-on-images-with-python-and-pillow/
CC-MAIN-2022-27
refinedweb
2,580
75.71
Introduction This article explains approaches for ASP.NET mobile development to determine if an HTTP request is coming from a mobile phone and then redirecting the request to a page optimized for a mobile browser. This has been created using the version 0.1.10.3 of the 51degrees.mobi foundation API. Please note these instructions will require changes to assembly names, namespaces and file names to work with the latest version of the 51degrees.mobi foundation API. Method 1: Using ASP.NET to detect the user agent will make us ask “Is there any better way to achieve this?” Method 2.1: Using 51degrees.mobi foundation - Create a C# ASP.NET website. - The website will be created with a default web form “Default.aspx”, keep the name as it is. - Add a web page to the website using “Add New Item -> Web Form”. Name the web form to “M.aspx” Step 2: 51Degrees.mobi resource download Following files need to be added to the web site created in Step 1. - App_Data/wurfl.xml.gz - App_Data/web_browsers_patch.xml - bin/FiftyOne.Foundation.dll The above files can be extracted from the 51degrees.mobi foundation Enhance download available here. Once downloaded your website should have following folder structure. Step 3: Web.config changes The Web.config file should be changed to allow your existing web site to detect mobile devices. Please follow the instructions as provided in the user guide. After the Web.config changes, redirect element of the fiftyOne section needs to be changed as shown below. <redirect mobileHomePageUrl="~/M.aspx" /> Step 4: Mobile page (M.aspx) Add the following code to M.aspx and M.aspx.cs Listing: M.aspx <%@ Page <body> <form id="form1" runat="server"> <asp:Label <asp:Label <asp:Label <asp:Label <asp:Label <asp:Label <asp:Label </form> </body> </html> Listing: M.aspx.cs.Page {", //51degrees.mobi Foundation provides more detailed information //about the device capabilities. LabelPlatform.Text = "Platform : " + ((MobileCapabilities)Request.Browser).Platform .ToString(); LabelBrowser.Text = "Browser : " + ((MobileCapabilities)Request.Browser).Browser .ToString(); LabelJpg.Text = "Image : " + ((MobileCapabilities)Request.Browser) .PreferredImageMime.ToString(); } } Step 5: Build the Website using “Build -> Build Web site” menu Step 6: Download Mobile Emulators to test web site You can download emulators which are listed here Foundation API. Apart from this, 51degrees.mobi Foundation API also gives information of device capabilities which can you used for customization. Method 2.2: Using 51degrees.mobi foundation API to detect the user agent [MVC] A simple application is used 1:. Note: Make sure that you select .NET Framework 3.5 from the dropdown list at the top of the New Project dialog or the ASP.NET MVC Web Application project template would not appear. Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project as shown below. Because we would not be creating tests in this article select the No option and click the OK button. When you create a new ASP.NET MVC application with Visual Studio, you get a sample application by default. It has a standard set of folders: Models, Views, and Controllers folder. You can see this standard set of folders in the Solution Explorer window as shown below. We’ll need to add files/folders to Views and Controllers folders in order to build the Mobile device detection application. In the Solution Explorer window, right-click the Views folder and select the menu option Add, New Folder. Name the new folder as Mobile as shown below Step 2: 51degrees.mobi resource download To download the source code of MVC application explained in this section, go to downloads tab and select the MVCMobileDetect under latest release. Step 3: Web.config changes The Web.config file should be changed to allow your existing web site to detect mobile devices. Please follow the instructions as provided in the user guide. Step 4:” as shown. - Click the Add button to add the new controller to your project. Listing: Controllers\MobileController.cs(); } } } Now we need ASP.NET to look for different views if the device is a mobile. Add following code to HomeController.cs in order to load views optimized for mobile. Listing: Controllers\HomeController.cs(); } } } Step 5: Creating the ASP.NET MVC view The Index() method in the MobileController.cs returns a view named Index under Views-> Mobile folder. We need to create this view for mobiles apart from Nokia, Iphone and Blackberry. Follow these steps: - Right-click the Index() method in the code editor and select the menu option Add View as seen below. - In the Add View dialog, verify that none of the checkboxes are checked as seen below. After you complete these steps, a new view named Index.aspx is added to the Views\Mobile folder. Follow same steps for methods Nokia(),Iphone() and Blackberry() to create views as seen below. Mobile folder structure” width=”158″ height=”94″ /> The contents of the Index view are included in below Listing. Listing: Views\Mobile\Index.aspx <%@Capabilities)Request.Browser).Platform.ToString() %> </h6> <h6>Browser : <%= ((MobileCapabilities)Request.Browser).Browser.ToString() %> </h6> <h6>Image : <%= ((MobileCapabilities)Request.Browser) .PreferredImageMime.ToString() %> </h6> </div> </body> </html> Use the same method to add the html code for the views Nokia.aspx, Iphone.aspx and BlackBerry.aspx. Step 6: Build the application using Build menu Step 7: Download mobile emulator to test the displayed..). Different MVC views loaded for different devices with device capability information is as shown above.. Reference : Hi, Look also apache mobile filter I thing could be a good solution for professional multichannel site. I apologise, but you could not paint little bit more in detail. vimax
https://lchandara.wordpress.com/2011/11/07/mobile-device-detection-and-redirection-with-51degrees-mobi/
CC-MAIN-2017-26
refinedweb
938
52.66
About Blogging. Reflections on WebCT. Interesting reflections by Emily at Filament on using WebCT: "My big complaint about WebCT is that it cuts students off from the real internet. I especially hate that the messaging system is not real email and doesn't allow you to email outside of the program. It creates these little communities and then abruptly disbands them at the end of the semester instead of allowing the continued networking of real internet communities." [Filament] Absolutely! Knock down the walls says I![James Farmer's Radio Weblog] Imagine an educator who has her or his students having a great debate or discussion online during a course and then..... where does this great conversation of ideas, thoughts, and notions go after the course is over... does it get "thrown out" like so many things these days? After you get into weblogging, you see where something like webct may be coming short and has the potential to be better than it is. or not? I have been thinking about that myself when some of our staff have classes at the local university. I say.. why not blog your cousework as an option.. some are willing.. but the professor is another story. I do not get emails back from professors on this. If work for a class is to be authentic as it can be, the journey to one's answers and conclusions should be posted. Teachers can take the knowledge they have gained and extend and refine their thinking and practice as they work though the year. This is heavy.... Why am I, a elementary school techie thinking over a challenge that people who make a lot more money than I do at the university level, should be seriously looking at. WIRED: BLOG SPACE. "Ever since the Web entered the popular consciousness, observers have noted that it puts information at your fingertips but tends to keep wisdom out of reach. In a space organized around connected minds, however, the search for wisdom becomes more promising." [elearningpost] Another good quote: "What happens when you start seeing the Web as a matrix of minds, not documents?" Good question![James Farmer's Radio Weblog] Had to post this for the quotes! Started a Praxis weblog on using Manila. A space to plan, take note and get a better handle on Manila use in my school community MetaMap - Graphical Map of Metadata and other Standards Initiatives. "The MetaMap is a pedagogical graphic which takes the form of a subway map. Its aim is to help the information science community to understand metadata standards, sets, and initiatives of interest in this area." Now this is extremely cool and helpful - this map shows both what issues particular standards and initiatives try to address (the 'lines' they reside on), the media types they apply to (the colours of the subway 'lines') and also the interrelation of various standards and initiatives (where the lines have shared 'stops'). Cooler still is that it seems to run off of (or at least have a connection to) a structured directory that catalogues these standards and initiatives. Does require the SVG plugin, and they explain why they have chosen this format. - SWL - via David Mattison's [TenThousandYearBlog] which I subscribe to, yet only found this by chance as his main RSS feed seems to be broken. Still, dig further into his categories as he is still blogging and finding great stuff.[EdTechPost] Ride this train. The end product of a university course. Nice to see where we have been. Dave Winer wants to get Harvard blogging.... [Beth Potier] Dave Winer says in this article: "The idea of having a laboratory like Harvard University for learning about this technology is incredible." I would rather say: "the idea of having a laboratory like the World Wide Web for learning about this technology is incredible." To my knowledge none of the educational and pedagogical pioneers in "Blogland" can be found at Harvard... and if there are some, they are really trying hard not to connect with the folks that George Siemens recently indentified as Current Edu-bloggers. [Sebastian Fiedler][Seblogging News] Right on Seb! Dave should know bettern than anyone regarding bootstrapping. Bootstrapping in regards to blogging crosses most boundaries. Getting and giving help does not stop at ones institutional doors. Quite the contrary. Knowledge management and weblogs. Knowledge.[McGee's Musings] It is called Praxis, which deals with the construction of knowledge in the here and now. That cyclical endeavor of making sense of our endeavors in light of new insights and information. It is lifelong learning in the concrete. If anything, this is the stuff that we need to be passing on to our students. We need to model this behavior. As a faculty, we need to practice this behavior as a group. If a faculty is not about focusing on practice and refining it, then there is no praxis on an organizational level, and most likely lacking at the classroom level. That is why I think that weblogs may be one tool to expose our practice. School districts should honor teaching professionals with time in the day or at least during the week to reflect alone and with ones co-workers so that looking at the practice and student work is a meaningful ritual. New feature: Creative Commons, RSS and Manila. [Scripting News] Manila admins... another update .. another feature. I like the Swim Fan theme because not only is up to standard but also has a easy edit button for adding html links a la blogrolling. That is something that I have been waiting for. When we migrated to the new server this year, I have not touched the theme question. I want to keep things as simple as possible for teachers and have them maintain their own site. The newer default theme provides Managing Editors with easy edit buttons on the home page. Bryan Bell told us in Chicago, that the newer default theme was a "one trick pony". No other theme had easy to edit site buttons like that one. So now, one can have a sharp website but also an easy way to add links to the homepage. Thank You, Bryan! Joi on RSS. Joi Ito likes my book is his experiments with RSS this weekend. His summary of the situation regarding the two... [Ben Hammersley.com] Ben Hammersley's "RSS Hacks" book by O'Reilly came out this week. I am now itiching to buy it. Exploring topics in RSS2.0. I've been doing some thinking about how to encode topic information into RSS2.0 feeds. As a simple test of the Radio callback facility I have implemented a very simplistic protocol. Within each <item> is a tag <topic id="topic_id" type="topic-type" source="url">topic name</topic> for each topic associated with the item (post). A concrete example (using the rsstopics namespace): <rsstopics:topic rsstopics:the state</rsstopics:topic> Whilst this does have the advantage that it's simple and direct it's also a bit silly to invent a new format for topic information when we have two standard culprits available already: RDF is a general format for describing resources. A resource in RDF terms is anything which can be uniquely identified by a URI. An RDF statement (utilizing Dublin Core metadata) that asserts me as the owner of my weblog might look something like: <rdf:Description rdf: <dc:Creator>Matt Mower</dc:Creator> </rdf:Description> If you cut away the syntactic fluff what this says is: Matt Mower is the Creator of Referring back to the problem at hand, describing what a post (expressed as an RSS item) is about we could come up with something like: <item rdf: <topic id="topic_id" type="topic-type" source="url">topic name</topic> </item> Which is more or less exactly where we started -- using RDF hasn't altered the solution but it has added some framework around it (in this case adding rdf:about to signal the presence of RDF data within the item). However we can go a step further. A useful article by Eric van der Vlist discusses this very subject and refers to the RSS1.0 taxonomy module. Somewhat counter to what you would expect RSS2.0 does not follow on from RSS1.0, nor does RSS1.0 follow on from the popular RSS0.9x formats. RSS1.0 is, depending upon your point of view, a step forward or an aberation. RSS1.0 uses a modular set of RDF based tags to describe items in the RSS feed. One such module is the Taxonomy module which is intended to allow classification of RSS channels & items. Using the taxonomy module you create something like: <item rdf: <taxo:topics> <rdf:Bag> <rdf:li <rdf:li </rdf:Bag> </taxo:topics> </item> Here the <topics> element contains a list (using the RDF defined Bag - or unorderer list - container element) of resources indicating topics that describe the item. Each resource then has a <topic> element that describes the topic. It might look something like: <taxo:topic rdf: <taxo:link><taxo:link> <rsstopics:type>generic</rsstopics:type> <dc:title>The State</dc:title> </taxo:topic> Although it's a jumble of RDF, the RSS1.0 taxonomy module, Dublic Core, and, a custom rsstopics schema this says exactly the same thing as the original: <topic id="topic_id" type="topic-type" source="url">topic name</topic> But do we have to deal with such an ugly mess? Perhaps not. Our original choices included the XML Topic Maps format. This is a complete specification for exchanging topic information. An example of a topic in XTM format might look something like: <topic id="the_state"> <instanceOf> <topicRef xlink: </instanceOf> <baseName> <baseNameString>The State</baseNameString> <occurence id="the-state-item"> <instanceOf> <topicRef xlink: </instanceOf> <resourceRef xlink: </occurence> </topic> Again this encodes the same information, using a standard format and only one required namespace (that of XTM itself). A URI such as points at a topic in another map (in this case a topic describing the topic-type generic). The use of XTM comes with a number of advantages with the main one being that there are an increasing number of tools available to process & manipulate it (for example, see topicmap.com). However there also a number of problems with this representation when you attempt to embed it within another XML format such as RSS. - It's not clear whether an XTM fragment such as this is valid when used in this way - Each time a topic is used we will be duplicating it's details, bloating the markup & potentially creating invalid entries - The <occurence> relation within the <topic> element is technically redundant. The enclosing <item> indicates the occurrence. One way to avoid these problems would be to embed the topics within the RSS <channel> definition and refer to them from each <item>. However we still need a way to refer to the topic and XTM doesn't provide this. If we had a good way to reference topics then we could either embed mini topic map within the RSS file, or just have the <topicmap> in an external file and point to it. What could we use? One possibility is RDF. Using a combination of RDF and XTM would mean something like: <item rdf: <rsstopics:topic></rsstopics:topic> <!-- XTM in an external map --> </item> or <item rdf: <rsstopics:topic>#topic-id</rsstopics:topic> <!-- XTM element inline in the RSS --> </item> In this example the item now refers to an XTM defined topic either elsewhere in the RSS feed (contained within a valid <topicmap> element) or within an external topic map. The referenced <topic> element can further describe the topic (names, types and so on) using all the expressiveness of XTM. It's also efficient since there is no duplicated information within the feed. I have described approaches using RDF, XTM and a hybrid of the two. Each has advantages and disadvantages although I believe the hybrid makes the best use of both formats. I'd welcome comments and or opinions from interested parties.[Curiouser and curiouser!] Quickiwiki, Swiki, Twiki, Zwiki and the Plone Wars. Great article on using wikis as both a PIM and collaborative content tool (and in fact on all things wiki, though there is so much here you almost have to know quite a bit about this before it starts to make any sense). By David Mattison, Access Services Archivist British Columbia Archives, Canand (GO Canada!!) Also has a great sidebar comparing wikis and blogs. Be warned though: if you haven't played with wikis and you thought blogs were addictive, be prepared to get sucked into a massively intertwined universe in which you can spend days! Think 'surfing the web' to the nth degree! - SWL [EdTechPost] A good overall description of what is out there in Wiki and Zope Land. Prepare to take a good half hour just visiting the resource links. A decent comparison between wikis and blogs with example sites. A very good place to start your adventure. I have to say that there were some resources that I did not know of in wikiland. Do visit, even if it is only for self knowledge. Mixing, tinkering - digital age. Mixing, Tinkering and Reusing in the Digital Age Comment: Short, point-form post of a John Seely Brown presentation. Quotables: "The... [elearnspace blog] What I got out of this is that there is a new digital ball game and educational paradigms from which I work out of is behind the times. Uses of media. I think we'll see much more of this: Digital Resume (via Ben Hammersley)...as our society stops thinking traditional, and starts... [elearnspace blog] This is such a cool resume! Now we all will not be able to do that Flash magic..yet.. but like I told the staff where I work, a blog can be your resume. Damn better than a traditional resume. I agree with Doc. Trackback is way too technical and prone to inevitable abuse. There is a better way to do this. [John Robb's Radio Weblog] Seems to be a disconnect between what trackback can do according to Movable Type creators and others. Seems the Trotts wowed them at Seabury , just on this point. I think the Trotts should write more as promised on Trackback and its usefulness and potential. The DGI Conference Just Keeps Getting Better. How unbelievably psyched am I about the Digital Genres Conference in may? The list of participants is growing bigger and... [Golublog] Come to the Digital Genres Conference!. It's official, 30-31 May 2003 in Chicago will be a special, me-organized conference: Digital Genres: Semiotic Technologies This Side of... [Golublog] Chicago Bloggers Yahoo Group Trott Report. Ben... [AKMA’s Random Thoughts] Good post which touches on the conversation with the creators of Movable Type in Evanston, Illinois. I found the conversation around virtual communities and blogging the most interesting. There are two schools in San Fran. that use MT and have great looking sites. A hint at what the new MT Pro. features, such as a photo gallery module. Weblogs and passion. I.[McGee's Musings] I have three points. The first is that bloggers are passionate about blogging. Second, this event was held in a major graduate school for training pastoral workers. Just like educators, a group that needs to get connected are the pastoral workers. Caregivers need support, too! I wonder if web based tools like blogs, may help pastoral workers. I think so. Sometimes a mission, be it in an urban area or rural, can be very isolating for any number of reaons. One needs to share about one's experiences and dialogue about the 'practice', especially if the folks one is working with would rather gab than get down to "business" . Three, I love McGee's critique of business looking at knowledge making as a a reusable tool instead of as a craft. Knowledge as craft.. that is inspirational. Amen! KM and technical trends. Technical trends bode well for KM Quote: "The challenge was and is to make more of the routine communication flowing... [elearnspace blog] I think George again hits the nail on the head, on his commentary on the KM article in Infoworld. Blogging is organic.... or is the best blogging is organic... hmmmm. I do believe that a person needs a good personal motive to blog. Architecting online communities. Joel Spolsky's very well-written piece titled "Building Communities with Software" provides insightful perspectives on what makes online communities work. Spolsky makes a good case for simplicity in design; he has paid attention to the tradeoffs inherent in many implementation details. The key idea:. More on building communities here, and in chromatic's piece here.[Seb's Open Research] Right on... ! Making room for disruptive and emergent technologies.... [Hugh Blackmer] I read this as a pretty good description of what the cluster of Webloggers who work in the field of education and learning is doing for me. The educational Blogger Network could really serve the "need to be better connected". Bringing together people who would otherwise "feel that they are working in a vacuum" should be one of our priorities. [Sebastian Fiedler][Seblogging News] AMEN! Lets see what comes out of the Bloggin Chicago with Erin Clerico and Bryan Bell at the National Writing Project's Blog Design Team training today and tomorrow. I can't believe it. Today the training is at Whittier School, where I work, in the heart of the Latino barrio of Pilsen in Chicago. We will be blogging the sessions at the EBN Manila site. Now that I'm working with Manila again, I'm remembering all the things that infuriate me about Manila. I can't for the life of me figure out how to get my new site to show me the Edit In Radio buttons so I can use the outliner to edit my templates. I refuse to edit the template in a web form. I will not do it! ;-> Anyway, I have gone to my own personal membership page and told the software that I have Radio and that it's running on port 5335. I've been to the prefs page for the site (I'm a managing editor) and made sure the pref is on there too. I look everywhere for the stinkin button, but it's nowhere to be found. I guess I'll have to resort to looking at the source code to figure out what I'm not doing that I need to do. [Scripting News] BAM! What happens when the big cheese doesn't work or play with his own product...... SebF,Will R, PatD and others have been asking for better features of Manila for tighter integration between Radio and Manila and just better and newer tools to help in collaboration. Userland, we need a roadmap, a sketch on where you are taking Manila. Public vs. private discussions in communities.. Seb Fiedler mentiones the importance of face to face interaction in a very recent post. This is a challenge for educators be they separated by oceans or highways, is to find time primarily and funds. The real point is that face to face meetings over a life of a project (s) is important even though we are pushing for the development of virtual communities and more digital collaboration.": - trust and safety - even if you talk about "open for everyone" things, it's much easier to talk to the audience you know. - speed and easy-to-do - we all busy and we jump into using tools that save us time without even thinking that it could be more beneficial to have public discussion. - ownership - like with blogging, we want to be sure that nobody can take it from us. The funny thing is that Angela is talking about something similar suggesting a combination of formal and informal KnowledgeBoard. I would love to see some studies on this...[Mathemagenic] Just as there are public and private places... George Siemens reflects on best uses of blog and wiki spaces to support online communities. Here the question revolves around moving back and forth from from establishing a personal identity on a personal blog.. and moving to a multi-author space where a shared identity around a theme or mission is established.. this is truly the commons. When to switch blogging tools?. I've been reading about a few bloggers moving off of manila or Radio. Here's the basic formula for when to switch. When you add up the: - Current value of my blogging tool - Expected value of the stream of improvements to my blogging tool - Cost of switching And find it is less than the: - Current value of an alternative tool - Expected value of the stream of improvements to the alternative tool Then it will be time to move. Every product manager faces this formula. Dave Winer leaving UserLand is a blow to the future value of the product. His radar for novel technologies and software architectures kept exciting new features coming every month for years. One of John Robb's challenges: making and keeping the promise of an exciting and valuable future for the product family.[a klog apart] John Robb can start by calling Erin Clerico at Weblogger about his new suite of tools... run John...My take is that a lot of open source cms look pretty lame and look like knock offs of one another... but I have a suspicion that new open source cms tools will be built to die for.. in by late this year.. So Userland better stay light on its feet! I luv Manila. Parent Voices in the Barrio. Today, I was invited to demonstrate something about technology to our parents interested in bilingual education. I chose weblogs to demonstrate. The parents will meet next week to write for themselves!. They seem to have a lot of ideas to write about. Publishing to the Internet seemed to be a nice option to them. Four of the moms never touched a computer, much less a wireless iBook before today.
http://radio.weblogs.com/0100504/categories/blogging/
crawl-002
refinedweb
3,684
64.61
Many CPians have written about COM, why again? Most people learned COM by building a InprocServer, i.e., a DLL file first, and then continued to write a LOCAL COM server together with a client. At this point, a simple example showing a LOCAL COM server and client will be very helpful. However, believe it or not, I spent hours searching the net, trying to find a small example of a LOCAL COM server and client so I can grow my own system based on it, but I never found one! Most of the examples I found are Inproc servers. In some cases, I found LOCAL servers, but the document only lists the basic steps/ideas without giving the code. As a matter of fact, from knowing the steps to building a real one is still quite a long way to go: you have to write the idl file, the reg file, you have to include different files at the right places (even in the right order! you will see), ..., and a single mistake will bring you very confusing error messages or results. I then found Andrew Troelsen's book and tried to follow his example. However, I moved his server code from the attached CD to my local PC only to find that his LOCAL server did not even compile - I finally figured out the reason (you will see if you continue to read) and I believe that he should have mentioned this problem in his book - this would have saved his readers lots of frustration and searching around. Meanwhile, he did not present the client code, so that is still not a whole story. InprocServer Inproc So I decided to write down all the necessary steps you should follow, all the real code you need to write, all the files you have to create, and all the things you want to remember if you decide to build a LOCAL COM server and client - this small example can then serve as a starting point for your much better and bigger (also ambitious) project. Still, let me clearly state that half of the credit should go to Andrew Troelsen: for the server side, I am using his example and his code (with the problem corrected), if you want to know more about this part, you can check his book out. Therefore, if you are interested in building a LOCAL COM server and client, this example might be helpful to you. Also, I assume you have the basic knowledge of COM: the architecture, the interfaces, COM run-time service functions, and the variety of tools that you can use to get the GUID and to inspect your components, so on and so forth. In the next section, a LOCAL COM server is constructed, and after that, a client is built. Enjoy! GUID In this section, the steps that are needed to build a LOCAL server are described. This simple server contains a single coclass called MyCar and the following three interfaces: ICreateMyCar, IEngine and IStats. The whole server is very much self-explained, so let the show begin! coclass MyCar ICreateMyCar IEngine IStats Step 1: Start VC6.0 and create a new WIN32 Application workspace, select "a simple application", and name it CarLocalServer (or whatever you want to). Step 2: create your idl file, it should look like the following, and name it CarLocalServerTypeInfo.idl: import "oaidl.idl"; // define IStats interface [object, uuid(FE78387F-D150-4089-832C-BBF02402C872), oleautomation, helpstring("Get the status information about this car")] interface IStats : IUnknown { HRESULT DisplayStats(); HRESULT GetPetName([out,retval] BSTR* petName); }; // define the IEngine interface [object, uuid(E27972D8-717F-4516-A82D-B688DC70170C), oleautomation, helpstring("Rev your car and slow it down")] interface IEngine : IUnknown { HRESULT SpeedUp(); HRESULT GetMaxSpeed([out,retval] int* maxSpeed); HRESULT GetCurSpeed([out,retval] int* curSpeed); }; // define the ICreateMyCar interface [object, uuid(5DD52389-B1A4-4fe7-B131-0F8EF73DD175), oleautomation, helpstring("This lets you create a car object")] interface ICreateMyCar : IUnknown { HRESULT SetPetName([in]BSTR petName); HRESULT SetMaxSpeed([in] int maxSp); }; // library statement [uuid(957BF83F-EE5A-42eb-8CE5-6267011F0EF9), version(1.0), helpstring("Car server with typeLib")] library CarLocalServerLib { importlib("stdole32.tlb"); [uuid(1D66CBA8-CCE2-4439-8596-82B47AA44E43)] coclass MyCar { [default] interface ICreateMyCar; interface IStats; interface IEngine; }; }; Insert this file into your project. Also, notice that all the GUIDs should be generated by using guidgen.exe, so your IDs will not look like the ones in the above file. I listed above every line of this file so you can have a clear picture about this simple server. For the rest of the files in the server, you can download them and read them through. Step 3: Insert the following files into your workspace: CarLocalServer.cpp, MyCar.cpp, MyCarClassFactory.cpp, Locks.cpp, MyCar.h, MyCarClassFactory.h and Locks.h. Now, here come the things that you really need to pay attention to (these two things are not mentioned in Troelsen's book, but they are the reasons that I could not compile): #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers If it does, make sure to get rid of it (comment it out). This is the other reason why I could not get the server successfully compiled (and it took me a while to figure this out). I really think Troelsen should have mentioned these two things. Well, if you happen to read his book, I hope you notice this article too, it might save you some time. Step 4: Create the .reg file. You can use whatever name you want for this file, but its content has to be exactly the same as the one you downloaded from this article, except: After you create this file, double click it, your Windows system should tell you that your components are successfully registered. Step 5: Build the whole project. You should have no compiling errors, and remember that you should at least run it once. Now you have it: a LOCAL COM server. Let me again say that this part of the code is from Troelsen's book and I just made little corrections as seen in step 3 (to get rid of the compiling errors). Also, I added some error protection in the server too; in case something goes wrong, you can get some error messages that make sense. Now, let us follow the following steps to build a LOCAL COM client. I will list the source code here and explain the important parts since Troelsen did not present the client in his book. Step 1: Start your VC6.0 again and create a new WIN32 Console Application workspace. Select "an empty project", and name it CarLocalClient (or whatever you want to). CarLocalClient Step 2: Create a new .cpp to be your client code, use whatever name you want for this file, and add it to the project. Your client code should look like the following: #include "../CarLocalServer/CarLocalServerTypeInfo.h" // use your own path here #include "../CarLocalServer/CarLocalServerTypeInfo_i.c" // use your own path here #include "iostream.h" // for showing possible mistakes void ShowErrorMessage(LPCTSTR,HRESULT); int main() { // initialize the COM runtime cout << "Initialize the COM runtime..."; CoInitialize(NULL); cout << "success." << endl; // declare variables HRESULT hr; IClassFactory* pICF = NULL; ICreateMyCar* pICreateMyCar = NULL; IEngine* pIEngine = NULL; IStats* pIStats = NULL; cout << endl << "Get the class factory interface for the Car class..."; hr = CoGetClassObject(CLSID_MyCar,CLSCTX_LOCAL_SERVER, NULL,IID_IClassFactory,(void**)&pICF); if ( FAILED(hr) ) { ShowErrorMessage("CoGetClassObject()",hr); exit(1); } else cout << "success." << endl; cout << "Create the Car object and get back the ICreateMyCar interface..."; hr = pICF->CreateInstance(NULL,IID_ICreateMyCar,(void**)&pICreateMyCar); if ( FAILED(hr) ) { ShowErrorMessage("CoCreateInstance()",hr); exit(1); } else cout << "success." << endl; // set parameters on the car cout << endl << "Set different parameters on the car..."; pICreateMyCar->SetMaxSpeed(30); BSTR carName = SysAllocString(OLESTR("COMCar?!")); pICreateMyCar->SetPetName(carName); SysFreeString(carName); cout << "success." << endl; cout << endl << "Query the IStats interface..."; pICreateMyCar->QueryInterface(IID_IStats,(void**)&pIStats); cout << "success." << endl; cout << endl << "Use the IStats interface to display the status of the car:" << endl; pIStats->DisplayStats(); cout << endl << "Query the IEngine interface..."; pICreateMyCar->QueryInterface(IID_IEngine,(void**)&pIEngine); cout << "success." << endl; cout << endl << "Start to use the engine..." << endl; int curSp = 0; int maxSp = 0; pIEngine->GetMaxSpeed(&maxSp); do { pIEngine->SpeedUp(); pIEngine->GetCurSpeed(&curSp); cout << "current speed is: " << curSp << endl; } while (curSp <= maxSp); if ( pICF ) pICF->Release(); if ( pICreateMyCar) pICreateMyCar->Release(); if ( pIStats ) pIStats->Release(); if ( pIEngine ) pIEngine->Release(); cout << endl << "Close the COM runtime..."; CoUninitialize(); cout << "success." << endl; return 0; } void ShowErrorMessage(LPCTSTR header, HRESULT hr) { void* pMsg; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,NULL,hr, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPTSTR)&pMsg,0,NULL); cout << header << ": Error(" << hex << hr << "): " << (LPTSTR)pMsg << endl; LocalFree(pMsg); } Notice the include statement: you don't really need to include anything like windows.h, you only need to include the CarLocalServerTypeInfo.h and CarLocalServerTypeInfo_i.c files, and these two files include all the necessary header files for you already. Notice that these two files are generated by your system after VC6.0 compiles CarLocalServerTypeInfo.idl file, and they are located in the workspace that you have created in Section 2. So you need to either copy them to your client workspace directory, or you can use a relative path like I did here. include To access your COM components (your coclass and interfaces), you first make the call to the COM service function CoGetClassObject(), and what you get from this call is the pointer to your IClassFactory interface. Once you have this interface, the rest seems to be obvious: you then make a call to CreateInstance() on this interface to start your journey. You may have noticed the CLSTX_LOCAL_SERVER parameter in CoGetClassObject() call, this is where we show that we are building a LOCAL server! CoGetClassObject() IClassFactory CreateInstance() CLSTX_LOCAL_SERVER Another choice is to call CoCreateInstance() instead of CoGetClassObject(). This function in fact makes a call to CoGetClassObject() and then another call to CreateInstance() just like what we did in our client code. Perhaps you should do what we did here in this client code: besides the performance considerations, it seems to be safer to do so: by making the two calls yourself, you can put error protections after each call, so if anything goes wrong, you have a fairly clear idea of where the problem is. On the other hand, if you use CoCreateInstance(), if this call fails, you lose control of where the problem is. Notice in this client code, we just show the error, we did not put any exception handling code - I just assume that you will be the one who will add the appropriate exception handlings. CoCreateInstance() Step 3: build the project and try it out. You should be able to "talk" to your COM server without making it a in-process DLL file. These are the basic steps of how to build a LOCAL COM server and client. If you really try it out, you will see that it does involve a fairly large amount of work, and again, a single mistake will give you very confusing error messages. Perhaps, after trying this example out, you will start to appreciate ATL more. This article presents a simple example of how to build your own LOCAL COM server and client. The real benefit of it, at least I hope, is that you can use this as a starting point to build much more practical and bigger projects. You might want to use ATL in your real work, but understanding what is going on under the hood is always good. Thank you for reading, and I certainly look forward <iostream.h> "iostream.h" <iostream> using namespace std 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/script/Articles/View.aspx?aid=8679
CC-MAIN-2014-52
refinedweb
1,948
61.06
Searched for: "net send sdk windows" About 17 results for "net send sdk windows" Reverse engineering your .NET applications The .NET Framework makes it easy to reverse engineer an existing application. Discover what techniques to use to deter prying eyes from deconstructing your code. TR member appeals to Canadian government to reorganize IT and go open source TechRepublic member Jaqui submitted a "Letter to the Editor," which in this case is actually a reprint of a letter that he wrote to a Member of Parliament about why the Canadian go... Found a two solutions. Just so everyone knows I found two solutions. One - if you have the resources this is preferable. Write your own software to do the switch. With .NET and the WMS SDK you can crea... Seamlessly integrate applications with eBay using its Windows SDK The eBay Windows SDK allows you to easily access eBay data within your application. Tony Patton gives you an overview of the functionality provided by the eBay Web services API. BizTalk Server 2004: Ten things you should know BizTalk Server 2004, Microsoft's third try at an integration server for bridging business processes internally and between companies, was a charm. But there's more under the hood t... Take advantage of .NET Framework command-line utilities Tony Patton examines the command-line tools installed with the .NET Framework and explains how you may use them in your projects. Embed me: Career opportunities in embedded software Writing software designed to be embedded in an appliance, phone, or some other real-world device is a growth area, but has its own set of challenges. First look: Microsoft Speech Server Speech recognition technologies could make a leap forward in business usage with Microsoft Speech Server 2004. See what it can do.... .NET demystifies encryption .NET makes cryptography a little simpler by putting everything into one SDK. Find out how to encrypt and decrypt a text file with the System.Security.Cryptography namespace.
http://www.techrepublic.com/search/?q=net+send+sdk+windows
CC-MAIN-2014-52
refinedweb
326
57.37