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
23 December 2010 08:32 [Source: ICIS news] SINGAPORE (ICIS)--Benzene values in Asia touched an 11-month high on Thursday, supported by buoyant energy futures and spikes in US benzene prices overnight, market players said. Spot values were hovering at a range of $1,040-1,050/tonne (€790-798/tonne) FOB (free on board) Korea on Thursday, up $20/tonne from Wednesday's close and up $60/tonne from the same period last week . These prices were the highest seen since 22 January 2010, according to ICIS data. Crude futures were hovering at above $90/bbl on Thursday, while US benzene values were at $3.62-3.64/gal FOB Barges on Wednesday. Firm prices in the downstream styrene monomer (SM) market were also aiding the strong benzene values, which have been on an uptrend this month, traders said. Meanwhile, toluene prices in Asia also rose by $15-20/tonne on Thursday to $940-950/tonne FOB ?xml:namespace> ($1 = €0.76) For more
http://www.icis.com/Articles/2010/12/23/9421961/asia-benzene-touches-11-month-high-on-strong-crude.html
CC-MAIN-2014-15
refinedweb
166
72.26
Every so often, while using Studio, I come across clever little gems (not the Ruby kind) that our team thoughtfully inserted into the product to improve usability. These gems don’t get a lot of fanfare, nor do they often warrant much attention on their own, but put together, they make for a smoother, intuitive user experience. Nearly invisible, they have become nearly indispensable to me. #1 Wrap in and Extract to Building along, building along, then all of a sudden I decide to cache part of a flow. I could drag a cache scope onto the canvas, then drag message processors inside its boundaries. Or, I could Command+click to select a few message processors on my canvas, then right-click to select Wrap in > Cache. Done. Similarly, if I wanted to just extract those message processors to a new, separate flow or sub flow, it’s right-click to select Extract to > Flow. Oh, right-click! Is there anything you can’t do? #2 Distraction-free modeling Want to get rid of the background noise and build your flows on a big, blank canvas? As an Eclipse-based IDE, take advantage of this OOTB feature: double-click the tab of your Studio project to minimize the other windows in Studio and maximize the canvas space. Double-click the tab again to resurface all the other windows. #3 Insta-docs! Let’s say you built an app in Studio and it is good. It’s elegant, it’s efficient, and it works like a charm. Everyone wants to see what you’ve done, and you want to show off your mad skillz. Rather than projecting Studio onto the meeting room wall, then trying to slide horizontally and vertically around the canvas, describing the different pieces verbally, you can instantly create much more presentable, and digestible, documentation that describes your project. From the File menu, select Export Studio Documentation to auto-generate an index.html file (and its attendant files) that contains all your flows, your XML and any content you added to the Documentation tab in each message processor. The layout of this documentation is designed to be presented to an audience, even if you’re not there to walk them through it. #4 Print canvas …and for your presentation, you can also print out your canvas to that your audience can reference the complete flow(s) as they are graphically rendered in Studio. From the File menu, select Export diagram to…, save the PNG and create hard or soft copies that display your app’s flow(s) as pretty graphics. #5 Tweak it There will always be little things that could use adjusting. Maybe you prefer an XML line width of 65 instead of the default 72; maybe you want to change the default target namespace; maybe you find red text *really* distracting and want to change the error message text color from red to a less-alarming shade of mauve. Whatever the tweak, use MuleStudio Preferences. (MuleStudio > Preferences, or Command+,) #6 Add libraries Ever find that you need to add user libraries? There’s a wizard for that. Right-click your project’s name, then select Build Path > Add Libraries… then answer all the wizard’s questions to add your library. Want to get rid of an old one? Right-click your project’s name, then select Build Path > Configure Build Path… Click the Libraries tab, then just select the one you want to pitch and click the Remove button. Gone! (Full details.) #7 Meddle with reality Using Studio’s Visual Debugger yet? Stay tuned for a blog post that highlights the best parts of Debugger for a trove of useful tips on how to use it. Meanwhile, I’ll just call out one little gem: changing the payload of a message at a breakpoint. Let’s say you’ve applied a bunch of breakpoints to your application so that when running in debug mode you can check on the payload of a message as it reaches and passes through each breakpoint. That might help you understand any potential weak points in the app, but what if you want to see what happens if you change just one little part of the payload? With debugger, you can do it! With your application running in debug mode, access one of the breakpoints, then click the little “X=Y=?” icon, which is the Expression Evaluator. In the yellow box that pops up, enter an expression to change the payload, then press enter. Click the Next Processor icon (or F6) to move forward to the next breakpoint, and note that your payload value in the message pane has changed. #8 Set an Exception Strategy as Default Though Studio automatically handles all exceptions with its default exception strategy, you can create your own custom global exception strategy, then make it the default for your application. Create a global exception strategy by first dragging an Exception Strategy onto your canvas outside and below all flows, then filling it with message processors to handle your exceptions. Then right-click the title bar of the exception strategy and select Set as default exception strategy. (Check the XML; there’s a new configuration global element sitting above all your flows referencing your global exception strategy as the application’s default.) #9 Create a POM for your new project If you know, or suspect, that at some point you’ll need to export your Studio project and continue building or modifying it with Maven, then you better start with a pom. If you normally click through wizards without reading anything (uh… isn’t that everyone?) then you might have missed it: on the third screen of the New Project wizard in Studio, there’s a checkbox labeled “Create POM file for project and maintain with Maven”. Check that. Now you get a POM to go with your project. #10 What have I done? If you’ve been playing around with your instance of Studio and have added a bunch of Mule extensions, runtimes, or plugins, you might find yourself wondering, “what the heck have I got installed here?” Or maybe that’s just me. Anyway, if you want to take a look, navigate to MuleStudio > Preferences, then click to select Install/Update. From there, click the link that reads Uninstall or update software that is already installed. Studio displays it all: Installed Software, Features, Plugins, Installation History. (Full details.) Those are my favs. Got some of your own to share? Add a comment below. Happy right-clicking! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/10-little-mule-studio-gems
CC-MAIN-2016-22
refinedweb
1,103
60.55
iEmitState Struct ReferenceThis interface describes the API for the emitter mesh object. More... #include <imesh/emit.h> Inheritance diagram for iEmitState: Detailed DescriptionThis interface describes the API for the emitter mesh object. Main creators of instances implementing this interface: - Emit mesh object plugin (crystalspace.mesh.object.emit) - iMeshObjectFactory::NewInstance() Main ways to get pointers to this interface: Main users of this interface: - Emit Loader plugin (crystalspace.mesh.loader.emit) Definition at line 293 of file emit.h. Member Function Documentation Add an aging moment, they are interpolated. time is the time since creation of the particle in msec. color is a gouraud color to set the particle to. (0..1) alpha can be used to make the particles transparent. the value 0 is a solid particle, the value 1 is an invisible particle the swirl value gives a swirlyness of the movement of the particle. rotspeed is the rotationspeed of the particle (per second). scale is the size of the particle at the time Get the number of aging moments. get the settings of aging moment i (0..number-1) get the particle attrator emitter. Null means no attractor. Get the force of the attractor. Get container box, particles are only allowed inside this box. returns true if the container box is enabled. Objects outside this box are not drawn. But they are also not restarted, since that would cause many short-aged particles. get field accel emitter, can be 0 get field speed emitter, can be 0 See if lighting is enabled. Get the number of particles used. Get the time to live for all particles, in msec. get the size of rect particles; Get the regular shaped particles sides and radius. get the particle start acceleration emitter get the particle start position emitter get the particle start speed emitter remove an aging moment replace the settings for the age at the timepoint given. set the particle attrator emitter, increfs. Position is given. Set the force of the attractor (negative gives repulsion). Set container box, particles are only allowed inside this box. Set the field accel emitter, increfs (given position determines accel). Set the field speed emitter, increfs (given position determines speed). Enable or disable lighting. Set the number of particles to use. Set the time to live for all particles, in msec. Set the particle system to use rectangular particles, given w, h. Set the particle system to use regular shaped particles. set the particle start acceleration emitter, increfs. Position is given. set the particle start position emitter, increfs set the particle start speed emitter, increfs. The position is given. true if using rect particles. false if using regular particles. The documentation for this struct 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/structiEmitState.html
CC-MAIN-2016-26
refinedweb
465
61.12
$ cnpm install control.foldl This is a port of the Haskell Control.Foldl package. This package provides efficient left folds in applictive styles. fantasy-land compatible. e.g. For calculating standard deviation using the formular below. const varianceFormular = sqrSum => length => mean => Math.sqrt(sqrSum / length - mean * mean) We can fold an array using this package's utility functions. import {sqrSum, length, mean} from 'control.foldl' // generate a fold const std = sqrSum .map(varianceFormular) .ap(length) .ap(mean) const arr = [1, 2] // actually run the fold by calling reduce const result = std.reduce(arr) // 0.5 It's very easy to write inefficient folds when multiple foldings are needed. e.g. here is a naive implementation of calculating standard deviation: const arr = [1, 2] const sqrSum = arr.reduce((acc, cur) => cur * cur + acc, 0) const length = arr.reduce((acc, _) => acc + 1, 0) const mean = arr.reduce((a, b) => a + b, 0) / length const std = varianceFormular(sqrSum)(length)(mean) The code above loop through the array every time reduce is called. Whereas, the example in the first section only loops once. It's also very easy to write efficient folds but not generic enough. e.g. const [sqrSum, length, sum] = arr.reduce( (acc, cur) => // calculating every step of square sum, sum and length at the same place [ acc[0] + cur * cur, // square sum acc + 1, // length acc + cur // sum ] [0, 0, 0], )([1, 2]) const std = varianceFormular(sqrSum)(length)(sum / length) The above code increase effeciency as in calculating every step of square sum, sum and length at the same place. Accordingly, it combines the starting values for each operation (square sum, sum and length) inside an array as the initial value to the reduce function. This approach can be easilly adopted for combining any number of foldings. This package is to provide abstraction over this approach and utility funcitons for various foldings for your needs. To come up a new fold base on existing folds (in this example calculating average of an array of numbers), first, write the algorithm in a curried function. // instead of (sum, length) => ... const avgAlgorithm = sum => length => sum / length Second, use map and ap to generate a fold import {sum, length} from 'control.foldl' const avg = sum // since avgAlgorithm take the sum of array first, we put sum here first .map(avgAlgorithm) // we use map to 'embed' avgAlgorithm into fold. .ap(length) // we use `ap` to bring the length of the array to the second argument of avgAlgorithm // the above does not actually doing any folding but instead constructing the folding like the example under `Why` section to be triggered. Thirdly, run the fold using reduce. avg.reduce([1, 2]) // 0.5 If none of the build-in utils satisfy your needs, you can always write your own (PR welcome): import {Fold} from 'control.foldl' const halfSum = Fold( (acc, cur) => acc + cur, // the reducer function, just like the one you pass to Array.prototype.reduce but with only the first 2 arguments (no index as the 3rd argument) 0, // the initial value sum => sum / 2 // this is the function runs after folding finishes. It receives the last accumulated value as input. The output will be the output when run the `reduce` method on `halfSum`. ) halfSum.reduce([1, 3]) // 2 Map before fold is a very common need. But a separate map from fold is not efficient. This package provides preMap for this. import {premapM, sum} from 'control.foldl' const sqr = a => a * a const sqrSum = premapM(sqr)(sum) // [1, 2] will only be looped once sqrSum.reduce([1, 2]) // 5 Similarly, there is a prefilter to combine a filter operation with fold efficiently. import {prefilter, sum} from 'control.foldl' const sumOver2 = prefilter(a => a > 2)(sum) // [1, 2, 3, 4] will only be looped once for summing and filtering at the same time sumOver2.reduce([1, 2, 3, 4]) // 7 The above example can be written like this: import {sum} from 'control.foldl' const halfSum = sum.map(a => a / 2) halfSum.reduce([1, 3]) // 2 This is because any fold (the sum imported in this case) is a functor, it maps the last param passed to Fold when constrcted (in sum, it is id). And id as a function is a functor itself as well. So maping on it is the same as compose a function on to id. This package also provide a monadic version of the Fold called FoldM. import daggy from 'daggy' // create a Monad called AMonad const AMonad = daggy.tagged('AMonad', 'a') AMonad.of = a => AMonad(a) AMonad.prototype.chain = function(f) { return f(this.a) } AMonad.prototype.map = function(f) { return AMonad(f(this.a)) } // make array a fantasy-land compatible Monoid Array.empty = _ => [] // this is in the source code: const sink = (Monad, Monoid) => act => FoldM( (m, a) => // the reducer function now needs to return values inside monadic context act(a) .map(m_ => r.concat(m, m_) ), Monad.of(Monoid.empty()), Monad.of ) const result = sink(AMonad, Array)( a => AMonad.of([a + 1, a + 3, a + 5]) ).reduce([1, 2, 3]) result.toString() // AMonad([2, 4, 6, 3, 5, 7, 4, 6, 8]) There are also monadic versions for premap and prefilter Sometime, you need to use the build-in non-monadic util together with FoldM. Then you need to convert them. import {generalize, sum} from 'control.foldl' const sumM = generalize( SomeMonad // this needs to be a fantasy-land compatible monad )(sum) sumM.reduce([1, 2, 3]) // SomeMonad(6) You can use map and ap just like before import {generalize} from 'control.foldl' const g = generalize(AMonad) const sumM = g(sum) const lengthM = g(length) const avg = sum => length => sum / length sumM .map(avg) .ap(lengthM) .reduce([9, 2, 4]) // AMonad(5) Type signaure, description and examples are in source code.
https://developer.aliyun.com/mirror/npm/package/control.foldl
CC-MAIN-2020-34
refinedweb
961
58.48
spacegrids 1.3.0 numpy array with grids and associated operations SPACEGRIDS README.), Levitus Data. If you have problems reading data and/ or interpreting metadata (or find a bug), the author would be happy to take a look (see also Github for email etc). Installs by typing “pip install spacegrids” on command line. On Mac, pip can be installed via “sudo easy_install pip”. On Ubuntu/ Debian, install dependencies via package manager if pip install fails: apt-get install python-{tk,numpy,matplotlib,scipy} Documentation: The following import statement provides all functionality: from spacegrids import ORGANISATION ON DISK Before using projects, Netcdf data must be organised in a projects directory tree..): - 1 downloads in the last day - 1249 downloads in the last week - 9898 downloads in the last month -.3.0.xml
https://pypi.python.org/pypi/spacegrids/1.3.0
CC-MAIN-2015-35
refinedweb
131
50.87
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. I just spent about an hour crafting a detailed message about what I need to do, but when I submitted it, I got an error and my message was wiped out. So I'm just going to give the bare essentials here and hopefully someone can help. I need to know what the status of an issue was before the transition post functions are executed. I need to skip a step in the workflow under certain conditions, so I'm using the "Fast Track Transition an issue" script, which must be placed after the fire event function. However, by that point, the issue's original status has been changed by the "linked status of the destination workflow step", and "issue.getStatus().name" returns the new status, not the original status. Is there a function call that I can use to access the original status? Thanks! Anne Can you access details of the issue prior to the change with originalIssue?(e.g. originalIssue.status?.name) No luck. Admittedly I'm just trying things and don't understand the difference between using the status?.name vs getStatus().name, tho in the end all of these return the status that I'm transitioning to, not the status the issue was in before the transition was initiated: The only way I've found yet to get the "previous" status is by putting a post function in as the very 1st step, before the "Set issue status to the linked status of the destination workflow step." But the Fast-track transition specifically says to put it after the "Fire Event" function, so maybe the best I can do it so store off the original Status in Step 1, and then access it in my custom script after the Fire Event? Ah yes. That rings a bell. There are other community posts that talk about using transientVards instead. Perhaps something here helps? I tried a bunch of things keying off that article, but they all also give me back the destination workflow. Just for completeness, and in case anyone searching wants to see, I tried all of the following: def myStep = transientVars["createdStep"] as Step def myStepId = myStep.getStepId() def prevStatus = ComponentAccessor.getConstantsManager().getStatus(myStepId as String) log.debug "In fast track, prevStatus.name is " + prevStatus.name log.debug "In fast track, prevStatus.id is " + prevStatus.id int actionId = transientVars.get("actionId") log.debug("The current transition id is: " + actionId)") And got the following debug output, where 4 is the Step for Ready To Build and 31 is the transition for Ready to Build... ;) In fast track, prevStatus.id is 4 The current transition id is: 31 Current action name: Ready to Build In fast track, originalIssue.status?.name is Ready To Build Maybe someday I'll figure out an elegant way to do it, but at this point I'm just going to store off the original status off in a variable at the beginning of the Post Function, and then compare it in the Fast Track Post Function. Thanks for your.
https://community.atlassian.com/t5/Marketplace-Apps-questions/How-to-find-the-status-before-the-PostFunction-executes/qaq-p/597769
CC-MAIN-2019-13
refinedweb
529
63.8
JabPreface From WikiContent Programming Jabber Original Book was Copyright 2002 bare-throated bellbird and the topic of Jabber is a trademark of O'Reilly & Associates, Inc. LEGO� is a registered trademark of The LEGO� Group. MINDSTORMS and Robotics Invention System are trademarks of The LEGO� Group. All other trademarks, service marks, and the like are the property of their owners. While every precaution has been taken in the preparation of this book, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. Preface. This is all rather abstract, so what do we mean by "extensible framework for exchanging information"? Taking it one word at a time: - Extensible - Jabber's substrate is XML. XML is inherently extensible in the sense - that tags can be added in a hierarchical sequence. Namespaces in XML - allow us to keep track of the meaning and organization of these tags. - Framework - You can put together a system for exchanging information using many - different tools. The point about the "framework" is that the - information exchanged and the entities that are exchanging it are - contextualized, bringing meaning and structure to the interactions. - Exchanging - Conversation is two-way, and it takes many forms - question and answer, - notification, compartmentalized discussion, and simple chat. Jabber - supports all these different types of conversation and more. - Information - One doesn't really say that information is exchanged in a - conversation, but when you bring applications into the mix of - conversing entities, it may well be the case. And it's not just - information exchanged in the form of conversations but also - information about the entities themselves that flows across this - context framework. It goes without saying: Jabber is an instant - messaging (IM) system. Instant messaging was Jabber's original raison d'�tre. Many deployments of Jabber software are to provide IM services, but Jabber is more than IM�certainly more than the phrase "instant messaging" represents. In this book you'll find out why this is so and how you can deploy solutions with Jabber that are more than mere chat. But most importantly, Jabber is fun! Like chess, which has a small set of rules but countless game possibilities, the technologies employed in Jabber and the Jabber protocol itself are straighforward. The possibilities are almost limitless. Furthermore, because of a fundamental design feature[1] (you might call it a "philosophical" angle), implementing Jabber-based solutions to your problems can be fun�really! The History of Jabber Jeremie Miller started the Jabber project early in 1998, and it was announced to the public in January 1999. To understand why Jabber came about, and in the form it took, let's look briefly at what existed in the IM world before Jabber. The Pre-Jabber History While the concept of live chat systems has existed for many years, with commands such as Unix's talk and VMS's phone, IM as we know it today existed as a concept and a handful of systems from companies such as Mirabilis, AOL, Microsoft, and Yahoo!. These systems (ICQ from Mirabilis, AIM from AOL, MSN from Microsoft, and Yahoo!IM from Yahoo!) allowed their users to chat to one another and avail themselves of IM-related services. However, an AIM user couldn't chat with an ICQ user, and MSN users couldn't interact with Yahoo!IM users. Each system was effectively closed to the outside world. Furthermore, the protocols that these systems used were also mostly closed�proprietary�which meant it was difficult to find clients for these IM systems other than the ones supplied by the IM system owner. Finally, the systems themselves were monolithic: multiple clients but a single server (or server farm). Although the companies were able to invest time and money into the problem, the fact remained that a monolithic architecture presented a scaling problem. Perhaps more relevant than that, companies that wanted to use IM services internally had to accept the fact that the conversations would be carried through the systems of a third party�namely the owners of these public IM systems. This was no more desirable than for a company to run its internal email using a public email service such as Hotmail. Of course, these systems did have their advantages. The clients were accomplished and easy to learn and use, and as long as your correspondents were using the same IM system and you didn't mind your messages being carried by another organization (for private individuals these wouldn't be unique circumstances; again, we are led to the email services parallel), then you could leave the system management to someone else and get on with chatting. Scratching an Itch Having all your contacts use the same IM system is all well and good in theory but in practice is rarely the case. (If you're like me and have only a few friends, then this is not so much of a problem.) Jeremie Miller had correspondents in different IM systems and consequently had to have different IM clients running on his desktop to keep up with them all. Many great software projects stem from a personal "itch" that someone wanted to scratch. This was the primary itch that Jeremie had�a single client for all IM interaction: panacea. Of course, one obvious solution would be to build a single client that supported all of the IM system protocols, but this approach had two drawbacks: - The proprietary nature of the protocols made it harder to implement the support required and would make the client overly complicated. - Every time the protocol, which wasn't under his control, changed or a new one came along, the client would have to be modified�a task not practical for a large user base. On top of that, GUI programming isn't everyone's cup of tea, and Jeremie preferred a solution that allowed him to concentrate on the underlying problems at hand and let others build the GUIs. Along Came Jabber So Jeremie resolved to create a solution that had the following characteristics: It would have its own internal protocol, based upon XML. This protocol should be: - Simple to understand and implement - Easy to extend - Open - The complexity of bridging the disparate proprietary IM protocols would remain at the server, each bridge being a plug-in module. - All the clients would have to implement only the single, simple open protocol; everything else would be implemented at the server. He called this solution "Jabber." The main architectural feature for Jabber that Jeremie strived for was that it should be simple enough for anyone to implement a Jabber server of his own. Unlike a centralized server environment, with all of the traffic routed through a central point, Jeremie envisioned that Jabber would be decentralized, allowing individuals, companies, and public organizations to run their own servers. This is particularly relevant for internal-only, IM-style corporate communications. Just as email servers are used to exchange mail using the Simple Mail Transport Protocol (SMTP), the Jabber servers are able to connect and exchange IM traffic whenever necessary. Figure P-1 illustrates Jabber's distributed architecture, with two separate Jabber servers serving separate users. Being open meant that Jabber could benefit from the help of anyone who wished to lend a hand, and administrators were empowered to be able to find and fix problems themselves if they so wished. ß Being XML-based, as opposed to another binary format, for example, meant that the protocol streams were easy for humans to read, extensible, and readily integrated (a great range of XML parsing and construction tools is already available). Being distributed meant that the Jabber system would belong to the people and that some of the scalability problems would be avoided. There remain some scalability issues, of course. Client-server communication that is TCP socket-based suffers from limitations of this technology. There are, however, initiatives to overcome these limitations with multiplexing techniques such as jpolld and dpsm (see). All of these features made for a good IM system design. But why stop at IM? Consider the client as an implementation of a simple protocol to exchange messages and presence information in XML structures and use plug-in services at the server, and what do you have? A language- and platform-agnostic XML routing framework. Good grief, what a mouthful! This is why my response to "What is Jabber?" is usually just: A really great technology! IM System Features This book assumes you have a basic knowledge of features commonly found in IM systems. In case you don't, here's a brief rundown of features relevant to what we'll be covering: - Presence - In many cases, there's not much point in sending a quick message to - someone if they're not there. Presence is a term used in IM to - describe the technique of exchanging information, in a controlled - manner, about availability (or unavailability). - The idea is that - when you connect to your IM server, your client sends an "I'm here" - message that is relayed to your correspondents. It does the opposite - when you disconnect. During the time you're connected, you can vary - the information about your availability to reflect your immediate - situation ("just popped out for coffee," "working on my resum��don't - disturb me!"). - Buddy List�/roster - Both terms (the former comes from the original IM systems, the latter - from Jabber) refer to a list of correspondents with whom you regularly - communicate and from whom you receive presence information. Depending - on the IM system, the list may be stored on the client or on the - server. Storing the list on the client has the (tenuous) advantage of - being accessible when you're not connected to the server. Storing the - list on the server means that you have a consistent roster content - regardless of the client or workstation you happen to use�the list - travels with you. - Jabber stores the roster on the server. - Push and pull - When you connect to an IM system, there may be information the client - needs to retrieve�pull�from the server (the roster, for instance). - This is under direct control of your client as it decides when to make - the retrieval. During the course of the connection, you'll receive - messages from your correspondents. You don't request these messages by - making a retrieve call to the server, as you would with the Post - Office Protocol (POP) or Internet Message Access Protocol (IMAP) to - retrieve email messages from the mail server; they're pushed to - you as they occur. : In other words, you could say that the client - must implement an event-based system, to listen out for and - subsequently handle the incoming information, by displaying a pop-up - window containing the chat message, for example. : The push/pull - system lends itself well to traffic other than IM traffic. - Client-server - It almost goes without saying that, like other IM systems, Jabber has - a client-server architecture. Clients and client libraries that - implement the Jabber protocol, such as Net::Jabber, - Jabber::Connection, Jabberpy, and - JabberBeans, are available for many languages (here, for : Perl, Python, and Java). - With Jabber, it is especially relevant to - stress that the "weight balance" in complexity terms, between the - client and the server, comes down heavily on the server side. Not only - does this mean that the complexity remains where it should be�on the - server�but also makes the task of writing clients easier and the - resulting software lighter. ; Multiple versus single server - We've already mentioned that the Jabber architecture does not dictate - a single, centralized server. Not only does this mean that - organizations can implement their own private system, but also that - developers are free to install their own server and develop new - plug-in services in addition to the IM bridges already available. What's Inside This book is not particularly about IM per se. Nor is it about the bridges to other IM systems. It's about the essence, the ideas, and the potential behind that concept and reality called Jabber. You will learn about the Jabber protocol and how to use Jabber's technology to implement not only IM-based solutions but also solutions that don't involve inane chat. You'll learn how to install and configure your own Jabber server. You will discover more about the features of Jabber that give it its propensity for being an ideal messaging glue for many communication solutions; all of Jabber's technology features�the building blocks and the protocol itself�are explained; and you'll get to know how Jabber can be implemented in a variety of situations�some involving IM, others not�through a series of application and problem scenarios with fully working code examples, or recipes, in Perl, Python, and Java. Here's a brief overview of what's in the book: - Part I - The first part of this book provides you with an introduction to - Jabber; you'll learn about its features, why it's more than an IM - system, and how to install and configure a Jabber server of your own. - Chapter 1 - We begin with an imaginary conversation with human and application - participants that shows how Jabber provides the supporting messaging - "plasma." A short script shows how simple it is to make use of - Jabber's power. - Chapter 2 - We take a look at some of the features�the nature�of Jabber, to - understand why Jabber is more than just an IM system. The features - introduced in this chapter will be revisited as core building material - for our recipes in Part I. - Chapter 3 - Here you'll learn how to retrieve and install the Jabber server and - perform minimal configuration, enough to be able to fire it up and use - it as a basis for the recipes in Part I. Some troubleshooting and - monitoring tips are also included. - Chapter 4 - Once we have our Jabber server installed and running, we take a closer - look at how the server has been designed. We focus on the server - makeup and the different ways it can be deployed. A detailed tour of - the standard configuration is also in this chapter. - Part II - The second part of this book provides detailed information about the - Jabber protocol and a series of recipes�practical solutions to - everyday problems�deployed in Jabber. The recipes use various Jabber - features as a way of illustrating parts of the protocol. - Chapter 5 - We take a detailed look at what Jabber looks like under the hood. We - examine Jabber IDs (JIDs), resource and priority, and XML streams, and - the basic Jabber building blocks (<message/>, - <iq/>, and <presence/>). - Chapter 6 - This chapter focuses on the standard Jabber namespaces used to - accomplish IM-related and other tasks. A description for each one is - given in turn. - Chapter 7 - This chapter looks at the steps needed to create and authenticate with - a user and examines the different types of authentication. We also - build a utility to create users in order to generate users for our - recipes. - Chapter 8 - This chapter looks at some simple examples of Jabber deployment using - basic features of message and presence, including presence - subscription. - Chapter 9 - Extending the themes introduced in Chapter 8, we look at how messages - can be extended to carry custom and compartmentalized data and how to - write a 'bot that serves in a conference room. Furthermore, we look at - how components are defined and written and examine how different event - models can coexist with Jabber's. - Chapter 10 - This chapter shows diverse applications of Jabber, from building an - online address book using Jabber as infrastructure, through exchanging - XML-RPC-encoded requests and responses over Jabber, to extending the - client scope of SAP's R/3 business software. Software Used in This Book The recipes in this book come in varying flavors, some in Perl, some in Python, and some in Java. These examples�to a greater or lesser degree�make use of prewritten libraries that provide at least the basic services needed to connect to a Jabber server and exchange data with it. Here's a summary of the versions of the languages used in this book, along with those libraries that are used, what features they offer, and where they're available. In addition, references to all of these libraries can be found on the Jabber development web site,. The installation instructions for the libraries can be found in the library packages themselves. Java The Java recipes in this book are written in Java 2 (J2SE�the Java 2 Standard Edition), specifically with the 1.3.1 version of the Java Development Kit (JDK). JabberBeans is the name of the Java library for Jabber used in this book. It offers comprehensive coverage of the features needed to write programs that interact with Jabber servers: connection, authentication, and the management of Jabber elements passed between your script and the Jabber server. The JabberBeans library can be obtained from. The version used in this book is 0.9.0-pre4. Perl The recipes have been built and tested with Perl 5.6.0, although earlier and later versions of release 5 will probably work just fine. Two libraries are available for programming Jabber solutions in Perl. Both come in the form of installable modules and are of the object-oriented persuasion. - Net::Jabber - This module is available on the Comprehensive Perl Archive Network - (CPAN), at. Net::Jabber provides basic - functionality for connecting to and interacting with a Jabber server, - in addition to a host of higher-level features for manipulating all of - the Jabber elements and making use of standard and custom namespaces. - - It relies upon a companion module XML::Stream, also - available on CPAN, that provides the underlying mechanisms for - creating connections to a Jabber server, as well as sending, - receiving, and interpreting (parsing) the fragments of conversation - between your script and that Jabber server. - The version of - Net::Jabber used in this book is 1.0022. The corresponding - version of XML::Stream used is 1.12. - Jabber::Connection - The Jabber::Connection module is available on CPAN and - provides the same basic features Net::Jabber does, albeit in - a more "RISC" (Reduced Instruction Set Computing) way. While it - provides similar functionality for connecting to and exchanging data - with a Jabber server, it offers, via a companion modulecalled - Jabber::NodeFactory, a lower-level API�similar to that in the - Jabber server itself�for constructing and manipulating the Jabber - elements. There are no high-level features; instead, you build your - own using the building blocks that the module provides. : The version - of Jabber::Connection used in this book is 0.02. Python The Python examples have been written with Python 2.0. Jabberpy is the name of the Python Jabber library used in the Python recipes in this book. As with Perl's Net::Jabber library set, Jabberpy provides its feature set from two separate libraries�jabber, which provides connectivity, authorization, and callback functions such as Net::Jabber and Jabber::Connection, and xmlstream, which provides the basic connectivity and parsing functions such as Net::Jabber's companion XML::Stream. The Jabberpy libraries are available from its project site, at. The version of Jabberpy used in this book is 0.2. Where to Go for More Information There are plenty of places out there on the Net to find out more about Jabber in general and programming with Jabber in particular. The main web site at jabber.org has a number of faces: - - This is the main entry point for all things Jabber. Start here if you - want to find out about Jabber generally. ; - You can find information on development efforts, both core and - peripheral, here. There are lists of projects, discussion forums, and - news items concerning new developments and initiatives in the Jabber - world. ; - This is the place to go to if you want more information on Jabber's - technology and protocols. It has a range of documents contributed by - various members of the Jabber community. In addition to the sites - listed here, there are other resources available online for learning - more about Jabber. Countless mailing lists, linked to from the - page, cover subjects ranging from identity and - profiles to security. The two main mailing lists are jadmin and - jdev, covering administrativeand development subjects, - respectively. All newcomers are welcome! Finally, there's a Jabber conference room called jdev where many of the Jabber developers hang out. Just point your Jabber client at conference.jabber.org and drop by for a chat. Conventions Used in This Book The following typographical conventions are used in this book: - Bold - Used for commands, programs, and options. All terms shown in bold are - typed literally. ; Italic - Used to show arguments and variables that should be replaced with - user-supplied values. Italic is also used to indicate new terms, URLs, - filenames, file extensions, directories, and to highlight comments in - examples. -.Note:These signify a tip, suggestion, or general note.Warning:These indicate a warning or caution. ==: - [3] We have a web site for the book, where we'll list examples, errata, and any plans for future editions. The site also includes a link to a forum where you can discuss the book with the author and other readers. You can access this site at: - For more information about this book and others, see the O'Reilly web site: Acknowledgments To my dearest wife, Sabine, who patiently and quietly took on all the demands of daily life for us during this project, allowing me to devote myself to researching and writing. To my son, Joseph, who knew I was writing a book but also knew that helping him build train tracks, drawing, and going on bicycle rides was always good tonic for a mind congested with XML. To my grandpa, Harold Lomax, who never tired of reading through what I had written to check and correct grammar and punctuation. To my editor, Chuck Toporek, who not only has great taste in music, but also has a sense of humor to match his infinite patience. Chuck taught me a great deal about writing and thinking, without me even realizing it was happening. Also, many thanks to David Chu, Chuck's editorial assistant. It's easy to miss the people behind the scenes when they do such a good job, so thanks for pushing my SGML files through when they needed to be checked by Tools, for coordinating the technical review, and for assisting Chuck to make this book happen. Thanks also to Lenny Muellner, my SGML guru. He helped me with my SGML queries and always kept me on the right track. To the reviewers of this book, Jens Alfke, Matthew Allum, Michael Bauer, Piers Harding, Jeremie Miller, and Thomas Muldowney, who gave up a lot of their time to provide me with wonderful feedback and great insights. Special thanks go to Piers, the best technical debating partner you could wish for; trying to keep up with him mentally is what drives me on. And, of course, where would this book be without the very thing that captured my imagination and held it all this time? Thanks to Jeremie and the team of core Jabber developers for building something so fascinating. Thanks also to the Jabber developer community at large, a more friendly bunch of diverse people one could hardly hope to meet. Finally, thanks to Tim O'Reilly and all of O'Reilly & Associates, Inc., for seeing Jabber for what it really is and for having confidence in me to write about it.
http://commons.oreilly.com/wiki/index.php?title=JabPreface&oldid=1582
CC-MAIN-2016-50
refinedweb
3,928
50.97
Many a times in a dataset we find Date Time Stamps which is the combination of Date and Time written in a perticular format. For analysis we have to split the Data Time Stamp such that we can get different information seperately like Year, Month, Day, Hour, Minute and Seconds. This can be easily done by using pandas. So this is the recipe on how we can split DateTime Data to create multiple feature in Python. Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects import pandas as pd We have imported only pandas which is requied for this split. We have created an empty dataframe then we have created a column 'date'. By using date_range function we have created a dataset of date time stamp by passing the parameters of starting date, periods i.e number of stamps and frequency as weekly. df = pd.DataFrame() df['date'] = pd.date_range('1/6/2020 01:00:00', periods=6, freq='W') print(df) Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro We have to split the date time stamp into few features like Year, Month, Day, Hour, Minute and Seconds. For each of the feature split there are pre defined functions. df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month df['day'] = df['date'].dt.day df['hour'] = df['date'].dt.hour df['hour'] = df['date'].dt.hour Now we are printing the final dataset and the output comes as: date 0 2020-01-12 01:00:00 1 2020-01-19 01:00:00 2 2020-01-26 01:00:00 3 2020-02-02 01:00:00 4 2020-02-09 01:00:00 5 2020-02-16 01:00:00 date year month day hour minute 0 2020-01-12 01:00:00 2020 1 12 1 0 1 2020-01-19 01:00:00 2020 1 19 1 0 2 2020-01-26 01:00:00 2020 1 26 1 0 3 2020-02-02 01:00:00 2020 2 2 1 0 4 2020-02-09 01:00:00 2020 2 9 1 0 5 2020-02-16 01:00:00 2020 2 16 1 0
https://www.projectpro.io/recipes/split-datetime-data-create-multiple-feature-in-python
CC-MAIN-2021-43
refinedweb
381
70.63
Hi, I recently developed a program which has source and header files in vc++! what I want to do is convert the same in C#. I got the idea of source files but how to import/use header files in C#(I want seperate file for class creation/ data initialization like header files)? help me! - 3 Contributors - forum4 Replies - 103 Views - 6 Years Discussion Span - comment Latest Post by JMC31337 C# does not use header files. Everything is contained in the class itself. The framework reads the "assembly" to determine what is available to other classes that call it. You can put your classes in separate files or in separate projects. Even if you are calling them from c++, you won't need a header. Edited by thines01: n/a old topic but if you want to use .h files with C# it really depends upon what youre trying to accomplish: For instance i am writing a memorystream picture box that will display a bitmap So i used bin2c to create the .h header file which contains my bitmap as a byte array which can be streamed so it would be something like bin2c -o bit.h image.bmp Bin2c will creat the bit.h with the file array as a: /* Generated by bin2c, do not edit manually */ /* Contents of file fake_login1.bmp */ const long int fake_login1_bmp_size = 37676; const unsigned char fake_login1_bmp[37676] = { ... array of bytes ... } delete the const long int fake_login1_bmp_size = 37676; change the const unsigned char fake_login1_bmp[37676] to: public static byte[] bit = { ... array of bytes .. } add the class so in all it would look like: /* Generated by bin2c, do not edit manually */ public class Test { public static byte[] bit = { .. array ...}; } then to compile the header with your app: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc /target:exe /out:123.exe 123.cs bit.h =================== to actually use the header byte array it would be something like: System.Drawing.Image newImage; MemoryStream stream = new MemoryStream(Test.bit); newImage = System.Drawing.Image.FromStream(stream); its basically creating a class which only contains your "data" or "variable" which yu can call.. make sure its a public class and a public static "variable" ie: byte[] array so that it can be accessed by any function Lastly: if youre trying to use .h files which contain functions written for C++ its not going to happen, you'll need to convert the C++ API into the C# API with [DLLImport] If its a C# class within a .h file its no different than that of main.cs class1.cs class2.cs class3.h class4.h Edited by JMC31337
https://www.daniweb.com/programming/software-development/threads/412965/how-to-use-header-h-files-in-c
CC-MAIN-2018-51
refinedweb
437
73.88
ncl_aggetp man page AGGETP — Allows a user program to get the values of a group of parameters containing one or more elements. Synopsis CALL AGGETP (TPGN,FURA,LURA) C-Binding Synopsis #include <ncarg/ncargC.h> void c_agget. Its value may be less than, equal to, or greater than, the length of the group specified by TPGN. The number of values transferred into FURA is the minimum of the two (but not less than one). You may, for example, get the first two parameters of a 100-parameter group by using LURA = 2. C-Binding Description The C-binding argument description is the same as the FORTRAN argument description. Usage This routine allows you to retrieve the current value of Autograph parameters. For a complete list of parameters available in this utility, see the autograph_params man page. Access To use AGGETP or c_aggetp, load the NCAR Graphics libraries ncarg, ncarg_gks, and ncarg_c, preferably in that order. To get smoother curves, drawn using spline interpolation, also load libdashsmth.o. Or, you can use the ncargf77 command to compile your program and load the above libraries, then, to get smoother curves, use the -dashsmth option. Messages See the autograph man page for a description of all Autograph error messages and/or informational messages. See Also Online: autograph, autograph_params, agback, agbnch, agchax, agchcu, agchil, agchnl, agcurv, agdshn, aggetc, aggetf, agget.
https://www.mankier.com/3/ncl_aggetp
CC-MAIN-2017-47
refinedweb
226
55.84
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. send mail updated field how to send mail if a field is updated ? for example in project.task, i want to send mail if assigned to is updated ? You can help me plzzz ? Thx First create Email Template for object project.task and then call following method either from create or write by overwriting them. def send_mail(self, cr, uid, ids, context=None): template_ids = email_template_obj.search(cr, uid, [('model_id.model', '=', 'project.task')]) if template_ids: values = email_template_obj.generate_email(cr, uid, template_ids[0], id, context=context) values['subject'] = "your_subject" values['email_to'] = "email_to_address" values['email_cc'] = "email_cc_address" values['body_html'] = "your_html_message" values['body'] = "your_html_message" mail_mail_obj = self.pool.get('mail.mail') msg_id = mail_mail_obj.create(cr, uid, values, context=context) mail_mail_obj.send(cr, uid, [msg_id], context=context) return True Overwrite write method in project_task class: def write(self, cr, uid, ids, vals, context=None): if vals.get('user_id', False): self.send_mail(cr, uid, ids, context=context) return super(project_task, self).write(cr, uid, ids, vals, context=context) Mail will be sent when you will change Assigned to in Project Task and click on Save. You can call this method from write/create method. Do you want to send mail when particular field is updated? You have to put this code in your custom module if you are creating any custom module or you can put it in project/project.py file under class project_task. Then once restart your server. i put this code in setting ==> action server ==> python code ==> project.task ==> and i copy this code and nothing ... def write(self, cr, uid, ids, vals, context=None): if vals.get('user_id', False): self.send_mail(cr, uid, ids, context=context) return super(project_task,!
https://www.odoo.com/forum/help-1/question/send-mail-updated-field-19963
CC-MAIN-2016-50
refinedweb
307
53.78
API docs¶ check50¶ - exception check50.EOF(value)¶ Raised when EOF is read from a child. This usually means the child has exited. - exception check50.Failure(rationale, help=None)¶ Exception signifying check failure. - Parameters rationale (str) – message to be displayed capturing why the check failed help (str) – optional help message to be displayed Example usage: out = check50.run("./cash").stdin("4.2").stdout() if 10 not in out: help = None if 11 in out: help = "did you forget to round your result?" raise check50.Failure("Expected a different result", help=help) - exception check50.Mismatch(expected, actual, help=None)¶ Exception signifying check failure due to a mismatch in expected and actual outputs. - Parameters expected – the expected value actual – the actual value help (str) – optional help message to be displayed Example usage: from re import match expected = "[Hh]ello, world!?\n" actual = check50.run("./hello").stdout() if not match(expected, actual): help = None if match(expected[:-1], actual): help = r"did you forget a newline ('\n') at the end of your printf string?" raise check50.Mismatch("hello, world\n", actual, help=help) - exception check50.Missing(missing_item, collection, help=None)¶ Exception signifying check failure due to an item missing from a collection. This is typically a specific substring in a longer string, for instance the contents of stdout. - Parameters item – the expected item / substring collection – the collection / string help (str) – optional help message to be displayed Example usage: actual = check50.run("./fibonacci 5").stdout() if "5" not in actual and "3" in actual: help = "Be sure to start the sequence at 1" raise check50.Missing("5", actual, help=help) - check50.check(dependency=None, timeout=60, max_log_lines=100)¶ Mark function as a check. - Parameters dependency (function) – the check that this check depends on timeout (int) – maximum number of seconds the check can run max_log_lines (int) – maximum number of lines that can appear in the log When a check depends on another, the former will only run if the latter passes. Additionally, the dependent check will inherit the filesystem of its dependency. This is particularly useful when writing e.g., a compilescheck that compiles a student’s program (and checks that it compiled successfully). Any checks that run the student’s program will logically depend on this check, and since they inherit the resulting filesystem of the check, they will immidiately have access to the compiled program without needing to recompile. Example usage: @check50.check() # Mark 'exists' as a check def exists(): """hello.c exists""" check50.exists("hello.c") @check50.check(exists) # Mark 'compiles' as a check that depends on 'exists' def compiles(): """hello.c compiles""" check50.c.compile("hello.c") @check50.check(compiles) def prints_hello(): """prints "Hello, world!\\n""" # Since 'prints_hello', depends on 'compiles' it inherits the compiled binary check50.run("./hello").stdout("[Hh]ello, world!?\n", "hello, world\n").exit() - check50.data(**kwargs)¶ Add data to the check payload - Params kwargs key/value mappings to be added to the check payload Example usage: check50.data(time=7.3, mem=23) - check50.exists(*paths)¶ Assert that all given paths exist. - Params paths files/directories to be checked for existence - Raises check50.Failure – if any path in pathsdoes not exist Example usage: check50.exists("foo.c", "foo.h") - check50.hash(file)¶ Hashes file using SHA-256. - Parameters file (str) – name of file to be hashed - Return type str - Raises check50.Failure – if filedoes not exist - check50.import_checks(path)¶ Import checks module given relative path. - Parameters path (str) – relative path from which to import checks module - Returns the imported module - Raises FileNotFoundError – if path / .check50.yamldoes not exist yaml.YAMLError – if path / .check50.yamlis not a valid YAML file This function is particularly useful when a set of checks logically extends another, as is often the case in CS50’s own problems that have a “less comfy” and “more comfy” version. The “more comfy” version can include all of the “less comfy” checks like so: less = check50.import_checks("../less") from less import * Note the __name__of the imported module is given by the basename of the specified path ( lessin the above example). - check50.include(*paths)¶ Copy files/directories from the check directory ( check50.internal.check_dir), to the current directory - Params paths files/directories to be copied Example usage: check50.include("foo.txt", "bar.txt") assert os.path.exists("foo.txt") and os.path.exists("bar.txt") - check50.log(line)¶ Add to check log - Parameters line (str) – line to be added to the check log The check log is student-visible via the --logflag to check50. - class check50.run(command, env={})¶ Run a command. - Parameters command (str) – command to be run env (dict) – environment in which to run command By default, the command will be run using the same environment as check50, these mappings may be overriden via the envparameter: check50.run("./foo").stdin("foo").stdout("bar").exit(0) check50.run("./foo", env={ "HOME": "/" }).stdin("foo").stdout("bar").exit(0) - exit(code=None, timeout=5)¶ Wait for process to exit or until timeout (5 sec by default) and asserts that process exits with code. If codeis None, returns the code the process exited with. ..note:: In order to ensure that spawned child processes do not outlive the check that spawned them, it is good practice to call either method (with no arguments if the exit code doesn’t matter) or .kill()on every spawned process. - Parameters code (int) – code to assert process exits with timeout (int / float) – maximum number of seconds to wait for the program to end - Raises check50.Failure – if codeis given and does not match the actual exitcode within timeout Example usage: check50.run("./hello").exit(0) code = check50.run("./hello").exit() if code != 0: raise check50.Failure(f"expected exit code 0, not {code}") - kill()¶ Kill the process. Child will first be sent a SIGHUP, followed by a SIGINTand finally a SIGKILLif it ignores the first two. - reject(timeout=1)¶ Check that the process survives for timeout. Useful for checking whether program is waiting on input. - Parameters timeout (int / float) – number of seconds to wait - Raises check50.Failure – if process ends before timeout - stdin(line, str_line=None, prompt=True, timeout=3)¶ Send line to stdin, optionally expect a prompt. - Parameters line (str) – line to be send to stdin str_line (str) – what will be displayed as the delivered input, a human readable form of line prompt (bool) – boolean indicating whether a prompt is expected, if True absorbs all of stdout before inserting line into stdin and raises check50.Failureif stdout is empty timeout (int / float) – maximum number of seconds to wait for prompt - Raises check50.Failure – if promptis set to True and no prompt is given - stdout(output=None, str_output=None, regex=True, timeout=3, show_timeout=False)¶ Retrieve all output from stdout until timeout (3 sec by default). If outputis None, stdoutreturns all of the stdout outputted by the process, else it returns self. - Parameters output (str, int, float, stream) – optional output to be expected from stdout, raises check50.Failureif no match In case output is a float or int, the check50.number_regex is used to match just that number”. In case output is a stream its contents are used via output.read(). str_output (str) – what will be displayed as expected output, a human readable form of output regex (bool) – flag indicating whether outputshould be treated as a regex timeout (int / float) – maximum number of seconds to wait for output show_timeout (bool) – flag indicating whether the timeout in seconds should be displayed when a timeout occurs - Raises check50.Mismatch – if outputis specified and nothing that the process outputs matches it check50.Failure – if process times out or if it outputs invalid UTF-8 text. Example usage: check50.run("./hello").stdout("[Hh]ello, world!?", "hello, world").exit() output = check50.run("./hello").stdout() if not re.match("[Hh]ello, world!?", output): raise check50.Mismatch("hello, world", output) check50.c¶ - check50.c.CC = 'clang'¶ Default compiler for check50.c.compile() - check50.c.CFLAGS = {'ggdb': True, 'lm': True, 'std': 'c11'}¶ Default CFLAGS for check50.c.compile() - check50.c.compile(*files, exe_name=None, cc='clang', max_log_lines=50, **cflags)¶ Compile C source files. - Parameters files – filenames to be compiled exe_name – name of resulting executable cc – compiler to use ( check50.c.CCby default) cflags – additional flags to pass to the compiler - Raises check50.Failure – if compilation failed (i.e., if the compiler returns a non-zero exit status). RuntimeError – if no filenames are specified If exe_nameis None, check50.c.compile()will default to the first file specified sans the .cextension: check50.c.compile("foo.c", "bar.c") # clang foo.c bar.c -o foo -std=c11 -ggdb -lm Additional CFLAGS may be passed as keyword arguments like so: check50.c.compile("foo.c", "bar.c", lcs50=True) # clang foo.c bar.c -o foo -std=c11 -ggdb -lm -lcs50 In the same vein, the default CFLAGS may be overriden via keyword arguments: check50.c.compile("foo.c", "bar.c", std="c99", lm=False) # clang foo.c bar.c -o foo -std=c99 -ggdb - check50.c.valgrind(command, env={})¶ Run a command with valgrind. - Parameters command (str) – command to be run env (str) – environment in which to run command - Raises check50.Failure – if, at the end of the check, valgrind reports any errors This function works exactly like check50.run(), with the additional effect that commandis run through valgrindand valgrind’s output is automatically reviewed at the end of the check for memory leaks and other bugs. If valgrindreports any issues, the check is failed and student-friendly messages are printed to the log. Example usage: check50.c.valgrind("./leaky").stdin("foo").stdout("bar").exit(0) Note It is recommended that the student’s code is compiled with the -ggdb flag so that additional information, such as the file and line number at which the issue was detected can be included in the log as well. check50.flask¶ - class check50.flask.app(path='application.py', app_name='app')¶ Spawn a Flask app. - Parameters path (str) – path to python file containing Flask app app_name – name of Flask app in file Example usage: check50.flask.app("application.py").get("/").status(200) - __init__(path='application.py', app_name='app')¶ Initialize self. See help(type(self)) for accurate signature. - content(output=None, str_output=None, **kwargs)¶ Searches for output regex within HTML page. kwargs are passed to BeautifulSoup’s find function to filter for tags. - get(route, data=None, params=None, follow_redirects=True)¶ Send GET request to app. - Parameters route (str) – route to send request to data (dict) – form data to include in request params – URL parameters to include in request follow_redirects (bool) – enable redirection (defaults to True) - Returns self - Raises check50.Failure – if Flask application throws an uncaught exception Example usage: check50.flask.app("application.py").get("/buy", params={"q": "02138"}).content() - post(route, data=None, params=None, follow_redirects=True)¶ Send POST request to app. - Parameters route (str) – route to send request to data (dict) – form data to include in request params – URL parameters to include in request follow_redirects (bool) – enable redirection (defaults to True) - Raises check50.Failure – if Flask application throws an uncaught exception Example usage: check50.flask.app("application.py").post("/buy", data={"symbol": "GOOG", "shares": 10}).status(200) - raw_content(output=None, str_output=None)¶ Searches for output regex match within content of page, regardless of mimetype. - status(code=None)¶ Check status code in response returned by application. If codeis not None, assert that codeis returned by application, else simply return the status code. - Parameters code (int) – codeto assert that application returns Example usage: check50.flask.app("application.py").status(200) status = check50.flask.app("application.py").get("/").status() if status != 200: raise check50.Failure(f"expected status code 200, but got {status}") check50.py¶ - check50.py.append_code(original, codefile)¶ Append the contents of one file to another. - Parameters original (str) – name of file that will be appended to codefile (str) – name of file that will be appende This function is particularly useful when one wants to replace a function in student code with their own implementation of one. If two functions are defined with the same name in Python, the latter definition is taken so overwriting a function is as simple as writing it to a file and then appending it to the student’s code. Example usage: # Include a file containing our own implementation of a lookup function. check50.include("lookup.py") # Overwrite the lookup function in helpers.py with our own implementation. check50.py.append_code("helpers.py", "lookup.py") - check50.py.compile(file)¶ Compile a Python program into byte code - Parameters file – file to be compiled - Raises check50.Failure – if compilation fails e.g. if there is a SyntaxError - check50.py.import_(path)¶ Import a Python program given a raw file path - Parameters path (str) – path to python file to be imported - Raises check50.Failure – if pathdoesn’t exist, or if the Python file at paththrows an exception when imported. check50.regex¶ - check50.regex.decimal(number)¶ Create a regular expression to match the number exactly: In case of a positive number: (?<![\d\-])number(?!(\.?\d)) In case of a negative number: number(?!(\.?\d)) (?<![\d\-])= negative lookbehind, asserts that there are no digits and no - in front of the number. (?!(\.?\d))= negative lookahead, asserts that there are no digits and no additional . followed by digits after the number. - Parameters number (any numbers.Number (such as int, float, ...)) – the number to match in the regex - Return type str Example usage: # Check that 7.0000 is printed with 5 significant figures check50.run("./prog").stdout(check50.regex.decimal("7.0000")) check50.internal¶ Additional check50 internals exposed to extension writers in addition to the standard API - class check50.internal.Register¶ Class with which functions can be registered to run before / after checks. check50.internal.registershould be the sole instance of this class. - after_check(func)¶ Run func once at the end of the check, then discard func. - Parameters func – callback to run after check - Raises check50.internal.Error – if called when no check is being run - after_every(func)¶ Run func at the end of every check. - Parameters func – callback to be run after every check - Raises check50.internal.Error – if called when a check is being run - check50.internal.compile_checks(checks, prompt=False, out_file='__init__.py')¶ Compile YAML checks to a Python file - Parameters checks – YAML checks read from config prompt (bool) – prompt user if out_filealready exists out_file (str) – file to write compiled checks - Returns out_file - Return type str - check50.internal.import_file(name, path)¶ Import a file given a raw file path. - Parameters name (str) – Name of module to be imported path (str / Path) – Path to Python file - check50.internal.load_config(check_dir)¶ Load configuration file from check_dir / ".cs50.yaml", applying defaults to unspecified values. - Parameters check_dir (str / Path) – directory from which to load config file - Return type dict - check50.internal.register = <check50.internal.Register object>¶ Sole instance of the check50.internal.Registerclass - check50.internal.run_root_dir = None¶ Temporary directory that is the root (parent) of all run_dir(s)
https://cs50.readthedocs.io/projects/check50/en/latest/api/
CC-MAIN-2021-25
refinedweb
2,475
50.43
>>convert* I've read an example of using qsort, in which the prototype shows us that the function is waiting for a void pointer to the first element of the array to be sorted. But i don't see where exactly they converted the pointer of values[] to a void pointer- it's just passed AS IT IS. Whereas the function is awaiting the "void *base". The same thing with the function that compares, which is passesd to qsort. It also awaits "const void*" whereas i pass integers to it. Code:void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))Code:#include <stdlib.h> int values[] = { 88, 56, 100, 2, 25 }; int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { qsort(values, 5, sizeof(int), cmpfunc); return(0); }
http://forums.devshed.com/programming-42/qsort-covert-void-950010.html
CC-MAIN-2018-05
refinedweb
139
70.23
. Filtering Email Messages in Microsoft Outlook Despite the fact that we are the Microsoft Scripting Guys we don’t see scripting as being the answer to all of life’s problems. (Most of them, maybe, but not all of them.) In fact, when it comes to system administration we tend to believe that the quickest and easiest solution is almost always the best solution. More often than not we find it quicker and easier to write a script than to use a command line tool or the graphical user interface. However, that isn’t always the case, and if it’s quicker and easier to use the GUI than to write and use a script, well, we recommend you use the GUI. (Besides, that would make one less scripting column we’ll have to write!) This is especially true when it comes to Microsoft Outlook. We haven’t written much about Outlook in Office Space, for two reasons: first, Outlook’s user interface is actually pretty good, and second, due in large part to the new security features that have been added to the program, Outlook scripts aren’t always faster and easier, and they can’t always be run in unattended fashion. If we’re going write about scripting against Microsoft Outlook, it will have to be because we’ve found an area where scripting outshines the user interface. We think we’ve found just such an area when it comes to filtering email messages. It’s not unusual for people to want to grab all the email messages that fit certain criteria and then do something with them. For example, maybe you want to take all the messages sent by Ken Myer and move them from the Inbox to a different folder. Maybe you want to take all the messages with the subject Project Proposal and print them. Maybe you want to take all the messages that have been marked for follow-up and dump the text into a single Word document. You can do things like that via the user interface. Or, you can do things like that using a script no more complicated than this:("[Subject] = 'Project Proposal'") For Each objMessage In colFilteredItems objMessage.PrintOut Next This script – which automatically prints all the emails with the subject line Project Proposal – begins by defining a constant named olFolderInbox, and then sets the value of this constant to 6; we’ll use this constant to tell the script which Outlook folder to bind to. Next we create an instance of the Outlook.Application object, and use the GetNamespace method to bind to the MAPI namespace (which happens to be the only namespace we can bind to). We then call the GetDefaultFolder method (passing our constant olFolderInbox as the only parameter), thus creating a connection to the Inbox. All that gets us to the point where we can start to do something interesting. To begin with, we use this line of code to return a collection containing all the items in the Inbox: With that collection in hand we can then call the Restrict method to filter out emails that don’t fit the specified criteria. Note that we aren’t deleting the emails from the Inbox, we’re just grabbing all the emails with the subject line Project Proposal and putting them in a new collection named colFilteredItems. We do this by enclosing the mail message property (Subject) in square brackets, adding an equal sign, and then enclosing the target subject line in single quotes. In other words: What if we wanted only email messages from Ken Myer? No problem; we do the same sort of thing: Again, we have the mail message property (From) in square brackets, an equal sign, and then the target subject line in single quotes. How about mail items marked for follow-up? Well, if you check out the MailItem documentation in the Microsoft Outlook VBA Language Reference, you’ll see that FlagStatus property is an integer value; further investigation will tell you that a 2 indicates that a message has been marked for follow-up. (Hint: Look up the enumeration values for the constant olFlagStatus.) Thus our code would look like this: Notice that we don’t enclose the value 2 in single quotes. Single quotes are used for string values; you don’t need them when working with numeric values or with Boolean values. For example, this code returns a collection of unread messages: Neat, huh? Generally speaking, if it’s a property of the MailItem object then you can filter on it. You can also combine filter requirements. For example, suppose you want only those unread messages that came from Ken Myer. Here you go: In this case we have two separate filters: [Unread] = True and [From] = 'Ken Myer'. All we’ve done is combine those two filters using the AND operator. Or how about emails that came from either Ken Myer or Pilar Ackerman: You get the idea. What’s cool, of course, is not only the ability to return a targeted set of emails, but to then do something with that entire set. In our sample script, we use the PrintOut method to print each email in the collection: You could just as easily dump each message into a Word document or a database. Alternatively, you might want to display each message in the command window. That’s as simple as echoing back the value of the Body property: Just like that, you now have a quick and easy way to read related emails from the command line. Like we said, this is one time where we find it quicker and easier to use a script than to use Outlook’s user interface. (And thank goodness we found yet another place where scripting really shines: after all, we’re not real keen on becoming the Microsoft Unemployed Guys.) We can’t guarantee that the scripts we showed you today represent the answers to all of life’s problems. But, then again, we can’t guarantee that they aren’t the answers to all of life’s problems, either. Hey, you never know….
https://technet.microsoft.com/en-us/library/3fd56986-0cec-4fa4-849b-975afa405874
CC-MAIN-2016-18
refinedweb
1,024
67.08
NAME AxKit::XSP::CharsetConv - AxKit XSP taglib for charset conversion SYNOPSIS Add the CharsetConv namespace to your XSP <xsp:page> tag: <xsp:page And add the taglib to AxKit (via httpd.conf or .htaccess): AxAddXSPTaglib AxKit::XSP::CharsetConv DESCRIPTION The XSP CharsetConv taglib implements character set conversion as implemented in iconv(), through the Apache::AxKit::CharsetConv module that comes with your standard AxKit install. You may wish to use it to convert data from misc. sources (databases, files, browser posts, the environment, etc...) that are not UTF-8 yet need to be included in the output of your XSP. Tag Reference There is only one tag provided by this taglib: charset-convert. It has two mandatory attributes, from and to, which are the character codes to convert (surprise) from and to. The to attribute defaults to UTF-8, which usually makes sense. The from attribute on the other hand defaults to ISO-8859-1. While this default is very eurocentric, it would have been an arbitrary choice no matter what my choice would have been... so I picked the one that's most useful to me :-) AUTHOR Robin Berjon, robin@knowscape.com Copyright (c) 2001 Robin Berjon. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/AxKit::XSP::CharsetConv
CC-MAIN-2018-30
refinedweb
220
65.32
I’ve recently had cause to parse some date values in Java. As a result I’ve produced a class which can manage to parse an awful lot of date formats. I thought I’d better document it in case someone found it useful. Certainly there doesn’t appear to be anything elsewhere which shows you how to parse lots of formats. I have found the order of date_formats to be very brittle, so I don’t recommend you change it without an awful lot of test cases. Anyway, without further to do, I present to you, the Pathological Date Parser for Java // Copyright 2006 David Pashley <david@davidpashley.com> // Licensed under the GPL version 2 import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; public class Date { private Calendar date; static String[] date_formats = { "yyyy-MM-dd'T'kk:mm:ss'Z'", // ISO "yyyy-MM-dd'T'kk:mm:ssz", // ISO "yyyy-MM-dd'T'kk:mm:ss", // ISO "EEE, d MMM yy kk:mm:ss z", // RFC822 "EEE, d MMM yyyy kk:mm:ss z", // RFC2882 "EEE MMM d kk:mm:ss zzz yyyy", // ASC "EEE, dd MMMM yyyy kk:mm:ss", //Disney Mon, 26 January 2004 16:31:00 ET "-yy-MM", "-yyMM", "yy-MM-dd", "yyyy-MM-dd", "yyyy-MM", "yyyy-D", "-yyMM", "yyyyMMdd", "yyMMdd", "yyyy", "yyD" }; public Date(String d) { SimpleDateFormat formatter = new SimpleDateFormat(); d = d.replaceAll("([-+]\d\d:\d\d)", "GMT$1"); // Correct W3C times d = d.replaceAll(" ([ACEMP])T$", " $1ST"); // Correct Disney timezones for (int i = 0; i < date_formats.length; i++) { try { formatter.applyPattern(date_formats[i]); formatter.parse(d); date = formatter.getCalendar(); break; } catch(Exception e) { // Oh well. We tried } } } } The only date formats I can’t get it to parse are <4-digit year>-<day of year> and <2digit year><day of year> (e.g. 2003-335 and 03335 for 2003-12-01). If you can add support for those and other date formats I’ll gladly take patches. on said: man Date::Parse on said: In germany, the most common date formats are “d.m.yy” and “dd.mm.yyyy” – consider having some localization support. on said: I agree with foo that you should look into Perl. It already has everything you are looking for and it’s less wordy. on said: Are there any easy ways of embedding perl in Java that don’t impose huge runtime costs? In the real world, you don’t have the option of saying to your manager “lol, im leeet lets stop using java in our product and use perl rofl lol luser!11!!”. In your parents basement you can probably get away with that though.
https://www.davidpashley.com/2006/05/25/date-parsing/
CC-MAIN-2021-21
refinedweb
444
65.93
14 May 2012 11:07 [Source: ICIS news] SINGAPORE (ICIS) -- Sinopec and PetroChina are expected to refine 30.00m-30.20m tonnes of crude altogether in May, with daily throughput up by 1.5% month on month to about 971,000 tonnes, sources from the two companies said on Monday. Sinopec’s crude throughput target for May is 18.7m-18.8m tonnes, with daily throughput up by 2.56% to about 606,000 tonnes, according to a company source. PetroChina plans to process 11.3m-11.4m tonnes of crude this month, with daily throughput stable at about 365,000 tonnes, said the company source. However, it will shut some other refineries for maintenance in May and the total capacity of these refineries under maintenance is around 37m tonnes/year, the source added. In northeast ?xml:namespace> In northwest The daily throughput of Sinopec and PetroChina, two of the country’s largest refiners, is expected to rise further in June as there will be less maintenance scheduled then, according to C1 Energy, an ICIS service
http://www.icis.com/Articles/2012/05/14/9559206/sinopec-petrochina-raise-daily-crude-throughput-by-1.5-in-may.html
CC-MAIN-2014-42
refinedweb
176
72.46
How to transfer parameters in th:href in spring boot Thymeleaf? These are my simple Thymeleaf table HTML file and Spring MVC controller codes. First below is my table image. I try to make some html codes to transfer the post id value to view codes when the 'Edit' or 'Delete' link are clicked, but I have no idea how to do. These are my Spring MVC Controller codes and view.html codes. @Controller public class PostController { @Autowired private PostService postService; @RequestMapping("/posts/view/{id}") public String view(@PathVariable("id") Long id, Model model) { Post post = postService.findById(id); model.addAttribute("post", post); return "posts/view"; } And, <table id="blogTable" border="1" width ="1000" height="400" align = "center"> <thead> <tr> <th>Post ID</th> <th>Post Title</th> <th>Post Content</th> <th>Date</th> <th>Author</th> <th>Action</th> </tr> </thead> <tbody> <tr th: <td th:Post ID</td> <td th:Post Title</td> <td th:Post Content</td> <td th:Date</td> <!-- <td th:Author</td> --> <td> <a href="posts/view.html" th:Edit</a><br/> ==> How to transfer the post.id parameter to th:href? <a href="posts/view.html" th:Delete</a> ==> How to transfer the post.id parameter to th:href? </td> </tr> </tbody> </table> I am a beginner in HTML and Spring. How can I put post.id value into view mvc controller through th:href tag? You can something try like following: <a href="posts/view.html" th:Edit</a><br/> <a href="posts/view.html" th:Delete</a> Standard URL Syntax, <a th:. They are not modified How do we add parameters to the URLs we create with @{} expressions? In this short article, we saw how to use Spring request parameters in combination with Thymeleaf. First, we created a simple controller that accepts request parameters. Second, we looked at how to use Thymeleaf to generate an HTML page that can call our controller. Spring Request Parameters with Thymeleaf, Learn how to use request parameters with Spring and Thymeleaf. Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2: We used th:object and th:field in the Thymeleaf template and In the following three sections, we'll use different HTML form elements for the user to pass data to Thymeleaf is a popular server-side template engine for Java-based web applications. In this article, you'll learn how to create HTML forms in Thymeleaf and how to handle the form submission on the backend using Spring Boot. I used in this format and work fine. <a th:Link</a> Spring Path Variables with Thymeleaf, Explore how to use Thymeleaf to create URLs with path variables. course, focused on the fundamentals of Spring 5 and Spring Boot 2: We use path variables when we want to pass a value as part of the URL. a th:. On this page we will provide Thymeleaf form action, form submit and image src example with attribute values. Thymeleaf provides th:attr attribute that can be used to evaluate html tag attributes in group. Thymeleaf also provides specific attribute to evaluate html attribute, for example th:src, th:title and th:alt for image and th:action for How to construct dynamic URL using Thymeleaf, These are my simple Thymeleaf table HTML file and Spring MVC controller codes. First below is my table image. I try to make some html codes to transfer the Spring Data JPA is a key component of Spring Boot's spring-boot-starter-data-jpa that makes it easy to add CRUD functionality through a powerful layer of abstraction placed on top of a JPA implementation. This abstraction layer allows us to access the persistence layer without having to provide our own DAO implementations from scratch. How to construct URLs in Thymeleaf, We would be using link expressions, a type of Thymeleaf Standard Epression: <a th:Order ID</a> Would like to pass several parameters, O/P: <a href="/orderdetails?id=3& @RequestParam and @PathVariable annotations in Spring MVC? The parameters. image. Spring Boot + Thymeleaf HTML Form Handling (Part 1) A th:href = @{/pathvars/item. image. How to transfer parameters in th:href in spring Url with pathvariable · Issue #89 · thymeleaf/thymeleaf · GitHub, For example, if your Spring Boot application is configured to use the webapp <a th:What is Thymeleaf?</a> To add query parameters to a URL, you have to specify them using parenthesis Here is an example that shows how you can pass a path variable in the URL: Thymeleaf is a highly flexible server-side template engine that provides link expression as part of the standard dialects to build complex URLs with dynamic parameters. Read Next: How to use Thymeleaf in Spring Boot ️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.
http://thetopsites.net/article/52494233.shtml
CC-MAIN-2020-34
refinedweb
810
63.09
Defining Lookups¶ What are Lookups?¶ Lookups define the corresponding ajax views used by the auto-completion fields and widgets. They take in the current request and return the JSON needed by the jQuery auto-complete plugin. Defining a Lookup¶ django-selectable uses a registration pattern similar to the Django admin. Lookups should be defined in a lookups.py in your application’s module. Once defined you must register in with django-selectable. All lookups must extend from selectable.base.LookupBase which defines the API for every lookup. from selectable.base import LookupBase from selectable.registry import registry class MyLookup(LookupBase): def get_query(self, request, term): data = ['Foo', 'Bar'] return [x for x in data if x.startswith(term)] registry.register(MyLookup) Lookup API¶ LookupBase. get_query(request, term)¶ This is the main method which takes the current request from the user and returns the data which matches their search. LookupBase. get_item_label(item)¶ This is first of three formatting methods. The label is shown in the drop down menu of search results. This defaults to item.__unicode__. LookupBase. get_item_id(item)¶ This is second of three formatting methods. The id is the value that will eventually be returned by the field/widget. This defaults to item.__unicode__. LookupBase. get_item_value(item)¶ This is last of three formatting methods. The value is shown in the input once the item has been selected. This defaults to item.__unicode__. LookupBase. get_item(value)¶ get_itemis the reverse of get_item_id. This should take the value from the form initial values and return the current item. This defaults to simply return the value. LookupBase. create_item(value)¶ If you plan to use a lookup with a field or widget which allows the user to input new values then you must define what it means to create a new item for your lookup. By default this raises a NotImplementederror. LookupBase. format_item(item)¶ By default format_itemcreates a dictionary with the three keys used by the UI plugin: id, value, label. These are generated from the calls to get_item_id, get_item_valueand get_item_label. If you want to add additional keys you should add them here. The results of get_item_labelis conditionally escaped to prevent Cross Site Scripting (XSS) similar to the templating language. If you know that the content is safe and you want to use these methods to include HTML should mark the content as safe with django.utils.safestring.mark_safeinside the get_item_labelmethod. get_item_idand get_item_valueare not escapted by default. These are not a XSS vector with the built-in JS. If you are doing additional formating using these values you should be conscience of this fake and be sure to escape these values. There are also some additional methods that you could want to use/override. These are for more advanced use cases such as using the lookups with JS libraries other than jQuery UI. Most users will not need to override these methods. LookupBase. format_results(self, raw_data, options)¶ Returns a python structure that later gets serialized. This makes a call to paginate_results prior to calling format_item on each item in the current page. LookupBase. paginate_results(results, options)¶ If SELECTABLE_MAX_LIMIT is defined or limitis passed in request.GET then paginate_resultswill return the current page using Django’s built in pagination. See the Django docs on pagination for more info. Lookups Based on Models¶ Perhaps the most common use case is to define a lookup based on a given Django model. For this you can extend selectable.base.ModelLookup. To extend ModelLookup you should set two class attributes: model and search_fields. from __future__ import unicode_literals from selectable.base import ModelLookup from selectable.registry import registry from .models import Fruit class FruitLookup(ModelLookup): model = Fruit search_fields = ('name__icontains', ) registry.register(FruitLookup) The syntax for search_fields is the same as the Django field lookup syntax. Each of these lookups are combined as OR so any one of them matching will return a result. You may optionally define a third class attribute filters which is a dictionary of filters to be applied to the model queryset. The keys should be a string defining a field lookup and the value should be the value for the field lookup. Filters on the other hand are combined with AND. User Lookup Example¶ Below is a larger model lookup example using multiple search fields, filters and display options for the auth.User model. from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'username__icontains', 'first_name__icontains', 'last_name__icontains', ) filters = {'is_active': True, } def get_item_value(self, item): # Display for currently selected item return item.username def get_item_label(self, item): # Display for choice listings return u"%s (%s)" % (item.username, item.get_full_name()) registry.register(UserLookup) Lookup Decorators¶ Registering lookups with django-selectable creates a small API for searching the lookup data. While the amount of visible data is small there are times when you want to restrict the set of requests which can view the data. For this purpose there are lookup decorators. To use them you simply decorate your lookup class. from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.decorators import login_required from selectable.registry import registry @login_required class UserLookup(ModelLookup): model = User search_fields = ('username__icontains', ) filters = {'is_active': True, } registry.register(UserLookup) Note The class decorator syntax was introduced in Python 2.6. If you are using django-selectable with Python 2.5 you can still make use of these decorators by applying the without the decorator syntax. class UserLookup(ModelLookup): model = User search_fields = ('username__icontains', ) filters = {'is_active': True, } UserLookup = login_required(UserLookup) registry.register(UserLookup) Below are the descriptions of the available lookup decorators. ajax_required¶ The django-selectable javascript will always request the lookup data via XMLHttpRequest (AJAX) request. This decorator enforces that the lookup can only be accessed in this way. If the request is not an AJAX request then it will return a 400 Bad Request response. login_required¶ This decorator requires the user to be authenticated via request.user.is_authenticated. If the user is not authenticated this will return a 401 Unauthorized response. request.user is set by the django.contrib.auth.middleware.AuthenticationMiddleware which is required for this decorator to work. This middleware is enabled by default. staff_member_required¶ This decorator builds from login_required and in addition requires that request.user.is_staff is True. If the user is not authenticatated this will continue to return at 401 response. If the user is authenticated but not a staff member then this will return a 403 Forbidden response.
http://django-selectable.readthedocs.io/en/latest/lookups.html
CC-MAIN-2017-26
refinedweb
1,075
59.8
Created on 2010-08-19 09:11 by mhuewe, last changed 2010-11-30 09:17 by mark.dickinson. This issue is now closed. It seems that commit r81636 broke urllib2's AbstractBasicAuthHandler because the "retried" attribute isn't reset on success. Therefore it's limited to 6 requests. The attached patch should fix this problem. The patch is fine. Fixed in r84207(release27-maint). Fixed in py3k (r84210) and release31-maint(r84211). I discovered a new problem while fixing this. It will be taken care in issue9643. Grr. Why wasn't this fix backported to the release maintenance branch before 2.6.6 was released? I've just had an application break as a result of upgrading from 2.6.5 to 2.6.6. Oh well, too late now. :-( </grumble> Ouch. My mistake. Had not realize then, that code that actually broke things was merged in 2.6.x and it had to be fixed too. :( Ah well, it turned out to be fairly easy to work around, at least. :-) Just in case any other urllib2 users have to deal with this in 2.6.6 (and also manage to find their way to this bug report :-): it's easy to monkeypatch your way around the problem. E.g.: import sys import urllib2 if sys.version_info[:2] == (2, 6) and sys.version_info[2] >= 6: def fixed_http_error_401(self, req, fp, code, msg, headers): url = req.get_full_url() response = self.http_error_auth_reqed('www-authenticate', url, req, headers) self.retried = 0 return response urllib2.HTTPBasicAuthHandler.http_error_401 = fixed_http_error_401
https://bugs.python.org/issue9639
CC-MAIN-2018-05
refinedweb
254
71.61
Results 1 to 2 of 2 - Join Date - Feb 2012 - 12 - Thanks - 11 - Thanked 0 Times in 0 Posts Thinking about switching to java should i? Im useing python and im thinking about switching to java for multiple form. But i need to know if it so ports the game im trying to make. can someone let me know if i should stick with python or move to java for the kind of game i would like to make. -A turn based rpg -Online capabilities -Isometric angle - Join Date - Mar 2012 - 25 - Thanks - 0 - Thanked 3 Times in 3 Posts By your description it is not clear what is your task at all and what are points with which you stuck. Switching to java will be of benefit only if you know java better then python. Both systems allow do almost anything, but in different ways (sometimes slightly different, sometimes totally different). In both languages you will not find anything like: Code: import rpg import fun myRpg = new RpgGame(); myRpg.start() fun.have()
http://www.codingforums.com/java-and-jsp/253816-thinking-about-switching-java-should-i.html?s=049b931a3aa19d30a76da6bdceb390a7
CC-MAIN-2015-48
refinedweb
173
75.13
In this tutorial, we’ll demonstrate how to build a YouTube video search application using Angular and RxJS. We’ll do this by building a single-page application that retrieves a list of videos from YouTube by passing in a search query and other parameters to the YouTube search API. We’ll use the following tools to build our app. - TypeScript, a typed superset of JavaScript that compiles to plain JavaScript and provides type capabilities to JavaScript code - Angular, a JavaScript framework that allows you to create efficient and sophisticated single-page applications - RxJS, a library for composing asynchronous and event-based programs by using observable sequences. Think of RxJS as Lodash but for events You should have a basic understanding of how these tools work to follow along with this tutorial. We’ll walk through how to use these tools together to build a real-world application. As you go along, you’ll gain practical insight into the core concepts and features they provide. You can find the final code in this GitHub repository. Prerequisites You’ll need to have certain libraries installed to build this project locally. Ensure you have the Node package installed. We’ll use Angular CLI v6.0.0 to generate the project, so you should ideally have that version installed to avoid weird errors later on. Project setup 1. Structure the application Before we start writing code, let’s conceptualize the features to be implemented in the application and determine the necessary components we’ll need. We’ll keep it as simple as possible. At the core, we’ll need to have an input element that allows the user to type in a search query. That value will get sent to a service that uses it to construct a URL and communicate with YouTube’s search API. If the call is successful, it will return a list of videos that we can then render on the page. We can have three core components and one service: a component called search-input for the input element, a component called search-list for rendering the list of videos, and a parent component called search-container that renders both the search-input and search-list components. Then we’ll have a service called search.service. You could think of a service as the data access layer (DAL), that’s where we’ll implement all the relevant functionality that’ll enable us to communicate with the YouTube search API and handle the subsequent response. In summary, there will be three components: search-container search-input search-list The search-input and search-list components will be stateless while search-container will be stateful. Stateless means the component never directly mutates state, while stateful means that it stores information in memory about the app state and has the ability to directly change/mutate it. Our app will also include one service: search.service Now let’s dive into the technical aspects and set up the environment. 2. Set up the YouTube search API We’ll need to get a list of YouTube videos based on whatever value is typed into the input element. Thankfully, YouTube provides a way that allows us to do exactly that by using the YouTube search API. To gain access to the API, you’ll need to register for an API token. First, if you don’t already have one, you’ll need to sign up for a Google account. When that’s done, head over to the Google developer console to create a new project. Once the project is successfully created, follow the steps below to get an API token. - Navigate to the credentials page by clicking on Credentialslocated on the sidebar menu - Click on the + CREATE CREDENTIALSbutton located at the top of the page and select API key.A new API key should be created. Copy that key and store it somewhere safe (we’ll come back to it shortly) - Head over to the API and Services page by clicking on APIs & Serviceslocated at the top of the sidebar - Click on ENABLE APIs AND SERVICESat the top of the page. You’ll be redirected to a new page. Search for the YouTube Data API and click on the Youtube Data API v3option. Once again, you’ll be redirected to another page. Click Enableto allow access to that API With that done, we can start building out the application and the necessary components. 3. Scaffold the application Create a directory for the application. From your terminal, head over to a suitable location on your system and issue in the following commands. # generate a new Angular project ng new youtube-search ` # move into it cd youtube-search This uses the Angular CLI to generate a new project called youtube-search. There’s no need to run npm install since it automatically installs all the necessary packages and sets up a reasonable structure. Throughout this tutorial, we’ll use the Angular CLI to create our components, service, and all other necessary files. Building the application 1. Set up the search service Before we build the search service, let’s create the folder structure. We’ll set up a shared module that will contain all the necessary services, models, etc. Make sure you’re in your project directory and navigate to the app folder by running the following command. cd src/app Create a new module called shared by running the following command in the terminal. ng generate module shared This should create a new folder called shared with a shared.module.ts file in it. Now that we have our module set up, let’s create our service in the shared folder. Run the following command in the terminal. ng generate service shared/services/search This should create a search.service.ts file in the shared/services folder. Paste the following code into the search.service.ts file. We’ll examine each chunk of code independently. // search.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SearchService { private API_URL = ''; private API_TOKEN = 'YOUR_API_TOKEN'; constructor(private http: HttpClient) {} getVideos(query: string): Observable <any> { const url = `${this.API_URL}?q=${query}&key=${this.API_TOKEN}&part=snippet&type=video&maxResults=10`; return this.http.get(url) .pipe( map((response: any) => response.items) ); } } First, take a look at the chunk of code below. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) [...] In the first part of the code, we simply import the necessary files that’ll help us build our service. map is an RxJS operator that is used to modify the response received from the API call. HttpClient provides the necessary HTTP methods. @Injectable() is a decorator provided by Angular that marks the class located directly below it as a service that can be injected. { providedIn: 'root'} signifies that the service is provided in the root component of the Angular app, which in this case is the app component. Let’s look at the next chunk: [...] export class SearchService { private API_URL = ''; private API_TOKEN = 'YOUR_API_KEY'; constructor(private http: HttpClient) {} getVideos(query: string): Observable <any> { const url = `${this.API_URL}?q=${query}&key=${this.API_KEY}&part=snippet&type=video&maxResults=10`; return this.http.get(url) .pipe( map((response: any) => response.items) ); } } We have two private variables here. Replace the value of API_KEY with the API token you got when you created a new credential. Finally, the getVideos method receives a search query string passed in from the input component, which we’ve yet to create. It then uses the http get method to send off a request to the URL constructed. It returns a response that we handle with the map operator. The list of YouTube video details is expected to be located in the response.items object and, since we’re just interested in that, we can choose to return it and discard the other parts. Due to the fact that the search service uses the HTTP client, we have to import the HTTP module into the root component where the service is provided. Head over to the app.module.ts file located in the app folder and paste in the following code. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ HttpClientModule, BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } That’s basically all for the search service. We’ll make use of it soon. 2. Add a video interface file Let’s quickly set up an interface file. A TypeScript interface allows us to define the syntax to which any entity must adhere. In this case, we want to define certain properties each video object retrieved from the Youtube search API should contain. We’ll create this file in the models folder under the shared module. Run the following command in your terminal. ng generate interface shared/models/search interface This should create a search.interface.ts file. Copy the following code and paste it in there. export interface Video { videoId: string; videoUrl: string; channelId: string; channelUrl: string; channelTitle: string; title: string; publishedAt: Date; description: string; thumbnail: string; } Interfaces are one of the many features provided by TypeScript. If you aren’t familiar with how interfaces work, head to the TypeScript docs. Setting up the stylesheet We’ll be using Semantic-UI to provide styling to our application so let’s quickly add that. Head over to the src folder of the project, check for the index.html file, and paste the following code within the head tag. <link rel="stylesheet" type="text/css" href=""> Your index.html file should look something like this: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>YoutubeSearch</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Added Semantic Ui stylesheet --> <link rel="stylesheet" type="text/css" href=""> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> Setting up the stateless components 1. Develop the search input component The next step is to set up the stateless components. We’ll create the search-input component first. As previously stated, this component will contain everything that has to do with handling user input. All stateless components will be in the components folder. Make sure you’re in the app directory in your terminal before running the following command. ng generate component search/components/search-input This creates a search-input component. The great thing about using Angular’s CLI to generate components is that it creates the necessary files and sets up all boilerplate code, which eases a lot of the stress involved in setting up. Add the following HTML code to the search-input.html file. This is just basic HTML code and styling using semantic UI: <div class="ui four column grid"> <div class="ten wide column centered"> <div class="ui fluid action input"> <input #input </div> </div> </div> Take note of the #input line added to the input element. This is called a template reference variable because it provides a reference to the input element and allows us to access the element right from the component. Before we start working on the component file, there are a few things to handle on the input side: - Set up an event listener on the input element to monitor whatever the user types - Make sure the value typed has a length greater than three characters - It’s counterintuitive to respond to every keystroke, so we need to give the user enough time to type in their value before handling it (e.g., wait 500ms after the user stops typing before retrieving the value) - Ensure the current value typed is different from the last valu. Otherwise, there’s no use in handling it This is where RxJS comes into play. It provides methods called operators that help us implement these functionalities/use cases seamlessly. Next, add the following code in the search-input.component.ts file. // search-input.component.ts import { Component, AfterViewInit, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core'; import { fromEvent } from 'rxjs'; import { debounceTime, pluck, distinctUntilChanged, filter, map } from 'rxjs/operators'; @Component({ selector: 'app-search-input', templateUrl: './search-input.component.html', styleUrls: ['./search-input.component.css'] }) export class SearchInputComponent implements AfterViewInit { @ViewChild('input') inputElement: ElementRef; @Output() search: EventEmitter<string> = new EventEmitter<string>(); constructor() { } ngAfterViewInit() { fromEvent(this.inputElement.nativeElement, 'keyup') .pipe( debounceTime(500), pluck('target', 'value'), distinctUntilChanged(), filter((value: string) => value.length > 3), map((value) => value) ) .subscribe(value => { this.search.emit(value); }); } } Let’s take a look at a few lines from the file above. ViewChild('input')gives us access to the input element defined in the HTML file previously. 'input'is a selector that refers to the #inputtemplate reference variable we previously added to the input element in the HTML file ngAfterViewInitis a lifecyle hook that is invoked after the view has been initialized. In here, we set up all code that deals with the input element. This ensures that the view has been initialized and we can access the input element, thereby avoiding any unnecessary errors later on Now let’s look at the part of the code found in the ngAfterViewInit method. - The fromEventoperator is used to set up event listeners on a specific element. In this case, we’re interested in listening to the keyupevent on the input element - The debounceTime()operator helps us control the rate of user input. We can decide to only get the value after the user has stopped typing for a specific amount of time — in this case, 500ms - We use the pluck('target','value')to get the value property from the input object. This is equivalent to input.target.value distinctUntilChanged()ensures that the current value is different from the last value. Otherwise, it discards it. - We use the filter()operator to check for and discard values that have fewer than three characters - The mapoperator returns the value as an Observable. This allows us to subscribe to it, in which case the value can be sent over to the parent component (which we’ve yet to define) using the Outputevent emitter we defined. That’s all for the search-input component. We saw a tiny glimpse of just how powerful RxJS can be in helping us implement certain functionalities. 2. Develop the search list component Now it’s time to set up the search-list component. As a reminder, all this component does is receive a list of videos from the parent component and renders it in the view. Because this is also a stateless component, we’ll create it in the same folder as the search-input component. From where we left off in the terminal, go ahead and run the following command. ng generate component search/components/search-list Then head over to the search-list.component.ts file created and paste the following code in there. // search-list.component.ts import { Component, OnInit, Input } from '@angular/core'; import { Video } from '../../../shared/models/search.interface'; @Component({ selector: 'app-search-list', templateUrl: './search-list.component.html', styleUrls: ['./search-list.component.css'] }) export class SearchListComponent implements OnInit { @Input() videos: Video[]; constructor() { } ngOnInit() { } } The file above is fairly straightforward. All it does is receive and store an array of videos from the parent component. Let’s take a look at the HTML code, switch to the search-input.html file, and paste in the following code. <div class="ui four column grid"> <div class="column" * <div class="ui card"> <div class="image"> <img [src]="video.thumbnail"> </div> <div class="content"> <a class="header" style="margin: 1em 0 1em 0;">{{ video.title }}</a> <div class="meta"> <span class="date" style="font-weight: bolder;"> <a [href]="video.channelUrl" target="_blank">{{ video.channelTitle }}</a> </span> <span class="ui right floated date" style="font-weight: bolder;">{{ video.publishedAt | date:'mediumDate' }}</span> </div> <div class="description"> {{ video.description?.slice(0,50) }}... </div> </div> <a [href]="video.videoUrl" target="_blank" class="extra content"> <button class="ui right floated tiny red right labeled icon button"> <i class="external alternate icon"></i> Watch </button> </a> </div> </div> </div> In the file above, we simply loop through the array of videos in our component and render them individually, this is done using the *ngFor directive found in the line above: <div class="column" * Building the stateful component Let’s create the parent component, search-container. This component will directly communicate with the search service sending over the user input and then pass the response to the search-list component to render. Since the search-container is a stateful component, we’ll create this in a different directory than the other two components. In the terminal once again, you should still be in the app directory. Type in the following command. ng generate component search/container/search-container Before we start writing code, let’s take a step back and outline what we want to achieve. This component should be able to get user inputs from the search-input component. It should pass this over to the search service, which does the necessary operations and returns the expected result. The result should be sent over to the search-list component, where it will be rendered. To implement these things, paste the following code into the search-container.component.ts file. // search-container.component.ts import { Component } from '@angular/core'; import { SearchService } from 'src/app/shared/services/search.service'; import { Video } from 'src/app/shared/models/search.interface'; @Component({ selector: 'app-search-container', templateUrl: './search-container.component.html', styleUrls: ['./search-container.component.css'] }) export class SearchContainerComponent { inputTouched = false; loading = false; videos: Video[] = []; constructor(private searchService: SearchService) { } handleSearch(inputValue: string) { this.loading = true; this.searchService.getVideos(inputValue) .subscribe((items: any) => { this.videos = items.map(item => { return { title: item.snippet.title, videoId: item.id.videoId, videoUrl: `{item.id.videoId}`, channelId: item.snippet.channelId, channelUrl: `{item.snippet.channelId}`, channelTitle: item.snippet.channelTitle, description: item.snippet.description, publishedAt: new Date(item.snippet.publishedAt), thumbnail: item.snippet.thumbnails.high.url }; }); this.inputTouched = true; this.loading = false; }); } } In the code above, the handleSearch method takes in the user input as an argument. It then communicates with the getVideos method in the search service passing in the input value as an argument. The subscribe function invokes this service call and the response from the getVideos method is passed to it as the items argument. We can then filter out the necessary values needed and add that to the videos array in the component. Let’s quickly work on the HTML, paste this into search-container.html and we’ll go through it after: <div> <app-search-input (search)="handleSearch($event)"></app-search-input> <div * <div class="ui raised aligned segment red warning message"> <i class="warning icon"></i> <span class="ui centered" style="margin: 0 auto;">No Video Found</span> </div> </div> <div * <div class="ui active centered inline loader"></div> </div> <app-search-list *</app-search-list> </div> In the file above, we simply render both child components, search-input and search-list, and add the necessary input binding to the search-list component. This is used to send the list of videos retrieved from the service to the component. We also listen to an event from the search-input component that triggers the handleSearch function defined earlier. Edge cases are also handled, such as indicating when no videos are found, which we only want to do after the input element has been touched by the user. The loading variable is also used to signify to the user when there’s an API call going on. By default in every Angular application, there’s a root component, usually called the app-root component. This is the component that gets bootstrapped into the browser. As a result, we want to add the search-container component to be rendered there. The search-container component renders all other components. Open the app.component.html file and paste the code below. <div class="ui centered grid" style="margin-top: 3rem;"> <div class="fourteen wide column"> <h1 class="ui centered aligned header"> <span style="vertical-align: middle;">Youtube Search </span> <img src="/assets/yt.png" alt=""> </h1> <app-search-container></app-search-container> </div> </div> Testing out the Application We’re all done! Now let’s go ahead and test our app. In your terminal, run the following command to kickstart the application. ng serve You may encounter an error similar to ERROR in ../../node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected. This doesn’t have to do with the code but rather the RxJS package installation. Luckily, there’s a very straightforward and easy solution to that. By default, all Angular applications are served at localhost:4200, so go ahead and open that up in your browser. Here’s what it should look like: Conclusion You should now have a good understanding of how to use Angular and RxJS to build a YouTube video search application. We walked through how to implement certain core concepts by using them to build a simple application. We also got a sense of RxJS’s powerful features and discussed how it enables us to build certain functionalities with tremendous ease. Best of all, you got a slick-looking YouTube search app for your troubles. Now you can take the knowledge you gained and implement even more complex features with the YouTube API. “Build a YouTube video search app with Angular and…” 7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src/app/app.component.ts:5:16 5 templateUrl: ‘./app.component.html’, ~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component AppComponent. ** Angular Live Development Server is listening on localhost:4200, open your browser on ** i got the error like this,plzz tell me the solution
https://blog.logrocket.com/build-a-youtube-video-search-app-with-angular-and-rxjs/
CC-MAIN-2020-40
refinedweb
3,642
56.25
0 I am creating a MAC Database for my home network which shall contain a list of names of those on the network and allow me to quickly search for people when I get a warning about a user. I am using switch statements to go to each main section (sorry, I am new to C++ and I can't remember the name for it). The following is what I have so far, including two switch statements which I am attempting to use but unfortunately failing at: #include <iostream> #include <fstream> #include <windows.h> #include <string> using namespace std; void View_Account() //View All Available Accounts { cout << "View Account"; } void Modify_Account() //Modify All Available Accounts { cout << "Modify Account"; } int main() { int Option; //User Menu Selection int Password = -1; //User Password; } return 0; } How would I get it to go to the View_Account part when using a switch statement? Thank you
https://www.daniweb.com/programming/software-development/threads/398291/switch-statement-help
CC-MAIN-2017-30
refinedweb
149
51.04
On Wed, Aug 11, 2010 at 12:06 PM, Chris Rebert <clp2 at rebertia.com> wrote: > On Wed, Aug 11, 2010 at 11:43 AM, Pramod <pramo4d at gmail.com> wrote: >> Hi >> >> I want to know the how we input values into the matrix (N*N size) >> from keyboard in python, >> >> Here I wrote Matrix programe in C++ >> >> This asks values from key board and print on the console N*N matrix ; >> >> Thanks in advance .... >> >> >> #include<iostream> >> using namespace std; >> int main() >> { >> double **a; >> int i,j,n; >> cout<<"Enter size of the matrix\n"; >> cin>>n; >> for(i=0;i<n;i++){ >> for(j=0;j<n;j++) >> a[i][j] = random(); >> //or >> //cin>>a[i][j]; >> cout<<endl; >> } >> for(i=0;i<n;i++){ >> for(j=0;j<n;j++) >> cout<<a[i][j]<<"\t"; >> cout<<endl; >> } >> delete [] a; >> } > > from random import random > from sys import exit > > while True: > try: > N = int(raw_input("Enter size of the matrix: ")) > except ValueError: > print "Invalid input. Try again." > except EOFError: > exit(1) > else: > break > > a = [[random() for j in xrange(N)] for i in xrange(N)] > stringified = "\n".join("\t".join(row) for row in a) > print stringified Should have prefaced that with an "untested" disclaimer. Make that: stringified = "\n".join("\t".join(str(cell) for cell in row) for row in a) - Chris
https://mail.python.org/pipermail/python-list/2010-August/584500.html
CC-MAIN-2018-09
refinedweb
223
67.28
I need a school assignment finished coding by tomorrow morningemplois As discussed..................As discussed....................As discussed................../As discussed..................As discussed.................. Im a life coach in need of a book to be published and writted with my ideas and bring a juicy story in it my book has 150 pages with 300 words in every page. - Add image with link on public landing page /home to public event page - On saturday, /home should look like before. Attached: - image to be placed with link (event link sent on private chat) - where to place on desktop version - where to place on mobile version... ... Here's an example of one that I like that someone else made for a different company: [se connecter pour voir l'URL] You can fill the text with Lorem Ipsum as long as I can edit it! Must be on brand with Premier Housing Management. 2) We broke ground on a new senior living home and we want I need 2 page landing page design One for homepage and the other one is submit form. Deadline is very hot I need to finish by today Please touch me asap Must have modern eyes Thank you images edits (NEEDED NOW, CANT WAIT UNTIL TOMORROW) please respond ONLY if you available now......... I have 6 psd files that need to be converted to a wordpress website for tomorrow morning. It needs to be pixel perfect and no website builder will be used. The website needs to be fully responsive and functional. I need an Android app. I would like it designed and built. Individual Freelancers only Under 500 words General content Fixed rate Thanks I want a project on this topic "Airborne wind energy - Wind Today, Green Tomorrow. T... Upload a video to two pages on finished Shopify Site (Replacing Image Banner) Hi There! We have made a Wordpress website But we are not happy about the design of the top part of the site (menu / slider / boxes) We have made several designs: [se connecter pour voir l'URL] But are not happy with them ;) So we would like to get - several ideas for design (logo / menu / slider / boxes).: Need an accountant for send by tomorrow. Very simple excel work. Chance of working together in future again if satisfied.. I need a new website. I need you to design and build my blog. I need an expert in Wordpress/WooCommerce and the WooCommerce Custom Product Designer found at [se connecter pour voir l'URL] My website is [se connecter pour voir l'URL] and the designer can be see at [se connecter pour voir l'URL] It just needs some finishing touched ie: Print Screen You can look at the 3 examples that i uploaded as how I'd wish it'd be done. It's a design that'll go on a black bag which will be handed out at our event so we need the rights to that design. The design will have to go in the centre square of the bag as shown. It should be done as followed: - Our logo should go in the centre of the bag in bright Build an IOS application within 24 hours by connecting to a backed API and retrieve text videos and voice. We requires some assist to finalize a few last changes for our website. changes includes: - front page modify, change a few text to icon, etc.. - enable install plugin - modify news letter setting - one page display issue in mobile device - Assist a few instruction Once changes done, will be checked and payment only released when 100% satisfaction Develop a comprehensive Instagram API integration layer in C#, that would allow our application to seamlessly post to instagram and read from instagram. fix bug in angular 6 ag-grid project should work through team viewer or any desk should complete it this thursday morning 7 am us time . Dont bid if you cant work now and cant work through team viwer . A children's book about manners and etiquette import and export need furniture designer Individual Freelancers ONLY Flat rate of $15 Thanks English into simplified Chinese Due tomorrow Flat rate of $25 individual Freelancers ONLY Thanks I have a .csv file of data. I would like a Macro and data table built that would turn that data file into a specific finished product. I would then like to be able to add more data onto the sheet and it convert it as well. n... I fi...+ pa... Please see attachment before you bid. need a help now. Needs to be finished in 1 hour. Budget: 10 AUD An easy and straightforward typing task Thanks I need an account checker! today finished I pay 100$ ... I need 1 or 2 article writers for my 14 articles 1000 words. I will pay 3 aud per 1000 words. I need reliable and sincere writers for this project. write `` agree'' in your proposal.
https://www.fr.freelancer.com/job-search/I-need-a-school-assignment-finished-coding-by-tomorrow-morning/
CC-MAIN-2018-51
refinedweb
819
69.41
ESP8266 Deploying Micropython and Using REPL ESP8266 The ESP8266 is a low-cost Wi-Fi microchip with full TCP/IP stack and microcontroller capability produced by Espressif Systems. One of the coolest things about this cip is it can run Micropython. If you are new to programming or hardware/embedded systems and want to get into those, ESP8266 is a good way to get started. Micropython MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments. - Source As Micropython follows Python 3 coding standard. It is very easy for people who know python to get into hardware stuff. Let’s get started I’m using NodeMCU for now. If your are not from electronics/embedded systems background, it is better to go with development boards like NodeMCU than using chips and breadboards and if you are from electronics background; these development boards are very useful for prototyping. Download the firmware. You can find the stable and nightly builds for micropython for ESP8266 in MicroPython’s Download section Deploy the firmware on ESP8266 To deploy the Firmware on ESP8266 there is a python tool called esptool. You can install it using pip (this tool is written in python, so if you are on linux or on mac os you will already have python installed with either pip or easy_install. If you are on windows, you need to install python first to use this tool.) or you can install the latest version from it’s github repo To install esptool using pip $ pip install esptool To install esptool from github repo $ git clone $ cd esptool $ python setup.py build $ python setup.py install Once this tool is installed you first need to erase the flash of ESP8266 modeule using following command. $ esptool.py --port /dev/ttyUSB0 erase_flash To deploy the firmware you have just downloaded $ esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect 0 esp8266-20180511-v1.9.4.bin For some boards with a particular FlashROM configuration (e.g. some variants of a NodeMCU board) you may need to use the following command to deploy the firmware (note the -fm dio option): $ esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm dio 0 esp8266-20180511-v1.9.4.bin After you successfully deployed the firmware the controller will reset itself and then you are ready to use the REPL. For those who don't know about REPL, it stands for Read–Eval–Print Loop it is the "language shell". If you have used the python intepreter before; that is REPL. Using REPL You can access the MicroPython REPL on ESP8266 in two different ways. - Over Serial or tty Port - Web REPL REPL Over Serial Port To access the prompt over USB-serial you need to use a terminal emulator program. There are various good tools available for this purpose. Windows - TeraTerm - Putty Linux - Minicom - PicoCom - Screen - GtkTerm MacOs - Screen There are plenty of other tools avalable for each of these platforms you can choose whichever you like. The default baudrate for the module is 115200. WebREPL WebREPL allows you to use the Python prompt over WiFi, connecting through a browser. The latest versions of Firefox and Chrome are supported. Connect the module using USB Serial and set password for WebREPL import webrepl_setup Go to WebREPL client from browser. Then Connect to the NodeMCU’s accesspoint. The ESSID is of the form MicroPython-xxxxxxwhere the x’s are replaced with part of the MAC address of your device (so will be the same everytime, and most likely different for all ESP8266 chips). The password for the WiFi is micropythoN Enter IP: ws://192.168.4.1:8266/and click connect. Enter the password you just set in the terminal screen on your browser. Once this is done you will see the “ >>>” prompt, now you can use your ESP8266 module from your web browser itself. In the next post I’ll be writing about networking with ESP8266 (connecting 8266 module to a wifi network and making http requests from and to ESP8266).
http://girishjoshi.io/post/esp8266-deploying-micropython-and-using-repl/
CC-MAIN-2018-47
refinedweb
697
62.48
I'm making a simulator which involves dispersing objects randomly over the NavMesh. I have code for getting random point on the mesh, and I am caching 200 - 400 such positions in Start(). However this, along with other heavy lifting done in other Start methods, like Instantiates into object pools etc., cause a long delay at the start of the program (20-40 seconds). What is the best practice way to provide a loading/progress indicator for work done in Start()? I already implemented the loading bar from here: , but this jumps straight to 90% and then freezes while the Start() work is done (I understand this is because there's is not much in the way of assets to load, but lots happening in the Start() of scripts. Is there a way even I can change the text in the load bar from a Start() method after calling loadLevelAsync? The scene loading script: using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using UnityEngine.UI; public class SceneSelector : MonoBehaviour { public Texture2D white; public Texture2D stripes; public Texture2D window; private AsyncOperation async; private Object loadBarPrefab; private GameObject loadbarObject; private GUIStyle loadingBarStyle; private int windowWidth = 400; private int windowHeight = 200; private float barWidth = 300; private float barHeight = 50; // Use this for initialization void Start () { loadBarPrefab = Resources.Load("LoadingBar"); loadbarObject = (GameObject)Instantiate(loadBarPrefab); loadbarObject.SetActive(false); } public void RestartCurrentScene() { async = SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex); } void OnGUI() { if (async != null) { GUI.DrawTexture(new Rect((Screen.width / 2) - (windowWidth / 2), (Screen.height / 2) - (windowHeight / 2), windowWidth, windowHeight), window); GUI.DrawTexture(new Rect((Screen.width / 2) - (barWidth / 2), (Screen.height / 2) - (barHeight / 2), barWidth, barHeight), stripes); GUI.DrawTexture(new Rect((Screen.width / 2) - (barWidth / 2), (Screen.height / 2) - (barHeight / 2), barWidth/*maybe100*/ * async.progress, barHeight), white); GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.contentColor = Color.black; GUI.Label(new Rect((Screen.width / 2) - (barWidth / 2), (Screen.height / 2) - (barHeight / 2), barWidth, barHeight), "***Loading: " + string.Format("{0:N0}%", async.progress * 100f) + "***"); } } } Is it possible to pass a message from a script's Start() to a load bar/message in this Awake and Start get called in order with additive scenes? 1 Answer How can I get the last frame before a new level was loaded ? 1 Answer Load and run scene in background 1 Answer What does (not loaded) mean? 0 Answers Scene starts before scene loading is finished 0 Answers
https://answers.unity.com/questions/1349694/display-loadingprogress-indicator-from-start.html
CC-MAIN-2019-51
refinedweb
395
58.58
On Sat, Sep 23, 2000 at 03:03:50PM -0700, Ulf Carlsson wrote: > > It's the assembler as below text case demonstrates. > > Thanks. I'll take a look at it. I remember that I've looked at this > problem once before. This piece of gold in bfd/elf32-mips.c seems to be the problem: /* Determine whether a symbol is global for the purposes of splitting the symbol table into global symbols and local symbols. At least on Irix 5, this split must be between section symbols and all other symbols. On most ELF targets the split is between static symbols and externally visible symbols. */ /*ARGSUSED*/ static boolean mips_elf_sym_is_global (abfd, sym) bfd *abfd ATTRIBUTE_UNUSED; asymbol *sym; { return (sym->flags & BSF_SECTION_SYM) == 0 ? true : false; } So our objects are correct, just IRIX flavoured at this point ... Now for a proper fix I think I need somebody who knows IRIX ELF like his pocket ... Ralf
http://www.linux-mips.org/archives/linux-mips/2000-09/msg00078.html
CC-MAIN-2015-22
refinedweb
152
73.88
Style The Arm Mbed OS codebase is hosted on GitHub, and you can submit new features or bug fixes. Please follow the guidelines for GitHub pull requests and the coding style guide in your submissions. Tip: Please also read the workflow section for a review of the process and legal requirements. Code acceptance After the code has gone through automated testing, developers will take a look and comment on the pull request. If all is well and acceptable, your code will be ready for merging into the central development branch. Coding style Whether you're writing new code or fixing bugs in existing code, please follow the Mbed OS coding style. Mbed OS follows the K&R style, with at least two exceptions (see Rules). The only exception to this coding style involves third-party code. Third-party code should be added to the .astyleignore file located in the Mbed OS root directory. You can use Artistic Style (AStyle) to format your code. Use the command-line switch to select the correct style and point to the file you want to edit: astyle -n --options=.astylerc $(full_path_to_file) File .astylerc defines Mbed OS code style and it's in the Mbed OS root directory. Code sample static const PinMap PinMap_ADC[] = { {PTC2, ADC0_SE4b, 0}, {NC , NC , 0} }; uint32_t adc_function(analogin_t *obj, uint32_t options) { uint32_t instance = obj->adc >> ADC_INSTANCE_SHIFT; switch (options) { case 1: timeout = 6; break; default: timeout = 10; break; } while (!adc_hal_is_conversion_completed(instance, 0)) { if (timeout == 0) { break; } else { timeout--; } } if (obj->adc == ADC_CHANNEL0) { adc_measure_channel(instance); adc_stop_channel(instance); } else { error("channel not available"); } #if DEBUG for (uint32_t i = 0; i < 10; i++) { printf("Loop : %d", i); } #endif return adc_hal_get_conversion_value(instance, 0); } Rules - Indentation - four spaces. Please do not use tabs. - Braces - K&R style. - One true brace style (1TBS) - use braces for statements of type if, else, whileand for(exception from K&R). - One line per statement. - Preprocessor macro starts at the beginning of a new line; the code inside is indented according to the code above it. - Cases within switchare indented (exception from K&R). - Space after statements of type if, while, for, switch. The same applies to binary operators (like, +and *) and the ternary operator ( ?and :). - Each line preferably has at most 120 characters. - For pointers or references, the symbols *or &are adjacent to a name ( analogin_t *obj. analogin_t &obj). If you omit the name, place the space between the type and *(such as int *or int &). - For function return pointers or references, the symbols *or &are adjacent to a function name ( int *func()or int &func()). - Don't leave trailing spaces at the end of lines. - Empty lines should have no trailing spaces. - Unix line endings are default option for files. - Use capital letters for macros. - A file should have an empty line at the end. Naming conventions Classes - Begin with a capital letter, and each word within a class also begins with a capital letter (AnalogIn, BusInOut). - Methods contain small letters, with words separated by underscore. - Private members start with an underscore: __User defined types (typedef))). - Structures - suffix _t- to denote it is a user-defined type. - Enumeration - the type name and values name - same naming convention as classes (for example MyNewEnum). Functions - Contain lower case letters (as methods within classes). - Words separated by underscore (wait_ms, read_u16). An example: #define ADC_INSTANCE_SHIFT 8 class AnalogIn { public: /** Create an AnalogIn connected to the specified pin. * * @param pin AnalogIn pin to connect to * @param name (optional) A string to identify the object */ AnalogIn(PinName pin) { analogin_init(&_adc, pin); } /** Read the input voltage, represented as a float in the range [0.0, 1.0]. * * @returns * A floating-point value representing the current input voltage, measured as a percentage */ uint32_t read() { return analogin_read(&_adc, operation); } protected: analogin_t _adc; }; typedef enum { ADC0_SE0 = (0 << ADC_INSTANCE_SHIFT) | 0, } ADCName; struct analogin_s { ADCName adc; }; typedef struct analogin_s analogin_t; Namespaces Namespaces used to group subsystems are lower case, such as rtos and event. If not in a specific subsystem, C++ APIs are in namespace mbed. A few APIs remain in the global namespace for backward compatibility. Occasionally, namespaces are used to act as-if "static singleton" objects. One example is namespace ThisThread in rtos (which was modeled after C++11 std::this_thread). These namespaces follow the class naming convention, so calls to their functions look like calls to static class methods. Below is an example of typical namespace use in a source file: using namespace rtos; // for ThisThread using namespace std::chrono_literals; // for 1s ThisThread::sleep_for(1s); Doxygen documentation All functions and methods should contain documentation using Doxygen. Compiler settings All C and C++ code submitted to Mbed OS must compile with GCC Arm Embedded and Arm Compiler 6. Mbed OS: - Uses the GNU11 standard for C. - Uses the GNU++14 standard for C++. - Sets the chartype to unsigned. - Disables C++ exceptions. - Disables C++ runtime type information. - Disables variable length arrays (C++ only).
https://os.mbed.com/docs/mbed-os/v6.2/contributing/style.html
CC-MAIN-2020-34
refinedweb
813
65.83
you are one with the memes you are one with the memes h0ly sm0kes the collision resolution is nice @RohilPatel I'm starting to think people are more likely to upvote familiar faces versus impressive repls. Email professor/teacher about the downtime. I'm sure they'll give an extension. import ass lol sorry im immature A place that hosts my code online is very handy and have been able to complete projects from multiple locations that I wouldn't have been able to otherwise. I mainly use it to quench my thirst for dumb programming ideas that I come up with. no one can convince me their indentation syntax is a good idea @Duvangamer3845 maybe this picture will help Keep track of the red rectangle on the sprite sheet and you will know how to draw your animation. The right side is the final canvas drawing ill never forget the introduction to a particular unit in my systems programming class: Professor: Welcome back to CS361, today we're going to learn about forking and killing children and how to have them reaped by their parents. (he was talking about parent and child processes lol) we live in a society Repl should have sections containing people's creations. Like a section for games, apps, and stuff. It seems a lot of people's work is stuffed in the bottom of repl talk. @KelvinVerhey I also don't understand the point of a desktop app when you can just use this website on your desktop. I would see why someone would attempt a mobile app for repl but the desktop version already exists (that is, this website). I wouldn't feel too bad. The line clear algorithm works and I'd say that's the hardest thing about programming tetris. It also looks way better than mine. welcome back I derived this function: function checkCollision(a, b) { return (a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y); } From this page: Usage: var rectA = {x: 10, y: 10, width: 10, height: 10}; var rectB = {x: 10, y: 15, width: 10, height: 10}; if (checkCollision(rectA, rectB)) { console.log('Collision detected'); } this news made me sadface i draw pictures ascii pac man JavaScript is what's most commonly used to provide functionality to web pages (unless you're a diehard CSS expert). Java CAN be used for websites (see .jsp) Being programming languages they naturally have a lot in common (classes, variables, functions, etc...) but are typically used for completely different things. Whoever named JavaScript has some serious explaining to do. what a coincidence, repl.it had a community challenge with exactly that What I did was break up the digits into a list of triplets 123456789 -> [[1,2,3],[4,5,6],[7,8,9]] Each group [1,2,3] has its own unit quantifier (thousand, million, billion...) that I put into a list: vector<string> unit_quantifier = { "" , // first triplet is blank because 'hundred' is a special case "thousand", "million" , "billion" , etc... } Since [1,2,3] is the third triplet in this example, that matches the unit_quantifier's third item: "million" My general algorithm was this: 1. Break the big number up into groups of 3 a. numbers missing get replaced with 0: `1002`->`[0,0,1],[0,0,2]` 2. Print the biggest triplet first, down to the smaller ones a. print the digits first b. followed by its unit quantifier 3. Repeat 2 until you have printed the entire number a language made up of emojis Is this happening in a particular repl? Is it happening in a console? I'm interested in the statistics of people who sort by hotvs sort by new that could have something to do with it
https://repl.it/@mwilki7?tab=comments
CC-MAIN-2021-04
refinedweb
636
70.94
Full Circle THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY LINUX LABS GNOME 3 vs UNITY ISSUE #50 - June 2011 REVIEWED! PAM FACIAL RECOGNITION HOW TO: USE KDE 4.6 GNASHING AT GNOME, UPSET WITH UNITY? full circle magazine #50 1 full circle magazine is neither affiliated with, nor endorsed by, Canonical Ltd. contents ^ Full Circle HowTo Program In Python Pt24 THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY p.08 Linux News p.04 My Desktop Opinions My Story p.27 My Opinion p.31 p.48 LibreOffice Pt5 p.14 Ubuntu Dev. Pt2 p.17 Command & Conquer p.05 Ubuntu Games p.43 I Think... p.33 Use KDE 4.6 p.21 Linux Labs p.25 Q&A p.45 Review p.39 Top 5 p.50 Letters p.41 Columns BACK NEXT MONTH Write For Full Circle p.24 Ubuntu Women p.07 the Ubuntu projects, and the views and opinions in the full circle magazineendorsement. #50 2 magazine should in no way be assumed to have Canonical contents ^ EDITORIAL This magazine was created using : Welcome to another issue of Full Circle! A fter all the negativity surrounding Unity and Ubuntu 11.04, I've written an article about KDE. As many of you will know, I used to use KDE back in the 3.5 days, but when the 4.0 debacle happened I jumped ship and went to default Gnome flavored Ubuntu. KDE has now matured enough in 4.6 that it's pretty much back on form with its 3.5 days, so Kubuntu 11.04 is on my desktop machine. Have a read through the article, and watch the video I made, maybe you'll take a shine to KDE and forget about any horror you may have with Unity. I'd also like to take this opportunity to wish Greg a happy second anniversary! Greg (Mr. Python) has been writing his HowTo series now for two years. This month he brings you Part 24. Send him an email of thanks, I'm sure he'll appreciate it. Our cover story this issue is PAM, and facial recognition technology. Call it coincidence, but just days before this issue was compiled, the stories hit the headlines (here in the UK) about Facebook automatically using facial recognition technology on people's photographs to automatically tag photos with users' names. PAM doesn't quite go that far, but it does allow you to use your face as your login. Just don't break your nose, or get plastic surgery! And finally, I think this month's My Opinion might spark some controversy with one reader saying that the downfall of Ubuntu will be none other than... Canonical! I'm interested in what other readers will have to say about that piece. Full Circle Podcast Released every two weeks, each episode covers all the latest Ubuntu news, opinions, reviews, interviews and listener feedback. The Side-Pod is a new addition, it's an extra (irregular) short-form podcast which is intended to be a branch of the main podcast. It's somewhere to put all the general technology and non-Ubuntu stuff that doesn’t fit in the main podcast. Hosts: Robin Catling Ed Hewitt Dave Wilkins All the best, and keep in touch. Ronnie ronnie@fullcirclemagazine.org full circle magazine #50 3 contents ^ LINUX NEWS Asus To Preload Ubuntu On Eee PCs Asustek has announced that it will ship three models of its Eee PC's with Ubuntu 10.10 preinstalled. Canonical announced Asus' decision to load the Eee PC 1001PXD, 1011PX and 1015PX with Ubuntu 10.10 as one that will "make it one of the most userfriendly PCs on the market". When Asus introduced the Eee PC back in 2007, it shipped with the Xandros Linux distribution, however once Microsoft realised that netbooks were becoming a big seller, it came out with a cut down version of its Windows operating system. Ubuntu has produced a version of its Linux distribution for several years for netbooks. However [...] many users don't want to bother installing another operating system, a fact that has not been lost on Canonical. Source: theinquirer.net Linux 3.0 'Steady Plodding Progress' Linus Torvalds has put penguins out of their misery by revealing that the next version number for the Linux kernel will be –. Source: channelregister.co.uk #50 4 Google Docs Offline Support Confirmed Google. Source: cmswire.com contents ^ COMMAND & CONQUER LaTeX Written by Lucas Westermann Before I begin this month's article, I would like to share two of John Niendorf's uses for gm (thanks for sharing them!). They are: alias imgresize='gm mogrify resize 640x480 *.jpg *.JPG' alias frameall='gm mogrify mattecolor yellow -frame 5x5+0+5 *.JPG *.jpg *.jpeg *.png' These aliases could be either pasted into your .bashrc file, or to a dedicated aliases file. The upper command resizes all the jpeg files to 640 x 480, and the second one adds a frame around all jpeg and png files. N ow, on to this month's article. As some of you may know, typing mathematical formulae (in lectures, or classes, or for any other reason) within programs such as OpenOffice or LibreOffice is not the easiest thing in the world. Especially when you start getting into set theory or other advanced mathematical concepts with Greek letters, symbols like “for all”, and so forth. For these sorts of things, I highly recommend using LaTeX (see Issue 11 for a basic introduction to LaTeX). In this article, I will be introducing you to some math packages and some useful tips and tricks for formatting mathematical formulae nicely. As for software, I'm quite fond of Texmaker, and the texlive packages offered in the official Ubuntu repositories should include all the packages I refer to here. Document Preamble The preamble is all the text included before the \begin{document} line in Latex. This includes document settings, headers, footers, package imports, and package settings. My typical math documents contain the following packages: tikz (for diagrams/graphs, for which I load the decorations.markings tikz library) amsmath – offers enhancements to all basic mathematical functionality full circle magazine #50 amsfonts – offers special math formatting (math calligraphy (\mathcal{}), math block text (\mathbb{}), etc.) amssymb – offers the ability to display numbered equations, inline math, etc. hyperref (when using a table of contents) – Allows the creation of click-able links in TeX documents. Below is an actual preamble that I use for my Linear Algebra notes (the document section \documentclass[12pt,a4paper]{article} % page counting, header/footer \usepackage{fancyhdr} \usepackage{lastpage} \usepackage[ngerman]{babel} \usepackage{tikz} \usetikzlibrary{decorations.markings} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{graphicx} \usepackage[utf8]{inputenc} \usepackage{hyperref} \addtolength{\oddsidemargin}{-.525in} \addtolength{\evensidemargin}{-.525in} \addtolength{\textwidth}{1.5in} \hypersetup{unicode=true,pdfborder={0 0 0 [0 0]}, linkcolor=blue} \title{Lineare Algebra} \author{Lucas Westermann} \pagestyle{fancy} \fancyhead{} \fancyfoot{} \fancyhead[L,L]{Lineare Algebra} \fancyhead[R,R]{Lucas Westermann} \fancyfoot[R,R]{Seite \thepage\ von \pageref{LastPage}} \fancyfoot[L,L]{\hyperlink{contents}{Inhaltsverzeichnis}} \renewcommand{\headrulewidth}{0.4pt} \renewcommand{\footrulewidth}{0.4pt} \setlength{\headheight}{16pt} 5 contents ^ COMMAND & CONQUER consists of only two include statements – and the references for utf8 and ngerman are because my lecture is in German). Graph A (\mathbb{K}_1^2) & \alpha + 0 = 0 + \alpha = \alpha \\ (\mathbb{K}_1^3) & \alpha \cdot -\alpha = -\alpha \cdot \alpha = 0 \\ TikZ is probably the most complicated package to use, so I will cover it first. The following is the code used to create graph A: (\mathbb{K}_1^4) & \alpha + \beta = \beta + \alpha \end{align*} \begin{tikzpicture}[node distance=2cm, auto] This results in the text shown below. \node (1) {$\hat{1}$}; \node (2) [right of = 1] {$\hat{2}$}; \node (3) [below of = 2] {$\hat{3}$}; \draw[decoration={markings,ma rk=at position 1 with {\arrow[ultra thick]{>}}},postaction={decor ate}] (1) to node {1} (2); \draw[decoration={markings,ma rk=at position 1 with {\arrow[ultra thick]{>}}},postaction={decor ate}] (2) to node {3} (3); \draw[decoration={markings,ma rk=at position 1 with {\arrow[ultra thick]{>}}},postaction={decor ate}] (3) to node {2} (1); \end{tikzpicture} + \beta)+\gamma \\ This code creates 3 nodes (named 1, 2 and 3). The information in the braces (“{}”) is the label for the node (what is displayed), so leaving it blank results in an empty node. The next three lines “\draw” create the lines between nodes (using the node names – which is in the normal brackets), and labelled again by what’s within the braces. The align* environment allows you to use tabbing characters (“&”) to align the text nicely. This is especially useful when doing a proof, and you want to align the equations at their equals signs. The \mathbb{} results in the blocked K. The “_” and “^” refers to sub and superset. If you have a super/subset that is longer than a single character, you will need to enclose it in braces. The \alpha, \beta, and \gamma refers to the Greek letters. The \cdot is a multiplication sign, the double backslashes denote line breaks, and the rest is self-explanatory. Other useful commands are things like: “\forall” (the upside-down A symbol) “\exists” (reversed E) “\in” (the curved e-symbol used when referring to sets) “\cup” (union symbol – set theory) “\cap” (intersection symbol – set theory) “\mathcal{}” (makes the letter in braces cursive – used by my professor when referring to a basis – a set of linearly independent Using the math packages to create and align equations: \begin{align*} (\mathbb{K}_1^1) & \alpha +(\beta + \gamma )= (\alpha full circle magazine #50 6 contents ^ COMMAND & CONQUER vectors) I hope you've found this article useful. I could have covered more examples, but regardless of how many I covered, it would still suit only a small number of use-cases. As such, you should view these as examples of what you can do with LaTeX. See the further reading section for a link to a useful manual. If you've any questions, or requests, email me at lswest34@gmail.com. Please put the words Full Circle Magazine, FCM, or C&C in the subject line, so I don't overlook it. Server Circle is a new question and answer site run by techies. Users with any level of experience can ask technical questions for free about anything server related, and receive answers from trusted experts, who are rated by the community. With time you can earn reputation points, and even financial rewards, by contributing your answers to questions from other people. Further Reading: – Wikibook covering a large amount of standard uses of LateX. For all other non-standard uses, a quick google search should suffice. f/ - Included in the zip file (see the Downloads section) is a great manual for many uses of the TikZ package. Lucas has learned all he knows from repeatedly breaking his system, then having no other option but to discover how to fix it. You can email Lucas at: lswest34@gmail.com. NOTE: Server Circle is not affiliated with, nor endorsed by, Full Circle magazine. full circle magazine #50 7 contents ^ HOW-TO W Program In Python - Part 24 Written by Greg Walters OW! It's hard to believe that this is the 24th issue already. Two years we've been learning Python! You've come a very long way. This time we are going to cover two topics. The first is printing to a printer, the second is creation of RTF (Rich Text Format) files for output. Generic Printing under Linux So let's start with printing to a printer. The idea to cover this came from an email sent by Gord Campbell. It's actually easy to do most printing from Linux, and easier than that other operating system that starts with “WIN” - and I won't deal with that OS. As long as all you want to print is straight text, no bold, italics, font changes, etc, it's fairly easy. Here's a simple app that will print directly to your printer... import os pr = os.popen('lpr','w') (line 5) we close the file, which will send the data out to the printer. pr.write('print test from linux via python\n') We can also create a text file, then send it out to the printer like this... pr.write('Print finished\n') import os pr.close() filename = 'dummy.file' This is fairly easy to understand as long as you expand your mind just a bit. In the above code, 'lpr' is the print spooler. The only requirement is that we have already configured 'lpd' and that it's running. More than likely, when you use a printer under Ubuntu, it's already done for you. 'Lpd' is usually referred to as a “magicfilter” that can automatically convert different types of documents to something the printer can understand. We are going to print to the 'lpr' device/object. Think of it simply as a file. We open the file. We have to import 'os'. Then in line 2, we open the 'lpr' with write access assigning it to the object variable 'pr'. We then do a 'pr.write' with anything we want to print. Finally os.system('lpr %s' % filename) full circle magazine #50 In this case, we are still using the lpr object, but we are using the 'os.system' command to basically create a command that looks to linux like we sent it from a terminal. I'll leave you to play with this for now. PyRTF Now let's deal with RTF files. RTF format (that's kind of like saying PIN number since PIN stands for Personal Identification Number, so that translates to Personal-Identification-Number Number. Something from the 8 “ Wow! It's hard to believe that this is the 24th issue already. Two years we've been learning Python! department of redundancy department, huh?) was originally created by the Microsoft Corporation in 1987, and its syntax was influenced by the TeX typesetting language. PyRTF is a wonderful library that makes it easy to write RTF files. You have to do some planning up front on how you want your files to look, but the results will be well worth it. First, you need to download and install the PyRTF package. Go to and get the PyRTF-0.45.tar.gz package. Save it someplace and use archive manager to unpack it. Then using terminal, go to where you unpacked it. First we need to install the package, so type “sudo python setup.py install” and it will contents ^ PROGRAM IN PYTHON - PART 24 be installed for you. Notice there is an examples folder there. There's some good information there on how to do some advanced things. Here we go. Let's start as we usually do, creating the stub of our program which is shown on the next page, top right. Before going any further, we'll discuss what's going on. Line 2 imports the PyRTF library. Note that we are using a different import format than normal. This one imports everything from the library. Our main working routine is MakeExample. We've stubbed for now. The OpenFile routine creates the file for us with the name we pass into it, appends the extension “rtf”, puts it into the “write” mode, and returns a file handle. We've already discussed the if __name__ routine before, but to refresh your memory, if we are running the program in a standalone mode, the internal variable __name__ is set to “__main__”. If we call it as an import from another program, then it will just ignore that portion of the code. Here, we create an instance of the Renderer object, call the MakeExample routine, getting the returned object doc. We then write the file (in doc) using the OpenFile routine. Now for the meat of our worker routine MakeExample. Replace the pass statement with the code shown below. Let's look at what we have done. In the first line we create an instance of Document. Then we create an instance of the style sheet. Then we create an instance of the section object and append it to the document. Think of a section as a chapter in a book. Next we create a paragraph using the Normal style. The author of PyRTF has preset this to be 11point Arial font. We then put whatever text we want into the #!/usr/bin/env python from PyRTF import * def MakeExample(): pass def OpenFile(name) : return file('%s.rtf' % name, 'w') if __name__ == '__main__' : DR = Renderer() doc = MakeExample() DR.Write(doc, OpenFile('rtftesta')) print "Finished" paragraph, append that to the section, and return our doc document. That is very easy. Again, you need to plan your output fairly carefully, but nothing too onerous. Save the program as “rtftesta.py” and run it. When it's completed, use openoffice (or LibreOffice) to open the file and look at it. Now let's do some neat things. First, we'll add a header. Once again, the author of PyRTF has given us a predefined style called Header1. We'll use that for our header. In between the doc.Sections.append line and the p = Paragraph line, add the doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append(section) p = Paragraph(ss.ParagraphStyles.Normal) p.append('This is our first test writing to a RTF file. ' 'This first paragraph is in the preset style called normal ' 'and any following paragraphs will use this style until we change it.') section.append(p) return doc full circle magazine #50 9 contents ^ PROGRAM IN PYTHON - PART 24 following. p = Paragraph(ss.ParagraphStyles. Heading1) p.append('Example Heading 1') section.append(p) Change the name of the rtf file to “rtftestb”. It should look like this: DR.Write(doc, OpenFile('rtftestb')) Save this as rtftestb.py and run it. So now we have a header. I'm sure your mind is going down many roads thinking about what more can we do. Here's a list of what the author has given us as the predefined styles. Normal, Normal Short, Heading 1, Heading 2, Normal Numbered, Normal Numbered 2. There's also a “ Let's look at how to change fonts, font sizes and attributes (bold, italic, etc) on the fly. p = Paragraph(ss.ParagraphStyles.Normal) p.append( 'It is also possible to provide overrides for elements of a style. ', 'For example you can change just the font ', TEXT(' size to 24 point', size=48), ' or', TEXT(' typeface to Impact', font=ss.Fonts.Impact), ' or even more Attributes like', TEXT(' BOLD',bold=True), TEXT(' or Italic',italic=True), TEXT(' or BOTH',bold=True,italic=True), '.' ) section.append(p) List style, which I will let you play with on your own. If you want to see more, on this and other things, the styles are defined in the file Elements.py in the distribution you installed. While these styles are good for many things, we might want to use something other than the provided styles. Let's look at how to change fonts, font sizes and attributes (bold, italic, etc) on the fly. After our paragraph and before we return the document object, insert the code shown top right, and change the output filename to rtftestc. Save the file as rtftestc.py. And run it. The new portion of our document should look like this... It is also possible to provide overrides for elements of a style. full circle magazine #50 For example you can change just the font size to 24 point or typeface to Impact or even more Attributes like BOLD or Italic or BOTH. Now what have we done? Line 1 creates a new paragraph. We then start, as we did before, putting in our text. Look at the fourth line (TEXT(' size to 24 point', size = 48),). By using the TEXT qualifier, we are telling PyRTF to do something different in the middle of the sentence, which in this case is to change the size of the font (Arial at this point) to 24-point, followed by the 'size = ' command. But, wait a moment. The 'size =' says 48, and what we are printing says 24 point, and the output is actually in 24-point text. What's going on here? Well the size command is in half points. So if we 10 want an 8-point font we have to use size = 16. Make sense? Next, we continue the text and then change the font with the 'font =' command. Again, everything within the inline TEXT command between the single quotes is going to be affected and nothing else. Ok. If that all makes sense, what else can we do? We can also set the color of the text within the TEXT inline command. Like this. p = Paragraph() p.append('This is a new paragraph with the word ', TEXT('RED',colour=ss.Colo urs.Red), contents ^ PROGRAM IN PYTHON - PART 24 ' in Red text.') section.append(p) Notice that we didn't have to restate the paragraph style as Normal, since it sticks until we change it. Also notice that if you live in the U.S., you have to use the “proper” spelling of colour. Here are the colors that are (again) predefined: Black, Blue, Turquoise, Green, Pink, Red, Yellow, White, BlueDark, Teal, GreenDark, Violet, RedDark, YellowDark, GreyDark and Grey. And here is a list of all the predefined fonts (in the notation you must use to set them): Arial, ArialBlack, ArialNarrow, BitstreamVeraSans, BitstreamVeraSerif, BookAntiqua, BookmanOldStyle, BookmanOldStyle, Castellar, CenturyGothic, ComicSansMS, CourierNew, FranklinGothicMedium, Garamond, Georgia, Haettenschweiler, Impact, LucidaConsole, LucidaSansUnicode, MicrosoftSansSerif, PalatinoLinotype, p = Paragraph(ss.ParagraphStyles.Courier) p.append('Now we are using the Courier style at 8 points. ' 'All subsequent paragraphs will use this style automatically. ' 'This saves typing and is the default behaviour for RTF documents.',LINE) section.append(p) p = Paragraph() p.append('Also notice that there is a blank line between the previous paragraph ', 'and this one. That is because of the "LINE" inline command.') section.append(p) MonotypeCorsiva, Papyrus, Sylfaen, Symbol, Tahoma, TimesNewRoman, TrebuchetMS and Verdana. So now you must be thinking that this is all well and good, but how do we make our own styles? That's pretty easy. Move to the top of our file, and before our header line, add the following code. result = doc.StyleSheet NormalText = TextStyle(TextPropertySet(res ult.Fonts.CourierNew,16)) ps2 = ParagraphStyle('Courier',Norm alText.Copy()) result.ParagraphStyles.append (ps2) Before we write the code to actually use it, let's see what we have done. We are creating a new full circle magazine #50 stylesheet instance called result. In the second line, we are setting the font to 8-point Courier New, and then “registering” the style as Courier. Remember, we have to use 16 as the size since the font size is in half-point values. Now, before the return line at the bottom of the routine, let's include a new paragraph using the Courier style. So now you have a new style you can use anytime you want. You can use any font in the list above and create your own styles. Simply copy the style code and replace the font and size information as you wish. We can also do this... NormalText = TextStyle(TextPropertySet(res ult.Fonts.Arial,22,b old=True,colour=ss.C olours.Red)) ParagraphStyle('ArialBoldRed' ,NormalText.Copy()) result.ParagraphStyles.append (ps2) And add the code below... p = Paragraph(ss.ParagraphStyles. ArialBoldRed) p.append(LINE,'And now we are using the ArialBoldRed style.',LINE) section.append(p) to print the ArialBoldRed style. Tables Many times, tables are the only way to properly represent data in a ps2 = 11 contents ^ PROGRAM IN PYTHON - PART 24 document. Doing tables in text is hard to do, and, in SOME cases, it's pretty easy in PyRTF. I'll explain this statement later in this article. Let's look at a standard table (shown below) in OpenOffice/LibreOffice. It looks like a spreadsheet, where everything ends up in columns. Rows go left to right, columns go down. Easy concept. Let's start a new application and call it rtfTable-a.py. Start with our standard code (shown on the next page) and build from there. We don't need to discuss this since it's basically the same code that we used before. Now, we'll flesh out the TableExample routine. I'm basically using part of the example file provided by the author of PyRTF. Replace the pass statement in the routine with the following code... doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append(section) This part is the same as before, so we'll just gloss over it. table = Table(TabPS.DEFAULT_WIDTH * 7, TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3) #!/usr/bin/env python from PyRTF import * def TableExample(): pass def OpenFile(name): return file('%s.rtf' % name, 'w') if __name__ == '__main__': DR = Renderer() doc = TableExample() DR.Write(doc, OpenFile('rtftable-a')) print "Finished" This line (yes, it's really one line, but is broken up for easy viewing) creates our basic table. We are creating a table with 3 columns, the first is 7 tabs wide, the second and third are three tabs wide. We don't have to deal with tabs alone, you can enter the widths in twips. More on that in a moment. yles.Heading2,'Heading2 Style')) c1 = Cell(Paragraph('Row One, Cell One')) c3 = Cell(Paragraph('More Normal Style')) c2 = Cell(Paragraph('Row One, Cell Two')) table.AddRow(c1,c2,c3) c2 = Cell(Paragraph(ss.ParagraphSt yles.Normal,'Back to Normal Style')) table.AddRow(c1,c2,c3) This group of code sets the data for row number two. Notice we can set a different style for a single or multiple cells. Here we are setting the data that goes into each cell in the first row. c1 = Cell(Paragraph(ss.ParagraphSt yles.Heading2,'Heading2 Style')) c1 = Cell(Paragraph(ss.ParagraphSt c2 = Cell(Paragraph(ss.ParagraphSt yles.Normal,'Back to Normal c3 = Cell(Paragraph('Row One, Cell Three')) full circle magazine #50 12 Style')) c3 = Cell(Paragraph('More Normal Style')) table.AddRow(c1,c2,c3) This sets the final row. section.append(table) return doc This appends the table into the section and returns the document for printing. Save and run the app. You'll notice that everything is about what you would expect, but there is no border for the table. That can make things difficult. Let's fix that. Again, I'll mainly use code from the contents ^ PROGRAM IN PYTHON - PART 24 example file provided by the PyRTF author. Save your file as rtftable-b.py. Now, delete everything between 'doc.Sections.append(section)' and 'return doc' in the TableExample routine, and replace it with the following... thin_edge = BorderPS( width=20, style=BorderPS.SINGLE ) thick_edge = BorderPS( width=80, style=BorderPS.SINGLE ) thin_frame = FramePS( thin_edge, thin_edge, thin_edge, thin_edge ) thick_frame = FramePS( thick_edge, thick_edge, thick_edge, thick_edge ) mixed_frame = FramePS( thin_edge, thick_edge, thin_edge, thick_edge ) Here we are setting up the edge and frame definitions for borders and frames. table = Table( TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3 ) c1 = Cell( Paragraph( 'R1C1' ), thin_frame ) row three. c2 = Cell( Paragraph( 'R1C2' ) ) c3 = Cell( Paragraph( 'R1C3' ), thick_frame ) table.AddRow( c1, c2, c3 ) In row one, the cells in column one (thin frame) and column 3 (thick frame) will have a border around them. c1 = Cell( Paragraph( 'R2C1' ) ) c2 = Cell( Paragraph( 'R2C2' ) ) section.append( table ) So. You have just about everything you need to create, through code, RTF documents. See you next time! Source code can be found at pastebin as usual. The first part can be found at which is the sum of rtftest.py (a-e), and the second rtftable.py (a-b) is at. c3 = Cell( Paragraph( 'R2C3' ) ) table.AddRow( c1, c2, c3 ) None of the cells will have a border in the second row. c1 = Cell( Paragraph( 'R3C1' ), mixed_frame ) c2 = Cell( Paragraph( 'R3C2' ) ) c3 = Cell( Paragraph( 'R3C3' ), mixed_frame ) table.AddRow( c1, c2, c3 ) Once again, cells in column 1 and three have a mixed frame in full circle magazine #50 Greg Walters is owner of RainyDay Solutions, LLC, a consulting company in Colorado and has been programming since 1972. He enjoys cooking, hiking, music, and spending time with his family. His website is. 13 contents ^ HOW-TO I Libre Office - Part 5 Written by Elmer Perry n the previous part of this series, we discussed using frames for document layout. In this part, we will turn to another useful layout tool in LibreOffice Writer: Sections. Sections differ from frames in several respects, but, in some ways, they can achieve the same results. While both will allow you to divide a portion of your document into columns, when you use sections, you have no control over the width. Sections will take the entire width from the left margin to the right margin. Sections also cannot break in the middle of a paragraph. You cannot link sections together the way you link frames. While you cannot link sections together, sections give you the ability to link to other documents, or to a section in another document. Perhaps the best way to think about sections is as a way to divide your document into different pieces like introduction, argument 1, argument 2, etc. Sections can also allow you to separate a portion of a document for use in another document. Sections can become a powerful tool for allowing you to pull content from other documents. remind you what the quotation is about. (For example, one of my quotes is from Albert Einstein on science. I named it quote_science.) Using Sections Once you have made each of the quotes its own section, save the file as quotes.odt. For our example, we will import quotations from a document of quotes. Start a new document, and add a list of different quotes. Do the following for each of the quotes: Next, let's create a new document, and add some paragraph body text. (Hint: You can add dummy text to your document by typing “dt” and pressing the F3 key.) Write a leadin to your quote, and press enter. To get our quote from our quotes document, Insert > Section. As always, give the section a name that helps you remember what it is. Select the Link checkbox. Click on the file browser button (…) next to File name. Select the document containing your quotes, and Open. Use the Section dropdown box to select the quote you want to insert into your document. If you want to writeprotect your quote from editing, check Protected under Writeprotection. You can also protect the section from editing with a password. (NOTE: Write protection, even with a password, Select the entire quote. On the menus, got to Insert > Section. Give the quote a name that will full circle magazine #50 14 contents ^ LIBRE OFFICE - PART 5 does not guarantee someone cannot hack your document and change its content.) You can add the other quotes from your quote document using the same method. new document. Both are possible. The choice is really yours. The one thing to remember is changing a linked section in a document will Editing Sections Now that we have added our quotes, let's make them stand out by indenting them and giving them a background color. Format > Sections. The edit Sections dialog presents you with a list of sections in your document. Select the section you want to edit. In the main window of the dialog, we can change the link document, or the section in the document the section is linked to. Here we can also change the write-protection and visibility of the section. (I can't think of any practical reason why you would hide a portion of the document, but the option is there should you need it.) Click the Options... button to bring up the options dialog. On the Indents tab, change the Before section and After section to 0.30â€?. On the Background tab, select a color for the background of your quote. Click OK. Change the other quotation sections, and then click OK on the Edit Sections dialog. Your quotes now have an indentation and a background color. Changes Made in Linked Document If you need to change the information in a section linked to another document, you might ask whether it is better to change the original document or within the full circle magazine #50 15 not be reflected in the original document, but changes in the original document may be reflected in the linking document. You can control how updates are done in the LibreOffice Writer options: Tools > Options > LibreOffice Writer > General. Under Update, you can choose to have links updated automatically, manually, or never. Automatically will update the links when a document with links is opened. Manually will ask you whether you want to update links. Never will not update links when a document with links is opened. Manually Updating contents ^ LIBRE OFFICE - PART 5 Links If you make changes in the original document, and you want to update the linked document to reflect those changes, you have two ways to update the linked document. Edit > Links... will display the Edit Links dialog. Here you can select individual links and update them. To update all the links at once, use Tools > Update > Links. Frames or Sections? In some cases, whether you use frames or sections matters little. There are situations where either can accomplish the tasks. However, taking the time to consider the functionality of each can help you make the best choice. For example, if you are doing a research paper, and you have compiled your quotes and data into a Writer document, sections would probably be your best choice for inserting pieces of the data into your paper. However, if you need to start an article on a page, skip a page, and finish it on another page, linked frames is a better choice. Taking some time to think about the purpose, layout, and content sources of your document, and the functionality of frames and sections, will help you decide the best tool for your document. While frames and sections are similar in many ways, they have different functionality that makes them suitable for different purposes. The powerful ability to link to portions of another document makes sections unique. Remember to plan your layout and decide ahead which tools you will use to accomplish the task. In the next article, we will look at page styles, headers, and footers in Writer documents. Elmer Perry is a children's minister in Asheville, North Carolina whose hobbies include web design, programming, and writing. His website is eeperry.wordpress.com full circle magazine #50 Zero Downtime the heart of our networking infrastructure is state-of-the-art BGP4 routing that offers optimal data delivery and automatic multihomed failover between our outstanding providers. Customers may rest assured that we only use the highest quality of bandwidth; our policy is to pay more for the best of breed providers and because we buy in bulk this doesn't impact our extremely competitive pricing. At Below Zero we help you to achieve Zero Downtime. w w w. z e r o d o w n t i m e .co. u k 16 contents ^ HOW-TO Written by Daniel Holbach T here are a number of things you need to do to get started developing for Ubuntu. This article is designed to get your computer set up so that you can start working with packages, and upload your packages to Launchpad. Here’s what we’ll cover: • Installing packaging-related software. This includes: • Ubuntu-specific packaging utilities • Encryption software so your work can be verified as being done by you • Additional encryption software so you can securely transfer files • Creating and configuring your account on Launchpad • Setting up your development environment to help you do local builds of packages, interact with other developers, and propose your changes on Launchpad. Note: It is advisable to do packaging work using the current development version of Ubuntu. Doing so will allow you to test Ubuntu Development Pt. 2- Set Up changes in the same environment where those changes will actually be applied and used. Don’t worry, though, the Ubuntu development release wiki page ( elopmentReleases) shows a variety of ways to safely use the development release. Install Basic Packaging Software There are a number of tools that will make your life as an Ubuntu developer much easier. You will encounter these tools later in this guide. To install most of the required tools, run this command: sudo apt-get install gnupg pbuilder ubuntu-dev-tools bzr-builddeb apt-file This command will install the following software: gnupg – GNU Privacy Guard contains tools you will need to full circle magazine #50 create a cryptographic key with which you will sign files you want to upload to Launchpad. pbuilder – a tool to do reproducible builds of a package in a clean and isolated environment. ubuntu-dev-tools (and devscripts, a direct dependency) – a collection of tools that make many packaging tasks easier. bzr-builddeb (and bzr, a dependency) – distributed versioncontrol tools that make it easy for many developers to collaborate and work on the same code while keeping it trivial to merge each other’s 17 number of purposes. In our case, it is important that you can sign files with your key so they can be identified as something that you worked on. If you upload a source package to Launchpad, it will accept the package only. Afterwards, it will ask you if you want it to expire the key at some stage. It is safe to say “0”, which means the key will never expire. The last questions will be about your name and email address. Just pick the ones you are contents ^ HOWTO - UBUNTU DEVELOPMENT 2 - SET UP going to use for Ubuntu development here, you can add additional email addresses later on. Adding a comment is not necessary. Then you will have to set a passphrase. Choose a safe one. Now GPG will create a key for you, which can take a little bit of time; it needs random bytes, so if you give the system some work to do it will be just fine. Move the cursor around! Once this is done, you will get a message similar to this06 communicate with Launchpad. To generate a SSH key, enter: ssh-keygen -t rsa The default file name usually makes sense, so you can just leave it as it is. For security purposes, it is highly recommended that you use a passphrase. Set up pbuilder full circle magazine #50 Pbuilder allows you to build packages locally on your machine. It serves a couple of purposes: • The build will be done in a minimal and clean environment. This helps you make sure your builds succeed in a reproducible way, but without modifying your local system. • There is no need to install all necessary build dependencies locally. • 18: • What Launchpad is, and creating a Launchpad account • Uploading your GPG and SSH keys to Launchpad • Configuring Bazaar to work with Launchpad • Configuring Bash to work with Bazaar About Launchpad Launchpad is the central piece of infrastructure we use in Ubuntu. It not only stores our packages and contents ^ HOWTO - UBUNTU DEVELOPMENT 2 - SET. Get a Launchpad account If you don’t already have a Launchpad account, you can easily create one (at:). ( count/NewAccount) on Launchpad has more information about the process, and additional settings you can change. Upload your GPG key to Launchpad To find out about your GPG fingerprint, run: gpg --fingerprint <email@address.com> and it will print out something> full circle magazine #50 sub 06 4096R/51FBE68C 2010-12- Head to /+editpgpkeys and copy the part about your 19 window. Back on the Launchpad website, use the Confirm button and Launchpad will complete the import of your OpenPGP key. Find more information at count/ImportingYourPGPKey Upload your SSH key to Launchpad Open /+editsshkeys ( count/CreatingAnSSHKeyPair) on Launchpad. Configure Bazaar contents ^ HOWTO - UBUNTU DEVELOPMENT 2 - SET UP Bazaar is the tool we use to store code changes in a logical way, to exchange proposed changes and merge them, even if development is done concurrently.. export DEBFULLNAME="Bob Dobbs" A PLEA ON BEHALF OF THE PODCAST PARTY export DEBEMAIL="subgenius@example.c om" As you heard in episode #15 of the podcast, we're calling for opinion topics for that section of the show. Now save the file, and either restart your terminal or run: Instead of us having a rant about whatever strikes us, why not prompt us with a topic and watch for the mushroom clouds over the horizon! It's highly unlikely that the three of us will agree. source ~/.bashrc (If you use a shell different from the default (which is bash), please edit the configuration file for that shell accordingly.) Or, an even more radical thought, send us an opinion by way of a contribution! NEXT MONTH: Fixing a bug. Note: If you can not remember the ID, go to and see where it redirects you. The part after the “~â€? in the URL is your Launchpad ID.) Configure your shell It would be great to have contributors come on the show and express an opinion in person. Similar to Bazaar, the Debian/Ubuntu packaging tools need to learn about you as well. Simply open your ~/.bashrc in a text editor, and add something like this to the bottom of it: Robin full circle magazine #50 20 contents ^ HOW-TO I Use KDE 4.6 Written by Ronnie Tucker f you're gnashing your teeth at Gnome3, or unhappy with Unity, then maybe you should try KDE. Kubuntu gives you the best of both worlds. Not only does it give you Ubuntu as a foundation, but it comes with KDE 4 as its default desktop. This article is for those of you thinking about trying KDE but are worried it's too different from your beloved Gnome. The first difference you'll notice about the default KDE desktop is that the main taskbar is at the bottom of the screen, but don't worry, you can rearrange pretty much everything in KDE. The 'Desktop Folder' box is what's known as a 'widget'. Widgets are little apps (for want of a better word) that run on your desktop and give you quick access to things. Moving over the widget gives you access to some controls to remove, lock, or configure, the widget. Another shortcut to settings is to click the icon in the top right of the screen menu lets you add it to your favourites), Applications (that are installed), Computer (your drives and places), Recently Used for files (or apps), and Leave, which lets you reboot, or close down, your machine. The big 'K' button (above right) at the bottom left is your main access point for all your apps The tabs along the bottom are quick links to your Favourites (right clicking on an app in the full circle magazine #50 21 While Gnome has Nautilus as its file browser, KDE has Dolphin (shown on the next page, top left). This can be accessed by clicking K > Favourites > File Manager (Dolphin). Initially it may seem bulky with contents ^ HOWTO - USE KDE 4.6 the Places down the left, and the Information down the right, but those can be removed or configured as you see fit, especially the Information box on the right. KDE lets you rate files (out of five stars) and even 'tag' files with descriptive words. This makes finding files so much easier later on in life. In K > Applications > Graphics you have, amongst other things, Okular which is used for viewing documents, Gwenview, for viewing images, and Ksnapshot which is for taking screenshots. K > Applications > Internet gives you a torrent client (KTorrent), messenger client (Kopete), an IRC client, desktop sharing apps, feed readers, even a dialup client. Its default browser is rekonq, but there's a one click link in there to install Firefox. Under Multimedia, KDE gives you one of the best audio players anywhere, Amarok. Not only that, but you get one of the best disc burning apps too, K3B. Even when I used Gnome I installed Amarok and K3B. If you install 11.04 then you'll get LibreOffice in the Office section along with many contact and personal organisers, time trackers, and even a formula editor. Under System, you'll have access to the information centre, partition manager, screen resize/rotate, system monitor, and more. This is also where you'll find Software Management (KPackageKit) which is the KDE equivalent of Synaptic for access to repositories. Utilities gives you text editors, virtual keyboards, and the like. Settings takes you to the System Settings for the whole of KDE. This one handy window lets you edit account details, application full circle magazine #50 appearance (where you can make any GTK apps look KDE native), file associations, and much more. Desktop Effects lets you use the KDE native effects which mimic those seen in Compiz. Sharing, as the name suggests, lets you connect to your other machines whether Windows or Linux. Network Settings lets you get deeper into networking while Workspace Appearance lets you completely change the look of the default KDE. Speaking of which, KDE is linked to several sites which let you grab themes and wallpapers very easily. A right click on the desktop, and choose Desktop Settings, gives you a window with what you have so far in wallpapers. But clicking Get New Wallpapers takes you online (within the window) to view downloadable wallpapers Clicking install gets you a new wallpaper in seconds. The same is true for themes. Adding a widget to your desktop can be helpful too. My personal favourite is the post-it note widget which is very handy, especially with a memory like mine. A right click on the desktop and choosing Add Widgets gets you a list of all the currently installed Widgets. Again a click on the Get New Widgets button will let you download new ones in a jiffy. Scroll along the widgets and drag and drop the widget to the desktop. Clicking the big yellow post-it note lets you type some reminder text while the buttons that slide out the side will let you resize, configure, or rotate your post-it note. Clicking somewhere on the slideout panel will let you move the widget. 22 contents ^ HOWTO - USE KDE 4.6 As it says, Get and Remove Software lets you see what you have installed or what you can install via categories. But you can still search by name too. Software Updates will list available updates, which is also shown with a cog icon in your taskbar. In fact, your entire taskbar, at the bottom of the screen, is made up of widgets, so you can rearrange things, even create a new taskbar at the top of the screen keeping the bottom bar for more widgets. Settings shows you which repositories you have access to, but clicking Edit Origins will let you easily add a repository. Going back to Dolphin, you can configure it to taste. Clicking the View menu will let you add/remove panels (such as the Places and Information), but also add panels such as a Terminal. I've only scratched the surface of what KDE can do. If having Unity makes you miss having a proper desktop, give KDE a try, Kubuntu especially, as it's easier to use than you might think. NOTE: A video showing most of what you’ve read can be seen at: EgQUDPRt7zw Opening the KPackageKit you will see that it's quite different from Synaptic. Zooming in/out will resize your icons and you can change view modes and turn on/off previews. Previews are nice, and actually allow you to preview audio/video files in the Information panel. full circle magazine #50 23 If you’d like to know more about KDE then drop me an email at ronnie@fullcirclemagazine.org and I’ll write a Part Two on how to further customise KDE. contents ^ HOW-TO Write For Full Circle Magazine Written by Ronnie Tucker Guidelines T he single rule for an article is that it must somehow be linked to Ubuntu or one of the many derivatives of Ubuntu (Kubuntu, Xubuntu, Lubuntu, etc). Write your article in whichever software you choose. I would recommend OpenOffice, but PLEASE SPELL AND GRAMMAR CHECK IT! Writing In your article, please indicate where you would like a particular image to be placed. Please do not embed images into your Open Office document. Images Images should be JPG with low compression. Regarding image sizes: if in doubt, send a full size screengrab and we will crop the image. If you are writing a review, please follow the guidelines shown here. For a more detailed list of the style rules and common pitfalls please refer to: g is not English, don't worry. Write your article, and one of the proofreaders will read it for you and correct any grammatical or spelling errors. Not only are you helping the magazine and the community, but we'll help you with your English! full circle magazine #50 REVIEWS Games/Applications When reviewing games/applications please state clearly: • • • • • • • title of the game who makes the game is it free, or a paid download? where to get it from (give download/homepage URL) is it Linux native, or did you use Wine? your marks out of five a summary with positive and negative points Hardware When reviewing hardware please state clearly: • • • • • • • make and model of the hardware what category would you put this hardware into? any glitches that you may have had while using the hardware? easy to get the hardware working in Linux? did you have to use Windows drivers? marks out of five a summary with positive and negative points You don't need to be an expert to write an article - write about the games, applications and hardware that you use every day. 24 contents ^ LINUX LAB U Gnome Shell -vs- Unity Written by Robin Catling nity is Ubuntu's somewhat condescending attempt to produce a desktop environment with usability in mind. It rather patronizes the classic Gnome desktop, which was always functional rather than stylish, but has served Linux users well for some years. Gnome 3, with Gnome Shell, brings major changes, too. Gnome Shell and Unity are the Gnome-based desktops designed from the start with usability and new users in mind. Unity is native to Ubuntu and its derivatives, whereas Gnome Shell will be available across many distributions. The new user wants visual cues for everything; simplicity in layout, messages and notifications; also a quick way to pin favorite programs and files where they are accessible with a single click. Similarly, they want a quick way to find, well, everything else. The veteran hacker, by contrast, wants freedom to customize and configure a working environment for day-in, day-out use. So what do they get? Both are desktop shells, interfaces that interact with a common Gnome back-end and applications. On the surface, they are both informed by shared design principles - not to mention each other, since they are concurrent developments. Throw in a splash of Macintosh, a big pinch of interfaces from music players to phones, and we get a massive culture shock compared to more familiar desktops. That translates to more mouse-mileage, and changes of screens and panels, than classic Gnome 2. There are far fewer options for customization in both, corralling unruly users who might otherwise break out of the defined standard. Finding the other controls that you need will demand the patience to search many layers below the main desktop. Panels and Launchers Both shells park their panels on the left side of the screen; the ‘Dashboard’ in Gnome 3, the full circle magazine #50 'Launcher' in Unity. Designers believe that this works best for net-books and other landscapeaspect screens, so that's where the panels are fixed. Gnome 3 uses a minimum of two screens; a working desktop in which programs run, and the full-screen overlay which is Gnome Shell for configuring and launching programs. Unity retains a launcher (or dock) with a top context menu, and all running programs on a single screen which is always visible. Gnome Shell's Dashboard sits fullscreen and previews the running applications. It scales down the thumbnail views of all of them, as more programs are opened. The top panel, titled “Activities,” has a search box for finding applications. Unity's Launcher brackets running applications 25 with small arrows, replacing taskswitcher buttons. Some say these are elegant space-savers, I find them uselessly illegible. The Launcher accommodates an overflow of application icons by showing a concertina’d stack at the bottom of the single column; it opens quickly when you need to scan them. I’d rather have a better way of managing that single column at the outset. Unity features a 'Dash' of sorts; 'Application Spaces' is a near- full screen panel which shows all the installed applications. It is filterable by categories (equivalent to Gnome 2's main menu categories), and includes a search field right in the Dash panel itself. I contents ^ LINUX LAB - GNOME SHELL vs UNITY find this manages the available onscreen real-estate badly, displaying a single line of items plus a link announcing how many items are not displayed - even if there is only one. And this is the problem I have with both shells; struggling so hard to eliminate drop-down menus in favor of more visual icons and dashboards, they impose on the user the need to learn these new working methods without actually making things any easier. The rightclick context menu has disappeared, and a whole chunk of productivity with it. Window Management By default, neither interface allows custom window resizing. It’s default or maximum. Both use hotspots on the edges of the desktops to minimize or maximize, or to tile windows. Gnome 3 even eliminates title-bar buttons forcing you to rely on the hot spots. This all seems like enforced conformity, limiting user choice for no clear benefit. Customization Both interfaces feature fixed, bare, top bars; you get a clock and a collection of indicators; controls for sound, batteries, network, and user account information. Gnome 3 also uses the panel for a task indicator - something you don't get in Unity. Yes, you can at least change colors and wallpapers in both. Unity will auto-hide the panel (but only on the left), Gnome won't. Beyond that, customizing your desktop is controversial. You want to add applets to your desktop panel, or application launchers to the desktop? Gnome 3 doesn't give you the the option of desktop icons at all, and the Unity framework steers you away from them. an array of icons is not anything that I want to regularly do in either of them. They've flattened the hierarchy of drop-down menus and left us with hordes of multi-colored icons. Meanwhile, file management is left largely untouched and unloved. Yes, I know we're all going to have our 'stuff' stored on the cloud soon, but that's not now. 'Now' is still Nautilus file manager, with all its faults and limitations. Verdict It seems to me they both fall uncomfortably between netbook and smartphone, using grids of icons and non-linear operations. I've seen it called “the smartphone, one-size-fits-all approach.” I'm not sure this is the way to world domination. Why so much mousing-around the desktop? Do I want to have to learn the keyboard shortcuts? In which case why bother switching from classic Gnome desktop at all? I can’t help thinking KDE 4.x does much of this so much better? 26 Unity might have an edge on elegance of design. Although Gnome 3 handles virtual workspaces better, it still seems to be working out complexity that should never have made it past the first Beta release. At least Unity delivers notifications that are colloquial and helpful. Gnome 3 is something of a sullen beast. I have an issue with the 'dash' in both. Finding an application from full circle magazine #50 If you're a new Linux user, these shells are going to confuse the beejeezus out of you, whilst frustrating the living daylights out of veteran hackers. It might work for the young and open-minded, the just-getting-things-done, social-surfing, living-on-line users. On small, light-weight machines, under casual use, Unity and Gnome Shell could work well. But at some stage, the new user becomes a veteran, and productivity will hit brick walls deliberately built by both. Unfinished brick walls at that; Gnome 3 might yet ditch some of its complexity; I am also aware that Unity has evolved fast and is not in its finished form. Who knows what changes will come from real-world use of what is effectively a large-scale public beta-test? contents ^ MY STORY I Written by Dr. Pu Kuang am a physician and a postgraduate student of Hematology. I live in the city of Chengdu, sitting in the southeast of China, a beautiful place where you can have much great food. I first knew a PC when I was no more than five years old. At that time, the PC was nothing but a video game player with which I inserted a floppy disk and typed some letters, and played. I learned barely nothing but several commands in DOS. After a few years, I started to write some Basic programs when I was older. I was keen on programing, I tried to write some programs to draw complex curves and play music. I even tried to write a game myself but didn't manage to do so. In 1999, I bought my first desktop. Intel Celeron 333, 64M memory plus 4M graphic card was a popular profile at that time in China. Anyhow, at that time, a desktop like that would cost an ordinary employee like my father almost one month's income. That desktop was pre-installed with Windows 98 by the retailer, a pirated version, of course. For most of the PC consumers in my country, Microsoft Windows was their only choice, otherwise they would pay much more for a Macintosh. But most of us did not pay for software, instead we spent no more than 1 dollar to buy a pirated CD with Windows in the flea-market. At the turn of the twentyfirst century, the Internet boomed in my country. More and more people began to download pirated Windows systems packed inside a ghost file. I updated my second desktop's OS to Windows XP too. But I gradually found that such files were always packed with trojans and backdoor programs aiming at peeping into private information like credit-card passwords, codes for e-mail or Warcraft accounts, etc. full circle magazine #50 To get rid of these risks, I tried Ubuntu systems on my desktop, that was Ubuntu 7.04 or 7.10. The boot logo was so nice - more beautiful than what it now looks like. With great passion, I spent quite a lot of time to set up the system before I really began to “use” it, because at that time many settings can not be modified in a graphic interface. One of the most attractive things was that when you need special software, you can find almost any program you want and download it without difficulty, rather than search for it and its crack all the way around the Internet, and jump from site to site in order to locate a faster server. However, the system broke down several times, and finally it became unbootable. I tried to fix up the problem myself, but did not make 27 it because I was not familiar with Grub. So I gave up, and sadly shifted back to the risky pirated Windows XP. About 1 year later, I learned that a release version of Ubuntu system was available for netbooks. So again, I installed this system, but this time on my ASUS EeePC1000HE. It was about one year and a half ago. Before that, I tried the OS the manufacturer offered and Moblin 2.0 (a system for netbooks initially developed by Intel but now joined with Meego). I was satisfied with neither of them. They had many defects in function and looks, unlike Ubuntu. This time, Ubuntu worked well and works well up to the very moment I write this sentence with OpenOffice. The system has been updated from 8.04 to 10.10 all the way. I am very surprised but so happy to find that Ubuntu really has made so much progress as it upgraded. For example, I can select any popular source server in a GUI instead of beginning with “sudo gedit...” So many applications like R-Kward (package contents ^ MY STORY for scientific statistics, and its GUI), Chromium, Adobe PDF reader, have been added to the Software Center or Synaptic package manager, so that I have almost forgotten how to type “sudo aptget...” :-P. For a none-skillful user, using commands to do everything is really difficult, though now I can use them a little when necessary. Also, I am able to use OpenOffice Writer and Bibus (an application for bibliography management) to write my papers. To write in Chinese, I choose IBUS, a more convenient input method compared to SCIM, as the default input method. Also, I can make use of Jemboss (a package for biological research) to make alignments of the DNA sequences as soon as I get them in the laboratory, but without worrying about having the system infected by any trojan or virus. Another thing to be emphasised is that I can finally read Full Circle Magazine through Chromium (alias for Chrome web browser in Linux), and all the bookmarks and settings are cloned intact. Of course, I should not forget “gconf-editor”, with which I can easily set so many parameters that we might have set with gedit or vi. In addition to all the advantages I have mentioned above, this time Ubuntu is becoming more and more goodlooking than ever before, though many old users probably miss the classical Human theme. I enjoyed the style the designer offered for netbooks, these icons are large enough for ordinary users, and they have bright colors and look really lovely. However, I gave up this, because my netbook turned out to be quite slow. So I went back to the original gnome interface. I selected a nice wallpaper from a KDE wallpaper package I downloaded through Synaptic Package Manager. I also made a dock which I had always been crazy about since I first saw it on an Imac, docking all those commonly used programs on it as you can see in the first snapshot. I love the gmail gadget. It looks nice and will check mail for me every time I log in and tell me how many messages are left unread. On the system panel, I placed as few buttons as possible since the screen is relatively narrow. I set the background color to brown, for I would for once or twice miss the classic style of Human too. I reduced the number of working areas to only two, one for working, full circle magazine #50 the other for entertainment. Simple is the best, isn't it? Thanks to god, in spite of the integrated graphic card, it can still display some special effects, for example, switching between working areas like what Windows 7 can do (see picture 2). I think this is even cooler. So I could always be somewhat flattered when I showed of my desktop to my friends. By doing that, I hope they 28 would be struck by Ubuntu and began to use it too. All in all, I am now more than satisfied with my current system. But can you believe there is even more to be expected? Though life as a physician and a medical student can be sort of mechanical and tiresome, Ubuntu really adds much joy and excitement to my life anyway. contents ^ MY STORY Written by Knightwise S pring is upon us. Although it might still be hiding behind the last folds of winter, the first rays of sun are starting to crack open a sky of murky white and grey. I know this because the reflection of what appears to be a "sunny but cold" morning continuously throws its glare against my screen, beckoning me to come outside and play. By the angle of the light, I know that it is a devilish scheme of the icequeen of winter and her rascal friend "budding spring" to make me go outside for a walk... and, after noticing that it might look sunny, but is still cold, rush back in to pack up warmer than an imperial snowtrooper. Yet today I am far too enwrapped in my personal quest, that lies just beyond my grasp, to be lured outside by mother nature. Behind my keyboard, I embark on an epic quest to find and retrieve the holy grail of automated computing: I want to syncronise my latest podcasts to my phone, using an automated script. I might catch some of you frowning in puzzlement, mouthing the words "Knightwise, there are programs for that, programs like Itunes and stuff", and I must say you are correct. For years I have used this loyal application to download the gleaming gold of user-created content to my precious Ipod. So why seek other ways? For one, it is the fault of a little green goblin. Well, not so much a Goblin as a Droid logo that stands for the technology behind my Smartphone - the htc Desire. Its “freedom loving, open source, anyone can play oh rootme! rootme! rootme!" calls border on the edge of slutty as the device tries to pry some "creative hacking spirit" from my mind. The second antagonist, its brown circled logo watching me like the eye of Mordor is my Ubuntu server. Tucked away behind our television, a hidden realm of infinite possibilities, endless tweaking, and complete customisation. I stand before a vast landscape of ignorance, armed only with curiosity and enthusiasm, and full circle magazine #50 wonder if I can bridge the void between the two towers? In the distance, the green android goblin dances around the brown mountain of Ubuntu, behind me my Ipod snuggles up to my leg as I sit in the shadow of a giant white Imac and the closed source technology it stands for. The grey wizard Steve tries to comfort me by whispering soothing words into my ear: "Why leave the walled garden? You can do anything you want here, as long as you do it my way". His words are tempting, soothing, safe. They almost take away the pain of having to manually download and synchronize all my podcasts to my Ipod before I leave for work. The white straight jacket of the Itunes asylum almost feels comfortable. Almost. But, I choose to embark on the unmapped roads of the interwebs to reach my goal. To tweak, tune, hack, and script the dragon of technology to serve me and my green goblin. To have the power of the brown tower (that sounds wrong) at my fingertips, to 29 become master instead of servant. I push open the white doors of the white kingdom. Behind me, somebody slays an open source unicorn to convince me to stay... but its death-cries are lost on the open roads I embark on. My only map in this unknown labyrinth is "the google". This omnipresent oracle can be persuaded in divulging the right answers, if only you ask the right questions. When I, however, ask in what direction I must walk, it points me to 20 directions at the same time. "Which one is the right one?" I scream. "Every one" whispers the Google. Thus I use its directions to re-formulate my question over and over, trying to get a clearer answer, but there is just too much information out there. One of Google's arrows point me toward a gigantic square entitled "Ubuntu Forums". This magic place beholds both questions and answers yet its inhabitants are invisible. The square is littered with old matrix printer paper. Each "chain" consisting of a question and contents ^ MY STORY subsequently filled with replies, suggestions, and other answers concerning the topic. I wade around them for hours, but do not find the answer I seek, So, I pick up a blank piece of paper and write down my own question. I let the paper fall back into the enormous pile and wait as I look around. At the sound of rustling paper, I look back to see that an invisible friend has written an answer to my question on my thread... I reply, put the paper down, and wait ... the process magically repeats itself. Who IS this stranger? Why does he want to help me? Slowly but surely the general direction where I want to go starts to become clear. With the help of my unknown library friend, we are able to define my quest clearer and clearer. I walk through the labyrinth, the forum thread streaming behind me like an endless letter, other strangers writing down their answers and direction as we go along. Suddenly, I hear the noises of babbling voices and rattling keyboards, around the corner I find a tavern called "The IRC”. “The place where everyone talks about everything, all the time" the google whispers when I inquire about the place. "The trick is to find the right room". Thus I wander inside this great establishment, and open door after door, peeking inside room after room. Some rooms are empty, some have patrons that do not speak, others are bustling with the chatter of voices. I find a chamber that bears the name of the brown tower, and step inside. After politely saying hello and listening to the conversations that go on inside, I ask if I may ask a question. "The statement is redundant" bellows somebody inside the room. "Asking if you can ask redundant". I almost turn on my heels and step outside, shocked by his attitude, as he slaps me on the shoulder, hands me a virtual pint, and says: “Ok, so what was that question”. I tell the patrons my Epic tale. Of the road I have traveled, the arrows google has shown me, and I wave around the paper thread I brought from the library. This mysterious letter that seems to write itself. As by magic, several of the patrons in the room break from their conversations and start to help me. They discuss what I have achieved so far, they read through the Forum thread that is still being written, and throw up full circle magazine #50 suggestions of their own. I marvel at the enthusiasm and friendliness of these strangers who take the time to solve this problem with me. With their answers I race out the door, heading closer and closer to my direction. My own enthusiasm, combined with the knowledge I have acquired and the collective minds of the people helping me on my quest, seem to make the labyrinth crumble into one straight road towards my destination. I am close! I call out to the people in the Tavern and the Library... " YES!" I hear them call... I slice down the last pesky bugs that stand in the way of my quest, iron out the last glitches of code in the script, and see the end of my journey coming ever closer. As all of us fix the last corrupt character in the script, I slide in my code into the gates of the Open Source Kingdom, my green goblin laughing and giggling with expectation. The giant gate clicks and the open source kingdom opens up to me. I look behind me, expecting to see the long, deserted stretch of road that led me here on my solemn and lonely quest. My breath catches in my 30 throat as they are all there, the invisible helpers from the library, the patrons from the IRC-tavern, the many souls who wrote the arrows google gave me. A massive army of smiling faces that helped me in achieving my goal. I smirk at that stupid frodo guy who only had about 5 helpers while I seem to be accompanied by an army of thousands. All of them devoting a little bit of their time and effort to help me achieve my goal. On the horizon I see "Jobs the Grey" utter a curse as he randomly rejects another developer access to the application store. "Because it’s Monday and my shoes are blue" he shouts at the questioning face of the latter. As my code runs, and my green goblined Android phone receives the podcasting episodes via a script, I look back at the things I've learned, the friends I've made, and the goal I've accomplished. In the edge of my vision, I see a lost soul with a map, trying to find his way in the land of the open sources. She is a total stranger, yet I walk up to her... "Lets see what we can do to help you"... My army roars as we embark on another campaign. contents ^ MY OPINION W Written by W. Robert Laggly hen I first used Ubuntu, it was version 9.04. WOW! It reminded me of what Red Had v.2 had - no nonsense, solid, stable, but Ubuntu had a strong update for today. Apple is losing its base with computers, I live in an area of Apple country. After Leopard and Snow Leopard release, the Applelifers started looking for something else. This is not just one or two, folks are not happy with Apple. Because of this attitude, I cannot understand the success of iToys. The problem is not the backbone of the software which is excellent, it is the layout and attitude of the designers. Microsoft got scared and formatted Windows 7 similar to iMac on steroids. This is the worst mistake in design since the “Blue Screen” crash on the release of Windows by Bill Gates (April 20, 1998, at COMDEX.) The Windows 7 engine is excellent, if anyone can use it other than some twelve-yearold. It is built upon Windows 2000. Again, an excellent engine, but Downfall Of Ubuntu, Canonical with designers’ ego in the way. Ubuntu was poised to take over the market on April 23rd, 2009. Yes, there were some back-end issues that needed addressing. Instead of improving the engineside (the kernel), Ubuntu went off on tangents, as did the big boys. Ubuntu 10.04 and 10.10 were slow, and prone to lockup and crashes. The bells and whistles were overwhelming the foundations of Ubuntu. The newest release, Ubuntu 11.04 with Unity, is destroying the underpinnings of Ubuntu. I backed down to version 9.04 from 10.10. I am staying here until Ubuntu and Canonical return to what was being attempted a solid working engine for computers in open source. I have publicly proclaimed such, and will load 9.04 and full circle magazine #50 continue teaching new users the workings of Ubuntu. I will not load or use the later releases. The new toys added since 9.04 may have been added in order to help Canonical or some of the design folks to have larger bank accounts. Whatever the reasoning, good, bad, or indifferent, the results are not good. In the Full Circle Podcast, episode #19, the comment was made that Ubuntu was losing its support in hopes of gaining Windows and possibly iMac users. I am sorry that a specific quote cannot be given, the ramblings of the podcast were hard to follow. Saying this, it is still an excellent tool to use. The podcast needs to be only tightened, not scrubbed - good job. It should be encouraged that all of the availabilities (repositories) of version 9.04 be re-opened, 31 and that if software is being designed, a stable version for 9.04 be included. As a second step for release 12, the version 11 ideas should be scrapped as a bad dream, and re-building from version 9 should recommence. But let us not abandon these ideas, read on. What about all the new toys in 10 and 11? A simple fix is to have these as either tangent versions of Ubuntu, or as add-ons for those who wish such features. The ability of backing away from such features should be easy and painless. The whole digital field is expanding in almost every direction almost at the speed of sound. A platform that is rocksteady and dependable, such as Ubuntu 9.04, should be the basis of future releases. One person’s great idea is another person’s Hell. I still miss my IBM Selectric typewriter. I am now looking for a replacement for the one I sold. contents ^ MY OPINION Designing for the future This is what I believe users wish from their computers: • Faster service and usage. • Dependable service and longevity. • Security from spying and other back-door espionage by outsiders and software providers. • A Common-sense approach to software layout, and at least relevant information about the software easily provided. with only the need to add tentacles into the operating system. Yes, the old ways will not work today, but the idea is solid, totally self-contained software packages with something that is a new version of the old DLL files linking to the operating system. Let us always remember How can software be designed? The end-user always has the final no. It appears that version 11 is failing, let’s not have Ubuntu fail also because of some bad decisions by the developers on how the new features will be made available. The Windows and Mac users are starting to understand open source. It is surprising how many computers have free software such as OpenOffice as a replacement or parallel to Microsoft Office. The time has come for Linux, if Linux and Ubuntu will provide the foundation. Let us remember how many of the old DOS packages were made. They were totally self-contained If desktop computers are going to survive, they have to be fast with the software, Yes, this may dip into the profits of some by having Ubuntu come back to its roots. From this sound building block of an always improved 9.04 Ubuntu, the other features are now the simple option of each user choosing instead of someone deciding to cram something down the throats of others. full circle magazine #50 not an obstacle to fight. The real success in software will be when software is designed to fit into the world-view of each user, not the developers. Just as in days past when computers were slow and cumbersome, they have again returned to being slow and cumbersome - not from technical issues, but from the poor design and egos of developers who have great ideas and little world experience. By working together 32 we shall have the best system for everyone. The miracles of design in some of the software is unbelievable, the weakness is not allowing the professionals in each field the opportunity to design the layout. contents ^ Last month's question was: I THINK... Should Ubuntu keep its current schedule, or switch to a rolling release? If you chose 'Scheduled Release', should it stay as 6 monthly, or become yearly? * Should Ubuntu keep its current schedule, or switch to a rolling release? Don't Care Rolling Release Scheduled Release “ It's important that ubuntu stick to its aim of security. By switching to a rolling release, Ubuntu would forfeit security and functionality, for bleeding-edge software. As an Arch user (rolling release system), I can say that the issues that would crop up could scare off a large number of Ubuntu's user base, and also destroy the belief that "Ubuntu is easy to use". Lucas Westermann “ "Once a year release. The public is ‘used to’ ubuntu scheduled releases, but one a 8 63 38 year would be better... less strain on devs, etc, more stable features, and bugs fixed pre-release." syko “ Rolling plus LTS milestones would make sense. If it moves to rolling release, it would become the ultimate Linux based OS; I hope Mark will make the decision to move to a rolling release. Marian “ Keep every 6 months Move to once per Year Meh, I Don't Care 7% 58% 35% With every 6 months’ releases, we got some Big Updates at one time, and it is full circle magazine #50 good. Small updates just not so interesting and epic... Mixabuben “ 67 29 11 61% 27% 10% Top Votes By Country U.S.A. Prefer not to say United Kingdom Canada Australia Argentina Belgium France Germany Netherlands 17 16 13 9 5 4 4 4 4 4 16% 15% 12% 8% 5% 4% 4% 4% 4% 4% I am about to switch to Arch Linux 100% because of this. I love apt but hate reinstalling stuff every six months, and ubuntu upgrades always break too much stuff. Plus, I like the freedom to choose, and right now I choose Gnome 3 and rolling releases. A rolling release is the only future way to go if Linux ever wants to become a serious contender for the desktop - not * Voting may be skewed by Rolling Release voters chosing a release schedule. many new Linux users want to 33 contents ^ I THINK... constantly update their releases. Herman “ My choice depends a lot on whether Unity continues or Gnome 3 comes to Ubuntu. I look forward to the scheduled releases. Do what works best, but I hate having to remove everything to do an upgrade. So, rolling release appeals to me. Stephen R Douglas “ "We don't need releases before they are fully tested and ready. The worst thing is to have a new release that causes all kinds of problems. I don't want problems. If I did I would use something like Debian unstable. Release it only when it is ready, and don't ask us users to find the problems. I love ubuntu, and stay with the LTS releases for just that reason. If the LTS begins to have ‘problems’, I will switch to another distro. Jerry Turba “ Stick with scheduled releases. The rush to get Natty / Unity out ended in the current disaster - rolling releases would make that worse. 6 months is good, but annual wouldn't be bad if we were changing things for the better, not the dumber - as just happened in April. Annual would give more time to work out bugs before rushing to release, which might have made Unity worth having. As it is, I'd rather use a windoze machine than Natty with Unity. Robin Goodfellow “ I think each release of ubuntu should be perfect with fewer bugs as possible. The current scheduled release every 6 months provides very little time for ubuntu community to bug-fix most of the bugs. We need more time to fix the bugs to make ubuntu the perfect OS. skumara “ Scheduled releases can help in publicity, but rolling releases are the way to go so that people need not do a fresh install every time. (Most people I know break their systems upgrading to newer releases, and just do a fresh install). Salvadesswaran Srinivasan “ I'm not sure there is any issue to be addressed here. What's wrong with the current schedule? If small updates are full circle magazine #50 needed, don't we get them through Update Manager when they are available with larger updates on a six monthly cycle. It all seems fine to me. Why change a working formula? JFR “ I think more frequent updates in smaller increments would be more manageable. Dave Nelson “ In my opinion, it should actually be a mix of both. I often manually install the latest svn versions of certain software, because I really want or need some features, and often Ubuntu still is behind in packaging the newest stable software. In a one year, cycle I would need to wait longer for official updates of some software, but if it could be mixed with a rolling release, then that would be solved. I'd suggest a scheduled release for major updates and upgrades (Unity, Gnome 3, etc...), and a continuous rolling release for the minor type of updates. That way, Ubuntu could have more time to prevent situations like with the 11.04 release, because, well, let's face it, it is the ‘Windows ME or Vista’ of Linux at the moment.. Unity got 34 released way too early, and ubuntu even messed up the classic mode. I'm used to quality in Linux, and am very critical about it. If that happens again, I move to Debian. Bart “ As long as the developers can maintain a 6-month scheduled release, there seems no compelling reason to switch to a rolling release. With a scheduled release, you know when to expect next releases. This fact alone should make it easier for sysadmins to plan and schedule upgrade paths and rollouts. Tom “ Scheduled, and only LTS - as it should be rock solid! 6 months is good for alpha and beta testing, so I'm personally using only LTS releases. CLI “ Like Arch and Linux Foresight, a rolling release distro feels the way to go. For one it is more efficient and flexible; allowing and enabling one to go back and forth is an easy way to fix and solve issues that can arise. Conrad Linde contents ^ I THINK... “ I use Debian as rolling release onto a second machine, and I think it's more comfortable to admin. apt-get dist-upgrade or upgrade is more fast & easy than a full setup. A good way to manage a rolling release is the CUT project on Debian or the MintUpdate for LMDE : packages are available in the main repository when they are stable enough for end users. Free to you to add another repo... lame duck “ Go with a rolling release. After all we had Unity imposed on us so why not do something else just as stupid? anon “ Most of the major packages I use have been already out-ofdate in every *buntu release for the last 4 years. I get a newer obsolete version with each scheduled release. I now have 150 plus repositories to try and keep up-to-date, and I build or install outside synaptic 10 of the major applications like Gimp, LibreOffice, etc. R. Geleick “ Both are needed, so why not make the LTS scheduled and the normal releases rolling? Bourlas “ I think that a "half-rolling" release model, like the Chakra Linux one, will be the perfect compromise for all needs. With this model, you have to install only once, and then all application packages will be updated "immediately", while system packages (graphic drivers, kernel, etc), will be tested for a while, and eventually updated. Nick “ Scheduled releases allow for important experimentation, and to make a clean break from older set-ups. Six-monthly seems to be too much for Canonical; there is always a rush before release. Yearly would take off the pressure and allow a better-shaped release. Retain the LTS releases, though, as they are important. Paddy Landau A rolling release seems much more convenient, providing newly added packages are tested before releasing them in the wild. The advantage of this is that you have the latest version when it arrives, and it avoids “ full circle magazine #50 having to make a major change every 6 months. I live somewhat on the bleeding edge, and, to do that, I now use a number of ppa repositories to get the latest SW from. It would be useful if they had 2 types of releases, an LTS for users who want stability and support, and a rolling distribution in between LTS releases, providing always the latest SW releases. Marc “ The six-month schedule release seems more like a race against time rather than a good upgrade with no bugs. anon “ I think they should stick with the scheduled release. Whether it's six months, or a year, doesn't matter. However, what they should be doing is this: decide what they want each LTS to look like (within as much reason as possible). Work on one or two of those features in each intermediate release, and concentrate on bug-fixing for the main focus of each intermediate release. They're doing this now, to an extent. But, I would like to see them concentrate more on bugfixing for at least one or two 35 releases in the near future. Wipe out as many of the long-standing bugs as they can (especially the paper-cuts). Patrick D. “ Even if we use rolling release, we may still need to install from DVD from zero (for new PC, or, if we for some reason forgot to update for a long time Aloysius “ Scheduled releases create a dependable Linux distribution advantage. The discipline to keep to the schedule sets Ubuntu apart and strongly supports its growth. Art Gunn “ Ubuntu has matured to the point that it doesn't need new releases every six months. New releases can now be made when there are significant changes and without the pressure of a 6month schedule. Harry Webb “ Getting stuck with old software until a new release is my main dislike in Ubuntu. Especially when new software just doesn't make into a new release like Vim 7.3 with Maverick. Of contents ^ I THINK... course ppa's can often solve this, but that does take away some of the convenience of having a central repository, since ppa's sometimes come and go. Patrick “ Since the Ubuntu developers are going to be fixing a lot of Unity bugs, we shouldn't have to install a new version to get those fixes. Rolling Release would solve this. Russell Rolling releases are great for bleeding edge environments; however, if you are attempting to build widelydistributable packages, you need to know what versions of libraries and tools are available to the OS. anon “ Does not matter. They have limited our choice even further with 11.04 chasing some of us away. There have never seen so many negative comments in other releases. I think the vision of everyone using computers like tablets is flawed. Bullet “ “ Having a known and set release schedule allows both home and business users to better plan upgrades. Rolling releases would bring chaos to a process that works very well. Anthony Papillion “ A rolling release would allow me to keep an OS on my system without having to feel like I need to cleanly install my system every six months. After a clean install, then there is all the reinstalling and tweaking it to the way I had it before, only this can take hours. Chris “ I use Ubuntu 10.10 and find it quicker than KDE 4.? by a mile. I sure wish 10.10 was a rolling release. harold I think the rolling release approach is easier for most people who just want to get work done with their machines, and not have the hassle of a fresh install every 6 months. I like PCLinuxOS for this reason. I have run it on one of my computers for two years, and don't plan on replacing it. I have another machine running Mint Debian for the same reason. (This doesn't stop me from burning a disk of full circle magazine #50 “ every Ubuntu release that comes along.) Chuck Pilger “ I like scheduled because i love stability of my pc. Filippo Locatelli “ I'm a laptop user, and Boottime is everything for me. If they can do a rolling release with a fast boot time, I'll be in 7th Heaven. (I've been thinking about Linux Mint Debian Edition but understands it boots rather slowly). I have a lot of extra software that I use. Reinstalling every 6 months is not nice! (don't know how well upgrades go nowadays) Tobie “ I think for the greater adoption numbers that Mark Shuttleworth is aiming for that would be the way to go.... Similar like the service packs in windows or the enterprise Linuxes, the ordinary non-technical average Joe would like it installed and easily updated for many years - to just get things done. As a long time Linux user, I have no problem with either way, but then, I do put a lot of thinking into my use of software. 36 Len Gingrich “ "Scheduled releases always have show stopping bugs because of deadlines. Rolling releases would fix these as and when they happen. Latest apps could also be pushed out a lot sooner." teemac A rolling release means that there is less pressure to release something that is not ready. Unity provides a good example. The developers decided they didn't want to/couldn't wait for 11.10, so released it in 11.04 even though it is buggy and clearly not ready. A rolling release would allow additional time to iron out the bugs. Steve Guard “ “ Although, with the current level of development that Canonical is making, 6 months is a bit short. More testing and bug tracking is needed." Eduardo “ Go to a rolling release and delete Unity immediately! Seriously, It would be nice to get new versions of programs (eg. libreoffice, etc) faster, but this contents ^ I THINK... might mean occasional regressions. LTS or back to Debian. Alice Cooper nDR01d It gives me the opportunity to upgrade twice a year - which is as much time as I want to spend. Good compromise between old apps and effort Ulrich “ “ I'm using Linux Mint DEBIAN Edition (LMDE) and it's the best distro I have used. It will be very difficult for Ubuntu Debian to surpass Linux Mint, but going Debian Rolling Release is a step closer to perfection. killmess “ Stability, NOT Bleeding edge. One of the reasons I chose Ubuntu was its stability, otherwise I would have chosen Fedora and their policy of not having a LTS. If Ubuntu goes rolling release, I'm moving to either Mint Scheduled is best cause it creates excitement during testing and launching. It also creates creativity on what to implement beyond the available features. To me, Rolling Release is much on bug fixes. Robert Ngalu “ I think the scheduled releases and the support time are just right. You don't need to wait too long for new software, but if you are more interested in stability, you just stay with the LTS release. I'm concerned that a pure rolling release strategy would affect the stabilty too much. If you desperately need one new piece of software (Firefox 5 or whatever), there's always the option of using a PPA. Kerstin “ The question I'd like to pose for FCM#51 is: Which distro(s) do you use, and with which desktop manager(s)? To give your answer, go to: full circle magazine #50 37 contents ^ full circle magazine #50 38 contents ^ REVIEW PAM Facial Recognition Written by Nedim Muminović H ave you ever imagined logging in to your system using only your face? Sounds like science fiction, but it is now possible with an application called PAM Face Authentication. Using a webcam, it scans your face and allows you to log in without typing a password. No more passwords. The application was developed as part of the Google Summer-ofCode 2008 for openSUSE. The project was then extended during the Google Summer-of-Code 2009 to make it compatible with the KDE and Pardus distributions. The official website is pam-faceauthentication.org, and it contains instructions on how to install the application. In this text we will install the application from source code. In my experience, available packages for Ubuntu and Kubuntu do not work with the latest releases. Users of previous versions are lucky. They can install it using the available packages. Webcam drivers gspca and uvc are integrated in the kernel, so you don't need to install the drivers manually. Let’s start with the installation. Installation The first step is to install all dependencies. If you try to do it using the available documentation, you will notice it is not possible. The problem is caused by packages which don't exist! The solution is instead of libhighgui4 write libhighgui2.1. Here are the corrected commands: tar zxf pam-faceauthentication-0.3.tar.gz && cd pam-face-authentication-* mkdir build && cd build cmake -D CMAKE_INSTALL_PREFIX=/usr .. make sudo make install Configuration To login to your system with face recognition, we must start with the face trainer. Just type qtfacetrainer in terminal, or go to Applications > Lost and Found > Qt Face Trainer. Follow the instructions. sudo apt-get install buildessential cmake qt4-qmake libx11-dev libcv-dev libcvaux-dev libhighgui2.1 libhighgui-dev libqt4-dev libpam0g-dev checkinstall When we have installed all the dependencies, we begin downloading, compiling, and installing the app. Execute these commands one-by-one. cd /tmp && wget /files/pam-faceauthentication-0.3.tar.gz full circle magazine #50 39 contents ^ REVIEW: PAM FACIAL RECOGNITION Next step is making a file which will contain plug-in information. Type these commands consecutively: cat << EOF | sudo tee /usr/share/pamconfigs/face_authentication /dev/null Name: face_authentication profile Default: yes Priority: 900 Auth-Type: Primary Auth: [success=end default=ignore] pam_face_authentication.so enableX EOF After that, enable the plug-in using the following command: sudo pam-auth-update -package face_authentication Finally, you are finished with the installation. Users with enabled Auto login must disable it manually by going to System Administration > Login Screen > Convenience, and untick Enable Auto-Login. Problems During testing, in a few cases, the application was unable to recognize me and it was frustrating. Fortunately, login with a password is still possible. Also, there were cases when the webcam was connected, but the application warned me that the webcam was disconnected. increased usage of these applications. Until then, there is no need to install it. Sooner or later, you will be frustrated by the accuracy of recognition. The best thing about PAM face authentication is it is free. Reading this text, you probably asked yourself something like “Is it possible to cheat the application?â€?. I am leaving the reader to find the answer! A video of PAM Facial Recognition can be seen at: =PhReQgyprLg Positive: Easy to use. Negative: Documentation is out-of-date, few bugs, hard to install, accuracy of recognition. Overall Since this is the only application of this type available for Linux, it does a good job. It can even be compared to commercial applications. Currently, all applications of this type aren't accurate. In a few years, we could expect it to be the default way to log in to your system with full circle magazine #50 40 contents ^ LETTERS Universal Installer W ith all the fuss over Unity isn't it time all distro developers regardless of preference collaborated on a Universal Installer that worked across the board instead of concerning themselves with trying to impress? If Linux really wants to take on Windows - and Windows is certainly trying to destroy open source - perhaps they should realise it is Windows' singlemindedness, and singlepointedness, that are the real reasons they continue to dominate the market. I believe very strongly that this lack of true unity is the main reason Linux continues to lag behind. Distros can still be diverse without being perverse. Creating a universal OS installer would go a long way to getting far more people on board. Anyone who has tried different distros knows the problems this diversity of installation procedures can lead to. Most people don't have the Every month we like to publish some of the emails we receive. If you would like to submit a letter for publication, compliment or complaint, please email it to: letters@fullcirclemagazine.org. PLEASE NOTE: some letters may be edited for space. patience to deal with the differences in installation. The different Installation processes are only interesting to geeks who live to tinker. Most people want to switch on quick, do what they have to do, and thats it. If they have some fun along the way then fine, but what they don't want, or need, is to be put off at the first hurdle. Billie Improving Software I think that the most important question to ask the users of Linux distributions is not about the OS, but about the software that runs under the OS. I think that the best possible OS is something that the users do not even notice, it is unobtrusive, and it works without getting in the way (e.g. the other day I was copying some files from an NTFS portable HDD to a Windows 7 notebook NTFS HDD, and I got errors about the length of file names). full circle magazine #50 Join us on: So, in the end, the scope of asking questions to the end users about the OS appears (at least to me) somewhat limited (and relevant mostly to the interface which, in the end, is important but not overly so). Therefore the big questions are relevant to the improvement of the software library. From my side the very big matter is that the spreadsheet capabilities of OpenOffice/LibreOffice are too much behind that of Excel. It is imperative to introduce a non linear solver, to improve the charting and to "port" some Excel addons (e.g. Xnumbers and Xmatrix, fundamental for engineering calculations). Giulio What New Features? S 41 hould Linux interfaces be making so much effort to look like Windows? facebook.com/fullcircle magazine twitter.com/#!/fullcirclemag linkedin.com/company/fullcircle-magazine ubuntuforums.org/forum display.php?f=270 The reason for posing this is with the Unity and Gnome 3 efforts to do 3D windows things truely are looking more like Microsoft. Its pretty, but does it improve things? I use Metacity because it allows, amongst lots of other subtle usability features, placing windows side-by-side and they have this nice bit of 'pressure' needed to push them past one another. This makes it easy to line up several windows without getting RSI. So, the seeming bent by the leading lights in the community to dump 2D and its sensible approach to an interface leaves me a bit concerned. Roy contents ^ LETTERS Unity Tweaks A lot of readers seemed to be having trouble tweaking Unity. For general tweaking I found this article very helpful /things-to-tweak-fix-afterinstalling.html. Among other things, this will tell you how to get rid of the workspace icon on the dock that one reader was complaining about. For Compiz tweaking you can install the compizconfig-settingsmanager, which is not installed by default, and use that to make some changes. For those complaining about having to search through the entire list of programs to find what you want, you can still find programs under the older categories of Accessories, Education, etc. It is not obvious where this is. But once in the Dash (where you go to search for programs) in the upper right corner is the old category list. There may be a down arrow there, I do not have my computer with Unity sitting in front of me at the moment. Also using the Dash just begin typing any part of the name of the program you want and some choices will begin to appear. home server to serve my photos. Sue Newland What, No Xen? Home Photo Server I want to take this opportunity to tell you that I really like your magazine and learn from each issue. This evening i installed SSH on my desktop and am going to try accessing it from my laptop. If that is successful, I'm going to get my daughter to try accessing it and if that works, I'll set up a photo gallery of photos I've shot over the years, including about a thousand of my first grandson. I'll also give the site to my sister and a cousin to see how it all works and if that is successful may give it to a few close friends with whom I'd like to share my photos. I have some gallery programs, jAlbum, which I used to set up a web site from windoze. They have a Linux version and it is quite good. I'll also try gallery to see how that compares. I think it will be exciting to have a full circle magazine #50 Michael C onsidering full Xen support just recently landed in the kernel it was a little disappointing not to see Xen even mentioned in the recent Full Circle article on virtual machines. Admittedly Xen is rather different than the other products mentioned and arguably not as suited to a casual user. However, it seems like something still worth mentioning, if only to note it's differences. SloggerK Kindle & Google Earth Wrinkles S everal months ago, I decided that I would like to have some ebooks from Amazon, so I downloaded the Kindle For PC program (Windows version) and it wouldn't 42 install with the default Wine. After some searching, I found the way to get it it work on Ubuntu 10.10 was to download Wine 3, a beta version. So far, I have had no problems with this version. sudo add-apt-repository ppa:ubuntu-wine/ppa && sudo apt-get update && sudo aptget install wine1.3 Because I already had an Amazon account it, left me with some oversized text boxes on the screen. This was fixed by downloading the Microsoft True Type fonts (sudo apt-get install msttcorefonts). It seems that Goggle Earth needs them for its display. Brian Cockley contents ^ UBUNTU GAMES A Trine Written by Ed Hewitt few weeks ago, Wolfire Games released the highly anticipated 3rd Humble Bundle, known this time round as the ‘Humble Frozenbyte Bundle’. Yet again, the bundle sold well - reaching over $900,000 in 7 days, with Linux being the number 2 platform with an average purchase price of $11.82. Trine is one of the 5 games released by Frozenbyte, and it makes its debut on Linux, after being a successful game on Windows, Mac, and PS3. can all be released from the ‘Trine’. The gameplay of Trine is unique - even though it is a 2D platformer at its core, it has made great additions to this tried and tested genre. For starters, as mentioned, the ability to change your character during each level to solve a puzzle or handle a certain encounter. The Knight is your heavy character - which can take a lot of damage, and is used mainly in combat. Though the Knight is used in puzzles for lifting and moving heavy objects, the Wizard is mainly used to solve puzzles - he Trine is a side-scrolling active can lift objects and spawn platformer in a medieval fantasy platforms to walk across. The Thief setting, the story involves around can be used for combat, with its three playable characters known as the Wizard, the Knight, and the ability to fire bows - although she is more useful for moving though Thief. These characters pursue an artifact known as the ‘Trine’, which the level. She is very agile, and, - when all three of them touch the with the aid of her grapple, she can ‘Trine’ - they merge into one being. reach high places. Each level is fairly consistent in its layout, and This unified being allows the will all require the use of each of player to switch between the the three character’s skills. The three characters to be able to puzzles are mostly easy, and complete a challenge within each mainly focus around moving and level. The rest of the story is enjoyable, and involves you finding spawning certain objects, and out about the ‘Trine’ and how they interacting with the physics of the full circle magazine #50 game. The puzzles do become hard, but not annoying to solve. There are plenty of monsters to slay, puzzles to solve, and objects to obtain throughout the lengthy campaign. Trine is begging for a co-op mode, since three players can take the role of each of the three characters to complete each mission. While co-op was added into the PC and PS3 versions of this title, via LAN and Local Play, it is a huge omission from the Linux version. There is sadly no LAN or even shared keyboard option for 43 co-op action. With only the single player story to play through, there are no other modes to play after you have beaten all the missions. Though there is plenty of replayability in the missions, once the puzzles have been solved, there is less enjoyment playing through Trine a second time. The graphics, sound, and atmosphere are perfect in Trine. Graphically, the game is stunning from varied textures and levels, to the finer details such as the lighting and shadows. The soundtrack, combined with sound contents ^ UBUNTU GAMES effects throughout the game, is stella - a surprise for an Indie to get the music and voice actors perfect. Currently, Trine is the best looking game on Linux. With the high quality graphics and advanced physics engine, it is a demanding title to see Trine in its full glory. Trine is one of the top titles for Linux gaming, thanks to its excellent gameplay mechanics and stunning graphics. Each level has been carefully designed to have a mixture of combat, puzzle solving, and platforming; with each character being critical to complete each level. However, with the lack of a co-op mode, and a story campaign which has little need to play through again, Trine does fall short in these areas. Trine is very enjoyable, and a different Indie title which I would recommend Linux gamers to give a play through. System Requirements 2Ghz CPU 512MB RAM 1GB HDD Space ATi Radeon X800/nVidia GeForce 6800 or better Right is a video showing Trine in action. LXdwRmiZam4 Score: 8/10 Good: Stunning Graphics Unique Gameplay Bad: No Co-Op Ed Hewitt, aka chewit (when playing games), is a keen PC gamer and sometimes enjoys console gaming. He is also co-host of the Full Circle Podcast! full circle magazine #50 44 contents ^ Q&A If you have Ubuntu-related questions, email them to: questions@fullcirclemagazine.org, and Gord will answer them in a future issue. Please include as much information as you can about your problem. Compiled by Gord Campbell Q My Asus laptop runs at above 60째C at best, using Natty. It often goes as high as 80째C when I have several tabs open in Firefox, and sometimes shuts down because it is too hot. A (Thanks, Jackn!) I now never see more than 65째C. I've used two Firefox add-ons (AdBlock and FlashBlock), I cleaned the fan and vents ( default.asp?newsID=4020), and I propped up the far end of the laptop such that it's tilted to expose the vents. Q My computer's manufacturer has released a new version of the BIOS. I don't use Windows at all; how can I update my BIOS? A Go to this web site: Q Sometimes, videos have a blue tint, and stay that way until I reboot. I have an Nvidia video card. A Go to this web site: tion.com/ubuntu/fixblue-tinted-video-in- ubuntu Q In Ubuntu 11.04, when a window is opened, if it is sufficiently large, it maximizes. How can I disable this auto-maximize behavior? A Install CompizConfig Settings Manager (CCSM). Run it, and go to the Window Management section. Select "Grid". There is a tab labelled "Edges" that controls the Resize Actions and Thresholds. full circle magazine #50 45 Q What hardware does my computer need to run Unity? A Canonical has produced this information: DemystifyingUnityGraphicsHardwa reRequirements Q How can I set up a sound track for a presentation in LibreOffice? A It's old, but it still works: n/index?qid=20080527003902AAY uk1N Q I just added a hard drive in my computer; it shows up in disk utility and I have formatted it. How can I access it? contents ^ Q&A A If you open any of the "Places," on the left side you should see a line that says "nnn GB Filesystem" where nnn is the size of your new hard drive. Click on it, and now you can create folders and paste files. nmblookup [name of a computer] Q I use Remote Desktop in Ubuntu 10.10 to connect to several Windows 2008 servers. How can I transfer files back and forth between my computer and the servers? A (Thanks to e79 on the Ubuntu Forums) Install Remmina from the Ubuntu Software Center. In the first config window, specify a "Share Folder." When navigating "Computer" from the server, you can copy/paste to or from the Share Folder. Q A (Thanks to Ernesto RD in the Ubuntu Forums) Click on "Places," Network. It should show you the names of all the computers on your network. Open Accessories/Terminal, and enter the command: How can I find the IP address of the computers on my network? It will show you the IP address of that computer. Q I would like to move /home to another disk. A It's in the Community Documentation: y/Partitioning/Home/Moving Q What is the name of the conky configuration file? full circle magazine #50 A Q It's .conkyrc and it goes in your home folder. I want to convert a raw DV file to H.264 using ffmpeg. I run this command: ffmpeg -i dvgrab-001.dv acodec faac -vcodec h264 -f flv test.flv and it says, "Unknown encoder 'h264'". A Use -acodec libfaac and -vcodec libx264 Q I have a 3.5-inch floppy drive, with Ubuntu 11.04 Natty Narwhal. When I put a floppy disk into the drive and click on the drive in 'Computer' it says 'Unable to mount location, no media in the drive'. A (Thanks to Coffeecat in the Ubuntu Forums) Put a floppy disc in the drive, open a terminal, and enter this command: 46 udisks --mount /dev/fd0 Also, you need to use floppies slightly differently in Linux. When you drag and drop files to the floppy file manager window, they may not be written immediately, but remain in cache memory. Therefore, before you physically remove the disc, right-click on the desktop icon to unmount it. Pending writes will then be made after which you can safely remove the disc. Q How can I install the Sun (Oracle) Java JRE? A Q Go to this web site: site/easylinuxtipsproject /java Is there any way I can convert mp3 files to aac? contents ^ Q&A A Run System/Administration/ Synaptic Package Manager. Search for sound converter, select to install it and click "Apply". It should appear in Sound & Video. In Preferences, you set the format of the output file. interfaces... GTK+ is suitable for (programming) projects ranging from small one-off tools to complete application suites." Q Pesky File Ownership I would like to have two monitors. Do I need two graphics cards? A Most modern graphics cards have multiple outputs. With the power off, connect the two monitors. They will probably both show the same output. Run System > Preferences > Monitors, and change the settings. Q A What is GTK? From the gtk.org web site: "GTK+, or the GIMP Toolkit, is a multiplatform toolkit for creating graphical user the "change owner" command: chown It suggested my next command: chown --help Tips and Techniques I keep my computers pretty simple: one user with the same name on all computers, no oddball applications, simple folder structure. I would never run into a problem with file ownership, would I? I sat and read through what appeared. It's pretty murky, but there were a couple of examples. I used these commands: The "-c" told chown to show me each change it made. The "R" meant "recursive," so it would not just change the folder "miro," but also everything under it. It listed each of the files, and the folder itself, and said it had changed each of them to have the owner "gord". Just what I wanted! cd shared sudo chown -cR gord miro It finally happened. While using my laptop, I connected to the shared folder on my desktop. I created a sub-folder called miro, and copied a few media files into it. Back at the desktop, I could play the media files just fine, but when I went to delete them, no joy. When I looked at the file properties from Nautilus, they were owned by root, not gord. I knew what command could modify file ownership, so I opened Accessories/Terminal and entered full circle magazine #50 47 contents ^ MY DESKTOP Your chance to show the world your desktop or PC. Email your screenshots and photos to: misc@fullcirclemagazine.org and include a brief paragraph about your desktop, your PC's specs and any other interesting tidbits about your setup. I have been using Ubuntu since Hardy. I love tweaking my desktop to maximize screen size; I use the most common applications available for web browsing, file sharing, photo editing, social networking and communicating. I've Used Ubuntu since version 6.06. Great OS. I’m still learning all about Linux and especially Ubuntu. Now I use version 10.04 on my laptop. This was taken on an HP Pavilion dv3t notebook running Ubuntu 10.10. It has an Intel Core 2 Duo and 4GB of RAM. I'm a big fan of the notebook brand so I used one of HP's wallpapers. AWN dock is my launcher with Faenza Variant Cupertino icons. Toshiba Satellite A305SD AMD Turion 64 Dual Core Mobile (but I use Ubuntu 32-bit). 4 GB 800 Mhz RAM ATI 3200 Graphics Card. I've used Screenlets and CairoDock for Task Bar, and Marvel Comic Desktop Background. This design makes use of all the vertical and horizontal screen space. The icons are Chromium, Mozilla Firefox 4 beta, Liferea, Skype, Gwibber, Pidgin, Virtualbox, and Rhythmbox. Jorge Rozo Jean Austin Rodriguez full circle magazine #50 48 contents ^ MY DESKTOP I'm a 20-year-old Italian boy who started using Ubuntu with 10.04 (yes, I'm a beginner). My desktop is really simple but I like it; I first installed the DarkRoom theme which was brown, and changed it using dark colours. The icons are Faenza, from gnome-look.org, they remind me of iOS. Now I'm using Maverick on my 8-year-old desktop PC with: - Intel Pentium4 @ 2.53GHz - 512mb of Ram - Nvidia GeForce4 mmx440 with 128mb of memory - 14" Samsung Monitor 1024x768 - DVD player All works perfectly from the beginning, except the graphic card, but I'm planning to solve the problem some day. Rosario Lombardo I've been using Ubuntu since 6.06, and now I'm using Ubuntu 10.10 on my new machine. My desktop may look a little bit weird. First, the panel: I don't like the default menu and task list, so I made it like this. I really like the idea. Second, I'm using AWN to hold the launchers and task list; I put it on the right side as I found that this way best suits my wide-screen monitor, and the Intellihide of AWN also works well. Third, I didn't put many widgets on my desktop, as I don't really look at the desktop. The wallpapers are from a default set in Ubuntu, there are about 20 looping periodically. At last, the terminal, that's guake, I hide almost everything except the terminal (of course) I have included this because I look at it much more than my desktop :) Lu full circle magazine #50 49 contents ^ TOP 5 USB Installers Written by Andrew Min Ubuntu Live USB creator Universal USB Installer usbcreator-kde, depending on your desktop environment.. full circle magazine #50 50 contents ^ TOP 5 - USB INSTALLERS LinuxLive USB Creator LiveUSB Install. To install LinuxLive USB Creator, use the installer from the homepage. full circle magazine #50 51 contents ^ TOP 5 - USB INSTALLERS UNetbootin Homepage: UNetbootin, use the unetbootin package in the universe repositories. Because the show is produced by the Ubuntu UK community, the podcast is covered by the Ubuntu Code of Conduct and is therefore suitable for all ages. Available in MP3/OGG format in Miro or iTunes, or listen to it directly on the site. full circle magazine #50 52 #51: Sunday 10th July 2011. Release date for issue #51: Friday 29th July #50 53 contents ^
https://issuu.com/intelligenthome/docs/issue50_en
CC-MAIN-2016-50
refinedweb
20,263
72.66
Justification Self-contained header files can be included in arbitrary order (without implicit dependencies). A self-contained source file explicitly includes all header files from which typedefs, defines, function prototypes etc. are used in the source. Each header file includes those other header files from which it uses typedefs, defines and function references. In this way self-contained source files can be compiled and checked with SQ in isolation, thus before they are used by or integrated with other parts. Especially for interface header files it holds that when the compiler or SQ determine (potential) problems they mostly can be resolved easily before other code developed on basis of the content of these header files is written. Example CCBX_header.h header file content: #include "header/ownbool.h" /* RIGHT: because of ownbool usage */ int CCBX_fn(ownbool b); and inclusion in .c source file: #include "header/ownbool.h" /* RIGHT: because of usage of ownbool */ #include "CCBX_header.h" /* RIGHT: because of usage CCBX_fn */ ... static int ccby_fn(void) { int e = OK; bool b1 = TRUE; /* #include "header/ownbool.h" needed */ e = CCBX_fn(b1); /* #include needed */ ..
https://tics.tiobe.com/viewerC/index.php?ID=34&CSTD=Rule
CC-MAIN-2022-05
refinedweb
180
58.48
SFML Game For Class Helphave you got the sfml lib and is it linked with your compiler btw this is the only file and this co... SFML Game For Class Helpsorry guys the link doesnt work so heres the code [code]int main() { sf::Window window(sf::Vid... SFML Game For Class Helphi guys Ive been learning sfml and now in class at school I have to make a game my classmates all... 2d sandbox need some guidancethis is my computer code so far i checked it for errors on eclipse and it is full of errors for ... 2d sandbox need some guidance#include <iostream> #include <string> using namespace std; // Maximum number of items the playe... This user does not accept Private Messages
http://www.cplusplus.com/user/cyril98/
CC-MAIN-2015-27
refinedweb
123
76.86
Path Information and Enumeration - PDF for offline use - - Sample Code: - - Related APIs: - Let us know how you feel about this Translation Quality 0/250 last updated: 2017-09 Get information about paths and enumerate the contents The SKPath class defines several properties and methods that allow you to obtain information about the path. The Bounds and TightBounds properties (and related methods) obtain the metrical dimensions of a path. The Contains method lets you determine if a particular point is within a path. It is sometimes useful to determine the total length of all the lines and curves that make up a path. This is not an algorithmically simple task, so an entire class named PathMeasure is devoted to it. It is also sometimes useful to obtain all the drawing operations and points that make up a path. At first, this facility might seem unnecessary: If your program has created the path, the program already knows the contents. However, you've seen that paths can also be created by path effects and by converting text strings into paths. You can also obtain all the drawing operations and points that make up these paths. One possibility is to apply an algorithmic transform to all the points. This allows techniques such as wrapping text around a hemisphere: Getting the Path Length In the article Paths and Text you saw how to use the DrawTextOnPath method to draw a text string whose baseline follows the course of a path. But what if you want to size the text so that it fits the path precisely? For drawing text around a circle, this is easy because the circumference of a circle is simple to calculate. But the circumference of an ellipse or the length of a Bézier curve is not so simple. The SKPathMeasure class can help. The constructor accepts an SKPath argument, and the Length property reveals its length. This is demonstrated in the Path Length sample, which is based on the Bezier Curve page. The PathLengthPage.xaml file derives from InteractivePage and includes a touch interface: <local:InteractivePage <Grid BackgroundColor="White"> <skia:SKCanvasView x: <Grid.Effects> <tt:TouchEffect </Grid.Effects> </Grid> </local:InteractivePage> The PathLengthPage.xaml.cs code-behind file allows you to move four touch points to define the end points and control points of a cubic Bézier curve. Three fields define a text string, an SKPaint object, and a calculated width of the text: public partial class PathLengthPage : InteractivePage { const string text = "Compute length of path"; static SKPaint textPaint = new SKPaint { Style = SKPaintStyle.Fill, Color = SKColors.Black, TextSize = 10, }; static readonly float baseTextWidth = textPaint.MeasureText(text); ... } The baseTextWidth field is the width of the text based on a TextSize setting of 10. The PaintSurface handler draws the Bézier curve and then sizes the text to fit along its full length: void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); // Draw path with cubic Bezier curve using (SKPath path = new SKPath()) { path.MoveTo(touchPoints[0].Center); path.CubicTo(touchPoints[1].Center, touchPoints[2].Center, touchPoints[3].Center); canvas.DrawPath(path, strokePaint); // Get path length SKPathMeasure pathMeasure = new SKPathMeasure(path, false, 1); // Find new text size textPaint.TextSize = pathMeasure.Length / baseTextWidth * 10; // Draw text on path canvas.DrawTextOnPath(text, path, 0, 0, textPaint); } ... } The Length property of the newly created SKPathMeasure object obtains the length of the path. This is divided by the baseTextWidth value (which is the width of the text based on a text size of 10) and then multiplied by the base text size of 10. The result is a new text size for displaying the text along that path: As the Bézier curve gets longer or shorter, you can see the text size change. Traversing the Path SKPathMeasure can do more than just measure the length of the path. For any value between zero and the path length, an SKPathMeasure object can obtain the position on the path, and the tangent to the path curve at that point. The tangent is available as a vector in the form of an SKPoint object, or as a rotation encapsulated in an SKMatrix object. Here are the methods of SKPathMeasure that obtain this information in varied and flexible ways: Boolean GetPosition (Single distance, out SKPoint position) Boolean GetTangent (Single distance, out SKPoint tangent) Boolean GetPositionAndTangent (Single distance, out SKPoint position, out SKPoint tangent) Boolean GetMatrix (Single distance, out SKMatrix matrix, SKPathMeasureMatrixFlags flag) The SKPathMeasureMatrixFlags are: The Unicycle Half-Pipe page animates a stick figure on a unicycle that seems to ride back and forth along a cubic Bézier curve: The SKPaint object used for stroking both the half-pipe and the unicycle is defined as a field in the UnicycleHalfPipePage class. Also defined is the SKPath object for the unicycle: public class UnicycleHalfPipePage : ContentPage { ... SKPaint strokePaint = new SKPaint { Style = SKPaintStyle.Stroke, StrokeWidth = 3, Color = SKColors.Black }; SKPath unicyclePath = SKPath.ParseSvgPathData( "M 0 0" + "A 25 25 0 0 0 0 -50" + "A 25 25 0 0 0 0 0 Z" + "M 0 -25 L 0 -100" + "A 15 15 0 0 0 0 -130" + "A 15 15 0 0 0 0 -100 Z" + "M -25 -85 L 25 -85"); ... } The class contains the standard overrides of the OnAppearing and OnDisappearing methods for animation. The PaintSurface handler creates the path for the half-pipe and then draws it. An SKPathMeasure object is then created based on this path: public class UnicycleHalfPipePage : ContentPage { ... void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); using (SKPath pipePath = new SKPath()) { pipePath.MoveTo(50, 50); pipePath.CubicTo(0, 1.25f * info.Height, info.Width - 0, 1.25f * info.Height, info.Width - 50, 50); canvas.DrawPath(pipePath, strokePaint); using (SKPathMeasure pathMeasure = new SKPathMeasure(pipePath)) { float length = pathMeasure.Length; // Animate t from 0 to 1 every three seconds TimeSpan timeSpan = new TimeSpan(DateTime.Now.Ticks); float t = (float)(timeSpan.TotalSeconds % 5 / 5); // t from 0 to 1 to 0 but slower at beginning and end t = (float)((1 - Math.Cos(t * 2 * Math.PI)) / 2); SKMatrix matrix; pathMeasure.GetMatrix(t * length, out matrix, SKPathMeasureMatrixFlags.GetPositionAndTangent); canvas.SetMatrix(matrix); canvas.DrawPath(unicyclePath, strokePaint); } } } } The PaintSurface handler calculates a value of t that goes from 0 to 1 every five seconds. It then uses the Math.Cos function to convert that to a value of t that ranges from 0 to 1 and back to 0, where 0 corresponds to the unicycle at the beginning on the top left, while 1 corresponds to the unicycle at the top right. The cosine function causes the speed to be slowest at the top of the pipe and fastest at the bottom. Notice that this value of t must be multiplied by the path length for the first argument to GetMatrix. The matrix is then applied to the SKCanvas object for drawing the unicycle path. Enumerating the Path Two embedded classes of SKPath allow you to enumerate the contents of path. These classes are SKPath.Iterator and SKPath.RawIterator. The two classes are very similar, but SKPath.Iterator can eliminate elements in the path with a zero length, or close to a zero length. The RawIterator is used in the example below. You can obtain an object of type SKPath.RawIterator by calling the CreateRawIterator method of SKPath. Enumerating through the path is accomplished by repeatedly calling the Next method. Pass to it an array of four SKPoint values: SKPoint[] points = new SKPoint[4]; ... SKPathVerb pathVerb = rawIterator.Next(points); The Next method returns a member of the SKPathVerb enumeration. These values indicate the particular drawing command in the path. The number of valid points inserted in the array depends on this verb: Movewith a single point Linewith two points Cubicwith four points Quadwith three points Conicwith three points (and also call the ConicWeightmethod for the weight) Closewith one point Done The Done verb indicates that the enumeration is complete. Notice that there are no Arc verbs. This indicates that all arcs are converted into Bézier curves when added to the path. Some of the information in the SKPoint array is redundant. For example, if a Move verb is followed by a Line verb, then the first of the two points that accompany the Line is the same as the Move point. In practice, this redundancy is very helpful. When you get a Cubic verb, it is accompanied by all four points that define the cubic Bézier curve. You don't need to retain the current position established by the previous verb. The problematic verb, however, is Close. This command draws a straight line from the current position to the beginning of the contour established earlier by the Move command. Ideally, the Close verb should provide these two points rather than just one point. What's worse is that the point accompanying the Close verb is always (0, 0). This means that when you enumerate through a path, you'll probably need to retain the Move point and the current position. The static PathExtensions class contains several methods that convert the three types of Bézier curves into a series of tiny straight lines that approximate the curve. (The parametric formulas were presented in the article Three Types of Bézier Curves.) The Interpolate method breaks down a straight line into numerous short lines that are only one unit in length: static class PathExtensions { ... static SKPoint[] Interpolate(SKPoint pt0, SKPoint pt1) { int count = (int)Math.Max(1, Length(pt0, pt1)); SKPoint[] points = new SKPoint[count]; for (int i = 0; i < count; i++) { float t = (i + 1f) / count; float x = (1 - t) * pt0.X + t * pt1.X; float y = (1 - t) * pt0.Y + t * pt1.Y; points[i] = new SKPoint(x, y); } return points; } static SKPoint[] FlattenCubic(SKPoint pt0, SKPoint pt1, SKPoint pt2, SKPoint pt3) { int count = (int)Math.Max(1, Length(pt0, pt1) + Length(pt1, pt2) + Length(pt2, pt3)); SKPoint[] points = new SKPoint[count]; for (int i = 0; i < count; i++) { float t = (i + 1f) / count; float x = (1 - t) * (1 - t) * (1 - t) * pt0.X + 3 * t * (1 - t) * (1 - t) * pt1.X + 3 * t * t * (1 - t) * pt2.X + t * t * t * pt3.X; float y = (1 - t) * (1 - t) * (1 - t) * pt0.Y + 3 * t * (1 - t) * (1 - t) * pt1.Y + 3 * t * t * (1 - t) * pt2.Y + t * t * t * pt3.Y; points[i] = new SKPoint(x, y); } return points; } static SKPoint[] FlattenQuadratic(SKPoint pt0, SKPoint pt1, SKPoint pt2) { int count = (int)Math.Max(1, Length(pt0, pt1) + Length(pt1, pt2)); SKPoint[] points = new SKPoint[count]; for (int i = 0; i < count; i++) { float t = (i + 1f) / count; float x = (1 - t) * (1 - t) * pt0.X + 2 * t * (1 - t) * pt1.X + t * t * pt2.X; float y = (1 - t) * (1 - t) * pt0.Y + 2 * t * (1 - t) * pt1.Y + t * t * pt2.Y; points[i] = new SKPoint(x, y); } return points; } static SKPoint[] FlattenConic(SKPoint pt0, SKPoint pt1, SKPoint pt2, float weight) { int count = (int)Math.Max(1, Length(pt0, pt1) + Length(pt1, pt2)); SKPoint[] points = new SKPoint[count]; for (int i = 0; i < count; i++) { float t = (i + 1f) / count; float denominator = (1 - t) * (1 - t) + 2 * weight * t * (1 - t) + t * t; float x = (1 - t) * (1 - t) * pt0.X + 2 * weight * t * (1 - t) * pt1.X + t * t * pt2.X; float y = (1 - t) * (1 - t) * pt0.Y + 2 * weight * t * (1 - t) * pt1.Y + t * t * pt2.Y; x /= denominator; y /= denominator; } return points; } static double Length(SKPoint pt0, SKPoint pt1) { return Math.Sqrt(Math.Pow(pt1.X - pt0.X, 2) + Math.Pow(pt1.Y - pt0.Y, 2)); } } All these methods are referenced from the extension method CloneWithTransform shown below. This method clones a path by enumerating the path commands and constructing a new path based on the data. However, the new path consists only of MoveTo and LineTo calls. All the curves and straight lines are reduced to a series of tiny lines. When calling CloneWithTransform, you pass to the method a Func<SKPoint, SKPoint>, which is a function with an SKPaint parameter that returns an SKPoint value. This function is called for every point to apply a custom algorithmic transform: static class PathExtensions { public static SKPath CloneWithTransform(this SKPath pathIn, Func<SKPoint, SKPoint> transform) { SKPath pathOut = new SKPath(); using (SKPath.RawIterator iterator = pathIn.CreateRawIterator()) { SKPoint[] points = new SKPoint[4]; SKPathVerb pathVerb = SKPathVerb.Move; SKPoint firstPoint = new SKPoint(); SKPoint lastPoint = new SKPoint(); while ((pathVerb = iterator.Next(points)) != SKPathVerb.Done) { switch (pathVerb) { case SKPathVerb.Move: pathOut.MoveTo(transform(points[0])); firstPoint = lastPoint = points[0]; break; case SKPathVerb.Line: SKPoint[] linePoints = Interpolate(points[0], points[1]); foreach (SKPoint pt in linePoints) { pathOut.LineTo(transform(pt)); } lastPoint = points[1]; break; case SKPathVerb.Cubic: SKPoint[] cubicPoints = FlattenCubic(points[0], points[1], points[2], points[3]); foreach (SKPoint pt in cubicPoints) { pathOut.LineTo(transform(pt)); } lastPoint = points[3]; break; case SKPathVerb.Quad: SKPoint[] quadPoints = FlattenQuadratic(points[0], points[1], points[2]); foreach (SKPoint pt in quadPoints) { pathOut.LineTo(transform(pt)); } lastPoint = points[2]; break; case SKPathVerb.Conic: SKPoint[] conicPoints = FlattenConic(points[0], points[1], points[2], iterator.ConicWeight()); foreach (SKPoint pt in conicPoints) { pathOut.LineTo(transform(pt)); } lastPoint = points[2]; break; case SKPathVerb.Close: SKPoint[] closePoints = Interpolate(lastPoint, firstPoint); foreach (SKPoint pt in closePoints) { pathOut.LineTo(transform(pt)); } firstPoint = lastPoint = new SKPoint(0, 0); pathOut.Close(); break; } } } return pathOut; } ... } Because the cloned path is reduced to tiny straight lines, the transform function has the capability of converting straight lines to curves. Notice that the method retains the first point of each contour in the variable called firstPoint and the current position after each drawing command in the variable lastPoint. These are necessary to construct the final closing line when a Close verb is encountered. The GlobularText sample uses this extension method to seemingly wrap text around a hemisphere in a 3D effect: The GlobularTextPage class constructor performs this transform. It creates an SKPaint object for the text, and then obtains an SKPath object from the GetTextPath method. This is the path passed to the CloneWithTransform extension method along with a transform function: public class GlobularTextPage : ContentPage { SKPath globePath; public GlobularTextPage() { Title = "Globular Text"; SKCanvasView canvasView = new SKCanvasView(); canvasView.PaintSurface += OnCanvasViewPaintSurface; Content = canvasView; using (SKPaint textPaint = new SKPaint()) { textPaint.Typeface = SKTypeface.FromFamilyName("Times New Roman"); textPaint.TextSize = 100; using (SKPath textPath = textPaint.GetTextPath("HELLO", 0, 0)) { SKRect textPathBounds; textPath.GetBounds(out textPathBounds); globePath = textPath.CloneWithTransform((SKPoint pt) => { double longitude = (Math.PI / textPathBounds.Width) * (pt.X - textPathBounds.Left) - Math.PI / 2; double latitude = (Math.PI / textPathBounds.Height) * (pt.Y - textPathBounds.Top) - Math.PI / 2; longitude *= 0.75; latitude *= 0.75; float x = (float)(Math.Cos(latitude) * Math.Sin(longitude)); float y = (float)Math.Sin(latitude); return new SKPoint(x, y); }); } } } ... } The transform function first calculates two values named longitude and latitude that range from –π/2 at the top and left of the text, to π/2 at the right and bottom of the text. The range of these values isn't visually satisfactory, so they are reduced by multiplying by 0.75. (Try the code without those adjustments. The text becomes too obscure at the north and south poles, and too thin at the sides.) These three-dimensional spherical coordinates are converted to two-dimensional x and y coordinates by standard formulas. The new path is stored as a field. The PaintSurface handler then merely needs to center and scale the path to display it on the screen: public class GlobularTextPage : ContentPage { SKPath globePath; ... void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); using (SKPaint pathPaint = new SKPaint()) { pathPaint.Style = SKPaintStyle.Fill; pathPaint.Color = SKColors.Blue; pathPaint.StrokeWidth = 3; pathPaint.IsAntialias = true; canvas.Translate(info.Width / 2, info.Height / 2); canvas.Scale(0.45f * Math.Min(info.Width, info.Height)); // radius canvas.DrawPath(globePath, pathPaint); } } } This is a very versatile technique. If the array of path effects described in the Path Effects article doesn't quite encompass something you felt should be included, this is a way to fill in the gaps..
https://docs.mono-android.net/guides/xamarin-forms/advanced/skiasharp/curves/information/
CC-MAIN-2017-43
refinedweb
2,681
58.38
Next: Which flavor to choose?, Previous: objfile-gdbdotext file, Up: Auto-loading extensions .debug_gdb_scriptssection For systems using file formats like ELF and COFF, when gdb loads a new object file it will look for a special section named .debug_gdb_scripts. If this section exists, its contents is a list of null-terminated entries specifying scripts to load. Each entry begins with a non-null prefix byte that specifies the kind of entry, typically the extension language and whether the script is in a file or inlined in .debug_gdb_scripts. The following entries are supported: SECTION_SCRIPT_ID_PYTHON_FILE = 1 SECTION_SCRIPT_ID_SCHEME_FILE = 3 SECTION_SCRIPT_ID_PYTHON_TEXT = 4 SECTION_SCRIPT_ID_SCHEME_TEXT = 6 If the entry specifies a file, gdb will look for the file first in the current directory and then along the source search path (see Specifying Source Directories), except that $cdir is not searched, since the compilation directory is not relevant to scripts. File. Script text entries allow to put the executable script in the entry itself instead of loading it from a file. The first line of the entry, everything after the prefix byte and up to the first newline ( 0xa) character, is the script name, and must not contain any kind of space character, e.g., spaces or tabs. The rest of the entry, up to the trailing null byte, is the script to execute in the specified language. The name needs to be unique among all script names, as gdb executes each script only once based on its name. Here is an example from file py-section-script.c in the gdb testsuite. #include "symcat.h" #include "gdb/section-scripts.h" asm( ".pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\n" ".byte " XSTRING (SECTION_SCRIPT_ID_PYTHON_TEXT) "\n" ".ascii \"gdb.inlined-script\\n\"\n" ".ascii \"class test_cmd (gdb.Command):\\n\"\n" ".ascii \" def __init__ (self):\\n\"\n" ".ascii \" super (test_cmd, self).__init__ (" "\\\"test-cmd\\\", gdb.COMMAND_OBSCURE)\\n\"\n" ".ascii \" def invoke (self, arg, from_tty):\\n\"\n" ".ascii \" print (\\\"test-cmd output, arg = %s\\\" % arg)\\n\"\n" ".ascii \"test_cmd ()\\n\"\n" ".byte 0\n" ".popsection\n" ); auto-load safe-path (see Auto-loading safe path). The path to specify in auto-load safe-path is the path of the file containing the .debug_gdb_scripts section.
http://sourceware.org/gdb/onlinedocs/gdb/dotdebug_005fgdb_005fscripts-section.html
CC-MAIN-2015-32
refinedweb
360
66.44
Very nice. Not only have multiple people edited this page for half a year without noticing that all the code is for the wrong calculator model (which, incidentally, is the main reason the routine exists, since writing a fast routine for the purpose on 68k calculators is non-intuitive), but the final TI-83+ code they've come up with crashes on the third line. :-P Page deleted. To prevent confusion between the different calculator models, any chance someone could whip up a different color scheme for the 68k namespace? Something subtle, just to make people realize they've wandered over onto the wrong part of the site. I'd do it myself, but I don't have a clue how.
http://tibasicdev.wikidot.com/forum/t-166151/list-search
CC-MAIN-2017-30
refinedweb
121
56.59
In this example, you will learn how to define a new custom document type. 1. Go to Site Manager -> Development -> Document types and click the New document type link. You will be redirected to the New document type wizard. In the first step, enter the following values: •Document type display name: Computer (this name will be displayed to the users) •Document type code name: custom.computer (custom is your namespace to distinguish your document types from system types that use the cms namespace, computer is the document type). You will use this value in web part properties later. Click Next. 2. In Step 2, you need to choose the name of the database table that will be used for storing computer details. You also need to enter the name of the primary key in this table. Enter the following values: •Table name: CUSTOM_Computer •Primary key name: ComputerID •Inherits fields from document type: (none) Click Next. 3. The wizard has created a new database table for computers. Now you need to define the fields of the document type (columns of the table). Use the New attribute ( ) button to create the following fields. For each field, enter the values, click Save field and repeat the procedure until you have all the listed fields defined. •Column name: ComputerName •Attribute type: Text •Attribute size: 200 •Field caption: Computer name •Form control type: Input •Form control: Text box •Column name: ComputerProcessorType •Attribute type: Text •Attribute size: 200 •Field caption: Processor type •Form control type: Input •Form control: Drop-down list •Editing control settings -> Data source: select Options and enter the following items into the text area, one per line: Athlon;Athlon Pentium XEON;Pentium XEON Pentium Core 2 Duo;Pentium Core 2 Duo •Column name: ComputerRamSize •Attribute type: Integer number •Field caption: RAM (MB) •Form control type: Input •Form control: Text box •Column name: ComputerHddSize •Attribute type: Integer number •Field caption: HDD (GB) •Form control type: Input •Form control: Text box •Column name: ComputerImage •Attribute type: File •Allow empty value: check the box •Field caption: Image •Form control type: Uploader •Form control: Upload file Please note that you can also define system fields that will be displayed when editing documents of this type on the Form tab. This can be done by clicking the New system attribute ( ) button. Using the Group drop-down list, you can then choose from the following two groups of system fields: •Document attributes - offers the system fields of documents. •Node attributes - offers the system fields of content tree nodes. Document or node system fields will then be offered in the Attribute name drop-down list. If you leave the Display attribute in the editing form check-box checked, the field will be visible on the document Form tab. Click Next. 4. Now you need to choose the field that will be used as document name. Choose the Use document name field option from the drop down list. It means that when you create a new computer document, its name will be automatically taken from the ComputerName value and this value will appear in site navigation and in the CMS Desk content tree. Click Next. 5. In Step 5, you need to select the document types under which computer documents will be displayed. Check only the Page (menu item) value, which means that editors will be able to create computer documents only under some page, not under an article or news document in the content tree. Click Next. 6. In Step 6, you need to choose which websites will use this document type. Check the appropriate website and click Next. 7. In Step 7, you are asked to specify how documents of this type will be indexed and displayed in the search results. For more information on these settings, please refer to this topic. Make your choice and click Next. 8. The wizard has finished the configuration of the new document type. It has automatically created not only the database table, but also the SQL queries for SELECT, INSERT, UPDATE and DELETE operations and a default transformation. Click Finish. Congratulations, you have learned how to define a new document type.
http://devnet.kentico.com/docs/6_0/devguide/Defining_a_new_document_type.htm
CC-MAIN-2016-26
refinedweb
689
58.32
import "github.com/open-policy-agent/opa/loader" Package loader contains utilities for loading files into OPA. AsBundle loads a path as a bundle. If it is a single file it will be treated as a normal tarball bundle. If a directory is supplied it will be loaded as an unzipped bundle tree. Deprecated: Use FileLoader.AsBundle() instead. CleanPath returns the normalized version of a path that can be used as an identifier. Paths returns a sorted list of files contained at path. If recurse is true and path is a directory, then Paths will walk the directory structure recursively and list files at each level. SplitPrefix returns a tuple specifying the document prefix and the file path. Errors is a wrapper for multiple loader errors. type FileLoader interface { All(paths []string) (*Result, error) Filtered(paths []string, filter Filter) (*Result, error) AsBundle(path string) (*bundle.Bundle, error) WithMetrics(m metrics.Metrics) FileLoader } FileLoader defines an interface for loading OPA data files and Rego policies. func NewFileLoader() FileLoader NewFileLoader returns a new FileLoader instance. Filter defines the interface for filtering files during loading. If the filter returns true, the file should be excluded from the result. GlobExcludeName excludes files and directories whose names do not match the shell style pattern at minDepth or greater. RegoFile represents the result of loading a single Rego source file. Rego returns a RegoFile object loaded from the given path. type Result struct { Documents map[string]interface{} Modules map[string]*RegoFile // contains filtered or unexported fields } Result represents the result of successfully loading zero or more files. All returns a Result object loaded (recursively) from the specified paths. Deprecated: Use FileLoader.Filtered() instead. AllRegos returns a Result object loaded (recursively) with all Rego source files from the specified paths. Filtered returns a Result object loaded (recursively) from the specified paths while applying the given filters. If any filter returns true, the file/directory is excluded. Deprecated: Use FileLoader.Filtered() instead. Compiler returns a Compiler object with the compiled modules from this loader result. ParsedModules returns the parsed modules stored on the result. Store returns a Store object with the documents from this loader result. Package loader imports 16 packages (graph) and is imported by 25 packages. Updated 2019-12-19. Refresh now. Tools for package owners.
https://godoc.org/github.com/open-policy-agent/opa/loader
CC-MAIN-2020-10
refinedweb
380
51.34
Many times you need to provide the user with the ability to reorder elements (such as items in a list) by dragging them. Without drag and drop, reordering can be a nightmare but script.aculo.us provides extended reordering support out of the box through the Sortable class. The element to become Sortable is passed to the create() method in the Sortable namespace: A Sortable consists of item elements in a container element. When you create a new Sortable, it takes care of the creation of the corresponding Draggables and Droppables. To use script.aculo.us's Sortable capabilities, you'll need to load the dragdrop module, which requires the effects module also. So your minimum loading for script.aculo.us will look like this: Here is the syntax of the create() method to create a sortable items. The create() method takes the id of a container element and sort them out based on the passed options. Use Sortable.destroy to completely remove all event handlers and references to a Sortable created by Sortable.create. NOTE: A call to Sortable.create implicitly calls on Sortable.destroy if the referenced element was already a Sortable. Here is simple syntax to call destroy function. You can use or more of the following options while creating your Sortable object. You can provide the following callbacks in the options parameter: This demo has been verified to work in IE 6.0. It also works in the latest version of Firefox. To understand it in better way you can Try it yourself with different options discussed in above table. Note the usage of tag:'li'. Similar way you can sort following list of images available in <div>: To understand it in better way you can Try it yourself with different options discussed in above table. The Sortable object also provides a function Sortable.serialize() to serialize the Sortable in a format suitable for HTTP GET or POST requests. This can be used to submit the order of the Sortable via an Ajax call. You can use or more of the following options while creating your Sortable object. In this example, the output of the serialization will only give the numbers after the underscore in the list item IDs. To try, leave the lists in their original order, press the button to see the serialization of the lists. Now, re-order some elements and click the button again. To understand it in better way you can Try it yourself. Following is the example showing how to move items from one list to another list. Note that the containment option for each container lists both containers as containment elements. By doing so, we have enabled the child elements to be sorted not only within the context of their parent, but this also enables them to be moved between the two containers. We set dropOnEmpty to true for both lists. To see the effect this option has on that list, move all the elements from one list into other so that one list is empty. You will find that it is allowing to drop element on empty list. To understand it in better way you can Try it yourself with different options discussed in above table. Of course, onUpdate is a prime candidate for triggering Ajax notifications to the server, for instance when the user reorders a to-do list or some other data set. Combining Ajax.Request and Sortable.serialize makes live persistence simple enough: Sortable.serialize creates a string like: List[]=1&List[]=2&List[]=3&List[]=4 where the numbers are the identifier parts of the list element ids after the underscore. Now we need to code file.php which will parse posted data as parse_str($_POST['data']); and you can do whatever you want to do with this sorted data. To learn more about AJAX, please go through our simple Ajax Tutorial.
http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=script.aculo.us&file=scriptaculous_sorting.htm
CC-MAIN-2014-10
refinedweb
648
65.32
jQuery plugin that makes easy to use clip-path on whatever tag under different browsers This is a jQuery plugin that makes using clip-path property easy on whatever tag under different browsers. Tested on latest Chrome, Safari, Firefox and Opera. It should work on Chrome ≥31, Firefox ≥31, Safari ≥7 and Opera ≥30. What it does? Let's say that you want to achieve something like this: Take a look at the example html file! So you need to have a rectangle (e.g. 300x200) and you have to crop this image with such coordinates: (0; 0), (145; 0), (150; 20), (155; 0), (300; 0), (300; 200), (0; 200), (0; 0) In Webkit all you have to do is to write a css style: -webkit-clip-path: polygon(0 0, 145px 0, 150px 20px, 155px 0, 300px 0, 300px 200px, 0 200px, 0 0) In Firefox and in W3C standard what you should do is: clip-path: url(#my-definition) and somewhere in the file: If your design is resposive, you might want to use relative unit - percents. Then, the expected values would be: polygon(0 0, 49% 0, 50% 10%, 51% 0, 100% 0, 100% 100%, 0 100%, 0 0) <polygon points="0 0, 0.49 0, 0.5 0.1, 0.51 0, 1 0, 1 1, 0 1, 0 0"></polygon> clip-path-polygon does this job for you! Install with or add it to your package.json: $ npm install clip-path-polygon Then require it: ; and use: $myElement; $ bower install clip-path-polygon --save and then add bower_components/clip-path-polygon/build/clip-path-polygon.min.js to your scripts. I'm assuming here that your bower installation folder is called bower_components. Download clip-path-polygon.min.js (minified) or clip-path-polygon.js (dev) and add it to you HTML file: If you want to compile the whole package with unit tests, run: npm install and then grunt (compilation) or grunt test (tests). I use mocha, sinonjs and expect.js for testing. Changlelog is available here: CHANGELOG.md Definition: clipPath(points [, options]) You can call it on a jQuery element: ; where points is an array of two-elements arrays: [[x0, y0], [x1, y1], [x2, y2]...] crops the element to this area defined by these points. There are some options that you can use: which gives you such an html code (remember that svg element has to have namespace!): To use relative values, you have to pass isPercentage option. You might want to name the SVG clippath definition differently too: which gives you such an html code (remember that svg element has to have namespace!):
https://www.npmjs.com/package/clip-path-polygon
CC-MAIN-2016-50
refinedweb
440
71.65
For quite sometime now, I am involved in the development of application software using the .NET Framework version 1.1. But there was one thing that .NET 1.1 really lacked. The support for something like 'Templates' found in the good old(?) C++. The support for the concept of type parameters, which makes it possible to design classes which take in a generic type and determine the actual type later on. This means that by using a generic type parameter T, you can write a single class MyList<T> and the client code can use it as MyList<int>, MyList<string> or MyList<MyClass> without any risk of runtime casts or boxing operations. T MyList<T> MyList<int> MyList<string> MyList<MyClass> My dear friends let me introduce you to the concept of 'Generics', which is included in .NET Framework version 2.0, and which can be considered very close to Templates in C++. Version 2.0 of the .NET Framework introduces a new namespace viz. System.Collections.Generic, which contains the classes that support this concept, like the List, Queue, Stack, LinkedList and many more which you can use effectively in your programs. System.Collections.Generic List Queue Stack LinkedList In the earlier versions, before .NET 2.0, generalization was accomplished by casting types to and from the universal base type System.Object. Generics provide a solution to this limitation in the common language runtime and the C# language. This limitation can be demonstrated with the help of the ArrayList collection class from the .NET Framework base class library. ArrayList is a highly convenient collection class that can be used without any modifications to store any reference or value type. System.Object ArrayList // The .NET Framework 1.1 way of creating a list ArrayList list1 = new ArrayList(); list1.Add(3); list1.Add(105); //... ArrayList list2 = new ArrayList(); list2.Add("First item."); list2.Add("Second item"); //... But this convenience comes at a cost. Any reference or value type that is added to an ArrayList is implicitly typecast to System.Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. The casting, boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant in scenarios where you must iterate through large collections. So, what we need is, flexibility of the ArrayList but it should be more efficient and should provide some ways of type checking by the compiler, without sacrificing on the reusability of that class with different data types. An ArrayList with a type parameter? That is precisely what generics provide. Generics would eliminate the need for all items to be type cast to Object and would also enable the compiler to do some type checking. In the generic List<T> collection, in System.Collections.Generic namespace, the same operation of adding items to the collection looks like this: List<T> // The .NET Framework 2.0 way of creating a list List<int> list1 = new List<int>(); list1.Add(3); // No boxing, no casting list1.Add("First item"); // Compile-time error For the client code, the only added syntax with List<T> compared to ArrayList is the type argument in the declaration and in instantiation. In return for this slightly greater coding complexity, you can create a list that is not only safer than ArrayList, but also significantly faster, especially when the list items are value types. Generic classes encapsulate operations that are not specific to any particular data type. The most common use for generic classes is with the collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in more or less the same way regardless of the type of the data being stored. public class Node <T> { T head; T next; } Here, T is the type parameter. We can pass any data type as parameter. This class can be instantiated like this: Node<string> node = new Node<string>(); This will tell the compiler that the properties, head and next are of type string. Instead of string, you can substitute this with any data type. string A generic method is a method that is declared with a type parameter. void Swap<T>( ref T left, ref T right) { T temp; temp = left; left = right; right = temp; } The following code example shows how to call the above method: int a = 1; int b = 2; Swap <int> (a, b); You can also omit the type parameter because the compiler will automatically identify it for you. The following is also a valid call to the same method: Swap (a, b); The following example demonstrates how you can write your own generic classes. The example shown below is a simple generic linked list class for demonstration purpose: using System; using System.Collections.Generic; public class MyList<T> //type parameter T in angle brackets { private Node head; // The nested class is also generic on T. private class Node { private Node next; //T as private member data type: private T data; //T used in non-generic constructor: public Node(T t) { next = null; data = t; } public Node Next { get { return next; } set { next = value; } } //T as return type of property: public T Data { get { return data; } set { data = value; } } } public MyList() { head = null; } //T as method parameter type: public void AddHead(T t) { Node n = new Node(t); n.Next = head; head = n; } public IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } } } Notice the declaration of the above class : public class MyList<T> T is the parameter type. Throughout the above code, the data type for the Node is T rather than any specific types like int or string or any other class. This gives flexibility to the programmer to use this class with any data type he wishes to use. Node int The following code example shows how the client code uses the generic MyList<T> class to create a list of integers. Simply by changing the type argument, the code below can be easily modified to create lists of strings or any other custom type: class Program { static void Main(string[] args) { //int is the type argument. MyList<int> list = new MyList<int>(); for (int x = 0; x < 10; x++) list.AddHead(x); foreach (int i in list) Console.WriteLine(i); Console.WriteLine("Done"); } } Okay. I think you have got a hang of the generics by now, right? Anybody who has worked with templates in C++ would find this almost similar. When a generic type or method is compiled into MSIL, it contains metadata that identifies it as having type parameters. How this MSIL which contains generic type is used is different based on whether or not the supplied type parameter is a value or reference type. When a generic type is first constructed with a value type as parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate places in the MSIL. Specialized generic types are created once for each of the unique value type used as parameter. For example, suppose your program code declared a Stack constructed of integers, like this: Stack<int> stack; At this point, the runtime generates a specialized version of the Stack class with the integer substituted appropriately as its parameter. Now, whenever your program code uses a stack of integers, the runtime reuses the generated specialized Stack class. In the following example, two instances of a stack of integers are created, and they share a single instance of the Stack<int> code: Stack<int> Stack<int> stackOne = new Stack<int>(); Stack<int> stackTwo = new Stack<int>(); However, if at another point in your program code another Stack class is created but with a different value type such as a long or a user-defined structure as its parameter, then the runtime generates another version of the generic type, this time substituting a long in the appropriate places in the MSIL. Conversions are no longer necessary because each specialized generic class natively contains the value type. long Generics work a bit differently for reference types. The first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with the object references substituted for the parameters in the MSIL. Then, each time a constructed type is instantiated with a reference type as its parameter, regardless of its type, the runtime reuses the previously created specialized version of the generic type. This is possible because all references are the same size. For example, suppose you had two reference types, a Customer class and an Order class, and that you created a stack of Customer types: Customer Order Stack<Customer> customers; At this point, the runtime generates a specialized version of the Stack class that, instead of storing data, stores object references that will be filled in later. Suppose the next line of code creates a stack of another reference type, called Order: Stack<Order> orders = new Stack<Order>(); Unlike the value types, another specialized version of the Stack class is not created for the Order type. Rather, an instance of the specialized version of the Stack class is created and the orders variable is set to reference it. Suppose you then encountered a line of code to create a stack of a Customer type: customers = new Stack<Customer>(); As with the previous use of the Stack class created with the Order type, another instance of the specialized Stack class is created, and the pointers contained therein are set to reference an area of memory the size of a Customer type. The C# implementation of generics greatly reduces code bloat by reducing the number of specialized classes created by the compiler for generic classes of reference types to just one. C# Generics and C++ templates are both language features that provide support for parameterized types. However, there are many differences between the two. At the syntax level, the C# generics are a simpler approach to parameterized types without any of the complexities of C++ templates. In addition, C# does not attempt to provide all the functionality that C++ templates provide. At the implementation level, the primary difference is that the C# generic type substitutions are performed at runtime and generic type information is preserved for the instantiated objects. Generics are a great way of writing classes that combine reusability, type safety and efficiency. Generics are commonly used with collections. .NET 2.0 has introduced a new namespace called System.Collections.Generic which contains classes that support generics. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here <code> public struct Rectangle : IComparable<Rectangle> { public int Height; public int Width; public Rectangle(int height, int width) { this.Height = height; this.Width = width; } public int CompareTo(Rectangle other) { return (this.Height * this.Width).CompareTo(other.Height * other.Width); } } public struct RectangleProperties { public bool HasBorders; // ... } public class Test { public void MyTest() { Dictionary<Rectangle, RectangleProperties> myDict = new Dictionary<Rectangle, RectangleProperties>(); myDict.Add(new Rectangle(100, 100), new RectangleProperties(/* ... */)); myDict.Add(new Rectangle(200, 200), new RectangleProperties(/* ... */)); RectangleProperties result; bool success = myDict.TryGetValue(new Rectangle(100, 100), out result); } } </code> General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/articles/8846/generics-explained-net-framework-version-2-0?pageflow=fixedwidth
CC-MAIN-2017-13
refinedweb
1,937
52.8
Skip navigation links java.lang.Object oracle.rules.rl.extensions.ClassFilter public class ClassFilter A filter that passes objects that are instances of a particular class. public ClassFilter(java.lang.String className, RuleSession rs) throws UndefinedException className- the name of the class that the filter should pass instances of. The class may be an RL class or a Java class. Consistent with RL semantics, it looks for an RL class with the specified name first and then looks for a Java class . rs- the RuleSession this filter will be used with. It is used to handle RL classes. UndefinedException public boolean accept(java.lang.Object object) acceptin interface ObjectFilter object- the object to apply the filter to. public void reset() resetin interface ObjectFilter Skip navigation links
http://docs.oracle.com/cd/E15523_01/apirefs.1111/e10663/oracle/rules/rl/extensions/ClassFilter.html
CC-MAIN-2014-35
refinedweb
126
51.44
Image Search Library #61 Posted 01 November 2009 - 12:57 AM #62 Posted 17 November 2009 - 10:20 PM Hey. Great library. I just made some chages, so i can search any HBitmap, too ( _WinAPI_LoadImage, _GDIPlus_BitmapCreateHBITMAPFromBitmap)( _WinAPI_LoadImage, _GDIPlus_BitmapCreateHBITMAPFromBitmap) ImageSearch.zip (659.4K) Number of downloads:ImageSearch.zip (659.4K) Number of downloads: //Edit: added speedshare mirror as requested by mortelrdv: Hi, the downloadlinks are dead. Can you provide another location? To look for an image which comes from the harddrive is not as good as the HBitmap solution... greetz and thx in advance Sundance #63 Posted 18 November 2009 - 08:11 AM Attached Files #64 Posted 18 November 2009 - 09:01 AM Attached Files #65 Posted 18 November 2009 - 12:39 PM Here is original ImageSearch DLL with AU3 wrapper and also with C++ sources. Thx both of you :-) Now going t work... greetz Sundance #66 Posted 18 November 2009 - 04:10 PM #67 Posted 18 November 2009 - 10:11 PM D:\Eigene Dateien\Programmierung\AutoIt Skripte\ImageSearch\ImageSearch.au3 (41) : ==> Subscript used with non-Array variable.: if $result[0]="0" then return 0 if $result^ ERROR ->22:58:29 AutoIT3.exe ended.rc:1 @error is giving me 1 which means: unable to use the DLL file I'am calling ImageSearch with the following parameters _ImageSearch("d:\pic.bmp", 0, 900, 563, 1020, 638, $iResultX, $iResultY) The BMP file exists and the coordinates are in the range of my desktop width/heigth Don't know where my problem lies... Somebody got a hint? greetz Sundance PS: I tried the ImageSearchDemo and it gives me the same error!! All files are from the original ImageSearch archive.. I should say, that i run under Windows 7 64Bit Edited by Sundance, 18 November 2009 - 10:13 PM. #68 Posted 18 November 2009 - 10:58 PM Read previous posts in this topic. This was reported already.Read previous posts in this topic. This was reported already. Back again at home i tried to use both ImageSearch Versions but get the same error on both: D:\Eigene Dateien\Programmierung\AutoIt Skripte\ImageSearch\ImageSearch.au3 (41) : ==> Subscript used with non-Array variable.: if $result[0]="0" then return 0 if $result^ ERROR ->22:58:29 AutoIT3.exe ended.rc:1 ... PS: I tried the ImageSearchDemo and it gives me the same error!! All files are from the original ImageSearch archive.. I should say, that i run under Windows 7 64Bit On 64bit OS it doesn't work. It's probably because DLL is compiled as 32bit. Try to recompile DLL from sources as 64bit one. But I'm not sure about that. #69 Posted 19 November 2009 - 05:49 AM #70 Posted 19 November 2009 - 06:57 AM Read previous posts in this topic. This was reported already. On 64bit OS it doesn't work. It's probably because DLL is compiled as 32bit. Try to recompile DLL from sources as 64bit one. But I'm not sure about that. Hi Zedna, after some hours of sleep i saw the post you mean. Sorry i did my post. I hate people who don't read older posts... sleepy greetz from germany Sundance #71 Posted 19 November 2009 - 03:56 PM I'm getting the same error below however I am running 32 bit XP.I'm getting the same error below however I am running 32 bit XP. Read previous posts in this topic. This was reported already. On 64bit OS it doesn't work. It's probably because DLL is compiled as 32bit. Try to recompile DLL from sources as 64bit one. But I'm not sure about that. Anything else that can cause this error? Thanks C:\Program Files\AutoIt3\Include\ImageSearch.au3 (44) : ==> Subscript used with non-Array variable.: if $result[0]="0" then return 0 if $result^ ERROR >Exit code: 1 Time: 0.837 #72 Posted 20 November 2009 - 11:21 AM how.to.do...that........ #73 Posted 22 January 2010 - 11:06 PM? Edited by HansHenrik, 22 January 2010 - 11:07 PM. #74 Posted 24 January 2010 - 03:04 PM Hi,Hi, when i compile the source as x86,? could you please upload the DLL for x64 systems. I tried to compile it with Visual C++ but didn't succeed. (Never did C++ before) for your problem with the source as x64 look at this post: #75 Posted 24 January 2010 - 11:00 PM anyway heres the 64-bit build as requested ^ I cant get the 64-bit dll to work. (not even by removing the array [0] part. (then it ALWAYS return false it seems, tho i have just tested it 2 times, could be that i messed up again.) (i merged post here) i may have a hardware-issue, or i was probably allot more tired than i thought while posting above post, or evil chinese hackers mess up my autoit, or some other magic.. now i have no problem getting either 32-bit or 64-bit build to work. ... wth?!??!?!????????? but now i got a friend witch get same problem on both dll's (again, wth??) btw could it be that the DllCall() fails? also heres a stupid workaround for the error that stops compiling, according to the link posted ^, it may help.. $result = DllCall("ImageSearchDLL.dll","str","ImageSearch","int",$x1,"int",$y1,"int",$right,"int",$bottom,"str",$findImage) ; If error exit if IsArray($result) Then;heres the workaround.. if $result[0]="0" then return 0 Else if $result="0" then return 0 EndIf Attached Files Edited by HansHenrik, 26 January 2010 - 07:00 PM. - riceking likes this #76 Posted 26 January 2010 - 07:26 PM #define HHB_PRINT_FAIL_IMAGE_SEARCH /* AutoHotkey Copyright 2003-2007 Chris Mallett (support@autohotkey.com) DLL conversion 2008: kangkengkingkong@hot "stdafx.h" // pre-compiled headers #include <olectl.h> // for OleLoadPicture() #include <Gdiplus.h> // Used by LoadPicture(). #include <windef.h> #include <windows.h> #include <winuser.h> #include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <shellapi.h> #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH std::string ERROR=""; #endif #define CLR_DEFAULT 0x808080 #define ToWideChar(source, dest, dest_size_in_wchars) MultiByteToWideChar(CP_ACP, 0, source, -1, dest, dest_size_in_wchars) #define CLR_NONE 0xFFFFFFFF #define IS_SPACE_OR_TAB(c) (c == ' ' || c == '\t') char answer[50]; HINSTANCE g_hInstance; #define SET_COLOR_RANGE \ {\ red_low = (aVariation > search_red) ? 0 : search_red - aVariation;\ green_low = (aVariation > search_green) ? 0 : search_green - aVariation;\ blue_low = (aVariation > search_blue) ? 0 : search_blue - aVariation;\ red_high = (aVariation > 0xFF - search_red) ? 0xFF : search_red + aVariation;\ green_high = (aVariation > 0xFF - search_green) ? 0xFF : search_green + aVariation;\ blue_high = (aVariation > 0xFF - search_blue) ? 0xFF : search_blue + aVariation;\ } #define bgr_to_rgb(aBGR) rgb_to_bgr(aBGR) inline COLORREF rgb_to_bgr(DWORD aRGB) // Fancier methods seem prone to problems due to byte alignment or compiler issues. { return RGB(GetBValue(aRGB), GetGValue(aRGB), GetRValue(aRGB)); } COLORREF ColorNameToBGR(char *aColorName) // These are the main HTML color names. Returns CLR_NONE if a matching HTML color name can't be found. // Returns CLR_DEFAULT only if aColorName is the word Default. { if (!aColorName || !*aColorName) return CLR_NONE; if (!_stricmp(aColorName, "Black")) return 0x000000; // These colors are all in BGR format, not RGB. if (!_stricmp(aColorName, "Silver")) return 0xC0C0C0; if (!_stricmp(aColorName, "Gray")) return 0x808080; if (!_stricmp(aColorName, "White")) return 0xFFFFFF; if (!_stricmp(aColorName, "Maroon")) return 0x000080; if (!_stricmp(aColorName, "Red")) return 0x0000FF; if (!_stricmp(aColorName, "Purple")) return 0x800080; if (!_stricmp(aColorName, "Fuchsia"))return 0xFF00FF; if (!_stricmp(aColorName, "Green")) return 0x008000; if (!_stricmp(aColorName, "Lime")) return 0x00FF00; if (!_stricmp(aColorName, "Olive")) return 0x008080; if (!_stricmp(aColorName, "Yellow")) return 0x00FFFF; if (!_stricmp(aColorName, "Navy")) return 0x800000; if (!_stricmp(aColorName, "Blue")) return 0xFF0000; if (!_stricmp(aColorName, "Teal")) return 0x808000; if (!_stricmp(aColorName, "Aqua")) return 0xFFFF00; if (!_stricmp(aColorName, "Default"))return CLR_DEFAULT; return CLR_NONE; } inline char *StrChrAny(char *aStr, char *aCharList) // Returns the position of the first char in aStr that is of any one of the characters listed in aCharList. // Returns NULL if not found. // Update: Yes, this seems identical to strpbrk(). However, since the corresponding code would // have to be added to the EXE regardless of which was used, there doesn't seem to be much // advantage to switching (especially since if the two differ in behavior at all, things might // get broken). Another reason is the name "strpbrk()" is not as easy to remember. { if (aStr == NULL || aCharList == NULL) return NULL; if (!*aStr || !*aCharList) return NULL; // Don't use strchr() because that would just find the first occurrence // of the first search-char, which is not necessarily the first occurrence // of *any* search-char: char *look_for_this_char, char_being_analyzed; for (; *aStr; ++aStr) // If *aStr is any of the search char's, we're done: for (char_being_analyzed = *aStr, look_for_this_char = aCharList; *look_for_this_char; ++look_for_this_char) if (char_being_analyzed == *look_for_this_char) return aStr; // Match found. return NULL; // No match. } inline char *omit_leading_whitespace(char *aBuf) // 10/17/2006: __forceinline didn't help significantly. // While aBuf points to a whitespace, moves to the right and returns the first non-whitespace // encountered. { for (; IS_SPACE_OR_TAB(*aBuf); ++aBuf); return aBuf; } inline bool IsHex(char *aBuf) // 10/17/2006: __forceinline worsens performance, but physically ordering it near ATOI64() [via /ORDER] boosts by 3.5%. // Note: AHK support for hex ints reduces performance by only 10% for decimal ints, even in the tightest // of math loops that have SetBatchLines set to -1. { // For whatever reason, omit_leading_whitespace() benches consistently faster (albeit slightly) than // the same code put inline (confirmed again on 10/17/2006, though the difference is hardly anything): //for (; IS_SPACE_OR_TAB(*aBuf); ++aBuf); aBuf = omit_leading_whitespace(aBuf); // i.e. caller doesn't have to have ltrimmed. if (!*aBuf) return false; if (*aBuf == '-' || *aBuf == '+') ++aBuf; // The "0x" prefix must be followed by at least one hex digit, otherwise it's not considered hex: #define IS_HEX(buf) (*buf == '0' && (*(buf + 1) == 'x' || *(buf + 1) == 'X') && isxdigit(*(buf + 2))) return IS_HEX(aBuf); } inline int ATOI(char *buf) { // Below has been updated because values with leading zeros were being intepreted as // octal, which is undesirable. // Formerly: #define ATOI(buf) strtol(buf, NULL, 0) // Use zero as last param to support both hex & dec. return IsHex(buf) ? strtol(buf, NULL, 16) : atoi(buf); // atoi() has superior performance, so use it when possible. } void strlcpy(char *aDst, const char *aSrc, size_t aDstSize) // Non-inline because it benches slightly faster that way. // Caller must ensure that aDstSize is greater than 0. // Caller must ensure that the entire capacity of aDst is writable, EVEN WHEN it knows that aSrc is much shorter // than the aDstSize. This is because the call to strncpy (which is used for its superior performance) zero-fills // any unused portion of aDst. // Description: // Same as strncpy() but guarantees null-termination of aDst upon return. // No more than aDstSize - 1 characters will be copied from aSrc into aDst // (leaving room for the zero terminator, which is always inserted). // This function is defined in some Unices but is not standard. But unlike // other versions, this one uses void for return value for reduced code size // (since it's called in so many places). { // Disabled for performance and reduced code size: //if (!aDst || !aSrc || !aDstSize) return aDstSize; // aDstSize must not be zero due to the below method. // It might be worthwhile to have a custom char-copying-loop here someday so that number of characters // actually copied (not including the zero terminator) can be returned to callers who want it. --aDstSize; // Convert from size to length (caller has ensured that aDstSize > 0). strncpy(aDst, aSrc, aDstSize); // NOTE: In spite of its zero-filling, strncpy() benchmarks considerably faster than a custom loop, probably because it uses 32-bit memory operations vs. 8-bit. aDst[aDstSize] = '\0'; } LPCOLORREF getbits(HBITMAP ahImage, HDC hdc, LONG &aWidth, LONG &aHeight, bool &aIs16Bit, int aMinColorDepth = 8) // Helper function used by PixelSearch below. // Returns an array of pixels to the caller, which it must free when done. Returns NULL on failure, // in which case the contents of the output parameters is indeterminate. { HDC tdc = CreateCompatibleDC(hdc); if (!tdc) return NULL; // From this point on, "goto end" will assume tdc is non-NULL, but that the below // might still be NULL. Therefore, all of the following must be initialized so that the "end" // label can detect them: HGDIOBJ tdc_orig_select = NULL; LPCOLORREF image_pixel = NULL; bool success = false; // Confirmed: // Needs extra memory to prevent buffer overflow due to: "A bottom-up DIB is specified by setting // the height to a positive number, while a top-down DIB is specified by setting the height to a // negative number. THE BITMAP COLOR TABLE WILL BE APPENDED to the BITMAPINFO structure." // Maybe this applies only to negative height, in which case the second call to GetDIBits() // below uses one. struct BITMAPINFO3 { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[260]; // v1.0.40.10: 260 vs. 3 to allow room for color table when color depth is 8-bit or less. } bmi; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biBitCount = 0; // i.e. "query bitmap attributes" only. if (!GetDIBits(tdc, ahImage, 0, 0, NULL, (LPBITMAPINFO)&bmi, DIB_RGB_COLORS) || bmi.bmiHeader.biBitCount < aMinColorDepth) // Relies on short-circuit boolean order. goto end; // Set output parameters for caller: aIs16Bit = (bmi.bmiHeader.biBitCount == 16); aWidth = bmi.bmiHeader.biWidth; aHeight = bmi.bmiHeader.biHeight; int image_pixel_count = aWidth * aHeight; if ( !(image_pixel = (LPCOLORREF)malloc(image_pixel_count * sizeof(COLORREF))) ) goto end; // v1.0.40.10: To preserve compatibility with callers who check for transparency in icons, don't do any // of the extra color table handling for 1-bpp images. Update: For code simplification, support only // 8-bpp images. If ever support lower color depths, use something like "bmi.bmiHeader.biBitCount > 1 // && bmi.bmiHeader.biBitCount < 9"; bool is_8bit = (bmi.bmiHeader.biBitCount == 8); if (!is_8bit) bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biHeight = -bmi.bmiHeader.biHeight; // Storing a negative inside the bmiHeader struct is a signal for GetDIBits(). // Must be done only after GetDIBits() because: "The bitmap identified by the hbmp parameter // must not be selected into a device context when the application calls GetDIBits()." // (Although testing shows it works anyway, perhaps because GetDIBits() above is being // called in its informational mode only). // Note that this seems to return NULL sometimes even though everything still works. // Perhaps that is normal. tdc_orig_select = SelectObject(tdc, ahImage); // Returns NULL when we're called the second time? // Appparently there is no need to specify DIB_PAL_COLORS below when color depth is 8-bit because // DIB_RGB_COLORS also retrieves the color indices. if ( !(GetDIBits(tdc, ahImage, 0, aHeight, image_pixel, (LPBITMAPINFO)&bmi, DIB_RGB_COLORS)) ) goto end; if (is_8bit) // This section added in v1.0.40.10. { // Convert the color indicies to RGB colors by going through the array in reverse order. // Reverse order allows an in-place conversion of each 8-bit color index to its corresponding // 32-bit RGB color. LPDWORD palette = (LPDWORD)_alloca(256 * sizeof(PALETTEENTRY)); GetSystemPaletteEntries(tdc, 0, 256, (LPPALETTEENTRY)palette); // Even if failure can realistically happen, consequences of using uninitialized palette seem acceptable. // Above: GetSystemPaletteEntries() is the only approach that provided the correct palette. // The following other approaches didn't give the right one: // GetDIBits(): The palette it stores in bmi.bmiColors seems completely wrong. // GetPaletteEntries()+GetCurrentObject(hdc, OBJ_PAL): Returned only 20 entries rather than the expected 256. // GetDIBColorTable(): I think same as above or maybe it returns 0. // The following section is necessary because apparently each new row in the region starts on // a DWORD boundary. So if the number of pixels in each row isn't an exact multiple of 4, there // are between 1 and 3 zero-bytes at the end of each row. int remainder = aWidth % 4; int empty_bytes_at_end_of_each_row = remainder ? (4 - remainder) : 0; // Start at the last RGB slot and the last color index slot: BYTE *byte = (BYTE *)image_pixel + image_pixel_count - 1 + (aHeight * empty_bytes_at_end_of_each_row); // Pointer to 8-bit color indices. DWORD *pixel = image_pixel + image_pixel_count - 1; // Pointer to 32-bit RGB entries. int row, col; for (row = 0; row < aHeight; ++row) // For each row. { byte -= empty_bytes_at_end_of_each_row; for (col = 0; col < aWidth; ++col) // For each column. *pixel-- = rgb_to_bgr(palette[*byte--]); // Caller always wants RGB vs. BGR format. } } // Since above didn't "goto end", indicate success: success = true; end: if (tdc_orig_select) // i.e. the original call to SelectObject() didn't fail. SelectObject(tdc, tdc_orig_select); // Probably necessary to prevent memory leak. DeleteDC(tdc); if (!success && image_pixel) { free(image_pixel); image_pixel = NULL; } return image_pixel; } HBITMAP LoadPicture(char *aFilespec, int aWidth, int aHeight, int &aImageType, int aIconNumber , bool aUseGDIPlusIfAvailable) // Returns NULL on failure. // If aIconNumber > 0, an HICON or HCURSOR is returned (both should be interchangeable), never an HBITMAP. // However, aIconNumber==1 is treated as a special icon upon which LoadImage is given preference over ExtractIcon // for .ico/.cur/.ani files. // Otherwise, .ico/.cur/.ani files are normally loaded as HICON (unless aUseGDIPlusIfAvailable is true or // something else unusual happened such as file contents not matching file's extension). This is done to preserve // any properties that HICONs have but HBITMAPs lack, namely the ability to be animated and perhaps other things. // // Loads a JPG/GIF/BMP/ICO/etc. and returns an HBITMAP or HICON to the caller (which it may call // DeleteObject()/DestroyIcon() upon, though upon program termination all such handles are freed // automatically). The image is scaled to the specified width and height. If zero is specified // for either, the image's actual size will be used for that dimension. If -1 is specified for one, // that dimension will be kept proportional to the other dimension's size so that the original aspect // ratio is retained. { HBITMAP hbitmap = NULL; aImageType = -1; // The type of image currently inside hbitmap. Set default value for output parameter as "unknown". if (!*aFilespec) // Allow blank filename to yield NULL bitmap (and currently, some callers do call it this way). return NULL; if (aIconNumber < 0) // Allowed to be called this way by GUI and others (to avoid need for validation of user input there). aIconNumber = 0; // Use the default behavior, which is "load icon or bitmap, whichever is most appropriate". char *file_ext = strrchr(aFilespec, '.'); if (file_ext) ++file_ext; // v1.0.43.07: If aIconNumber is zero, caller didn't specify whether it wanted an icon or bitmap. Thus, // there must be some kind of detection for whether ExtractIcon is needed instead of GDIPlus/OleLoadPicture. // Although this could be done by attempting ExtractIcon only after GDIPlus/OleLoadPicture fails (or by // somehow checking the internal nature of the file), for performance and code size, it seems best to not // to incur this extra I/O and instead make only one attempt based on the file's extension. // Must use ExtractIcon() if either of the following is true: // 1) Caller gave an icon index of the second or higher icon in the file. Update for v1.0.43.05: There // doesn't seem to be any reason to allow a caller to explicitly specify ExtractIcon as the method of // loading the *first* icon from a .ico file since LoadImage is likely always superior. This is // because unlike ExtractIcon/Ex, LoadImage: 1) Doesn't distort icons, especially 16x16 icons; 2) is // capable of loading icons other than the first by means of width and height parameters. // 2) The target file is of type EXE/DLL/ICL/CPL/etc. (LoadImage() is documented not to work on those file types). // ICL files (v1.0.43.05): Apparently ICL files are an unofficial file format. Someone on the newsgroups // said that an ICL is an "ICon Library... a renamed 16-bit Windows .DLL (an NE format executable) which // typically contains nothing but a resource section. The ICL extension seems to be used by convention." bool ExtractIcon_was_used = aIconNumber > 1 || (file_ext && ( !_stricmp(file_ext, "exe") || !_stricmp(file_ext, "dll") || !_stricmp(file_ext, "icl") // Icon library: Unofficial dll container, see notes above. || !_stricmp(file_ext, "cpl") // Control panel extension/applet (ExtractIcon is said to work on these). || !_stricmp(file_ext, "scr") // Screen saver (ExtractIcon should work since these are really EXEs). // v1.0.44: Below are now omitted to reduce code size and improve performance. They are still supported // indirectly because ExtractIcon is attempted whenever LoadImage() fails further below. //|| !_stricmp(file_ext, "drv") // Driver (ExtractIcon is said to work on these). //|| !_stricmp(file_ext, "ocx") // OLE/ActiveX Control Extension //|| !_stricmp(file_ext, "vbx") // Visual Basic Extension //|| !_stricmp(file_ext, "acm") // Audio Compression Manager Driver //|| !_stricmp(file_ext, "bpl") // Delphi Library (like a DLL?) // Not supported due to rarity, code size, performance, and uncertainty of whether ExtractIcon works on them. // Update for v1.0.44: The following are now supported indirectly because ExtractIcon is attempted whenever // LoadImage() fails further below. //|| !_stricmp(file_ext, "nil") // Norton Icon Library //|| !_stricmp(file_ext, "wlx") // Total/Windows Commander Lister Plug-in //|| !_stricmp(file_ext, "wfx") // Total/Windows Commander File System Plug-in //|| !_stricmp(file_ext, "wcx") // Total/Windows Commander Plug-in //|| !_stricmp(file_ext, "wdx") // Total/Windows Commander Plug-in )); if (ExtractIcon_was_used) { aImageType = IMAGE_ICON; hbitmap = (HBITMAP)ExtractIcon(g_hInstance, aFilespec, aIconNumber > 0 ? aIconNumber - 1 : 0); // Above: Although it isn't well documented at MSDN, apparently both ExtractIcon() and LoadIcon() // scale the icon to the system's large-icon size (usually 32x32) regardless of the actual size of // the icon inside the file. For this reason, callers should call us in a way that allows us to // give preference to LoadImage() over ExtractIcon() (unless the caller needs to retain backward // compatibility with existing scripts that explicitly specify icon #1 to force the ExtractIcon // method to be used). if (hbitmap < (HBITMAP)2) // i.e. it's NULL or 1. Return value of 1 means "incorrect file type". return NULL; // v1.0.44: Fixed to return NULL vs. hbitmap, since 1 is an invalid handle (perhaps rare since no known bugs caused by it). //else continue on below so that the icon can be resized to the caller's specified dimensions. } else if (aIconNumber > 0) // Caller wanted HICON, never HBITMAP, so set type now to enforce that. aImageType = IMAGE_ICON; // Should be suitable for cursors too, since they're interchangeable for the most part. else if (file_ext) // Make an initial guess of the type of image if the above didn't already determine the type. { if (!_stricmp(file_ext, "ico")) aImageType = IMAGE_ICON; else if (!_stricmp(file_ext, "cur") || !_stricmp(file_ext, "ani")) aImageType = IMAGE_CURSOR; else if (!_stricmp(file_ext, "bmp")) aImageType = IMAGE_BITMAP; //else for other extensions, leave set to "unknown" so that the below knows to use IPic or GDI+ to load it. } //else same comment as above. if ((aWidth == -1 || aHeight == -1) && (!aWidth || !aHeight)) aWidth = aHeight = 0; // i.e. One dimension is zero and the other is -1, which resolves to the same as "keep original size". bool keep_aspect_ratio = (aWidth == -1 || aHeight == -1); // Caller should ensure that aUseGDIPlusIfAvailable==false when aIconNumber > 0, since it makes no sense otherwise. HINSTANCE hinstGDI = NULL; if (aUseGDIPlusIfAvailable && !(hinstGDI = LoadLibrary("gdiplus"))) // Relies on short-circuit boolean order for performance. aUseGDIPlusIfAvailable = false; // Override any original "true" value as a signal for the section below. if (!hbitmap && aImageType > -1 && !aUseGDIPlusIfAvailable) { // Since image hasn't yet be loaded and since the file type appears to be one supported by // LoadImage() [icon/cursor/bitmap], attempt that first. If it fails, fall back to the other // methods below in case the file's internal contents differ from what the file extension indicates. int desired_width, desired_height; if (keep_aspect_ratio) // Load image at its actual size. It will be rescaled to retain aspect ratio later below. { desired_width = 0; desired_height = 0; } else { desired_width = aWidth; desired_height = aHeight; } // For LoadImage() below: // LR_CREATEDIBSECTION applies only when aImageType == IMAGE_BITMAP, but seems appropriate in that case. // Also, if width and height are non-zero, that will determine which icon of a multi-icon .ico file gets // loaded (though I don't know the exact rules of precedence). // KNOWN LIMITATIONS/BUGS: // LoadImage() fails when requesting a size of 1x1 for an image whose orig/actual size is small (e.g. 1x2). // Unlike CopyImage(), perhaps it detects that division by zero would occur and refuses to do the // calculation rather than providing more code to do a correct calculation that doesn't divide by zero. // For example: // LoadImage() Success: // Gui, Add, Pic, h2 w2, bitmap 1x2.bmp // Gui, Add, Pic, h1 w1, bitmap 4x6.bmp // LoadImage() Failure: // Gui, Add, Pic, h1 w1, bitmap 1x2.bmp // LoadImage() also fails on: // Gui, Add, Pic, h1, bitmap 1x2.bmp // And then it falls back to GDIplus, which in the particular case above appears to traumatize the // parent window (or its picture control), because the GUI window hangs (but not the script) after // doing a FileSelectFolder. For example: // Gui, Add, Button,, FileSelectFile // Gui, Add, Pic, h1, bitmap 1x2.bmp ; Causes GUI window to hang after FileSelectFolder (due to LoadImage failing then falling back to GDIplus; i.e. GDIplus is somehow triggering the problem). // Gui, Show // return // ButtonFileSelectFile: // FileSelectFile, outputvar // return //printf("\nloading image %s",(LPCTSTR)aFilespec); if (hbitmap = (HBITMAP)LoadImage(NULL, aFilespec, aImageType, desired_width, desired_height , LR_LOADFROMFILE | LR_CREATEDIBSECTION)) { // The above might have loaded an HICON vs. an HBITMAP (it has been confirmed that LoadImage() // will return an HICON vs. HBITMAP is aImageType is IMAGE_ICON/CURSOR). Note that HICON and // HCURSOR are identical for most/all Windows API uses. Also note that LoadImage() will load // an icon as a bitmap if the file contains an icon but IMAGE_BITMAP was passed in (at least // on Windows XP). //printf("\n got here"); if (!keep_aspect_ratio) // No further resizing is needed. return hbitmap; // Otherwise, continue on so that the image can be resized via a second call to LoadImage(). } // v1.0.40.10: Abort if file doesn't exist so that GDIPlus isn't even attempted. This is done because // loading GDIPlus apparently disrupts the color palette of certain games, at least old ones that use // DirectDraw in 256-color depth. else if (GetFileAttributes(aFilespec) == 0xFFFFFFFF) // For simplicity, we don't check if it's a directory vs. file, since that should be too rare. return NULL; // v1.0.43.07: Also abort if caller wanted an HICON (not an HBITMAP), since the other methods below // can't yield an HICON. else if (aIconNumber > 0) { // UPDATE for v1.0.44: Attempt ExtractIcon in case its some extension that's // was recognized as an icon container (such as AutoHotkeySC.bin) and thus wasn't handled higher above. hbitmap = (HBITMAP)ExtractIcon(g_hInstance, aFilespec, aIconNumber - 1); if (hbitmap < (HBITMAP)2) // i.e. it's NULL or 1. Return value of 1 means "incorrect file type". return NULL; ExtractIcon_was_used = true; } //else file exists, so continue on so that the other methods are attempted in case file's contents // differ from what the file extension indicates, or in case the other methods can be successful // even when the above failed. } IPicture *pic = NULL; // Also used to detect whether IPic method was used to load the image. if (!hbitmap) // Above hasn't loaded the image yet, so use the fall-back methods. { // At this point, regardless of the image type being loaded (even an icon), it will // definitely be converted to a Bitmap below. So set the type: aImageType = IMAGE_BITMAP; // Find out if this file type is supported by the non-GDI+ method. This check is not foolproof // since all it does is look at the file's extension, not its contents. However, it doesn't // need to be 100% accurate because its only purpose is to detect whether the higher-overhead // calls to GdiPlus can be avoided. if (aUseGDIPlusIfAvailable || !file_ext || (_stricmp(file_ext, "jpg") && _stricmp(file_ext, "jpeg") && _stricmp(file_ext, "gif"))) // Non-standard file type (BMP is already handled above). if (!hinstGDI) // We don't yet have a handle from an earlier call to LoadLibary(). hinstGDI = LoadLibrary("gdiplus"); // If it is suspected that the file type isn't supported, try to use GdiPlus if available. // If it's not available, fall back to the old method in case the filename doesn't properly // reflect its true contents (i.e. in case it really is a JPG/GIF/BMP internally). // If the below LoadLibrary() succeeds, either the OS is XP+ or the GdiPlus extensions have been // installed on an older OS. if (hinstGDI) { // LPVOID and "int" are used to avoid compiler errors caused by... namespace issues? typedef int (WINAPI *GdiplusStartupType)(ULONG_PTR*, LPVOID, LPVOID); typedef VOID (WINAPI *GdiplusShutdownType)(ULONG_PTR); typedef int (WINGDIPAPI *GdipCreateBitmapFromFileType)(LPVOID, LPVOID); typedef int (WINGDIPAPI *GdipCreateHBITMAPFromBitmapType)(LPVOID, LPVOID, DWORD); typedef int (WINGDIPAPI *GdipDisposeImageType)(LPVOID); GdiplusStartupType DynGdiplusStartup = (GdiplusStartupType)GetProcAddress(hinstGDI, "GdiplusStartup"); GdiplusShutdownType DynGdiplusShutdown = (GdiplusShutdownType)GetProcAddress(hinstGDI, "GdiplusShutdown"); GdipCreateBitmapFromFileType DynGdipCreateBitmapFromFile = (GdipCreateBitmapFromFileType)GetProcAddress(hinstGDI, "GdipCreateBitmapFromFile"); GdipCreateHBITMAPFromBitmapType DynGdipCreateHBITMAPFromBitmap = (GdipCreateHBITMAPFromBitmapType)GetProcAddress(hinstGDI, "GdipCreateHBITMAPFromBitmap"); GdipDisposeImageType DynGdipDisposeImage = (GdipDisposeImageType)GetProcAddress(hinstGDI, "GdipDisposeImage"); ULONG_PTR token; Gdiplus::GdiplusStartupInput gdi_input; Gdiplus::GpBitmap *pgdi_bitmap; if (DynGdiplusStartup && DynGdiplusStartup(&token, &gdi_input, NULL) == Gdiplus::Ok) { WCHAR filespec_wide[MAX_PATH]; ToWideChar(aFilespec, filespec_wide, MAX_PATH); // Dest. size is in wchars, not bytes. if (DynGdipCreateBitmapFromFile(filespec_wide, &pgdi_bitmap) == Gdiplus::Ok) { if (DynGdipCreateHBITMAPFromBitmap(pgdi_bitmap, &hbitmap, CLR_DEFAULT) != Gdiplus::Ok) hbitmap = NULL; // Set to NULL to be sure. DynGdipDisposeImage(pgdi_bitmap); // This was tested once to make sure it really returns Gdiplus::Ok. } // The current thought is that shutting it down every time conserves resources. If so, it // seems justified since it is probably called infrequently by most scripts: DynGdiplusShutdown(token); } FreeLibrary(hinstGDI); } else // Using old picture loading method. { // Based on code sample at HANDLE hfile = CreateFile(aFilespec, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (hfile == INVALID_HANDLE_VALUE) return NULL; DWORD size = GetFileSize(hfile, NULL); HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, size); if (!hglobal) { CloseHandle(hfile); return NULL; } LPVOID hlocked = GlobalLock(hglobal); if (!hlocked) { CloseHandle(hfile); GlobalFree(hglobal); return NULL; } // Read the file into memory: ReadFile(hfile, hlocked, size, &size, NULL); GlobalUnlock(hglobal); CloseHandle(hfile); LPSTREAM stream; if (FAILED(CreateStreamOnHGlobal(hglobal, FALSE, &stream)) || !stream) // Relies on short-circuit boolean order. { GlobalFree(hglobal); return NULL; } // Specify TRUE to have it do the GlobalFree() for us. But since the call might fail, it seems best // to free the mem ourselves to avoid uncertainy over what it does on failure: if (FAILED(OleLoadPicture(stream, 0, FALSE, IID_IPicture, (void **)&pic))) pic = NULL; stream->Release(); GlobalFree(hglobal); if (!pic) return NULL; pic->get_Handle((OLE_HANDLE *)&hbitmap); // Above: MSDN: "The caller is responsible for this handle upon successful return. The variable is set // to NULL on failure." if (!hbitmap) { pic->Release(); return NULL; } // Don't pic->Release() yet because that will also destroy/invalidate hbitmap handle. } // IPicture method was used. } // IPicture or GDIPlus was used to load the image, not a simple LoadImage() or ExtractIcon(). // Above has ensured that hbitmap is now not NULL. // Adjust things if "keep aspect ratio" is in effect: if (keep_aspect_ratio) { HBITMAP hbitmap_to_analyze; ICONINFO ii; // Must be declared at this scope level. if (aImageType == IMAGE_BITMAP) hbitmap_to_analyze = hbitmap; else // icon or cursor { if (GetIconInfo((HICON)hbitmap, &ii)) // Works on cursors too. hbitmap_to_analyze = ii.hbmMask; // Use Mask because MSDN implies hbmColor can be NULL for monochrome cursors and such. else { DestroyIcon((HICON)hbitmap); return NULL; // No need to call pic->Release() because since it's an icon, we know IPicture wasn't used (it only loads bitmaps). } } // Above has ensured that hbitmap_to_analyze is now not NULL. Find bitmap's dimensions. BITMAP bitmap; GetObject(hbitmap_to_analyze, sizeof(BITMAP), &bitmap); // Realistically shouldn't fail at this stage. if (aHeight == -1) { // Caller wants aHeight calculated based on the specified aWidth (keep aspect ratio). if (bitmap.bmWidth) // Avoid any chance of divide-by-zero. aHeight = (int)(((double)bitmap.bmHeight / bitmap.bmWidth) * aWidth + .5); // Round. } else { // Caller wants aWidth calculated based on the specified aHeight (keep aspect ratio). if (bitmap.bmHeight) // Avoid any chance of divide-by-zero. aWidth = (int)(((double)bitmap.bmWidth / bitmap.bmHeight) * aHeight + .5); // Round. } if (aImageType != IMAGE_BITMAP) { // It's our reponsibility to delete these two when they're no longer needed: DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); // If LoadImage() vs. ExtractIcon() was used originally, call LoadImage() again because // I haven't found any other way to retain an animated cursor's animation (and perhaps // other icon/cursor attributes) when resizing the icon/cursor (CopyImage() doesn't // retain animation): if (!ExtractIcon_was_used) { DestroyIcon((HICON)hbitmap); // Destroy the original HICON. // Load a new one, but at the size newly calculated above. // Due to an apparent bug in Windows 9x (at least Win98se), the below call will probably // crash the program with a "divide error" if the specified aWidth and/or aHeight are // greater than 90. Since I don't know whether this affects all versions of Windows 9x, and // all animated cursors, it seems best just to document it here and in the help file rather // than limiting the dimensions of .ani (and maybe .cur) files for certain operating systems. return (HBITMAP)LoadImage(NULL, aFilespec, aImageType, aWidth, aHeight, LR_LOADFROMFILE); } } } ;int test=LR_COPYRETURNORG; HBITMAP hbitmap_new; // To hold the scaled image (if scaling is needed). if (pic) // IPicture method was used. { // The below statement is confirmed by having tested that DeleteObject(hbitmap) fails // if called after pic->Release(): // "Copy the image. Necessary, because upon pic's release the handle is destroyed." // MSDN: CopyImage(): "[If either width or height] is zero, then the returned image will have the // same width/height as the original." // Note also that CopyImage() seems to provide better scaling quality than using MoveWindow() // (followed by redrawing the parent window) on the static control that contains it: hbitmap_new = (HBITMAP)CopyImage(hbitmap, IMAGE_BITMAP, aWidth, aHeight // We know it's IMAGE_BITMAP in this case. , (aWidth || aHeight) ? 0 : LR_COPYRETURNORG); // Produce original size if no scaling is needed. pic->Release(); // No need to call DeleteObject(hbitmap), see above. } else // GDIPlus or a simple method such as LoadImage or ExtractIcon was used. { if (!aWidth && !aHeight) // No resizing needed. return hbitmap; // The following will also handle HICON/HCURSOR correctly if aImageType == IMAGE_ICON/CURSOR. // Also, LR_COPYRETURNORG|LR_COPYDELETEORG is used because it might allow the animation of // a cursor to be retained if the specified size happens to match the actual size of the // cursor. This is because normally, it seems that CopyImage() omits cursor animation // from the new object. MSDN: "LR_COPYRETURNORG returns the original hImage if it satisfies // the criteria for the copy—that is, correct dimensions and color depth—in which case the // LR_COPYDELETEORG flag is ignored. If this flag is not specified, a new object is always created." // KNOWN BUG: Calling CopyImage() when the source image is tiny and the destination width/height // is also small (e.g. 1) causes a divide-by-zero exception. // For example: // Gui, Add, Pic, h1 w-1, bitmap 1x2.bmp ; Crash (divide by zero) // Gui, Add, Pic, h1 w-1, bitmap 2x3.bmp ; Crash (divide by zero) // However, such sizes seem too rare to document or put in an exception handler for. hbitmap_new = (HBITMAP)CopyImage(hbitmap, aImageType, aWidth, aHeight, LR_COPYRETURNORG | LR_COPYDELETEORG); // Above's LR_COPYDELETEORG deletes the original to avoid cascading resource usage. MSDN's // LoadImage() docs say: // "When you are finished using a bitmap, cursor, or icon you loaded without specifying the // LR_SHARED flag, you can release its associated memory by calling one of [the three functions]." // Therefore, it seems best to call the right function even though DeleteObject might work on // all of them on some or all current OSes. UPDATE: Evidence indicates that DestroyIcon() // will also destroy cursors, probably because icons and cursors are literally identical in // every functional way. One piece of evidence: //> No stack trace, but I know the exact source file and line where the call //> was made. But still, it is annoying when you see 'DestroyCursor' even though //> there is 'DestroyIcon'. // "Can't be helped. Icons and cursors are the same thing" (Tim Robinson (MVP, Windows SDK)). // // Finally, the reason this is important is that it eliminates one handle type // that we would otherwise have to track. For example, if a gui window is destroyed and // and recreated multiple times, its bitmap and icon handles should all be destroyed each time. // Otherwise, resource usage would cascade upward until the script finally terminated, at // which time all such handles are freed automatically. } return hbitmap_new; } HBITMAP IconToBitmap(HICON ahIcon, bool aDestroyIcon) // Converts HICON to an HBITMAP that has ahIcon's actual dimensions. // The incoming ahIcon will be destroyed if the caller passes true for aDestroyIcon. // Returns NULL on failure, in which case aDestroyIcon will still have taken effect. // If the icon contains any transparent pixels, they will be mapped to CLR_NONE within // the bitmap so that the caller can detect them. { if (!ahIcon) return NULL; HBITMAP hbitmap = NULL; // Set default. This will be the value returned. HDC hdc_desktop = GetDC(HWND_DESKTOP); HDC hdc = CreateCompatibleDC(hdc_desktop); // Don't pass NULL since I think that would result in a monochrome bitmap. if (hdc) { ICONINFO ii; if (GetIconInfo(ahIcon, &ii)) { BITMAP icon_bitmap; // Find out how big the icon is and create a bitmap compatible with the desktop DC (not the memory DC, // since its bits per pixel (color depth) is probably 1. if (GetObject(ii.hbmColor, sizeof(BITMAP), &icon_bitmap) && (hbitmap = CreateCompatibleBitmap(hdc_desktop, icon_bitmap.bmWidth, icon_bitmap.bmHeight))) // Assign { // To retain maximum quality in case caller needs to resize the bitmap we return, convert the // icon to a bitmap that matches the icon's actual size: HGDIOBJ old_object = SelectObject(hdc, hbitmap); if (old_object) // Above succeeded. { // Use DrawIconEx() vs. DrawIcon() because someone said DrawIcon() always draws 32x32 // regardless of the icon's actual size. // If it's ever needed, this can be extended so that the caller can pass in a background // color to use in place of any transparent pixels within the icon (apparently, DrawIconEx() // skips over transparent pixels in the icon when drawing to the DC and its bitmap): RECT rect = {0, 0, icon_bitmap.bmWidth, icon_bitmap.bmHeight}; // Left, top, right, bottom. HBRUSH hbrush = CreateSolidBrush(CLR_DEFAULT); FillRect(hdc, &rect, hbrush); DeleteObject(hbrush); // Probably something tried and abandoned: FillRect(hdc, &rect, (HBRUSH)GetStockObject(NULL_BRUSH)); DrawIconEx(hdc, 0, 0, ahIcon, icon_bitmap.bmWidth, icon_bitmap.bmHeight, 0, NULL, DI_NORMAL); // Debug: Find out properties of new bitmap. //BITMAP b; //GetObject(hbitmap, sizeof(BITMAP), &<img src='<#EMO_DIR#>/cool.png' class='bbc_emoticon' alt='B)' />; SelectObject(hdc, old_object); // Might be needed (prior to deleting hdc) to prevent memory leak. } } // It's our reponsibility to delete these two when they're no longer needed: DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); } DeleteDC(hdc); } ReleaseDC(HWND_DESKTOP, hdc_desktop); if (aDestroyIcon) DestroyIcon(ahIcon); return hbitmap; } int WINAPI ImageTest(int a) { return a + a; } // ResultType Line::ImageSearch(int aLeft, int aTop, int aRight, int aBottom, char *aImageFile) char* WINAPI ImageSearch(int aLeft, int aTop, int aRight, int aBottom, char *aImageFile) // Author: ImageSearch was created by Aurelian Maga. { // Many of the following sections are similar to those in PixelSearch(), so they should be // maintained together. //Var *output_var_x = ARGVAR1; // Ok if NULL. RAW wouldn't be safe because load-time validation actually //Var *output_var_y = ARGVAR2; // requires a minimum of zero parameters so that the output-vars can be optional. // Set default results, both ErrorLevel and output variables, in case of early return: //g_ErrorLevel->Assign(ERRORLEVEL_ERROR2); // 2 means error other than "image not found". //if (output_var_x) // output_var_x->Assign(); // Init to empty string regardless of whether we succeed here. //if (output_var_y) // output_var_y->Assign(); // Same. RECT rect = {0}; // Set default (for CoordMode == "screen"). //if (!(g.CoordMode & COORD_MODE_PIXEL)) // Using relative vs. screen coordinates. //{ // if (!GetWindowRect(GetForegroundWindow(), &rect)) // return OK; // Let ErrorLevel tell the story. // aLeft += rect.left; // aTop += rect.top; // aRight += rect.left; // Add left vs. right because we're adjusting based on the position of the window. // aBottom += rect.top; // Same. //} // Options are done as asterisk+option to permit future expansion. // Set defaults to be possibly overridden by any specified options: int aVariation = 0; // This is named aVariation vs. variation for use with the SET_COLOR_RANGE macro. COLORREF trans_color = CLR_NONE; // The default must be a value that can't occur naturally in an image. int icon_number = 0; // Zero means "load icon or bitmap (doesn't matter)". int width = 0, height = 0; // For icons, override the default to be 16x16 because that is what is sought 99% of the time. // This new default can be overridden by explicitly specifying w0 h0: char *cp = strrchr(aImageFile, '.'); if (cp) { ++cp; if (!(_stricmp(cp, "ico") && _stricmp(cp, "exe") && _stricmp(cp, "dll"))) width = GetSystemMetrics(SM_CXSMICON), height = GetSystemMetrics(SM_CYSMICON); } char color_name[32], *dp; cp = omit_leading_whitespace(aImageFile); // But don't alter aImageFile yet in case it contains literal whitespace we want to retain. while (*cp == '*') { ++cp; switch (toupper(*cp)) { case 'W': width = ATOI(cp + 1); break; case 'H': height = ATOI(cp + 1); break; default: if (!_strnicmp(cp, "Icon", 4)) { cp += 4; // Now it's the character after the word. icon_number = ATOI(cp); // LoadPicture() correctly handles any negative value. } else if (!_strnicmp(cp, "Trans", 5)) { cp += 5; // Now it's the character after the word. // Isolate the color name/number for ColorNameToBGR(): strlcpy(color_name, cp, sizeof(color_name)); if (dp = StrChrAny(color_name, " \t")) // Find space or tab, if any. *dp = '\0'; // Fix for v1.0.44.10: Treat trans_color as containing an RGB value (not BGR) so that it matches // the documented behavior. In older versions, a specified color like "TransYellow" was wrong in // every way (inverted) and a specified numeric color like "Trans0xFFFFAA" was treated as BGR vs. RGB. trans_color = ColorNameToBGR(color_name); if (trans_color == CLR_NONE) // A matching color name was not found, so assume it's in hex format. // It seems strtol() automatically handles the optional leading "0x" if present: trans_color = strtol(color_name, NULL, 16); // if color_name did not contain something hex-numeric, black (0x00) will be assumed, // which seems okay given how rare such a problem would be. else trans_color = bgr_to_rgb(trans_color); // v1.0.44.10: See fix/comment above. } else // Assume it's a number since that's the only other asterisk-option. { aVariation = ATOI(cp); // Seems okay to support hex via ATOI because the space after the number is documented as being mandatory. if (aVariation < 0) aVariation = 0; if (aVariation > 255) aVariation = 255; // Note: because it's possible for filenames to start with a space (even though Explorer itself // won't let you create them that way), allow exactly one space between end of option and the // filename itself: } } // switch() if ( !(cp = StrChrAny(cp, " \t")) ) // Find the first space or tab after the option. #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH error="It failed at nr 1, errorlevel is: "+ErrorLevel; return error.c_str(); #else return "0"; //new #endif // return OK; // Bad option/format. Let ErrorLevel tell the story. // Now it's the space or tab (if there is one) after the option letter. Advance by exactly one character // because only one space or tab is considered the delimiter. Any others are considered to be part of the // filename (though some or all OSes might simply ignore them or tolerate them as first-try match criteria). aImageFile = ++cp; // This should now point to another asterisk or the filename itself. // Above also serves to reset the filename to omit the option string whenever at least one asterisk-option is present. cp = omit_leading_whitespace(cp); // This is done to make it more tolerant of having more than one space/tab between options. } // Update: Transparency is now supported in icons by using the icon's mask. In addition, an attempt // is made to support transparency in GIF, PNG, and possibly TIF files via the *Trans option, which // assumes that one color in the image is transparent. In GIFs not loaded via GDIPlus, the transparent // color might always been seen as pure white, but when GDIPlus is used, it's probably always black // like it is in PNG -- however, this will not relied upon, at least not until confirmed. // OLDER/OBSOLETE comment kept for background: // For now, images that can't be loaded as bitmaps (icons and cursors) are not supported because most // icons have a transparent background or color present, which the image search routine here is // probably not equipped to handle (since the transparent color, when shown, typically reveals the // color of whatever is behind it; thus screen pixel color won't match image's pixel color). // So currently, only BMP and GIF seem to work reliably, though some of the other GDIPlus-supported // formats might work too. int image_type; HBITMAP hbitmap_image = LoadPicture(aImageFile, width, height, image_type, icon_number, false); // The comment marked OBSOLETE below is no longer true because the elimination of the high-byte via // 0x00FFFFFF seems to have fixed it. But "true" is still not passed because that should increase // consistency when GIF/BMP/ICO files are used by a script on both Win9x and other OSs (since the // same loading method would be used via "false" for these formats across all OSes). // OBSOLETE: Must not pass "true" with the above because that causes bitmaps and gifs to be not found // by the search. In other words, nothing works. Obsolete comment: Pass "true" so that an attempt // will be made to load icons as bitmaps if GDIPlus is available. if (!hbitmap_image) #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH error="It failed at nr 2, errorlevel is: "+ErrorLevel; return error.c_str(); #else return "0"; // new #endif // return OK; // Let ErrorLevel tell the story. HDC hdc = GetDC(NULL); if (!hdc) { DeleteObject(hbitmap_image); #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH error="It failed at nr 3, errorlevel is: "+ErrorLevel; return error.c_str(); #else return "0"; // new #endif // return OK; // Let ErrorLevel tell the story. } // From this point on, "goto end" will assume hdc and hbitmap_image are non-NULL, but that the below // might still be NULL. Therefore, all of the following must be initialized so that the "end" // label can detect them: HDC sdc = NULL; HBITMAP hbitmap_screen = NULL; LPCOLORREF image_pixel = NULL, screen_pixel = NULL, image_mask = NULL; HGDIOBJ sdc_orig_select = NULL; bool found = false; // Must init here for use by "goto end". bool image_is_16bit; LONG image_width, image_height; if (image_type == IMAGE_ICON) { // Must be done prior to IconToBitmap() since it deletes (HICON)hbitmap_image: ICONINFO ii; if (GetIconInfo((HICON)hbitmap_image, &ii)) { // If the icon is monochrome (black and white), ii.hbmMask will contain twice as many pixels as // are actually in the icon. But since the top half of the pixels are the AND-mask, it seems // okay to get all the pixels given the rarity of monochrome icons. This scenario should be // handled properly because: 1) the variables image_height and image_width will be overridden // further below with the correct icon dimensions; 2) Only the first half of the pixels within // the image_mask array will actually be referenced by the transparency checker in the loops, // and that first half is the AND-mask, which is the transparency part that is needed. The // second half, the XOR part, is not needed and thus ignored. Also note that if width/height // required the icon to be scaled, LoadPicture() has already done that directly to the icon, // so ii.hbmMask should already be scaled to match the size of the bitmap created later below. image_mask = getbits(ii.hbmMask, hdc, image_width, image_height, image_is_16bit, 1); DeleteObject(ii.hbmColor); // DeleteObject() probably handles NULL okay since few MSDN/other examples ever check for NULL. DeleteObject(ii.hbmMask); } if ( !(hbitmap_image = IconToBitmap((HICON)hbitmap_image, true)) ) #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH return "It failed at nr 4"; #else return "0"; //new #endif // return OK; // Let ErrorLevel tell the story. } if ( !(image_pixel = getbits(hbitmap_image, hdc, image_width, image_height, image_is_16bit)) ) goto end; // Create an empty bitmap to hold all the pixels currently visible on the screen that lie within the search area: int search_width = aRight - aLeft + 1; int search_height = aBottom - aTop + 1; if ( !(sdc = CreateCompatibleDC(hdc)) || !(hbitmap_screen = CreateCompatibleBitmap(hdc, search_width, search_height)) ) goto end; if ( !(sdc_orig_select = SelectObject(sdc, hbitmap_screen)) ) goto end; // Copy the pixels in the search-area of the screen into the DC to be searched: if ( !(BitBlt(sdc, 0, 0, search_width, search_height, hdc, aLeft, aTop, SRCCOPY)) ) goto end; LONG screen_width, screen_height; bool screen_is_16bit; if ( !(screen_pixel = getbits(hbitmap_screen, sdc, screen_width, screen_height, screen_is_16bit)) ) goto end; LONG image_pixel_count = image_width * image_height; LONG screen_pixel_count = screen_width * screen_height; int i, j, k, x, y; // Declaring as "register" makes no performance difference with current compiler, so let the compiler choose which should be registers. // If either is 16-bit, convert *both* to the 16-bit-compatible 32-bit format: if (image_is_16bit || screen_is_16bit) { if (trans_color != CLR_NONE) trans_color &= 0x00F8F8F8; // Convert indicated trans-color to be compatible with the conversion below. for (i = 0; i < screen_pixel_count; ++i) screen_pixel[i] &= 0x00F8F8F8; // Highest order byte must be masked to zero for consistency with use of 0x00FFFFFF below. for (i = 0; i < image_pixel_count; ++i) image_pixel[i] &= 0x00F8F8F8; // Same. } // v1.0.44.03: The below is now done even for variation>0 mode so its results are consistent with those of // non-variation mode. This is relied upon by variation=0 mode but now also by the following line in the // variation>0 section: // || image_pixel[j] == trans_color // Without this change, there are cases where variation=0 would find a match but a higher variation // (for the same search) wouldn't. for (i = 0; i < image_pixel_count; ++i) image_pixel[i] &= 0x00FFFFFF; // Search the specified region for the first occurrence of the image: if (aVariation < 1) // Caller wants an exact match. { // Concerning the following use of 0x00FFFFFF, the use of 0x00F8F8F8 above is related (both have high order byte 00). // The following needs to be done only when shades-of-variation mode isn't in effect because // shades-of-variation mode ignores the high-order byte due to its use of macros such as GetRValue(). // This transformation incurs about a 15% performance decrease (percentage is fairly constant since // it is proportional to the search-region size, which tends to be much larger than the search-image and // is therefore the primary determination of how long the loops take). But it definitely helps find images // more successfully in some cases. For example, if a PNG file is displayed in a GUI window, this // transformation allows certain bitmap search-images to be found via variation==0 when they otherwise // would require variation==1 (possibly the variation==1 success is just a side-effect of it // ignoring the high-order byte -- maybe a much higher variation would be needed if the high // order byte were also subject to the same shades-of-variation analysis as the other three bytes [RGB]). for (i = 0; i < screen_pixel_count; ++i) screen_pixel[i] &= 0x00FFFFFF; for (i = 0; i < screen_pixel_count; ++i) { // Unlike the variation-loop, the following one uses a first-pixel optimization to boost performance // by about 10% because it's only 3 extra comparisons and exact-match mode is probably used more often. // Before even checking whether the other adjacent pixels in the region match the image, ensure // the image does not extend past the right or bottom edges of the current part of the search region. // This is done for performance but more importantly to prevent partial matches at the edges of the // search region from being considered complete matches. // The following check is ordered for short-circuit performance. In addition, image_mask, if // non-NULL, is used to determine which pixels are transparent within the image and thus should // match any color on the screen. if ((screen_pixel[i] == image_pixel[0] // A screen pixel has been found that. { // Check if this candidate region -- which is a subset of the search region whose height and width // matches that of the image -- is a pixel-for-pixel match of the image. for (found = true, x = 0, y = 0, j = 0, k = i; j < image_pixel_count; ++j) { if (!(found = (screen_pixel[k] == image_pixel[j] // At least one pixel doesn't match, so this candidate is discarded. || image_mask && image_mask[j] // Or: It's an icon's transparent pixel, which matches any color. || image_pixel[j] == trans_color))) // This should be okay even if trans_color==CLR_NONE, since CLR none should never occur naturally in the image. break;. // Move to the next row within the current-candiate region (not the entire search region). // This is done by moving vertically downward from "i" (which is the upper-left pixel of the // current-candidate region) by "y" rows. k = i + y*screen_width; // Verified correct. } } if (found) // Complete match found. break; } } } else // Allow colors to vary by aVariation shades; i.e. approximate match is okay. { // The following section is part of the first-pixel-check optimization that improves performance by // 15% or more depending on where and whether a match is found. This section and one the follows // later is commented out to reduce code size. // Set high/low range for the first pixel of the image since it is the pixel most often checked // (i.e. for performance). //BYTE search_red1 = GetBValue(image_pixel[0]); // Because it's RGB vs. BGR, the B value is fetched, not R (though it doesn't matter as long as everything is internally consistent here). //BYTE search_green1 = GetGValue(image_pixel[0]); //BYTE search_blue1 = GetRValue(image_pixel[0]); // Same comment as above. //BYTE red_low1 = (aVariation > search_red1) ? 0 : search_red1 - aVariation; //BYTE green_low1 = (aVariation > search_green1) ? 0 : search_green1 - aVariation; //BYTE blue_low1 = (aVariation > search_blue1) ? 0 : search_blue1 - aVariation; //BYTE red_high1 = (aVariation > 0xFF - search_red1) ? 0xFF : search_red1 + aVariation; //BYTE green_high1 = (aVariation > 0xFF - search_green1) ? 0xFF : search_green1 + aVariation; //BYTE blue_high1 = (aVariation > 0xFF - search_blue1) ? 0xFF : search_blue1 + aVariation; // Above relies on the fact that the 16-bit conversion higher above was already done because like // in PixelSearch, it seems more appropriate to do the 16-bit conversion prior to setting the range // of high and low colors (vs. than applying 0xF8 to each of the high/low values individually). BYTE red, green, blue; BYTE search_red, search_green, search_blue; BYTE red_low, green_low, blue_low, red_high, green_high, blue_high; // The following loop is very similar to its counterpart above that finds an exact match, so maintain // them together and see above for more detailed comments about it. for (i = 0; i < screen_pixel_count; ++i) { // The following is commented out to trade code size reduction for performance (see comment above). //red = GetBValue(screen_pixel[i]); // Because it's RGB vs. BGR, the B value is fetched, not R (though it doesn't matter as long as everything is internally consistent here). //green = GetGValue(screen_pixel[i]); //blue = GetRValue(screen_pixel[i]); //if ((red >= red_low1 && red <= red_high1 // && green >= green_low1 && green <= green_high1 // && blue >= blue_low1 && blue <= blue_high1 // All three color components are a match, so this screen pixel. // Instead of the above, only this abbreviated check is done: if (image_height <= screen_height - i/screen_width // Image is short enough to fit in the remaining rows of the search region. && image_width <= screen_width - i%screen_width) // Image is narrow enough not to exceed the right-side boundary of the search region. { // Since the first pixel is a match, check the other pixels. for (found = true, x = 0, y = 0, j = 0, k = i; j < image_pixel_count; ++j) { search_red = GetBValue(image_pixel[j]); search_green = GetGValue(image_pixel[j]); search_blue = GetRValue(image_pixel[j]); SET_COLOR_RANGE red = GetBValue(screen_pixel[k]); green = GetGValue(screen_pixel[k]); blue = GetRValue(screen_pixel[k]); if (!(found = red >= red_low && red <= red_high && green >= green_low && green <= green_high && blue >= blue_low && blue <= blue_high || image_mask && image_mask[j] // Or: It's an icon's transparent pixel, which matches any color. || image_pixel[j] == trans_color)) // This should be okay even if trans_color==CLR_NONE, since CLR_NONE should never occur naturally in the image. break; // At least one pixel doesn't match, so this candidate is discarded.. k = i + y*screen_width; // Verified correct. } } if (found) // Complete match found. break; } } } //if (!found) // Must override ErrorLevel to its new value prior to the label below. // g_ErrorLevel->Assign(ERRORLEVEL_ERROR); // "1" indicates search completed okay, but didn't find it. end: // If found==false when execution reaches here, ErrorLevel is already set to the right value, so just // clean up then return. ReleaseDC(NULL, hdc); DeleteObject(hbitmap_image); if (sdc) { if (sdc_orig_select) // i.e. the original call to SelectObject() didn't fail. SelectObject(sdc, sdc_orig_select); // Probably necessary to prevent memory leak. DeleteDC(sdc); } if (hbitmap_screen) DeleteObject(hbitmap_screen); if (image_pixel) free(image_pixel); if (image_mask) free(image_mask); if (screen_pixel) free(screen_pixel); if (!found) // Let ErrorLevel, which is either "1" or "2" as set earlier, tell the story. #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH error="It failed at nr 5, errorlevel is: "+ErrorLevel; return error.c_str(); #else return "0"; #endif // Otherwise, success. Calculate xpos and ypos of where the match was found and adjust // coords to make them relative to the position of the target window (rect will contain // zeroes if this doesn't need to be done): //if (output_var_x && !output_var_x->Assign((aLeft + i%screen_width) - rect.left)) // return FAIL; //if (output_var_y && !output_var_y->Assign((aTop + i/screen_width) - rect.top)) // return FAIL; int locx,locy; //return g_ErrorLevel->Assign(ERRORLEVEL_NONE); // Indicate success. if (found) { locx = (aLeft + i%screen_width) - rect.left; locy = (aTop + i/screen_width) - rect.top; // printf("\nFOUND!!!!%d %d",locx,locy); sprintf_s(answer,"1|%d|%d|%d|%d",locx,locy,image_width,image_height); return answer; //return "ZZ"; } #ifdef HHB_PRINT_FAIL_IMAGE_SEARCH error="It failed at nr 6, errorlevel is: "+ErrorLevel; return error.c_str(); #else return "0"; #endif } i guess it would be more informative.. in ImageSearch.au3 replace if $result[0]="0" then return 0 if IsArray($result) Then MsgBox("teddybear2", "teddy title2","it IS an array, and it returned:"+$result+"") if $result[0]="0" then return 0 Else MsgBox("teddybear2", "teddy title2","it is NOT an array, and it returned:"+$result+"") if $result="0" then return 0 EndIf could someone __WITH THE PROBLEM__ test and post the results? Attached Files Edited by HansHenrik, 26 January 2010 - 07:33 PM. #77 Posted 28 January 2010 - 01:36 AM Edited by kjmarket, 28 January 2010 - 01:44 AM. #78 Posted 28 January 2010 - 10:34 PM #79 Posted 02 February 2010 - 08:27 PM #80 Posted 02 February 2010 - 08:32 PM can used images from resource to imagesearch.au3 ?? No unless somebody skilled make modification to this DLL. Look at post #50 here 2 user(s) are reading this topic 0 members, 2 guests, 0 anonymous users
http://www.autoitscript.com/forum/topic/65748-image-search-library/page-4
CC-MAIN-2013-20
refinedweb
9,372
56.35
By mswatcher via fastchicken.co.nz Published: Dec 16 2012 / 02:28. Tweet SaveShareSend Tags: .net, frameworks, other languages, reviews Voters For This Link (18) mswatcher aclarke ksh2dzone Martyr2 OtengiM bbraithwaite dt80257 yakkoh PrasadHonrao yGuy michal.lipski@n.pl esjr.pip.verisignlabs.com connornort daved150 Topnotch punitganshani Rogue Modron Neerajbhusare Miloskov replied ago: C# rocks, If I will do WinRT I will use C#. joesoap2000 replied ago: What is WinRT? sproketboy replied ago: Exactly. devdanke replied ago: Anders Hejlsberg is a great language designer. C# is a very good language that has benefited more than just C# programmers. C# is superior to Java in some ways. One thing I really like is its unified type system. And C#'s generics is better than Java's half-baked type-erasure generics. The whole .NET platform helped fuel the multiple languages that now run well on the JVM. Before .NET only Java and a poor implementation of Python ran on the JVM. What hurt C# is Microsoft's narrow minded focus on maintaining the Windows monopoly. Because of this Microsoft never allowed .NET/C# to succeed on other OSs. Yet doing so would have made more programmers learn and use .NET/C#. joesoap2000 replied ago: Java and C# have both lost a lot of their appeal, as they are no longer seen as cutting edge or new. These days all the excitement is around the next generation JVM language (Scala), and scripting languages like Python. For better or worse that's where things are at. sproketboy replied ago: Don't kid yourself. C# has it's own set of poor designs and the jvm has many advantages over .net. yakkoh replied ago: Interesting: can you be more specific about 'advantages'? sproketboy replied ago: A single unified binary. 64 bit for free. The ability to have multiple entry points for an executable. Guarantees on number precision etc across platforms. Guarantees on atomicity across platforms. Better long term compatibility. Runs more languages. Real-time implementation. etc... etc... etc... devent replied ago: C# is over-bloated and over-complicated. At least Java Generics are compatible, you don't need two types of Collection libraries like in C#. Who need a struct in a high-level language? Java solved the problem with namespaces better. Java have Ant, Maven, Grandle, Java have more and better open source libraries and tools. C# is Java + C++ + a lot of stuff nobody needs. Like delegates, #region, event. C# have the worst ever: XML as documentation. I really like to write lots and lots of < > when I write documentation. In Java you have at least the javadoc tags: {@code }.
http://www.dzone.com/links/c_is_dead_again_long_live_c.html
CC-MAIN-2014-41
refinedweb
438
69.68
This is partly a spoiler for my “Making Java Groovy” talk that I normally do at NFJS events and plan to use in my similar talk at JavaOne, but to celebrate the book going to the printer I thought I’d try to contribute something technical here. I’ve always felt that one of the keys to understanding Groovy was operator overloading. Operator overloading has a mixed reputation, conjuring up horror stories of developers changing + to be *, which might be good for job security but not good in general. (Ultimately it’s not be good for job security, either.) To be honest, I don’t do a lot of operator overloading in my own code, but I take advantage of it all the time. Most Groovy developers don’t realize how thoroughly operator overloading occurs throughout the Groovy JDK, among other places. This web page lists all the operators in Groovy and their corresponding methods. What’s easy to overlook, however, is that every operator in Groovy actually invokes a method. That table doesn’t just provide you with options — it’s what’s actually happening under the hood. Note that it’s not just operators like + or * that call methods. Array-like access (the [] operator) calls getAt and putAt on maps, and even == invokes the equals method. (Actually, == invokes the compareTo method if the class happens to implement java.util.Comparable, but according to the Comparable contract that ought to be equivalent.) The code simplifications that result are dramatic. For example, consider the plus method in java.util.Date, which takes an int representing the number of days: [sourcecode language=”groovy”] Date now = new Date() Date then = now + 3 assert 4 == (now..then).size() [/sourcecode] It’s also why you can not only concatenate with strings using +, you can also subtract substrings from them using the minus operator: [sourcecode language=”groovy”] String s = ‘silly string’ assert ‘more silly string’ == ‘more ‘ + s assert ‘string’ == s – ‘silly ‘ [/sourcecode] Note that in each case, the operator is returning a new string rather than modifying the original. Strings are still immutable, even in Groovy. Let me give a larger example that uses Groovy / Java integration to make coding easier. If you’ve ever done financial calculations in Java (or if you’ve ever seen Office Space), you know you need to use java.math.BigDecimal for the amounts rather than just doubles. But BigDecimal in Java is an annoying class to work with, because (1) you have to instantiate it, (2) you have to remember to use the constructor that takes a String, or the results are not predictable (see the JavaDocs for details), and (3) you lose all your operators and have to use all the associated method calls, keeping in mind that (4) all instances of the class are immutable. That makes for a rather verbose class when all you want is to wrap a numerical value. You can do all that, or you can take advantage of the fact that the native data type for floating point values in Groovy is already BigDecimal. Not only that, but the Groovy JDK includes methods like plus, minus, and multiply in the java.lang.Number class (the superclass of BigDecimal), so you can use your normal operators. The result is a class like: [sourcecode language=”groovy”] package com.mjg import groovy.transform.Canonical @Canonical class Account { BigDecimal balance = 0.0 BigDecimal deposit(BigDecimal amount) { balance += amount } BigDecimal withdraw(BigDecimal amount) { balance -= amount } } [/sourcecode] The only attribute is the balance, stored as a BigDecimal, initialized to zero. Since the attribute lacks a public or private modifier, Groovy automatically generates public getter and setter methods for it. The deposit and withdraw methods take advantage of operator overloading to update the balance using simple + and – operators. Finally, the Canonical AST transformation adds equals, hashCode, and toString methods to Account, as well as a “tuple” constructor that can be called from Java. That’s a lot of mileage for 16 lines of code. Before I use it from Java, let me verify that it works so far: [sourcecode language=”groovy”] package com.mjg // Normal Groovy ctor that sets the property Account acct = new Account(balance:250) assert 250 == acct.balance assert 300 == acct.deposit(50) assert 200 == acct.withdraw(100) // check the tuple ctor acct = new Account(150) assert 150 == acct.balance // toString method assert ‘com.mjg.Account(150)’ == acct.toString() // equals and hashCode Set accounts = [new Account(balance:250), new Account(250)] assert accounts.size() == 1 [/sourcecode] Accounts can be created using the normal map-based constructor or the tuple constructor, which in this case has only a single argument (because the class has a single attribute). Accessing the balance property actually invokes the getBalance method, which is supplied by Groovy automatically. The generated toString method is as shown, and to prove that both equals and hashCode are working I added two identical accounts (instantiated by either constructor) into a Set and verified that Groovy added only one of them. That’s all well and good, but if I can’t verify a Groovy class using Groovy tests, I might as well give it up. Instead, I want to access the Groovy class from Java. Here, therefore, is a highly contrived Bank class, in Java: [sourcecode language=”java”] package com.mjg; import java.math.BigDecimal; public class Bank { public Account openAccount(double initialBalance) { Account acct = new Account(); acct.deposit(new BigDecimal(initialBalance + "")); return acct; } public BigDecimal getBalance(Account acct) { return acct.getBalance(); } public BigDecimal addFunds(Account acct, double amount) { return acct.deposit(new BigDecimal(amount + "")); } public BigDecimal removeFunds(Account acct, double amount) { return acct.withdraw(new BigDecimal(amount + "")); } } [/sourcecode] The Bank has a method to open an account using a double, which is wrapped in a BigDecimal using the String-based constructor. Then addFunds and removeFunds just delegate to the associated methods in Account. To test this, I might as well switch back to Groovy again, but in a normal JUnit test: [sourcecode language=”groovy”] package com.mjg import static org.junit.Assert.*; import org.junit.Test; class BankTests { Bank bank = new Bank() Account acct = bank.openAccount(250); @Test void testOpenAccount() { assert acct } @Test void testGetBalance() { assert 250 == bank.getBalance(acct) } @Test void testAddFunds() { bank.addFunds(acct, 50) assert 300 == bank.getBalance(acct) } @Test void testRemoveFunds() { bank.removeFunds(acct, 100) assert 150 == bank.getBalance(acct) } } [/sourcecode] All the tests work without a problem, demonstrating how easy it is to switch from Groovy to Java and back again. If you ever have to add code to an existing Java system that involves BigDecimal, writing a class in Groovy is a very easy way to do it. In my book, incidentally, the chapter on Spring and Groovy uses a similar Account class, but with an added id. Then I implement an AccountDAO interface (written in Java, of course) using the a Groovy class that takes advantage of Spring’s JdbcTemplate (again from Java), complete with Spock tests. If you want to see the source code now, just check out ch07 in the GitHub repository for the book. As in this example, when I code in Groovy I don’t often do operator overloading, but the effects of it show up everywhere. Hopefully these simple examples will help you take advantage of it in the future. BTW, I received notice from Manning that I will have actual hard copies of Making Java Groovy at the SpringOne2GX conference next week. Even if you don’t want one, please come by and say hello. Don’t be surprised if I can’t stop grinning the entire time.
https://kousenit.org/2013/09/03/making-java-groovy-operator-overloading/
CC-MAIN-2020-29
refinedweb
1,266
55.03
I am trying to share the weights in different layers in one model. Please take a look at this example code: this code tries to share weights in fc1 and some parts of fc2 import torch import torch.nn as nn import torch.optim as optim class testModule(nn.Module): def __init__(self): super(testModule, self).__init__() self.fc1 = nn.Linear(5, 10, bias=True) self.fc2 = nn.Linear(10, 10, bias=False) self.shared_weights = nn.Parameter(torch.randn(10, 5), requires_grad=True) def forward(self, x): x = self.fc1(x) x = self.fc2(x) return x def share_weight(self): index = [1, 3, 5, 7, 9] self.fc1.weight.data = self.shared_weights self.fc2.weight.data[:, index] = self.shared_weights After calling the .share_weight() method and training, the weight in fc1.weight and fc2.weight[:, index] become different. Why would this happen and what is the behavior behind assigning weight.data as another tensor. How could I reach the goal of sharing fc1.weight and fc2.weight[:, index] in training.
https://discuss.pytorch.org/t/how-to-use-shared-weights-in-different-layers-of-a-model/71263/2
CC-MAIN-2022-33
refinedweb
169
64.88
- for each center we identify the subset of training points (its cluster) that is closer to it than any other center; - the means of each feature for the data points in each cluster are computed, and this mean vector becomes the new center for that cluster. The Scipy library provides a good implementation of the K-Means algorithm. Let's see how to use it: from pylab import plot,show from numpy import vstack,array from numpy.random import rand from scipy.cluster.vq import kmeans,vq # data generation data = vstack((rand(150,2) + array([.5,.5]),rand(150,2))) # computing K-Means with K = 2 (2 clusters) centroids,_ = kmeans(data,2) # assign each sample to a cluster idx,_ = vq(data,centroids) # some plotting using numpy's logical indexing plot(data[idx==0,0],data[idx==0,1],'ob', data[idx==1,0],data[idx==1,1],'or') plot(centroids[:,0],centroids[:,1],'sg',markersize=8) show()The result should be as follows: In this case we splitted the data in 2 clusters, the blue points have been assigned to the first and the red ones to the second. The squares are the centers of the clusters. Let's see try to split the data in 3 clusters: # now with K = 3 (3 clusters) centroids,_ = kmeans(data,3) idx,_ = vq(data,centroids) plot(data[idx==0,0],data[idx==0,1],'ob', data[idx==1,0],data[idx==1,1],'or', data[idx==2,0],data[idx==2,1],'og') # third cluster points plot(centroids[:,0],centroids[:,1],'sm',markersize=8) show()This time the the result is as follows: Your blog is awesome and has helped me discover all kinds of useful tidbits in scipy and numpy. Thank you! Thanks for the post. I have used kmeans to identify clusters (rings) in a matrix of sea surface height. The objective is to identify the rings and to determine their centroids. But kmeans requires as input parameter the number of clusters to be sought. That is a problem because I usually do not know previously how many rings will be present in the area. So, I was wondering how to avoid this kmeans limitation. Do you have any idea? Regards, Alex Hello Alexandre, how to find a good choice for k is a studied problem in machine learning. I suggest you to read this paper: Thanks for your comment! from where did you get the module "from scipy.cluster.vq import kmeans,vq"? where can I get it? this stuff looks great, btw. It come with the scipy installation: Excellent blog, JG. I love it. I use it and recommend it to others. One question. Many of the k-means tutorials that I've found rely on self-made, perfectly configured data -- i.e., they'll "generate" numbers in just the form necessary to get an easy k-means clustering. Whereas in the real world many of us are using k-means to cluster documents (using NLP) or other information that requires a great deal of work/formatting before we can even use k-means. For example, on documents first one must create a vector (tf-idf for instance) and then complete a similarity measurement (euclidean for instance). Thus, the greatest challenge to performing a k-means is often just getting the data into a format that the kmeans calls can work with. For instance, tutorials always seem to have their data in the following list-within-a-list format:[[number1, number2], [number1, number2], [number1, number2], [number1, number2]... ]. How would you recommend getting documents (i.e., natural language) into that format? Note that cosine similarity performed on a tf-idf vector always returns a single list, which isn't "clusterable" (to my knowledge). Any help appreciated and thank you in advance for all of your work. Hello, You could take a look to the vector space models. Those models make you able to build a fixed length vector using the frequencies of some words you're interested in. This post is a good introduction: I'll check it out. Thanks much, JG. i am not able to view the result what can be done.. show() command is not working sorted out.. Excellent! Help me much to understand k-means clustering. Is it possible to use this in a capacitated-VRP (vehicle routing problem) ? In which, each node has "demand", and there is a fixed vehicle's "capacity". Subject to: sum of all node's demands (in a cluster) is smaller-or-equal to vehicle's capacity. Any helps very much appreciated. Thank you. I mean as explained in here, "Cluster-First Route-Second Method" Thanks... This is excellent material, and your code explaining how to use the scipy implementation is beautiful and clear. Just recently I've implemented the algorithm in python myself, it's a lot of fun to play around with configurations to see the clustering in action: Could you please discuss a bit the role of 'whitening' which seems to be kind of highly reccommended by the scipy tutorial? Hi, you can find some general information about the whitening transformation here: Usually, when you have a data matrix, you use whitening in order to have unit variance across all the samples. This operation could improve the result of the k-means algorithm. Thank you very much for your post, it's very helpful. Here, your dataset has two variables that you partition into 2 and then 3 clusters, so it makes sense to plot the k-means clusters like this, with 1 variable on X-axis and one on the Y-axis. but what about if your dataset has more dimensions? Do you have any suggestions about ways to look at the output under these circumstances? Thanks, SS Hi, if you have more than two variables and you need to visualize your data in a 2D space, you need a dimensionality reduction method. Here's an example on how to use Isomap: Interesting, I'll check it out. Thanks for the speedy response! This comment has been removed by the author. This post has been very helpful. Thank you very much If I would like say 100 clusters from k-means, too many to do the plotting by hand as you have in this example, how would you visualise/plot the results from the clustering? You have to defined a list with a color for each cluster and plot each cluster separately with a for loop choosing the appropriate color each time. Great post. Do you know of anything similar that can find clusters in 3D space? For example, I have a set of particles each with x, y, z co-ordinates. How would I go about finding clusters (of various densities) in such a dataset? Any thoughts or ideas? kmeans works in 3D spaces. You just have to modify the input matrix. Fantastic. Will investigate it further. Thanks. Nice demonstration. But can you tell me how to use this scipy.cluster.vq module to generate codebook for an array of mfcc feature vectors. I've extracted the MFCC feature vectors (13 coefficients) ...now i wish to use vq to perform pattern matching stuff. any idea ? Of course, you could cluster your MFCC vectors in order to find similarities in some parts of your signal. But the applications that you can realize are related to the kind of signal you have (speech, music, ...). This comment has been removed by a blog administrator. Hi I have a problem using k-mean clustering with scipy. I have a set of data as x-axis and y-axis [[-0.0365, 0.0121], [ 0.0623, -0.0019], [ 0.0352, -0.0007], [ 0.0609, -0.0096]] If i use the k-mean function from matlab it clusters it properly(i mean as it is expected) i.e 1st row and last row comes under one cluster and middle two rows comes under one cluster. But, when i use scipy as it is told in this blog, results are not as expected i.e 1st row comes under one cluster and last 3 rows comes under another cluster. Can any one pls tell me why is it so? Tnx in advance:) Hi Shambhulingayya, just try to plot your data. You'll see that your first sample is an outlier (it's even the only one with a negative x and a positive y) and that the other 3 samples are close each other. The clustering provided by scipy makes more sense to me. Well, BTW FYI, I am using it for pattern recognition. The data sets i mentioned above are the output from the PCA(reduced dimensional dataset). But, in reality my patterns which i know by it's appearances are, (1st and 4th) are similar and (2nd and 4th are similar). Why i am doubting this because, if i cluster the same data using matlab then, clustering is happening perfectly right i.e 1st and 4th under one cluster and 2nd and 3rd under another cluster. Any thoughts in this...? FYI, here r the K-mean output of matlab and python which differ each other for same data set Matlab - Python - Try to use the same starting centroids and the same number of iterations on both the implementations. This comment has been removed by the author. Very Informative Blog! Could you please tell me how to identify which cluster stands for what? For eg, if I have 4 features for t-shirt sizes (age, weight, height, gender) and if I get 3 clusters, how to find which cluster out of the 3 stands for small size, medium size and large size? The values of the centroids represent your variables. If you look at them you will be able to understand which centroid represents the size of the related cluster. I am new to scipy. Can any one tell me how do I extract the data points belonging to each cluster? Here is the code- data = vstack(arr1) centroids,_ = kmeans(data,4) idx,_ = vq(data,centroids) plot(data[idx==0,0],data[idx==0,1],'ob',data[idx==1,0],data[idx==1,1],'or',data[idx==2,0],data[idx==2,1],'og',data[idx==3,0],data[idx==3,1],'oy') plot(centroids[:,0],centroids[:,1],'sg',markersize=8) Thank you so much for this writeup. It has helped me dip my toes into kmeans and scipy. I look forward to continuing. I had one quick question about labeling points. I have k=8 as my best fit for my data, and can differentiate the clusters well. I imported data from a pandas dataframe with an index, then subsequently into a numpy array to perform clustering and plotting-by-idx. Can you suggest a method to take the index.values from the dataframe and label the plot accordingly so I can associate the specific points with their sample of origin? I BDavis, DataFrame has the attribute index which gives what you probably want. Thank you for the prompt reply! I am able to obtain the ordered index, no problem. I am having difficulty integrating the sample titles contained within with the logical index plotting methods you implement. I was trying to iterate over it in a list, but associating it with the coordinates within the cluster data is elusive. What is the similarity measure of this implementation of k-means? Thank you. Hi, this algorithm uses the euclidian distance. Hey. Is it possible to use some other metrics like Pearson correlation? Or can I use precalculated distance matrix for the clustering? Hi L, not with this implementation. Works perfectly for me. thanks hey Every time you perform the algo, the centroid number happens to change making the plots colouring different at every run. Does anybody knows how to fix that? Thank you The initial centroid are randomly chosen. You can fix the initial random seed using this function: numpy.random.seed Thanks a lot, It's a nice trick. Another question, when you get the centroids from the "whiten" data, how do you get back the real values for these centroids? ... maybe not clear as a question It depends on how you "whithen" your data. If you simply removed the mean and divided by the standard deviation, you can just multiply by the old standard deviation and add the old mean again. Ok, I used python whiten which just divide each column by its std ... I thought it subtract the mean firstly to get a standard score... Thats why I couldnt get back to my real data. Thanks a lot ! Can you teach me how to do a Texture-based image segmentation using Kmeans clustering Hi, have a look at this post: is there any posts about how to create a filter bank by using Scipy function? No, sorry :) Is it possible to use Mahalanobis distance instead euclidean distance for K-means clustering ? Is it possible to use Mahalanobis distance instead euclidean distance for K-means clustering ? Hi pra, scipy doesn't allow you to specify a custom distance function, but you may want to give a look to this answer: Such a great example! Anyway, i have one question. Can we use k-means for clustering a connected undirected graph? There are variants of k-means that work on graphs, I suggestion you to have a look at the library networkx.
http://glowingpython.blogspot.it/2012/04/k-means-clustering-with-scipy.html
CC-MAIN-2017-30
refinedweb
2,237
65.12
Component libraries are great resources when it comes to developing React-based applications. They allow you to logically group your components in a way that lets others in your team explore them and pick & choose the ones they need. Component libraries are great resources when it comes to developing React-based applications. They allow you to logically group your components in a way that lets others in your team explore them and pick & choose the ones they need. Mind you, there are quite a lot of libraries out there already for you to re-use. But if you’re working on your own custom components then keeping them inside your own library is definitely what you’ll want to do. Worry not though, there are several options out there to help you in this task, so you don’t have to manually maintain a collection of possibly hundreds of components. And the best part? In this article, I’m going to tell you about three of them. Bit is a tool and platform for component collaboration. It offers a quick and easy way to isolate, test and then export your components to a collection on bit.dev. Components on bit.dev can be found using Bit’s search engine and rendered-live in Bit’s playground. Example: Bit’s live playground Out of the three ways to build your own React component library, Bit is the only one that offers a “natural” way to share your components with others. Mind you, the library is just code, and you can publish it into a place such as Github (and package to NPM). That would definitely solve that problem, but you’d be hard-press to publish the entire library into a single repository or have (and manage) one for each component (that is, if you’re hoping to let your consumers pick and choose which ones to use). So instead, you can use Bit.dev and have all your individual components published into a single catalog (essentially a components library) with minimum effort and have your consumers pick and choose which ones to import (either through NPM/Yarn or using Bit) with very little effort. Installing the Bit CLI tool is quite easy, simply execute the following command (assuming of course, you have npm installed): $ npm install bit-bin --global Once installed, you can join bit.dev and create a new collection, make sure you select its environment to be React and follow the steps described: $ cd your-project-folder $ bit login $ bit init Answer the required information and then start tracking the components in your library. This is assuming you have a similar folder structure to the previous examples, but feel free to use whatever structure you want (as long as they’re all on the same folder, you’ll have no issues). 2. Track components $ bit add src/components/* $ bit status 3. Configure the build step to be React. This step is required to create the distribution version of your components, which is of especial interest to the consumers interested in your components and for Bit’s platform, since it will also render them automatically for you. $ bit import bit.envs/compilers/react --compiler 4. Finally, tag your components and export them so others can see them and use them. $ bit tag --all 1.0.0 $ bit export <your-username>.<your-projects-name> With that, your components are published and can be used by anyone using npm or yarn like this: $ npm i @bit/<your-username>.<your-library-name>.<your-component-name> Or using yarn: $ yarn add @bit/<your-username>.<your-library-name>.<your-component-name> When it comes to creating your own components library, this particular package brings a lot of power to your terminal. With but a very simple npm installation, you can obtain a very powerful tool. And once installed, it’ll provide you with a very useful template for creating the entire library. Some of the key features of this utility are: Installing this package is extremely easy if you’re familiar with npm, just type the following: $ npm install -g create-react-library If for some reason, you’re not familiar with npm, you can check out how to install it over here. Just like installation, usage of this package is very straightforward, all you need is a simple command. Once executed, it’ll ask a few questions and with that information, it’ll create the required template. $ create-react-libary Yeap, that’s all you need because the actual details about the library you’re looking to create will be provided with the following questions: Now, that created the folder my-personal-library and you can simply execute the following commands (in different tabs) in order to get the project started: [Terminal 1]$ cd my-personal-project && npm start [Terminal 2]$ cd my-personal-project/example && npm start And you want the project to get started, because it’ll provide you with a web UI for you to test the components. Here is what your folder should look like by the end of the above commands: Just add your components into the src folder in order to; create your library and use the example folder to showcase them. If the above template filled with different files from the get-go was too much for you, this combo is the perfect alternative for you. Using these two tools (and maybe others to help you out with the development process) you can create your library from scratch! The basic tech stack you’ll need for that is: You can potentially extend that stack with things like Jest if you wanted to add unit tests capabilities (which you should by the way). The catch with this setup is that for you to gain total control over the code, you’ll be installing a few dependencies. But worry not my friend, lucky for you, the package ecosystem is great and it works like a charm, so it should just be a matter following these steps: $ mkdir react-sample-components-library $ cd react-sample-components-library $ npm init -y 2. Installing dependencies: $ npm install --save-dev react react-dom @emotion/core @emotion/styled $ npm install --save-dev react-styleguidist webpack $ npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react 3. Basic configuration After everything’s been installed, you should create the .babelrc file for and add the following into it: { "presets": ["@babel/preset-env", "@babel/preset-react"] } Finally, create the file styleguide.config.js at the root folder and add the following content: config.js module.exports = { webpackConfig: { module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader" } ] } }, }; Last, but certainly not least, add the following line to your package.json in order to configure the start command: ”start”: “styleguidist server” Now, you can simply write $ npm start and you’ll gain a web server on port 6060 where you can review your progress. With everything set up and configured, adding components into this library is actually quite easy. Just add the files to the src/components folder. As an example, adding the following code into src/components/Button.js automatically adds it to the library. import React from "react"; export default function Button({ text }) { return <button>{text}</button>; } And thanks to Styleguidist you can add a Button.md file into the same folder: A very simple button. import Button from "./Button"; <Button text="We Salute You!" /> With the Markdown and the code, the above documentation is created once you restart the webserver. React Component Libraries are definitely needed if you’re working on a team or hoping to make a cohesive group of components available for others to use. And as you’ve seen, there are plenty of options out there to help you create them. But if you’re really interested in sharing them while you’re also working on improving them, IMHO, Bit is definitely the way to go, since it not only allows you to publish them but it also helps you keep improving them (i.e bug fixing and new features) with minimum effort. Have you used any other tools to create your own react components libraries? Share them in the comments below, I’d love to know! react reactjs javascript programming Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development. One of the core ideas in functional programming is composition: building larger things from smaller things. The canonical example of this idea should be familiar with legos. React Slider: How to Build an Image Slider With React Hooks. Creation of all the components necessary to display an array of content, as well as the ability to navigate back and forth to each slide in our slider. Adding an autoplay feature. We will dive deeper into React Hooks and optimize the slider both for performance and visual appeal. We will achieve this by tapping into useEffect and some new memoization helpers. Welcome, how to create a react menu in Hindi. React js navbar in Hindi in 2020 using React Router Dom..
https://morioh.com/p/815952d1df20
CC-MAIN-2020-40
refinedweb
1,525
52.9
Hi, I have to write tic tac toe for a class and I have never even written a loop. Obviously I haven't put my study time in, but that's besides the point. Can someone please explain to me why this keeps repeating "Please make a selection:" even after I enter 1 or 2? It's probably obvious. Code:#include <iostream> #include <string> using namespace std; void printMenu(); float makeSel(); int main() { do{ printMenu(); makeSel(); //game goes here cout<<"game"<<endl; }while (makeSel()!=2); return 0; } void printMenu() { cout<<"Welcome to Tic-Tac-Toe!"<<endl<<"Three in a row wins!"<<endl; cout<<" 1).Play a game."<<endl<<" 2).Quit"<<endl; } float makeSel() { float sel; do{ cout<<"Please Make a Selection: "; cin>>sel; } while(sel!=1 ||sel!=2); return sel; }
https://cboard.cprogramming.com/cplusplus-programming/71535-tic-tac-toe-loop.html
CC-MAIN-2017-22
refinedweb
130
78.45
Splitgraph helps teams collaborate on data At Splitgraph, we're convinced there's better ways to collaborate on data than sharing CSV files. The ability to query other databases using Postgres queries, import data from hundreds of data sources, transform it with dbt, and travel back in time to any previous version all serve the same purpose: to give teams working with data a place to collaborate effectively. That said, if you're working with CSV files, we have that covered as well 😉. The quickest way to try Splitgraph is to simply sign up to Splitgraph.com, the public data portal open to everyone. You can import or connect your own data into private or public repositories. And you can query over 40,000 public data tables within 60 seconds, just by pointing your Postgres client to data.splitgraph.com:5432. Dedicated Data Portals For organizations, we also provide Dedicated Data Portals, which are private deployments of Splitgraph to the cloud infrastructure of your choice. You get all the same features of Splitgraph.com, except within a dedicated single-tenant instance that you can invite your teammates to. Dedicated Data Portals are currently in beta. Starting today, you can provision a demo environment free for 7 days with no credit card required. If you want to continue experimenting, just get in touch with us and we'll extend the trial. Once you're ready to buy, schedule a meeting to discuss your requirements and pricing. Try Splitgraph in a single-tenant environment In addition to the features available on the public Splitgraph.com, a Dedicated Data Portal enables you to: - Store your data in a single-tenant environment. - Get your own Splitgraph subdomain. - Invite colleagues, collaborators and customers. - Run Splitgraph in your cloud provider's region to minimize latency and transfer costs. - Integrate with your company's OAuth/SSO (e.g. Okta). - Gain in-depth control over sharing and unlimited namespaces. Deploy now Launch your own demo Dedicated Data Portal with just a few clicks (signup, but no credit card required). What to expect After you signup and deploy the demo, we'll send you an email in about 20 minutes, once your deployment is ready. It will look like this: Just click the button in the email to get started with your Dedicated Data Portal.
https://www.splitgraph.com/blog/demo-deployments-for-dedicated-data-portals
CC-MAIN-2022-21
refinedweb
386
56.05
Changing a TFS bound solution namespace Changing the namespace of a solution that has already progressed significantly down the development path can be a pain. Visual Studio doesn’t native support namespace refactoring and tools like R# can get bogged down with a huge set of changes. There is usually a dirty result if either of these tools are used as the project and solution directories are not renamed. These need to be done manually in Source Code Explorer which then throws out the relative paths stored in the solution file. Changing a namespace can be a messy job. In these circumstances it’s often best to hand craft an external solution to this problem. I’ve finally written that solution as a console app after doing this job the painful manual way too many times. The attached file contains the console application code. There is no defensive code against exceptions so it’s best to run this in the IDE. There are three constants you need to update before running this. These are the root path, find text and replace text. The code records everything that happens out to the console and a log file that is unique for each run.
http://www.neovolve.com/2009/10/06/changing-a-tfs-bound-solution-namespace/
CC-MAIN-2017-17
refinedweb
202
71.65
How to Load Third-Party Scripts Dynamically in JavaScript November 19th, 2021 What You Will Learn in This Tutorial How to dynamically load a JavaScript library like Google Maps by writing a script to automatically inject a tag into your page. a dynamic script loader In JavaScript, a common practice is loading in other packages and libraries into your app. Traditionally this is done via a package manager like NPM (Node Package Manager), but sometimes, we need to load JavaScript dynamically. "Dynamically" can also be read as "on the fly" or "from a third-party server." Generally the reason why we do this is that the script in question requires an API key or some other form of authentication before the script can load (or, the script is hosted remotely for security purposes to avoid it being tampered with). While we can add a <script></script> tag directly into our main index.html file, this is likely overkill as you will only need certain scripts on certain pages. To get around this, we can write a dynamic script loader that can be called on-demand from pages where a script is necessary. /lib/loadScript.js const urls = { googleMaps: ` }; export default (name = '', callback = null) => { const url = name && urls[name]; if (!name || !url) { throw new Error(`Must pass the name of a supported script: ${Object.keys(urls).join(', ')}`); } }; Getting started with our script, our goal is to create a function that we can import wherever we need it in our code. To make that possible, here, we create a file where we export default a function taking two arguments: name- The name of the script that we're trying to load. callback- A callback function to call after our script has loaded. For name, we expect this to be a name we've created. In our example here, we're going to load the Google Maps JavaScript API. Up top, we can see an object being created urls which has a property googleMaps defined on it, set to the URL Google gives us for their JavaScript library. Note: if you don't have an API key for Google Maps, you can obtain one following the steps here. In the URL here, we've replaced the apiKey query parameter that Google Maps expects with a pointer to a global value from the settings file in our app: joystick.settings.public.googleMaps.apiKey. Here, joystick.settings is a global value in the browser automatically populated with the contents of the settings file located in /settings.development.json at the root of our app. Making use of this convention here, we're saying that we expect there to be a value in that settings file located at apiKey nested in the public.googleMaps object, like this: /settings.development.json { "config": { "databases": [ { "provider": "mongodb", "users": true, "options": {} } ], "i18n": { "defaultLanguage": "en-US" }, "middleware": {}, "email": { "from": "", "smtp": { "host": "", "port": 587, "username": "", "password": "" } } }, "global": {}, "public": { "googleMaps": { "apiKey": "apiKey1234" } }, "private": {} } So it's clear, the line above will be read by JavaScript as The punchline being that the variable passed in the ${}part will be replaced by the value in our settings file (this is known as JavaScript string interpolation). /lib/loadScript.js const urls = { googleMaps: ` }; export default (name = '', callback = null) => { const url = name && urls[name]; if (!name || !url) { throw new Error(`Must pass the name of a supported script: ${Object.keys(urls).join(', ')}`); } }; Focusing back on our code, with our API key embedded, assuming that our urls object has a property matching the name argument passed to our loadScript() function, just inside of that function we attempt to get the URL for the script we want to load with name && urls[name]. This says "if name is defined and you can find a property on the urls object matching this name, return its value to us." In JavaScript, this urls[name] is known as "bracket notation." This allows us to dynamically retrieve values from an object using some variable or value. To be clear, if our urls object had a property pizza set to defined on it and we passed 'pizza' as the name for our script, we'd expect the url variable here to be set to Just below this, to be safe, we do a quick check to say "if we don't have a name defined, or, we don't have a url defined` throw an error." This will prevent our script from loading and warn us in the browser console so we can fix the issue. /lib/loadScript.js const urls = { googleMaps: ` }; export default (name = '', callback = null) => { const url = name && urls[name]; if (!name || !url) { throw new Error(`Must pass the name of a supported script: ${Object.keys(urls).join(', ')}`); } const existingScript = document.getElementById(name); if (!existingScript) { const script = document.createElement('script'); script.src = url; script.id = name; document.body.appendChild(script); script.onload = () => { if (callback) callback(); }; } if (existingScript && callback) callback(); }; Building out the rest of our function, now we get into the fun stuff. Assuming that a name was passed and matched a property on our urls object (meaning we got back a url), the next thing we need to do is make sure that we haven't already loaded the script in question before. This is important! Because we're loading JavaScript dynamically, generally speaking, there's potential for our function be called multiple times (either intentionally or accidentally). Because our script is going to append or add a <script></script> tag to our HTML, we want to prevent creating duplicates of it. Here, we look for an existing <script></script> tag with an id attribute equal to the name we passed in to loadScript. If we find it, we jump down to the bottom of our function, and, assuming we have a callback function defined, call that function (signaling that "yes, this script was already loaded and can be used"). If we don't find an existingScript, we want to load it dynamically. To do it, first, we create a new <script></script> tag element in memory (meaning it's not rendered to the page yet, just in the browser's memory storage). We expect this to create a DOM element (an object as far as our code is concerned) which we store in the variable script. On that object, we can set attributes on our new <script></script> tag dynamically. Here, we want to set to the src attribute to the url we obtained from the urls object above and the id attribute to the name we passed in to loadScript(). With those attributes set, our script is ready to be appended or "rendered" to our browser's HTML. To do it, we call to document.body.appendChild() passing in our script variable (JavaScript will recognize the format of the object as a valid DOM element and append it as requested). Because we're saying document.body here, we can expect this <script></script> tag to literally be appended as the last element inside of our HTML's <body></body> tag: Finally, after our script is appended, we assign an onload function to it which is the function our browser will call once the file located at the url we set to src is loaded. Inside, if our callback is defined, we call it. That does it for our loader's definition. Next, let's take a look at putting it to use and see how this works. Calling the dynamic script loader To put our loader to use, we're going to make use of the components feature built-in to the Joystick framework we started with at the beginning of the tutorial. When we ran joystick create app, we were automatically given a component at /ui/pages/index/index.js in our project. Let's open that file up and pull in our loadScript() function. /ui/pages/index/index.js import ui, { get } from "@joystick.js/ui"; import Quote from "../../components/quote"; import loadScript from "../../../lib/loadScript"; const Index = ui.component({ lifecycle: { onMount: (component) => { loadScript('googleMaps', () => { new google.maps.Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); }); }, }, methods: { ... }, events: { ... }, css: ` div p { font-size: 18px; background: #eee; padding: 20px; } #map { width: 100%; height: 300px; } `, render: ({ component, i18n }) => { return ` <div> <p>${i18n("quote")}</p> ${component(Quote, { quote: "Light up the darkness.", attribution: "Bob Marley", })} <div id="map"></div> </div> `; }, }); export default Index; Up top, we import loadScript from the /lib/loadScript.js path where we created it (omitting the .js on the end is fine here as our build tool will automatically attempt to load a .js file at this URL as part of the import process). The part we want to pay attention to is the lifecycle.onMount function being defined near the top of our component. If we look inside that function, we're calling to our loadScript() function first passing the name of the script we want to load, followed by our callback function. Look close at the callback. Remember: our goal is to load the Google Maps library so we can put it to use immediately after it's loaded. Here, because our callback is fired after our script is loaded, we can assume that Google Maps is available. Following that assumption, we make a call to the new google.maps.Map() method, passing in the DOM node where we want to load our map (if we look down in the render() function of our component, we can see a <div id="map"></div> being rendered as a placeholder where our map should be rendered. Here, we say document.getElementById() to get that <div></div> element's DOM node in the browser. That's it. If we take a look at our app in the browser at after a few milliseconds we should see our Google Map load (if not, double-check your API key and that any ad blockers are turned off). Wrapping up In this tutorial, we learned how to write a function to help us dynamically create and inject a <script></script> tag into our HTML. To do it, we took in the name of a script and mapped it to a URL where that script lives on an object and then used the document.createElement() function from JavaScript to create a script tag before appending it to the <body></body> tag in our DOM. Finally, we learned how to call to our loadScript() function to render a Google Maps map to the page. Get the latest free JavaScript and Node.js tutorials, course announcements, and updates from CheatCode in your inbox. No spam. Just new tutorials, course announcements, and updates from CheatCode.
https://cheatcode.co/tutorials/how-to-load-third-party-scripts-dynamically-in-javascript
CC-MAIN-2022-21
refinedweb
1,775
70.23
Because of its horizontally scalable shared-nothing architecture, the CrateDB open source database is well-suited for working with Kubernetes. Setting up a CrateDB cluster with Kubernetes can be done in just a few steps, and scaling up and down is straightforward – making the cluster particularly flexible. This step-by-step tutorial will show you how to get CrateDB and Kubernetes working together. CrateDB is used for real-time machine data processing, monitoring, and analytics. The open source database is suited for applications with high volumes of machine data (like anomaly detection), log data (like e-commerce), network data (like capacity planning), and IoT/IIoT data (like smart manufacturing, smart home products, and fitness gear). However, this database is probably not what you want to use if you require strong (ACID) transactional consistency or highly normalized schemas with many tables and joins. Kubernetes: From Pods, Controllers, and Services Container orchestration is the management, deployment and scaling of containerized systems. Within a Kubernetes cluster, at least one node must act as the master; the number of slaves is arbitrary. The containers are intelligently distributed across all Kubernetes nodes. Different Kubernetes components run on different servers depending on their function, with diverse instances of these components coordinating across multiple machines. To define the state of a Kubernetes cluster, three concepts are particularly important: pods, controllers, and services. Pods A Kubernetes pod represents a single computing unit, and thus the basic building block of a Kubernetes system. A pod can be a single container or several that are closely linked. For example, if a web application is deployed, a pod executes a single instance of the application. Pods can be scaled up horizontally by adding replica pods, or scaled-down by removing them. More complex applications often require more than one container. All containers in a pod share a common network interface, and each container has access to the storage volumes assigned to the pod. The official CrateDB Docker Image is very suitable as a single container pod; a combination of several can create a CrateDB cluster of any size. Controllers Controllers are used to create pods and perform management functions. Controllers manage sets of pods according to specified specifications, and Kubernetes provides several controllers for different purposes. For example, containers should ideally be stateless to eliminate negative effects if a container is destroyed, rebuilt, or moved to another server. Stateless containers are suitable for web applications that maintain the state compared to an external database. However, databases themselves require persistent storage: data shouldn’t be lost just because a container is rescheduled. To solve this, Kubernetes provides the StatefulSet controller that assigns each pod a fixed identity and a fixed storage space, which are retained during restarts and rescheduling. The controller creates all pods within a stateful set from the same template, but they are not interchangeable. Services Since the pods can be stopped, started, and rescheduled to any Kubernetes node, their assigned IP addresses change over time. However, client applications shouldn’t have to deal with changing IP addresses. That's what Kubernetes services are for: they serve as static interfaces providing access to one or more pods. A typical service is a load balancer that distributes incoming queries across the entire cluster. Setting up a Kubernetes Cluster Minikube provides a solution for executing Kubernetes locally, giving you a simple and powerful method of getting started with Kubernetes. Minikube can work with various hypervisors as a VM runtime, and is set up for use with the popular cross-platform option VirtualBox by default. If a compatible hypervisor such as VirtualBox is installed on the system, Minikube recognizes it and automatically sets up the VM. In addition, the standard command line kubectl is required, which controls the Kubernetes Cluster manager. Once these three components have been installed, the system can be started. By default, Minikube allocates 1GB of memory to the VM. This can be adjusted as required, as in the following example using 4GB, or “memory 4096”: To prepare the newly created Kubernetes cluster for use, Minikube now automatically configures kubectl. This can be checked with the following command: With the help of namespaces, Kubernetes divides the physical cluster into several areas. Technically speaking, no extra namespace needs to be created for the CrateDB cluster, but it’s advisable to keep an overview of the resources. The following command creates a new namespace: Now, if you query the existing namespaces, the newly created “crate” appears. While the default namespace is used if no other is specified, "kube-public" stands for all resources that are publicly available, and "kube-system" for the resources used internally by Kubernetes. Setting up CrateDB Services For CrateDB to function, each CrateDB node must be able to communicate with the other nodes in the cluster. To accomplish this, a Kubernetes service named crate-internal-service.yaml is created that displays on all pods that have the label “app: crate”. Labels are key/value pairs that stick to objects (such as pods) in order to give them attributes without changing their semantics. All CrateDB pods must be given the “app: crate” label. In addition, the following code defines a fixed IP address, and makes the service available on port 4300, the standard port that CrateDB uses for communication between the nodes. Here is the configuration: Now the service can be created: Kubernetes generates SRV records, which can be used to propagate the services of the cluster via DNS. In a later step, these can be used to set up CrateDB Unicast Host Discovery. So that clients can also run queries on CrateDB, it must be possible to address the pods externally. For this purpose, an external service (crate-external-service) is created. Like the internal service, it refers to all pods with the “app: crate” label. Kubernetes will now create an external load balancer. Typically, such a service is only available with a hosted solution. In this case, however, Kubernetes uses the load balancer that the hosted solution provides. This results in the following configuration: Now the external service can be created: Defining the CrateDB Controller The CrateDB cluster interfaces have now been created with the services. Next, a controller is needed to assemble and manage the cluster. The configuration for crate-controller.yaml contains the following points: - The Kubernetes controller creates pods: crate-0, crate-1, crate-2, etc. - The controller creates a stateful set called “crate-set”. This requires three CrateDB pods with a fixed identity and persistent storage. - Each pod has the “app: crate” label so that it can be addressed with the previously-created services. - Init containers (specialized containers that run within a pod in front of the app container) are used to configure the appropriate memory map limit so that CrateDB passes the bootstrap check. Such checks are carried out automatically in order to identify runtime problems. - 512MB is allocated to each pod, so that the cluster uses 1.5GB of the total of 4GB. This leaves room for growth. - The CrateDB containers that get each pod running are defined, Using version 4.1.4 of the CrateDB Docker image. - The crate-internal-service creates the SRV records. - Each pod provides various ports: port 4300 for communication within each node, port 4200 for HTTP clients, and port 5432 for PostgreSQL Wire Protocol clients. - Environment Variables are defined. Here CrateDB configures the size of the usable memory (CRATE HEAP SIZE) as 256 MB, or 50 percent of the available memory. - To facilitate a quick start, RAM Drive serves as a temporary storage solution. After the configuration has been saved, the controller can be created: The StatefulSet controller produces each CrateDB pod individually. This process can be observed with the following command: Finally, the CrateDB cluster is fully initialized: Accessing the CrateDB Cluster Before anyone can access CrateDB, the external service must be running: The “PORT(S)” column shows that Kubernetes port 31159 is connected to CrateDB port 4200 (HTTP) and Kubernetes port 31316 is connected to CrateDB port 5432 (PostgreSQL Wire Protocol). Due to a peculiarity of Minikube, the status of the external IP is still indicated with "pending". This requires a workaround. First, the Minikube services are queried separately: Two ports (192.168.99.100) are displayed, but both have HTTP as the specification. This is correct for the CrateDB HTTP port, but not for the PostgreSQL port. For the example described here, the HTTP port is 31159, and its functionality can be checked with a simple HTTP request. If the HTTP API response looks like this, everything works as expected: The network address (in this tutorial it’s 192.168.99.100:31159) can now be copied into the browser. The following CrateDB Admin UI should appear: Clicking on the Cluster screen in the left navigation menu shows that the CrateDB cluster has three nodes as expected: In our "Getting Started" guide you can find more details on importing test data and creating queries. Configuring Persistent Storage In practice, you’ll want to be sure data in the cluster can survive typical power cycling scenarios (switching the hardware off and on again) without damage. So far, the last lines of the example controller file crate-controller.yaml look like this: To set up persistent disk storage, Kubernetes provides the Persistent Volumes subsystem. It offers APIs for users and administrators that abstract away the details about how storage is provided from how it is consumed. One of these APIs is PersistentVolumesClaim. This instructs Kubernetes to request storage space from the underlying infrastructure. Kubernetes is agnostic about the implementation details. The part of the controller file described above (from volumes:) must now be replaced with a new configuration. In the following example, 1GB of persistent storage is requested per pod (in practice, other storage sizes can also be selected). The following config section belongs to the same indentation level as serviceName: "crate-set", meaning much further to the left: Unfortunately, the existing pods cannot be updated because the storage device is set to be changed. In the course of this change, all data that was previously written in CrateDB will be lost. The following commands show how the controller must be deleted and recreated: The following command can be used to verify whether 1GB is available for the pods: Scaling Horizontally to Five Nodes The ready-made CrateDB package, available for download from the Crate.io website, is limited to three nodes. Exceeding this limit leads to malfunctions. If you don't want to use the more powerful (but paid) enterprise version, can still expand your cluster by using CrateDB Community Edition “from the source.” The following code can be used to build CrateDB: The commit tag of the Git tag that corresponds to the version used must be inserted in place of “<TAG>”. As soon as the “gradlew” command has been successfully executed, the desired CrateDB CE release is stored as a compressed tarball archive in the app/build/distributions directory. Horizontal scaling is now easy to implement by increasing or decreasing the number of replicas used. In this example, the controller configuration initially defined three replicas: The number can be changed while the cluster is running. This is particularly useful if, for example, it’s necessary to adapt rapidly to traffic peaks. Note that this procedure is not ideal for making permanent changes – the CrateDB Admin UI will display a corresponding warning. The following changes are now made in the crate-controller.yaml file: The number of replicas is set from 3 to 5: The rest is done automatically by CrateDB: the Expected_Nodes are set to the value 5, and both Minimum_Master_Nodes and the Recover_After_Nodes are adjusted. These values should be at least as large as half the cluster size plus 1. For this example, the system now sets them from 2 to 3. Since this time only the "Replicas" and "Container" sections have been changed, the controller configuration can be updated directly: This process can also be observed with the kubectl command while it’s taking place. Kubernetes first ends the pods that were running, but then starts them again with the same identity and the same memory. Finally, the following result is visible: All five nodes can now also be seen in the Admin browser window. Scaling Down: Removing a Node From the Cluster As it pertains to CrateDB, there’s no difference whether a node should be removed from the cluster or whether it fails unexpectedly. In both cases, a node is removed from the cluster and CrateDB does the rest automatically. To test this, it’s advisable to load test data in the system first. Replicas and the Expected_Nodes can be set to 4 in the controller configuration, with everything else remaining as it is. The controller configuration is updated as follows: Kubernetes is now making the changes pod by pod. While the cluster is in the middle of the roll-out – i.e. in an inconsistent status – some checks will fail. By default, replication routines are configured so that CrateDB can help itself if shards (horizontal partitions) need to be recreated. While the process continues, the Admin UI shows some warnings. When the process is complete, everything should be back in line, with the scaling down process concluded successfully. CrateDB and Kubernetes work well as a team and make it possible to quickly set up a flexibly scalable cluster. Experimenting with test data can be useful when it comes to building experience, and gradually growing more familiar with using these technologies together.
https://crate.io/blog/how-to-set-up-a-cratedb-cluster-with-kubernetes
CC-MAIN-2022-33
refinedweb
2,255
53.51
Welcome to the 39th part of our machine learning tutorial series, and another tutorial within the topic of Clustering.. We continue the topic of clustering and unsupervised machine learning with the introduction of the Mean Shift algorithm. Mean Shift is very similar to the K-Means algorithm, except for one very important factor: you do not need to specify the number of groups prior to training. The Mean Shift algorithm finds clusters on its own. For this reason, it is even more of an "unsupervised" machine learning algorithm than K-Means. The way Mean Shift works is to go through each featureset (a datapoint on a graph), and proceed to do a hill climb operation. Hill Climbing is just as it sounds: The idea is to continually increase, or go up, until you cannot anymore. We don't have for sure just one local maximal value. We might have only one, or we might have ten. Our "hill" in this case will be the number of featuresets/datapoints within a given radius. The radius is also called a bandwidth, and the entire window is your Kernel. The more data within the window, the better. Once we can no longer take another step without decreasing the number of featuresets/datapoints within the radius, we take the mean of all data in that region and we have located a cluster center. We do this starting from each data point. Many data points will lead to the same cluster center, which should be expected, but it is also possible that other data points will take you to a completely separate cluster center. Immediately, however, you should begin to recognize the major downside for this operation: Scale. Scale sure seems to be a consistent problem. So we're running this optimization algorithm starting from every...single...datapoint. That's rough. There are some methods we can use to speed this up, but, regardless, this algorithm can still be quite costly. While this method is a hierarchical clustering method, your kernel can be flat or something like a Gaussian kernel. Recall the kernel is your "window." When finding the mean, we can either have every featureset with the same weight (flat kernel), or assign weights by proximity to the kernel's center (Gaussian Kernel). What is Mean Shift used for? Along with the clustering uses mentioned before, Mean Shift is also very popular in image analysis for both tracking and smoothing. For now, we're going to focus purely on the featureset clustering aspects. By now, we've covered the basics of using Scikit-Learn and visualization with Matplotlib, along with attributes of classifiers, so I will just plop the code down here: import numpy as np from sklearn.cluster import MeanShift = 100, centers = centers, cluster_std = 1.5) ms = MeanShift() ms.fit(X) labels = ms.labels_ cluster_centers = ms.cluster_centers_ print(cluster_centers) n_clusters_ = len(np.unique(labels)) print("Number of estimated clusters:", n_clusters_) colors = 10*['r','g','b','c','k','y','m']() Console Output: [[ 1.26113946 1.24675516 1.04657994] [ 4.87468691 4.88157787 5.15456168] [ 2.77026724 10.3096062 10.40855045]] Number of estimated clusters: 3 Chart:
https://pythonprogramming.net/hierarchical-clustering-mean-shift-machine-learning-tutorial/?completed=/k-means-from-scratch-2-machine-learning-tutorial/
CC-MAIN-2021-39
refinedweb
522
56.66
span8 span4 span8 span4 Hi! I am trying to convert a ESRI shapefile to a GMLwhich will be input for a calculation model that only takes GML. While building the conversion I get stuck at 2 issues. When you open the desired result and my current result in an Inspector, you will notice some difference leading to my issues: FeatureCollectionCalculator If you open the desired result in an Inspector and look at the single record (top printscreen below), you will notice a difference compared to my current result (bottom printscreen below). My own current result has every featureMember{}.owns in a new column, the desired result doesn’t. But instead has <missing value> in the column GML_parent_property. However, if I doubleclick on both (Feature Information screen opens) the result look largely the same. RoadNetwork Similar question as the FeatureCollectionCalculator but with 2 properties (element{}.owns and element{}.xlink_href). SRM2Road The printscreen below shows a random lineobject from the desired result. Among the attributes is a kind of list in list named ‘vehicles’ with 5 properties (StandardVehicle.maximumSpeed, StandardVehicle.stagnationFactor, StandardVehicle.strictEnforcement, StandardVehicle.vehiclesPerDay and StandardVehicle.vehicleType). The Vehicles{0} always has properties of Light Traffic, vehicles{1} always has properties of Normal freight etc. Just like the other examples this appears to be kind of a list. However, if you give the properties the same name for every traffictype, one will overwrite the other. In other words, if I rename the property of both LIGHT_TRAFFIC and NORMAL_FREIGHT to vehicleType the attribute of NORMAL_FREIGHT vehicleType will overwrite the one of LIGHT_TRAFFIC as both ‘columns’ have the same name. So it looks like I have to change the property name while being in a list somehow? Or is this solved while building the list? I included some results, a script etc to help you. Inside the zip you will find: AERIUS_Verkeersmodel_TEST_321_output_Totaal.GML my current result (script output) AERIUS_TEST_GML.GML intermediate result (output of the FeatureWriter in my script) NRU_Gebruiksfase_Plan_2025_(vru34)_02-04-2019.GML the desired result. Invulsheet AERIUS.xls User input used for metadata. What’s the name of the project etc. vru34_VRU34_2030B_20_milieu input shape, to be converted to GML. IMAER.XSD the schemadefinition, used in the desired result. AERIUS_Luchtkwaliteit_SHPtoGML.ZIP the FME Workbench (2016.1) and the most recent logfile (the script doesn’t throw any errors at the moment) Any help is greatly appreciated! Casper Safe_community_package.zip Answers Answers and Comments 12 People are following this question. Building nested GEOJson 3 Answers Complex KML: how convert them to vector formats? 2 Answers Nested JSON array to SQL table 2 Answers Nested Json templater 1 Answer How to change elements(namespaces) in GML ? 1 Answer
https://knowledge.safe.com/questions/95116/nested-lists-in-gml.html
CC-MAIN-2020-05
refinedweb
445
50.12
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll Preview Adding Contacts: Part 14:41 with Jason Seifer Our address book functionality is getting there. In this video, we implement the ability to add contacts via the command line. Code Samples def run loop do puts "Address Book" puts "a: Add Contact" puts "p: Print Address Book" puts "e: Exit" print "Enter your choice: " input = gets.chomp.downcase case input when 'a' add_contact when 'p' print_contact_list when 'e' break end end end def add_contact contact = Contact.new print "First name: " contact.first_name = gets.chomp print "Middle name: " contact.middle_name = gets.chomp print "Last name: " contact.last_name = gets.chomp contacts.push(contact) end Okay, so we have the beginning of our menu set up. 0:00 Let's go ahead and add another option to print out our contact list. 0:03 Now, if we scroll down here, we already have this method called print_contact_list 0:08 which does exactly what we want to. 0:13 So, all we need to do is add this as a menu option. 0:16 So we'll go ahead and add the option to print it out. 0:22 There we go. 0:29 That will just display it on the menu. 0:30 Now we need to add this as an option. 0:33 And this is really easy, all we need to do is say. 0:36 When the input is the letter p, we call the print_contact_list method. 0:40 Let's just make sure we spelled it correctly. 0:48 And we did. 0:51 So this should be everything that we need to do. 0:53 Let's go ahead and run this and make sure it works. 0:56 All right. Here are two options, 1:02 p to print the address book, and e to exit. 1:04 Well, let's go ahead and print it. 1:07 Well, it prints the word Contact List, but nothing's in there. 1:09 And why is that? 1:13 It's because we haven't added any contacts. 1:15 So, what we're gonna have to do is add the ability to add contacts in here. 1:18 Now we're gonna do that in two parts here. 1:28 So let's go ahead and add the ability to add a contact. 1:32 And add a menu item for it. 1:40 And we're just going to say when the input letter is a, 1:44 we're gonna call the add contact method, which we have to write now. 1:49 So this is gonna be similar to what we did before. 2:01 And let's go ahead, and since we're adding a contact, 2:05 which we're going to be appending to the internal contacts array, 2:09 let's go ahead and initialize a new contact. 2:13 And now we can just prompt the user to enter the information about their contact. 2:16 Enter their first name, and 2:24 then the same thing with last name. 2:28 Oops, forgot the middle name here. 2:38 Okay, that looks good. 2:49 Now we're in an interesting position here because we could append the contact to 2:51 the contacts array right now, but we still want to be able 2:55 to enter addresses or phone numbers for each contact. 3:00 Now we'll get to that in a minute, but for 3:04 right now let's just append the contacts array. 3:06 Now remember, we've got an attribute reader for the contacts array. 3:11 So we don't have to use the at sign to append it. 3:16 So we'll just say contacts.push and 3:20 it will be this contact right here. 3:26 So let's click down here and exit, all right, clear the screen, 3:32 I'm gonna run this again. 3:36 And see what happens so let me add a contact, Jason, no middle name, Seifer. 3:38 Okay that seems to have worked, now let's go ahead and print the address book. 3:44 Okay, looks like I'm in here, let me add another contact. 3:49 Nick Avery Pettit. 3:56 Okay, that seems to have worked. 4:00 Let's go ahead and print the address book. 4:03 Okay, looks like that's working. 4:06 And let's just see something really quickly here. 4:10 If we exit, and I'm gonna clear my screen, and if I restart again, 4:12 if we go to print the address book, 4:16 you'll notice that it's empty even though we just added Nick and Jason as contacts. 4:18 The reason is, that takes place entirely in memory and we are gonna be writing this 4:24 out to a file but we'll be doing that a little bit later. 4:28 Next up we're gonna be going through and doing the loop for adding addresses and 4:31 phone numbers to our contact before pinning them to the contact's array. 4:35
https://teamtreehouse.com/library/build-an-address-book-in-ruby/input-and-output-2/adding-contacts-part-1?t=121
CC-MAIN-2021-21
refinedweb
894
82.95
How to actually use rich:orderingListB Bozhanov Jan 27, 2010 5:27 PM I want to achieve something fairly trivial: - let the user reorder the elements in the rich:orderingList - on each reorder I want another component changed based on the new order (and an action method called before that) I tried with both <a4j:support and with <a4j:jsFunction (on "onchange" and "onchanged"), but the "value" of the ordering list is unchanged - i.e. the List to which I set the "value" attribute retains its initial order. I ended up calling "getExtendedDataModel" using reflection on the binded "HtmlOrderingList", which returns the properly ordered collection, but it is an ugly hack, and furthermore, it doesn't fit my case entirely. So, is this possibly a bug in the orderingList, or I'm misunderstanding something? 1. Re: How to actually use rich:orderingListIlya Shaikovsky Jan 28, 2010 5:55 AM (in response to B Bozhanov) 2. Re: How to actually use rich:orderingListB Bozhanov Jan 28, 2010 2:20 PM (in response to Ilya Shaikovsky)Both onorderchanged and onorderchange yield the same result. 3. Re: How to actually use rich:orderingListIlya Shaikovsky Jan 29, 2010 4:11 AM (in response to B Bozhanov)checked with richfaces-demo code under 3.3.3 snapshot. onorderchanged works just as you expects. And onorderchange works as described in your problem - but it's designed behavior - this event risen before actual order change. 4. Re: How to actually use rich:orderingListB Bozhanov Jan 31, 2010 2:29 PM (in response to Ilya Shaikovsky) Still not working here, Richfaces 3.3.2.SR1 <rich:orderingList <a4j:support .... </rich:orderingList> The converter gets the List reference, and finds the item by name (correctly). When I put System.out.println(stopsList); in the listReordered() method, it outputs the same sequence of objects after each reorder. I tried removing the "binding" temoporarily - doesn't work Using what code did you make it work? 5. Re: How to actually use rich:orderingListNick Belaevski Jan 31, 2010 6:42 PM (in response to B Bozhanov) Hi, You are using a4j:support that has immediate="true" and that prevents model beans from updating. See documentation for "immediate" attribute for more information. 6. Re: How to actually use rich:orderingListB Bozhanov Feb 1, 2010 2:21 AM (in response to Nick Belaevski) Yes, I'm aware of what "immediate" is doing, but this one seems to have slipped through my fingers. Perhaps because I don't want to validate (and eventually fail the validation) of other field in the page. But ajaxSingle should take care of that and not submit those. Thanks 7. Re: How to actually use rich:orderingListBaran Seil Sepour Aug 1, 2010 5:41 PM (in response to B Bozhanov) Hi there, I have source code like Bozhidar, but I could not get the new order in my backing bean. Would you plz help me? It is my ordering list: My rankList will be initialized in init() method in my backing bean: rankList = new ArrayList<Rank>(); rankList.add(new Rank("Alabama Montgomery")); rankList.add(new Rank("Alaska Juneau")); rankList.add(new Rank("Arizona Phoenix")); rankList.add(new Rank("Arkansas Little Rock")); rankList.add(new Rank("California Sacramento")); rankList.add(new Rank("Colorado Denver")); rankList.add(new Rank("Connecticut Hartford")); rankList.add(new Rank("Delaware Dover")); rankList.add(new Rank("Florida Tallahassee")); rankList.add(new Rank("Georgia Atlanta")); rankList.add(new Rank("Hawaii Honolulu")); rankList.add(new Rank("Idaho Boise")); and it is my findEperts method in my backing bean: public void findExperts (){ System.out.println("FIND EXPERT:Hi"+rankList); resultsList.clear(); BusinessLogic bs = new BusinessLogic(); resultsList = bs.search(searchedTopicList); } and it is my convertor: public class StringToRankListConverter implements Converter { public Object getAsObject(FacesContext context, UIComponent component, String value) { System.out.println("StringToRankListConverter value: "+value.toString()); String[] words = value.split (":"); String name = words[0]; Rank wonder = new Rank(name); return wonder; } public String getAsString(FacesContext context, UIComponent component, Object value) { return value.toString(); } } Sometimes a4j:support calls my findexperts method, and sometimes does not call. But I saw in my setRankList and getrankList and findExpert method that the rankList has the old order, not a new order. Thank in advance 8. Re: How to actually use rich:orderingListIlya Shaikovsky Aug 2, 2010 6:50 AM (in response to Baran Seil Sepour) - do not duplication questions please or you will loose the thread where we trying to answer.
https://developer.jboss.org/message/522704
CC-MAIN-2019-04
refinedweb
736
57.16
Introduction – Why My goal for this project was to find a way to deploy a new cluster in AWS, Microsoft Azure and Google. I am constantly spinning up and down Kubernetes clusters and running through scenarios for content creation and just learning scenarios. I have written several blogs talking about creating managed Kubernetes clusters in the three big clouds and some other options more recently. But I wanted to go one step further and wanted to automate the creation and removal of these environments for demo purposes. The goal is to make it simple to not only create these clusters using Terraform from Hashicorp but to then also have a very easy way to deploy Kasten K10 as well to each of the clusters. The purpose is to cover those on demand demo environments which deploys with one command and then allows me to rip it all down as well. You can find the raw code here; I have however been conscious of creating readme.md files throughout the repository as maybe only certain areas will be of interest. Walkthrough one example I figured it would or might be useful to also walk through how to use at least one of these public clouds terraform scripts. For this demo we are going to use the GKE option. Prerequisites On our workstation first we need the Google Cloud Platform account, we also need the gcloud sdk to be configured on our system, finally we need kubectl each of these options are not OS constrained so if you are running Linux, Windows or MacOS you are good to go here. I have also documented the steps for Google Cloud Platform specifically here. before we get into the walkthrough we are also going to need to install Terraform on our system, once again this will have you covered across Linux, Windows and MacOS. This resource should help get you going with Terraform. The first step is making sure you have gcloud configured correctly as per the section above and the link that dives into the step by step on authenticating to your GCP account. We then want to get our code downloaded from the following, be sure to have this located in your common location for code. git clone\_k8deploy.git You will notice that this contains the deployment steps for AWS EKS, Microsoft AKS and GKE for this walkthrough we are only interested in GKE, but you are more than welcome obviously to explore the other folders, we will also cover the helm folder later in the walkthrough. Let’s navigate to the GKE folder with the following command: cd learn-terraform-provision-gke-cluster I am using Visual Studio Code for my IDE so now we are into our folder you can run the following command to open the folder in VSCode code . You can check through the .tf files in the folder now and start to see what is going to be created, if you are new to terraform then I suggest you walking through the following to understand what is happening at each step before making specific changes to your deployment. The one folder that you need to update before anything will work is the terraform.tfvars this needs to contain your project ID and your region. You should change the region accordingly to where you would like everything to be deployed. You can get your project ID by running the following command gcloud config get-value project Once you have updated your file above, we can then get provisioning our cluster, simple stuff so far even if you are new to terraform. Back in your terminal that is in the GKE folder you should run the following command: this command will download the required providers. terraform init We can now go ahead and deploy our new GKE cluster along with a dedicated VPC away from any existing infrastructure you have in your Google Cloud Platform. Run the following and type in yes if you are happy to proceed at the prompt terraform apply Once you have hit enter after saying “yes” it will start deploying your new GKE cluster. You can go through and check beforehand what this is going to deploy, this script will deploy a new GKE regional cluster and this can be explained here. I do have a plan to also add a zonal cluster option to the scripts here or if someone has already created it then please share. After around 10 minutes possibly shorter you will have created your GKE cluster. For us to connect though we need to download the configuration for kubectl on our local machine to connect to the cluster. We can do this using the following command. gcloud container clusters get-credentials $(terraform output -raw kubernetes_cluster_name) –region $(terraform output -raw region) Once you have ran the above you can also confirm you have access by using the following confirmation command of checking your hosts. kubectl get nodes From the above command you should see 6 nodes in a ready state, this is because we have deployed 2 nodes in each zone of the region. You can also check the context with the following command to confirm you are indeed in the correct configuration. kubectl config get-contexts This will be useful later when we come to remove the cluster and we want to also remove the context and cluster from our kubectl configuration. At this stage we have a GKE cluster up and running and even this might be useful to some people but in the next section I want to add the functionality of deploying an application using the helm provider so that I can show and demonstrate the functionality of the application. Helm deployment of Kasten K10 and example As I mentioned the above gets us a fast way to deploy a new cluster without affecting our existing infrastructure, my use case here is to quickly spin up an environment for demos but also a fast way to destroy or get rid of the environment I created. In this example I want to be able to deploy Kasten K10 which is a tool that provides the ability to protect your applications within Kubernetes. In the git repository we downloaded earlier you should be able to navigate to the helm folder and within the folder you will see three additional folders and depending on your deployment of Kubernetes will determine the folder you choose. Before we continue, I will also highlight that in each of the Kubernetes deployment folders you will find a similar file to GKE_Instructions.md which walks through step by step including the helm deployment of your application. In your helm folder and then in our case the Google GKE folder you will see two files, kasten.tf and main.tf Now that we are in our terminal, we should again issue the following command to download the required providers. terraform init The next command along with your approval “yes” will go ahead and firstly create a namespace called “kasten-io” and then proceed to deploy from the helm chart the latest release version of Kasten K10. You can also add additional helm chart values to the kasten.tf file if you have specific requirements, you will see this to be the case in the other options for the other public cloud deployments. terraform apply You can follow the progress of the deployment by running the following command kubectl get pods –n kasten-io –w When all pods are up and running you can also run the following to get the public IP of the Kasten K10 dashboard as we set this with our helm chart option within kasten.tf kubectl get svc –n kasten-io You can then take this DNS / IP address and add to your browser to connect to your instance of Kasten K10 Address/k10/# Because we don’t want this now accessible to the world, we must obtain our token authentication that we also defined in our helm chart variables. You can follow this post to get that secret information. Deleting your cluster or application Ok so we are now at the stage where we might want to get rid of things or at least roll back to pre-Kasten K10 being deployed. It is easy to get things removed or reverted, we can run the following command from the helm folder to remove the Kasten deployment and namespace. Again, this is going to prompt you for a yes to continue. terraform destroy Let’s then say we are also done with the cluster as well, we can run the following command, for this to work you need to navigate to the first folder where we ran terraform apply the first time to create the cluster. This time I am going to share a faster way without the requirement to type in yes to make any of the terraform apply or destroy commands do what you want. terraform destroy –auto-approve So far so good? But we still have that kubectl context for the cluster, we can run the following command to get the cluster and context name. kubectl config get-contexts Then it’s a case of running the following to delete the context kubectl config delete-context And then the following to delete the cluster Kubectl config delete-cluster I do hope this was useful and I am also open to improving this workflow or adding additional features, my initial thoughts are for better and faster ways to demo I should also deploy a data service such as MySQL and add some data to it and automate the creation of backup policies etc. Discussion (0)
https://dev.to/michaelcade1/using-terraform-iac-to-automate-your-kubernetes-clusters-and-apps-23b5
CC-MAIN-2021-49
refinedweb
1,617
61.09
AS7: ReSTEasy EJB InjectionRaj Tiwari Jul 28, 2011 5:45 PM I have a JAX-RS application where I am trying to inject an EJB (@EJB). The injection annotation works for a servlet in teh same app, but not in ReSTEasy application. Is this not supported in AS7? 1. Re: AS7: ReSTEasy EJB Injectionjaikiran pai Jul 29, 2011 10:32 AM (in response to Raj Tiwari) Please post relevant code and configurations. 2. Re: AS7: ReSTEasy EJB InjectionRaj Tiwari Jul 31, 2011 2:39 AM (in response to jaikiran pai) Hi Jai, In the code below, userManagerLocal is the local interface of an EJB. The exact same injection puts the right EJB in a servlet in the same project, but not in the JAX-RS code below. In JAX-RS, it is injected as null. @ApplicationPath( "/api" ) @Path( "/users" ) public class UserManager extends Application { /** * Queries existence of a user. * @param sUserId * @return HTTP OK if user exists and NOT_FOUND if user does not exist * @throws NamingException */ @HEAD @Path( "/{userid}" ) public Response queryUserExists( @PathParam( "userid" )final String sUserId ) throws NamingException { final boolean bUserExists = userManager.queryUserExists( sUserId ); ... } ... @EJB private UserManagerLocal userManager; } 3. Re: AS7: ReSTEasy EJB InjectionRaj Tiwari Aug 2, 2011 12:09 PM (in response to jaikiran pai) Hi Jai, Any updates on this? Thanks. -Raj 4. Re: AS7: ReSTEasy EJB Injectionjaikiran pai Aug 7, 2011 11:20 AM (in response to Raj Tiwari) Is this still an issue against latest AS7 nightly build? 5. Re: AS7: ReSTEasy EJB InjectionAdams Tan Aug 8, 2011 4:04 AM (in response to Raj Tiwari) I had a similar issue before; problem was fixed by adding a "beans.xml" into WEB-INF. Do double check. Ad 6. Re: AS7: ReSTEasy EJB InjectionSamuel Tannous Dec 12, 2011 5:46 PM (in response to Raj Tiwari) I had the same issue and it took a while to find the answer but all I had to do was add the @Stateless annotation to the REST service. Apparently it must also be a session bean to add injection capabilities as mentioned here This is the original post I found which led me to Adam's blog: 7. Re: AS7: ReSTEasy EJB InjectionMaximos Sapranidis Apr 26, 2012 10:39 AM (in response to Raj Tiwari) I know this is older post but I am facing the same issue. I have tried both solutions (adding beans.xml file and setting the @Stateless annotations to rest class) but unfortunatelly none of them worked. Also tried to change the @EJB to @Inject but I keep getting null reference! Have anyone found a solution to this? am I doing something wrong? 8. Re: AS7: ReSTEasy EJB Injectionalvarohenry May 8, 2012 1:08 PM (in response to Maximos Sapranidis) Maximos I had the same problem. the problem was in my AppApplication class that extends of Application class. The resources with @Path annotation have to be in the getClasses() method instead of getSingletons() method. I changed: singletons.add(new MyService()); to: classes.add(MyService.class); I hope it help you. Regards. 9. Re: AS7: ReSTEasy EJB Injectionjack chen Sep 3, 2013 10:57 AM (in response to Raj Tiwari) I had same problem .I try use both ways (add beans.xml and change some codes in the class extends Application)and It works for me.If i only used one method it did not work for me. I need to add beans.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns:xsi="" xsi: </beans> and change the public class YourApplication extends Application public YourApplication () { getClasses().add(yourRESTServices.class); } @Override public Set<Class<?>> getClasses() { HashSet<Class<?>> set = new HashSet<Class<?>>(); return set; } } 10. Re: AS7: ReSTEasy EJB InjectionTiago Rico May 5, 2014 11:50 AM (in response to jack chen) I confirm Jack solution! Thank you all!
https://community.jboss.org/thread/170194
CC-MAIN-2015-32
refinedweb
633
64.81
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type. The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class. If you observe the following example, we are not providing any constructor to it. public class Sample { int num; public static void main(String args[]){ System.out.println(new Sample().num); } } If you compile and run the above program the default constructor initializes the integer variable num with 0 and, you will get 0 as result. The javap command displays information about the fields, constructors, and methods of a class. If you (after compiling it) run the above class using javap command, you can observe the default constructor added by the compiler as shown below − D:\>javap Sample Compiled from "Sample.java" public class Sample { int num; public Sample(); public static void main(java.lang.String[]); } public class Sample{ int num; Sample(){ num = 100; } Sample(int num){ this.num = num; } public static void main(String args[]){ System.out.println(new Sample().num); System.out.println(new Sample(1000).num); } } 100 1000
https://www.tutorialspoint.com/what-do-you-mean-by-default-constructor-in-java
CC-MAIN-2021-31
refinedweb
244
55.44
E2E (End-to-End) Testing in Ionic: An Introduction By Josh Morony Over the past few weeks, I have been releasing a series of tutorials about creating automated tests for Ionic (Angular) applications. The tutorials so far have focused on how to apply the Test Driven Development (TDD) methodology to unit test an Ionic application. If the concept of automated tests is new to you, or if you don’t understand why you would want to create automated tests for an application, I would recommend reading through my Test Driven Development series of tutorials. In this tutorial, we will be covering another type of automated test called End-to-End Testing, or E2E for short, and how to apply that to an Ionic/Angular application. We will just be focusing on the bare bones set up, for now, to get a simple E2E test running, I will cover strategies for creating effective E2E tests in future tutorials (like how to incorporate E2E tests into a TDD approach alongside your unit tests). This tutorial has been updated since it was originally published, and fortunately now unit and end-to-end tests are included in Ionic projects by default, so it is significantly easier to get started now. Before We Get Started Before you go through this tutorial, you should have at least a basic understanding of general Ionic and Angular concepts. You must also already have an appropriate development environment for these frameworks set up on your machine. You will also need to have a basic understanding of Jasmine and creating unit tests, as I will not be covering the theory behind creating tests with Jasmine in this tutorial. If these concepts are new to you, you should read An Introduction to TDD first. If you’re not familiar with Ionic/Angular already, I’d recommend reading my beginner Ionic tutorials first to get up and running and understand the basic concepts. If you want a much more detailed guide for learning Ionic/Angular, then take a look at Building Mobile Apps with Ionic & Angular. What is an E2E Test? So far, we have covered unit tests which test isolated units or chunks of your code. You might create unit tests for a single class in isolation to make sure its methods do what they are supposed to do. You don’t worry about any dependencies that class might have or anything it interacts with, all we are interested in is if that one unit is doing what it is supposed to do. A single unit test might test something as small and simple as whether a particular method makes a call to some other method when it runs. To create unit tests in Ionic we generally use two tools: Jasmine to create the tests, and Karma to automatically run the tests through a browser. An E2E test, on the other hand, allows us to test interactions between various components in our application. Basically, it allows us to test the application in a way that the user would actually use it. We can essentially simulate a user’s behaviour in our application (like a bot), and test for what is happening in the application. An E2E test might look something like this, for example: - Go to the index page - Click on the menu icon - Click on the ‘Products’ page - Expect the ‘Featured’ product category to be displayed To create E2E tests we will be using a tool called Protractor which will allow us to simulate user behaviour in this way, and it will run our tests for us automatically through a browser (you can actually see the actions being performed in real time, which is pretty cool) by using a Selenium server. We still use Jasmine with Protractor in order to define our E2E tests. 1. Generate a new Ionic/Angular Application We’re going to start off by generating a new Ionic application. Instead of using the blank template, which we would typically use, we are going to use the default tabs template so that we have something a little more interesting to test with Protractor. Run the following command to generate a new Ionic 2 application: ionic start ionic-e2e-example tabs --type=angular Once generated, make it your working directory by running the following command: cd ionic-e2e-example 2. Setting up E2E Tests This section used to be a lot longer, but fortunately now E2E tests are set up by default for us in new Ionic/Angular applications. All you need to do to run the E2E tests is run the following command: npm run e2e If you’re paying attention you might see the browser window pop up briefly to execute your tests. The default Ionic/Angular applications already have some tests included, so you should see a message like this indicating the successful execution of the default E2E test: new App should display welcome message Executed 1 of 1 spec SUCCESS in 2 secs. NOTE: You may get a warning about not having the correct version of Chrome, e.g: E/launcher - session not created: This version of ChromeDriver only supports Chrome version 77 Make sure that you upgrade your Chrome browser to solve this issue. 3. Understanding an E2E Test In a moment we will try to implement our own E2E test, but first, let’s take a look at the existing E2E test that we just executed. You can find this test at e2e/src/app.e2e-spec.ts: import { AppPage } from './app.po'; describe('new App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getPageTitle()).toContain('Tab One'); }); }); This test also imports an AppPage “page object”. We are going to cover this concept in future tutorials, but the basic idea is that a “page object” will provide us with some helper functions related to a specific page that we are running tests on (in this case, the logic for grabbing the page title is in the page object file, which makes the test in this file a bit cleaner and we can also share that logic in other tests). This E2E test is quite similar to a normal unit test that we create with Jasmine, except for a few key differences. One thing you might notice if you are already familiar with creating unit tests in Angular, is that we aren’t using TestBed and we don’t have to import or set up any components in the test. We are just using the application, so we point the browser to the root of the application and start interacting with it. It is the page object that handles navigating to the correct place in the browser with the navigateTo method: import { browser, by, element } from 'protractor'; export class AppPage { navigateTo() { return browser.get('/'); } getPageTitle() { return element(by.css('ion-title')).getText(); } } You can see that we use browser.get('/') to navigate the browser to the root of the application (e.g. the / route). It also uses a few imports from the protractor library. The browser will allow us to control the browser like by directing it to certain URLs, or asking it to wait a certain amount of time before continuing the test. The element and by imports allow us to find elements on the page and interact with them (e.g. get the text content of the element that matches the CSS selector ion-title). 4. Creating an E2E Test Now we are going to create our own simple E2E test and execute it. We are not going to worry too much about best practices or good testing methods here, we just want to get a simple test running. Future tutorials will cover various testing strategies and best practices in more depth. NOTE: If you want an in-depth introduction to Unit and E2E testing for Ionic and Angular, you might be interested in checking out my advanced course: Elite Ionic (Angular). Create a file at e2e/src/tabs.e2e-spec.ts and add the following: import { browser, element, by } from "protractor"; describe("tabs", () => { beforeEach(() => { browser.get("/"); }); it("the Tab One tab is displayed by default", () => { expect(element(by.css(".tab-selected ion-label")).getText()).toContain("Tab One"); }); it("the user can navigate to the Tab Two tab", async () => { await element(by.css("[tab=tab2]")).click(); browser.driver.sleep(500); expect(element(by.css(".tab-selected ion-label")).getText()).toContain("Tab Two"); }); }); In the test above, we have created two tests, and before each of the tests we redirect the browser back to the initial page with browser.get('/'). The first test checks that the Tab One tab is displayed by default. To do that it first uses a CSS attribute to grab the appropriate element, which is the tab button for the currently selected tab. You can use any normal CSS selector with by.css, and since the currently selected tab in an Ionic/Angular application will have the .tab-selected class we use that to grab the currently selected tab. We then check the getText to see if it is indeed the Tab One tab (in which case, it would contain the text Tab One). The next test is similar, except this time we grab a different tab and trigger a click on it to test that the user can browse to that tab. We tell the browser to wait for 500ms whilst the page transition occurs (which is likely longer than needed), and then we check that the <ion-label> element of the selected tab contains Tab Two. There are better ways to “wait” for things to happen rather than setting a manual “sleep” time for the browser, but we will be getting into that in future tutorials. We are also using an async test function here, and we use await to wait for the click Promise to resolve. If you aren’t familiar with async/await you can check out this video: Async / Await Basics in JavaScript Explained. If you prefer, you can also just use the standard then() promise syntax. If we run these tests with npm run e2e now, we should see the following result: new App ✓ should display welcome message tabs ✓ the Tab One tab is displayed by default ✓ the user can navigate to the Tab Two tab Executed 3 of 3 specs SUCCESS in 3 secs. Our default test is still passing, but now our two additional tests inside of the tabs test suite are also passing. Summary This is a reasonably basic introduction to Protractor and E2E tests in general, but hopefully, it helps explain some of the key concepts. I will be covering End-to-End testing more in future tutorials, including how to better structure your E2E tests and how you can incorporate E2E tests into a Test Driven Development approach.
https://www.joshmorony.com/e2e-end-to-end-testing-in-ionic-2-an-introduction/
CC-MAIN-2020-10
refinedweb
1,809
56.08
Finding derivative of a spline in Python using SciPy In this tutorial, we will learn how to find derivative of a spline in Python using SciPy. Here we have used: - SciPy Module - Matplotlib Spline First of all, we have to be familiar with the word spline. The spline is a piecewise polynomial function and this function is used in interpolating problems, specifically spline interpolation is mostly preferred as a method of estimating values between known data points. The derivative of a spline – SciPy here, we are focusing on the cubic spline. we can easily get cubic spline of any data by using the following library from scipy.interpolate import CubicSpline Input: here, for the x-axis, we are considering an array of nine elements and for the y-axis, we are considering the array of sine values of nine elements. from scipy.interpolate import CubicSpline import matplotlib.pyplot as plt import numpy as np x = np.arange(10) y = np.sin(x) cs = CubicSpline(x, y) s = np.arange(-1, 10, 0.1) fig, p = plt.subplots(figsize=(8, 4)) p.plot(x, y, 'o', label='value') p.plot(s, np.sin(s), label='original') p.plot(s, cs(s), label="C") p.plot(s, cs(s, 1), label="C1") p.plot(s, cs(s, 2), label="linear") p.set_xlim(-0.5, 14) p.legend(loc='upper right', ncol=3) plt.show() Output : Changes in values can be observed in the graph. You may also read:
https://www.codespeedy.com/find-derivative-of-a-spline-in-python-using-scipy/
CC-MAIN-2020-24
refinedweb
246
62.14
* Alan W. Irwin <irwin@...> [2004-04-16 12:56]: > To further discussion of this plan, I would be willing to summarize a list > of possible plplot6 API changes to reduce our API bloat. Everybody here, > please send suggestions to me off list. The following is the relatively > narrow questions that I will address: > > [...] What about an approach that is both radical and non-harmful? The radical aspect consists in changing completely the names of the functions (and also some prototypes, aiming at consistency). I would lean to have informative names like in modern libraries. Take the example of the gdk-pixbuf libray, recently discussed in this mailing list. Here are some function of its API: gdk_pixbuf_new gdk_pixbuf_get_colorspace gdk_pixbuf_get_has_alpha gdk_pixbuf_get_bits_per_sample gdk_pixbuf_get_pixels gdk_pixbuf_copy gdk_pixbuf_new_from_file gdk_pixbuf_new_from_data gdk_pixbuf_save gdk_pixbuf_saturate_and_pixelate gdk_pixbuf_scale gdk_pixbuf_animation_iter_on_currently_loading_frame Even if you are a newbie to the gdk-pixbuf library, you can almost immediately tell what each function above is expected to do. For the PLplot library, we could do something like this (the names below are a quick example, just to make my point): plbop -> plplot_begin_new_page plcol0 -> plplot_set_color_map0 plcont -> plplot_plot_contour plfill -> plplot_area_fill plgdev -> plplot_get_current_device_name plgver -> plplot_get_version pllab -> plplot_write_label plline -> plplot_draw_line plot3d -> plplot_plot_3d_surface plptex -> plplot_write_text_in_viewport plsdiori -> plplot_set_orientation plstyl -> plplot_set_line_style plwid -> plplot_set_pen_width etc. The names of the functions in the current PLplot API are way too cryptic and confusing. Besides that, they are too short, what increases the chance of interference with the user's namespace. The non-harmful aspect of this approach is that we can keep both APIs for a certain amount of time. The functions with short, cryptic names would be wrappers to the new functions (or vice-versa). At some point in the not so near future, we could deprecate the old API (or even remove it), but users will have time to switch to the new one. The advantage of this approach is that it does not introduce backwards incompatible changes, so that we keep the library soname. -- Rafael View entire thread
http://sourceforge.net/p/plplot/mailman/message/10283362/
CC-MAIN-2014-42
refinedweb
324
51.48
2 [ID:322] (2/5) in series: A Demonstration of the 'IPython' Interactive Shell video tutorial by Jeff Rush, added 07/07 directory navigation, system shell commands and the running of Python programs.: 99 (since July 30th) - Plays in last week:!! Thanks! I wanted to find out more about IPython and your demos are nice examples of how an experienced user wields this powerful tool. Great for a newbie to learn from. Experienced users would also probably learn a thing or two. I appreciate very much your IPython videos. Thanks a lot, they're so useful! Very interesting screencast, good speed of progress, doesnt get boring neither is too challenging. I am a perl berginner to intermediate programmer and interested python beginner. Really enjoyed watching it, keep the good work up! thanks for your kindness. I download ipython before, but i don't know what's ipython avantage. And now i get it. Thanks again. Nicely done Jeff. To the point and well organized. GREAT VIDEO, SLOW DOWN YOUR SPEECH. AS THE VIDEO GOES ON, YA TEND TO SPEAK FASTER. YOUR VIDEO PEAKS MY INTEREST TO LEARN IPYTHON MORE. this popup is gay I've been a python user since 1999, but for some reason have never got to grips with the ipython shell. The book Python for unix an dlinux system administration got me interested. I can't tell you the number of scripts I have written just to open a simple file from the command line and do some per line manipution. Being able to freely mix python and the command line is pretty exciting, I'm really enjoying your tutorial videos on this, thanks! Great presentations! I can't wait to see the rest! i have so far scanned the first video, meaning, i loaded the flash? and jumped around with the pointer. . I would have liked a quick and complete.overview of ipython. I use windows. If I am not using idle, I get stuck with --more--. I also do not get autocompletion which I rely on in idle. i will look at your second video. Thank you for the video. Fantastically helpful! Thank you for these videos. I'm a physicist and therefore am faking it in coding, but have found python fantastic, and can't believe I'm only discovering ipython now! Your videos are making the transition that much easier. BUMP? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Also, pushd pushes the current directory on to the stack then changes to the argument. Re comment 12 ... exactly my experience Also, pushd pushes the current directory on to the stack then changes to the argument. +1 Trying to get to the heart of what was going on with global/local scope of variables in the example at 8:20 I tried to recast the function as follows only to be given a NameErorr: name is not defined. I'd really appreciate a pointer as to where I'm going wrong here. In [1]: def go(regpat="*.py"): ...: !ls -l $regpat ...: ...: In [2]: go() --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/ush/webwork/<ipython console> /home/ush/webwork/<ipython console> in go(regpat) /usr/lib/python2.4/site-packages/IPython/iplib.pyc in <lambda>(cmd) 495 # The first is similar to os.system, but it doesn't return a value, 496 # and it allows interpolation of variables in the user's namespace. --> 497 self.system = lambda cmd: \ 498 self.hooks.shell_hook(self.var_expand(cmd,depth=2)) 499 /usr/lib/python2.4/site-packages/IPython/iplib.pyc in var_expand(self, cmd, depth) 628 self.user_ns, # globals 629 # Skip our own frame in searching for locals: --> 630 sys._getframe(depth+1).f_locals # locals 631 )) 632 /usr/lib/python2.4/site-packages/IPython/Itpl.pyc in __str__(self) 258 def __str__(self): 259 """Evaluate and substitute the appropriate parts of the string.""" --> 260 return self._str(self.globals,self.locals) 261 262 def __repr__(self): /usr/lib/python2.4/site-packages/IPython/Itpl.pyc in _str(self, glob, loc) 208 for live, chunk in self.chunks: 209 if live: --> 210 val = eval(chunk,glob,loc) 211 try: 212 app(str(val)) /home/ush/webwork/<string> NameError: name 'regpat' is not defined ? Great tutorial, thanks! great ipython sessions Good. Glad to learn of IPython. nice! I'm sure that I'll end up coming back over and over to this series (there's waaaaay too much good stuff in here to be able to digest it all in a single run through). One thing I take issue with, and this has NOTHING to do with the series itself, is the annoying crap that comes after the end of the video: on Firefox 3.0.5 on Ubuntu when the video completes Showmedo autoloads an ad for the SMD Club and then switches to a bit of Nagware asking for comments on the just watched vids ... so to get BACK to the video I just watched I need to *refresh my browser* and this is Bloody Obnoxious! It means that I need to stop the video before it completes if I want to go back and rewatch parts of it (and with a series as dense with detailed info as this that's pretty much a given) The Nagware is also responsible for the fact that 90% of the comments are worthless '--you get my vote!' nonsense that might just as well be Spam. I honestly cannot see how these auto-comments are doing anyone any good: with the signal to noise ratio so skewed how does any author hope to see any useful feedback?? Please consider killing the 'quick comment' nagware and adjusting your 'club' ads to play ONCE on completion? Very well done. Ipython is great buit hard to grok only by text ! Thank you these are great; some brief companion notes would help as well. it is hard to reremember everything that was demonstrated. Nice tutorial
http://showmedo.com/videotutorials/video%3Fname%3D1000020
CC-MAIN-2016-30
refinedweb
982
75.61
v2.0.8 release notes Released December 13, 2019. Downloads Binaries Docker docker pull yugabytedb/yugabyte:2.0.8.0-b5 YSQL Changes - [YSQL] Enable client-to-server TLS encryption for postgres process when use_client_to_server_encryptionis set to true. #2980 - [YSQL] Disable the unnecessary pggate-level auto read restarts. #2812 - [YSQL] yb-admin command to delete namespace, table, and index. #3069 - [YSQL] Assertion failed on TRUNCATE TABLEstatement. #1632 - [YSQL] Consider HASH column when seeking index for ORDER BYclause. #2792 YCQL Changes System improvements - Add log retention by op id policy documentation. #2773 - Switch Linuxbrew to 20181203T161736. #3044 - Check transaction status after load. #2186 - [2DC] Make cdc_pollerlog messages more descriptive - Lower max timeout on master async tasks from 1 hour to 15 minutes. #1655 - Clean up intents written for foreign key check. #3111 Platform - [YW] Add a Prometheus metrics export endpoint. #2459 - [YW] Recursively call task status API sequentially so there is no overlap. #2998 - [Platform] Move the CMK policy to be moved to KMS instead of having it universe level #2942.
https://docs.yugabyte.com/latest/releases/earlier-releases/v2.0.8/
CC-MAIN-2022-05
refinedweb
170
60.82
A Service Mesh for Kubernetes (Part 2): Pods Are Great Until They're Not You can use linkerd as a service mesh with Kubernetes. In Part 2 of this series, see how and why you should install linkerd using DaemonSets. Join the DZone community and get the full member experience.Join For Free In our recent post about linkerd on Kubernetes, A Service Mesh for Kubernetes, Part I: Top-Line Service Metrics, observant readers noticed that linkerd was installed using DaemonSets rather than as a sidecar process. In this post, we’ll explain why (and how!) we do this. As a service mesh, linkerd is designed to be run alongside application code, managing and monitoring inter-service communication, including performing service discovery, retries, load-balancing, and protocol upgrades. At a first glance, this sounds like a perfect fit for a sidecar deployment in Kubernetes. After all, one of Kubernetes’s defining characteristics is its pod model. Deploying as a sidecar is conceptually simple, has clear failure semantics, and we’ve spent a lot of time optimizing linkerd for this use case. However, the sidecar model also has a downside: deploying per pod means that resource costs scale per pod. If your services are lightweight and you run many instances, like Monzo (who built an entire bank on top of linkerd and Kubernetes), then the cost of using sidecars can be quite high. We can reduce this resource cost by deploying linkerd per host rather than per pod. This allows resource consumption to scale per host, which is typically a significantly slower-growing metric than pod count. And, happily, Kubernetes provides DaemonSets for this very purpose. Unfortunately, for linkerd, deploying per host is a bit more complicated than just using DaemonSets. Read on for how we solve the service mesh problem with per-host deployments in Kubernetes. A Service Mesh for Kubernetes One of the defining characteristics of a service mesh is its ability to decouple application communication from transport communication. For example, if services A and B speak HTTP, the service mesh may convert that to HTTPS across the wire, without the application being aware. The service mesh may also be doing connection pooling, admission control, or other transport-layer features, also in a way that’s transparent to the application. In order to fully accomplish this, linkerd must be on the sending side and the receiving side of each request, proxying to and from local instances. E.g. for HTTP to HTTPS upgrades, linkerd must be able to both initiate and terminate TLS. In a DaemonSet world, a request path through linkerd looks like the diagram below: As you can see, a request that starts in Pod A on Host 1 and is destined for Pod J on Host 2 must go through Pod A’s host-local linkerd instance, then to Host 2’s linkerd instance, and finally to Pod J. This path introduces three problems that linkerd must address: - How does an application identify its host-local linkerd? - How does linkerd route an outgoing request to the destination’s linkerd? - How does linkerd route an incoming request to the destination application? What follows are the technical details on how we solve these three problems. If you just want to get linkerd working with Kubernetes DaemonSets, see the previous blog post! How Does an Application Identify Its Host-Local linkerd? Since DaemonSets use a Kubernetes hostPort , we know that linkerd is running on a fixed port on the host’s IP. Thus, in order to send a request to the linkerd process on the same machine that it’s running on, we need to determine the IP address of its host. In Kubernetes 1.4 and later, this information is directly available through the Downward API. Here is an except from hello-world.yml that shows how the node name can be passed into the application: env: - name: NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName - name: http_proxy value: $(NODE_NAME):4140 args: - "-addr=:7777" - "-text=Hello" - "-target=world" (Note that this example sets the http_proxy environment variable to direct all HTTP calls through the host-local linkerd instance. While this approach works with most HTTP applications, non-HTTP applications will need to do something different.) In Kubernetes releases prior to 1.4, this information is still available, but in a less direct way. We provide a simple script that queries the Kubernetes API to get the host IP; the output of this script can be consumed by the application, or used to build an http_proxy environment variable as in the example above. Here is an excerpt from hello-world-legacy.yml that shows how the host IP can be passed into the application: env: - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: NS valueFrom: fieldRef: fieldPath: metadata.namespace command: - "/bin/sh" - "-c" - "http_proxy=`hostIP.sh`:4140 helloworld -addr=:7777 -text=Hello -target=world" Note that the hostIP.sh script requires that the pod’s name and namespace be set as environment variables in the pod. How Does linkerd Route an Outgoing Request to the Destination's linkerd? In our service mesh deployment, outgoing requests should not be sent directly to the destination application, but instead should be sent to the linkerd running on that application’s host. To do this, we can take advantage of a powerful new feature introduced in linkerd 0.8.0 called transformers, which can do arbitrary post-processing on the destination addresses that linkerd routes to. In this case, we can use the DaemonSet transformer to automatically replace destination addresses with the address of a DaemonSet pod running on the destination’s host. For example, this outgoing router linkerd config sends all requests to the incoming port of the linkerd running on the same host as the destination app: routers: - protocol: http label: outgoing interpreter: kind: default transformers: - kind: io.l5d.k8s.daemonset namespace: default port: incoming service: l5d ... How Does linkerd Route an Incoming Request to the Destination Application? When a request finally arrives at the destination pod’s linkerd instance, it must be correctly routed to the pod itself. To do this we use the localnode transformer to limit routing to only pods running on the current host. Example linkerd config: routers: - protocol: http label: incoming interpreter: kind: default transformers: - kind: io.l5d.k8s.localnode ... Deploying linkerd as a Kubernetes DaemonSet gives us the best of both worlds—it allows us to accomplish the full set of goals of a service mesh (such as transparent TLS, protocol upgrades, latency-aware load balancing, etc), while scaling linkerd instances per host rather than per pod. For a full, working example, see the previous blog post, or download our example app. And for help with this configuration or anything else about linkerd, feel free to drop into our very active Slack or post a topic on linkerd discourse. Published at DZone with permission of Alex Leong, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/a-service-mesh-for-kubernetes-part-2-pods-are-grea
CC-MAIN-2022-27
refinedweb
1,165
53.71
Release version: 2.15.4 | Release date: 07.04.2022 Minimum OS requirements: Unity 2017.4 (Api Compatibility Level - Experimental (.NET 4.6 Equivalent) or 2018.3+ Android API level 16 (Android OS 4.1) and above iOS 10.0 or higher Use XCode 13 or higher - CocoaPods 1.10.0 or higher Unity 2017.4 If you are using Unity 2017.4, you need to change Scripting Runtime Version in Player Settings > Other Setting to Experimental (.NET 4.6 Equivalent). HIGH-LEVEL Integration Steps: Step 1: Import SDK Step 2: Project Configuration Step 3: Initialize SDK Step 4: Configure Ad Types Use these instructions to integrate Appodeal Unity Plugin to your application. You can use our demo app as a reference project. Step 1. Import SDK 1.1 Download it Download Appodeal Unity Plugin 2.15.4 that includes the newest Android and iOS Appodeal SDKs with major improvements by clicking on the button below. 1.2 Import it To import Appodeal Unity Plugin, double-click on the Appodeal-Unity-Plugin-2.15.4-06.04.2022.unitypackage file, or go to Assets → Import Package → Custom Package. Keep all the files in the Importing Package window selected, and click Import .. After importing Appodeal Plugin, select File → Build Settings → Android in Unity menu bar. 2. Add flag Custom Gradle Template for Unity 2017.4 - Unity 2019.2 versions or Custom Main Gradle Template for Unity 2019.3 and higher (Build Settings → Player Settings → Publishing settings). permissions you want. External Dependency Manager Appodeal Unity Plugin includes External Dependency Manager package. You need to complete these following steps to resolve Appodeal's dependencies: 1. After importing Appodeal Plugin, select File → Build Settings → iOS in Unity menu bar. 2. The modules, that are required for the Appodeal SDK work, will be imported to your project during the build. You can edit them or add other modules in the Assets → Appodeal → Editor → NetworkConfigs directory. 2.2 . There is SKAdNetworks IDs in Info.plist format: Open Appodeal → Appodeal Settings window in Unity top bar menu. Tick the corresponding checkbox. 2.2.3 Configure App Transport Security Settings In order to serve ads, the SDK requires you to allow arbitrary loads. Set up the following key in info.plist of your app: Open Appodeal → Appodeal Settings window in Unity top bar menu. Tick the corresponding checkbox. 2.2. Add AdMob App Ids from the Unity Menu bar Appodeal → Appodeal Settings tool for each platform. AdMob App ID is the unique ID assigned to your app. To find the AdMob App ID in your AdMob account, go to Apps → your application → app settings and copy the AdMob App ID. For more information about Admob sync check out our FAQ. Step 3. Initialize SDK Before loading and displaying ads, you need to initialize Appodeal SDK, as follows: 3.1 Import Namespaces using AppodealAds.Unity.Api; using AppodealAds.Unity.Common; 3.2 Add Following Code.
https://wiki.appodeal.com/en/unity/get-started
CC-MAIN-2022-27
refinedweb
486
61.53
Linux® and UNIX® systems allow you to schedule jobs in the future, either just once or on a recurring schedule. A reader of another recent tip, Job scheduling with cron and at, wanted to know how to record a radio or TV program and stop the recording when the program ended. I was reminded of Ettore Bugatti, an Italian who built very fine cars in Alsace-Lorraine. When a customer asked about his use of cable-operated brakes, long after other car makers had switched to hydraulic brakes, Bugatti replied, "Monsieur, I make my cars to go, not to stop." So this tip adds brakes to your job scheduling needs. Terminating a job after a certain time, or after other criteria are met, usually involves having one process to run the job and another to monitor the completion criteria. In this tip you learn how to have a process manage the time while the real job runs. You also learn how to use the signal and trap facilities to terminate one of these tasks if the other finishes prematurely. The timer process The basic tool for timing things in a shell script is the sleep command, which causes the running shell to stop execution for a specified time. The default is to stop for a number of seconds, but you can append the time values with s, m, or h, for seconds, minutes, or hours, respectively. This suspends execution of the shell, so your real work needs to be running in another shell, which you accomplish by placing the task in the background using the & character. To get started, suppose you want to run a command for 10 minutes. Listing 1 shows a bash shell script that you might code to try running the xclock command for a specified period of time. Try it on your own system. Listing 1. First attempt using runclock1.sh #!/bin/bash runtime=${1:-10m} # Run xclock in background xclock& #Sleep for the specified time. sleep $runtime echo "All done" You should see a clock something like the one in Figure 1. Figure 1. A plain xclock The only thing wrong with this approach is that the script stopped but the clock did not. Parent, child, and orphan Listing 2 shows an enhanced runclock2.sh script that captures some information about the process ids of the shell and the xclock processes, along with the output of the script and the output of the ps command, showing the process status for xclock, after the shell completes. Listing 2. Gathering diagnostic information runclock2.sh Notice that the parent process id (PPID) in the first output of ps is 8619, which is the process id (PID) of the script. Once the script terminates, the clock process becomes an orphan and is assigned to be a child of the init process—process 1. The child does not terminate immediately when its parent terminates, although it will terminate when you log out of the system. Terminating a child process The solution to the problem of non-terminating child processes is to explicitly terminate them using the kill command. This sends a signal to a process, and that usually terminates the process. Later in this tip you see how a process can trap signals and not terminate, but here you use the interrupt signal (SIGINT) to terminate the clock. To see a list of signals available on your system, use the kill command with the -l option, as shown in Listing 3. Note that some signals are common to all Linux systems, but some may be specific to the particular machine architecture. Some, such as floating point exceptions (SIGFPE) or segment violation (SIGSEGV), are generated by the system, while others such as interrupt (SIGINT), user signals (SIGUSR1 or SIGUSR2), or unconditional terminate (SIGKILL), can be sent by applications. Listing 3. Signals on a Fedora Core 5 system [ian@attic Recall from Listing 2 that we captured the PID of the xclock process using the $! shell variable. Listing 4 shows how to use this information to send a terminate signal (SIGTERM) to the xclock process to terminate it. Listing 4. Terminating the child process using runclock3.sh If you omit the signal specification, then SIGTERM is the default signal. The SIG part of a signal name is optional. Instead of using -s and a signal name, you can just prefix the signal number with a -, so the four forms shown in Listing 6 are equivalent ways of killing process 9285. Note that the special value -0, as used in Listing 4 above, tests whether a signal could be sent to a process. Listing 6. Ways to specify signals with the kill command kill -s SIGTERM 9285 kill -s TERM 9285 kill -15 9285 kill 9285 Other termination conditions You now have the basic tools to run a process for a fixed amount of time. Before going deeper into signal handling, let's consider how to handle other termination requirements, such as repetitively capturing information for a finite time, terminating when a file becomes a certain size, or terminating when a file contains a particular string. This kind of work is best done using a loop, such as for, while, or until, with the loop executed repeatedly with some built-in delay provided by the sleep command. If you need finer granularity than seconds, you can also use the usleep command. You can add a second hand to the clock, and you can customize colors. Use the showrgb command to explore available color names. Suppose you use the command xclock -bg Thistle -update 1& to start a clock with a second hand, and a Thistle-colored background. Now you can use a loop with what you have learned already to capture images of the clock face every second and then combine the images to make an animated GIF image. Listing 7 shows how to use the xwininfo command to find the window id for the xclock command, then capture 60 clock face images at one second intervals, and finally combine these into an infinitely looping animated GIF file that is 50% of the dimensions of the original clock. Listing 7. Capturing images one second apart Timing of this type is always subject to some variation, so the import command to grab the clock image is run in the background, leaving the main shell free to keep time. Nevertheless, some drift is likely to occur because it does take a finite amount of time to launch each subshell for the background processing. This example also builds in a 5-second delay at the start to allow the shell script to be started and then give you time to click on the clock to bring it to the foreground. Even with these caveats, some of my runs resulted in one missed tick and an extra copy of the starting tick because the script took slightly over 60 seconds to run. One way around this problem would be to use the usleep command with a number of microseconds that is enough less than one second to account for the overhead, as shown by the commented line in the script. If all goes as planned, your output image should be something like that in Figure 2. Figure 2. A ticking xclock This example shows you how to take a fixed number of snapshots of some system condition at regular intervals. Using the techniques here, you can take snapshots of other conditions. You might want to check the size of an output file to ensure it does not pass some limit, or check whether a file contains a certain message, or check system status using a command such as vmstat. Your needs and your imagination are the only limits. Signals and traps If you run the getclock.sh script of Listing 7 yourself, and you close the clock window while the script is running, the script will continue to run but will print error messages each time it attempts to take a snapshot of the clock window. Similarly, if you run the runclock3.sh script of Listing 4, and press Ctrl-c in the terminal window where the script is running, the script will immediately terminate without shutting down the clock. To solve these problems, your script needs to be able to catch or trap some of the signals discussed in Terminating a child process. If you execute runclock3.sh in the background and run the ps -f command while it is running, you will see output similar to Listing 8. Listing 8. Process information for runclock3.sh Note that the ps -f output has three entries related to the runclock3.sh process (PID 10101). In particular, the sleep command is running as a separate process. One way to handle premature death of the xclock process or the use of Ctrl-c to terminate the running script is to catch these signals and then use the kill command to kill the sleep command. There are many ways to accomplish the task of determining the process for the sleep command. Listing 9 shows the latest version of our script, runclock4.sh. Note the following points: - The sleepcommand is explicitly run in the background. - The waitcommand is used to wait for termination of the sleepcommand. - The first trapcommand causes the stopsleepfunction to be run whenever a SIGCHLD, SIGINT, or SIGTERM signal is received. The PID of the sleeper process is passed as a parameter. - The stopsleepfunction is run as the result of a signal. It prints a status message and sends the sleepcommand a SIGINT signal. - When the sleepcommand terminates, for whatever reason, the waitcommand is satisfied. Traps are then cleared, and the xclockcommand is terminated. Listing 9. Trapping signals with runclock4.sh " >Listing 10 shows the output from running runclock4.sh three times. The first time, everything runs to its natural completion. The second time, the xclock is prematurely closed. And the third time, the shell script is interrupted with Ctrl-c. Listing 10. Stopping runclock4.sh in different ways Note how many times the stopsleep function is called as evidenced by the "Awaken" messages. If you are not sure why, you might try making a separate copy of this function for each interrupt type that you catch and see what causes the extra calls. You will also note that some job control messages tell you about termination of the xclock command and interrupting the sleep command. When you run a job in the background with default bash terminal settings, bash normally catches SIGCHLD signals and prints a message after the next terminal output line is printed. The set -bm command in the script tells bash to report SIGCHLD signals immediately and to enable job control monitoring, The alarm clock example in the next section shows you how to suppress these messages. An alarm clock Our final exercise returns to the original problem that motivated this article: how to record a radio program. We will actually build an alarm clock. If your laws allow recording of such material for your proposed use, you can build a recorder instead by adding a program such as vsound. For this exercise, we will use the GNOME rhythmbox application to illustrate some additional points. Even if you use another media player, this discussion should still be useful. An alarm clock could make any kind of noise you want, including playing your own CDs, or MP3 files. In central North Carolina, we have a radio station, WCPE, that broadcasts classical music 24 hours a day. In addition to broadcasting, WCPE also streams over the Internet in several formats, including Ogg Vorbis. Pick your own streaming source if you prefer something else. To start rhythmbox from an X Windows terminal session playing the WCPE Ogg Vorbis stream, you use the command shown in Listing 11. Listing 11. Starting rhythmbox with the WCPE Ogg Vorbis stream rhythmbox --play The first interesting point about rhythmbox is that the running program can respond to commands, including a command to terminate. So you don't need to use the kill command to terminate it, although you still could if you wanted to. The second point is that most media players, like the clock that we have used in the earlier examples, need a graphical display. Normally, you run commands with the cron and at facilities at some point when you may not be around, so the usual assumption is that these scheduled jobs do not have access to a display. The rhythmbox command allows you to specify a display to use. You probably need to be logged on, even if your screen is locked, but you can explore those variations for yourself. Listing 12 shows the alarmclock.sh script that you can use for the basis of your alarm clock. It takes a single parameter, which specifies the amount of time to run for, with a default of one hour. Listing 12. The alarm clock - alarmclock.sh Note the use of set +bm in the stopsleep function to reset the job control settings and suppress the messages that you saw earlier with runclock4.sh Listing 13 shows an example crontab that will run the alarm from 6 a.m. to 7 a.m. each weekday (Monday to Friday) and from 7 a.m. for two hours each Saturday and from 8:30 a.m. for an hour and a half each Sunday. Listing 13. The alarm clock - alarmclock.sh 0 6 * * 1-6 /home/ian/alarmclock.sh 1h 0 7 * * 7 /home/ian/alarmclock.sh 2h 30 8 * * 0 /home/ian/alarmclock.sh 90m Refer to our previous tip Job scheduling with cron and at to learn how to set your own crontab for your new alarm clock. In more complex tasks, you may have several child processes. The cleanup routine shows how to use the ps command to find the children of your script process. You can extend the idea to loop through an arbitrary set of children and terminate each one. Learn - This tip expands on our previous tip Job scheduling with cron and at, which introduces you to scheduling jobs on Linux. - See all Linux tips on developerWorks. -. - In the developerWorks Linux zone, find more resources for Linux developers, including Linux tutorials, as well as our readers' most recent favorite Linux articles and tutorials. -.
http://www.ibm.com/developerworks/linux/library/l-job-terminating/
CC-MAIN-2013-48
refinedweb
2,388
69.52
On Mon, Dec 01, 2003 at 02:28:20PM -0500, Nicholas Wourms wrote: > vinschen@redhat.com wrote: > >On Mon, Dec 01, 2003 at 01:23:47PM -0500, Nicholas Wourms wrote: > >>-. Btw., perhaps it's not that good an idea to implement flock using fcntl in Cygwin. According to the Linux manpage, flock only places advisory locks: "flock(2) places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock(2) and perform I/O on the file." Given that also the Linux kernel had problems with emulating flock using fcntl once, it might be a good idea to think about another solution, for instance keeping the flocked regions in a linked list within a per file table or something, and use this information only across applications using flock on the same files. Due to the pure advisory quality of the locking, the files don't have to be actually locked using Windows system calls. Just flock has to return sensible values. As on Linux, this would also have the advantage of having flock and fcntl semantics entirely separated. > extern "C" int > mkfifo (const char *path, mode_t mode) > { > return (mknod (path, (mode_t) (mode|S_IFIFO), 0)); > } Doesn't look wrong so, go ahead and submit a patch ;-) Corinna -- Corinna Vinschen Please, send mails regarding Cygwin to Cygwin Developer mailto:cygwin@cygwin.com Red Hat, Inc.
https://sourceware.org/pipermail/cygwin-developers/2003-December/007389.html
CC-MAIN-2022-33
refinedweb
232
58.01
setClass Percentile Create a Class Definition Create a class definition and return a generator function to create objects from the class. Typical usage will be of the style: myClass <- setClass("myClass", slots= ...., contains =....) where the first argument is the name of the new class and, if supplied, the arguments slots= and contains= specify the slots in the new class and existing classes from which the new class should inherit. Calls to setClass() are normally found in the source of a package; when the package is loaded the class will be defined in the package's namespace. Assigning the generator function with the name of the class is convenient for users, but not a requirement. - Keywords - classes, methods, programming Usage setClass(Class, representation, prototype, contains=character(), validity, access, where, version, sealed, package, S3methods = FALSE, slots) Arguments - Class character string name for the class. - slots The names and classes for the slots in the new class. This argument must be supplied by name, slots=, in the call, for back compatibility with other arguments no longer recommended. The argument must be vector with a names attribute, the names being those of the slots in the new class. Each element of the vector specifies an existing class; the corresponding slot must be from this class or a subclass of it. Usually, this is a character vector naming the classes. It's also legal for the elements of the vector to be class representation objects, as returned by getClass. As a limiting case, the argument may be an unnamed character vector; the elements are taken as slot names and all slots have the unrestricted class "ANY". - contains A vector specifying existing classes from which this class should inherit. The new class will have all the slots of the superclasses, with the same requirements on the classes of these slots. This argument must be supplied by name, contains=, in the call, for back compatibility with other arguments no longer recommended. See the section ‘Virtual Classes’ for the special superclass "VIRTUAL". - prototype, where, validity, sealed, package These arguments are currently allowed, but either they are unlikely to be useful or there are modern alternatives that are preferred. prototype: supplies an object with the default data for the slots in this class. A more flexible approach is to write a method for initialize(). where: supplies an environment in which to store the definition. Should not be used: For calls to setClass()appearing in the source code for a package the definition will be stored in the namespace of the package. validity: supplied a validity-checking method for objects from this class. For clearer code, use a separate call to setValidity(). sealed: if TRUE, the class definition will be sealed, so that another call to setClasswill fail on this class name. But the definition is automatically sealed after the namespace is loaded, so explicit sealing it is not needed. package: supplies an optional package name for the class, but the class attribute should be the package in which the class definition is assigned, as it is by default. - representation, access, version, S3methods All these arguments are deprecated from version 3.0.0 of R and should be avoided. representationis an argument inherited from S that included both slotsand contains, but the use of the latter two arguments is clearer and recommended. accessand versionare included for historical compatibility with S-Plus, but ignored. S3methodsis a flag indicating that old-style methods will be written involving this class; ignored now. Value A generator function suitable for creating objects from the class is returned, invisibly. A call to this function generates a call to new for the class. The call takes any number of arguments, which will be passed on to the initialize method. If no initialize method is defined for the class or one of its superclasses, the default method expects named arguments with the name of one of the slots and unnamed arguments that are objects from one of the contained classes. Typically the generator function is assigned the name of the class, for programming clarity. This is not a requirement and objects from the class can also be generated directly from new. The advantages of the generator function are a slightly simpler and clearer call, and that the call will contain the package name of the class (eliminating any ambiguity if two classes from different packages have the same name). If the class is virtual, an attempt to generate an object from either the generator or new() will result in an error. Basic Use: Slots and Inheritance The two essential arguments other than the class name are slots superclass information specifies which methods apply indirectly, through inheritance. See Methods_Details for inheritance in method selection. The slots in a class definition will be the union of all the slots specified directly by slots and all the slots in all the contained classes. There can only be one slot with a given name. A class may override the definition of a slot with a given name, but only if the newly specified class is a subclass of the inherited one. For example, if the contained class had a slot a with class "ANY", then a subclass could specify a with class "numeric", but if the original specification for the slot was class "character", the new call to setClass would generate an error. Slot names "class" and "Class" are not allowed. There are other slot names with a special meaning; these names start with the "." character. To be safe, you should define all of your own slots with names starting with an alphabetic character. Some inherited classes will be treated specially---object types, S3 classes and a few special cases---whether inherited directly or indirectly. See the next three sections. Virtual Classes Classes exist for which no actual objects can be created, the virtual classes. The most common and useful form of virtual class is the class union, a virtual class that is defined in a call to setClassUnion() rather than a call to setClass(). This call lists the members of the union---subclasses that extend the new class. Methods that are written with the class union in the signature are eligible for use with objects from any of the member classes. Class unions can include as members classes whose definition is otherwise sealed, including basic R data types. Calls to setClass() will also create a virtual class, either when only the Class argument is supplied (no slots or superclasses) or when the contains= argument includes the special class name "VIRTUAL". In the latter case, a virtual class may include slots to provide some common behavior without fully defining the object---see the class '>traceable for an example. Note that "VIRTUAL" does not carry over to subclasses; a class that contains a virtual class is not itself automatically virtual. Inheriting from Object Types. This appears as a pseudo-slot, ".Data" and can be treated as a slot but actually determines the type of objects from this slot.. Classes may also inherit from "vector", "matrix" or "array". The data part of these objects can be any vector data type. For an object from any class that does not contain one of these types or classes,, ".xData". See the example for class "stampedEnv" below. An object from such a class does not have a ".Data" pseudo-slot. For most computations, these classes behave transparently as if they inherited directly from the anomalous type. S3 method dispatch and the relevant as.type () functions should behave correctly, but code that uses the type of the object directly will not. For example, as.environment(e1) would work as expected with the "stampedEnv" class, but typeof(e1) is "S4". Inheriting from S3 Classes). Broadly speaking, both S3 and S4 method dispatch try to behave sensibly with respect to inheritance in either system. Given an S4 object, S3 method dispatch and the inherits function should use the S4 inheritance information. Given an S3 object, an S4 generic function will dispatch S4 methods using the S3 inheritance, provided that inheritance has been declared via setOldClass. For details, see setOldClass and Section 10.8 of the reference. Classes and Packages in a call to setClass, a corresponding class definition will be found, looking from the namespace of the current package, assuming the call in question appears directly in the source for the package, as it should to avoid ambiguity. The class definition must be already defined in this package, in the imports directives of the package's DESCRIPTION and NAMESPACE files or in the basic classes defined by the methods package. (The ‘methods’ package must be included in the imports directives for any package that uses S4 methods and classes, to satisfy the "CMD check" utility.) If a package imports two classes of the same name from separate packages, the packageSlot of the name argument needs to be set to the package name of the particular class. This should be a rare occurrence. References Chambers, John M. (2016) Extending R, Chapman & Hall. (Chapters 9 and 10.) See Also Classes_Details for a general discussion of classes, Methods_Details for an analogous discussion of methods, makeClassRepresentation Aliases - setClass - classGeneratorFunction-class Examples library(methods) # NOT RUN { ## A simple class with two slots track <- setClass("track", slots = c(x="numeric", y="numeric")) ## an object from the class t1 <- track(x = 1:10, y = 1:10 + rnorm(10)) ## A class extending the previous, adding one more slot trackCurve <- setClass("trackCurve", slots = c(smooth = "numeric"), contains = "track") ## an object containing a superclass object t1s <- trackCurve(t1, smooth = 1:10) ## A class similar to "trackCurve", but with different structure ## allowing matrices for the "y" and "smooth" slots setClass("trackMultiCurve", slots = c(x="numeric", y="matrix", smooth="matrix"), prototype = list(x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0))) ## A class that extends the built-in data type "numeric" numWithId <- setClass("numWithId", slots = c(id = "character"), contains = "numeric") numWithId(1:3, id = "An Example") ## inherit from reference object of type "environment" stampedEnv <- setClass("stampedEnv", contains = "environment", slots = c(update = "POSIXct")) setMethod("[[<-", c("stampedEnv", "character", "missing"), function(x, i, j, ..., value) { ev <- as(x, "environment") ev[[i]] <- value #update the object in the environment x@update <- Sys.time() # and the update time x}) e1 <- stampedEnv(update = Sys.time()) e1[["noise"]] <- rnorm(10) # } # NOT RUN { <!-- %dont show --> # }
https://www.rdocumentation.org/packages/methods/versions/3.5.2/topics/setClass
CC-MAIN-2020-05
refinedweb
1,718
52.9
Hello, first of all sorry if my question is stupid but I’m new to Ionic, Angular and TypeScript. I’m desperately trying to hide the keyboard after the user hits ‘return’ from my search bar and nothing that I’ve tried so far worked. I’ve followed these steps but whenever I call an instance, it doesn’t work. For example : this.keyboard.show() My “search.ts” has “ import { Keyboard } from '@ionic-native/keyboard'” constructor(public navCtrl: NavController, public navParams: NavParams, public api: ApiProvider, public keyboard: Keyboard) { } And wherever I call “keyboard.show()” Can anybody explain me why ? Thank you
https://forum.ionicframework.com/t/how-to-hide-the-keyboard/133745
CC-MAIN-2020-40
refinedweb
101
58.58
« Return to documentation listing #include <mpi.h> int MPI_Type_lb(MPI_Datatype datatype, MPI_Aint *displacement) INCLUDE ’mpif.h’ MPI_TYPE_LB(DATATYPE, DISPLACEMENT, IERROR) INTEGER DATATYPE, DISPLACEMENT, IERROR This deprecated routine is not available in C++. MPI_Type_lb returns the lower bound of a data type. This may differ from zero if the type was constructed using MPI_LB. The "pseudo-datatypes," MPI_LB and MPI_UB, can be used, respectively, to mark the lower bound (or the upper0, disp0), ..., (type(n-1), disp(n-1)} then the lower bound of Typemap is defined to be (min(j) disp(j) if no entry has lb(Typemap) = ( basic type lb (min(j) {disp(j) such that type(j) = lb} otherwise (max(j) disp(j) + sizeof((type(j)) + e Table of Contents
http://icl.cs.utk.edu/open-mpi/doc/v1.5/man3/MPI_Type_lb.3.php
CC-MAIN-2016-07
refinedweb
122
56.55
Patch is a command that is used to apply patch files to the files like source code, configuration. Patch files holds the difference between original file and new file. In order to get the difference or patch we use diff tool. Software is consist of a bunch of source code. The source code is developed by developers and changes in time. Getting whole new file for each change is not a practical and fast way. So distributing only changes is the best way. The changes applied to the old file and than new file or patched file is compiled for new version of software. Syntax patch [options] [originalfile [patchfile]] patch -pnum <patchfile $ patch --help Create Patch File Now we will create patch file in this step but we need some simple source code with two different version. We call the source code file name as myapp.c . myapp_old.c #include <stdio.h> void main(){ printf("Hi poftut"); } myapp.c #include <stdio.h> void main(){ printf("Hi poftut"); printf("This is new line as a patch"); } Now we will create a patch file named myapp.patch . $ diff -u myapp_old.c myapp.c > myapp.patch We can print myapp.patch file with following command $ cat myapp.patch Apply Patch File Now we have a patch file and we assume we have transferred this patch file to the system which holds the old source code which is named myapp_old.patch . We will simply apply this patch file. Here is what the patch file contains - the name of the patched file - the different content $ patch < myapp.patch Take Backup Before Applying Patch One of the useful feature is taking backups before applying patches. We will use -b option to take backup. In our example we will patch our source code file with myapp.patch . $ patch -b < myapp.patch The backup name will be the same as source code file just adding the .orig extension. So backup file name will be myapp.c.orig Set Backup File Version While taking backup there may be all ready an backup file. So we need to save multiple backup files without overwriting. There is -V option which will set the versioning mechanism of the original file. In this example we will use numbered versioning. $ patch -b -V numbered < myapp.patch As we can see from screenshot the new backup file is named as number like myapp.c.~1~ Validate Patch File Without Applying or Dry run We may want to only validate or see the result of the patching. There is a option for this feature. We will use --dry-run option to only emulate patching process but not change any file really. $ patch --dry-run < myapp.patch Reverse Patch Some times we may need to patch in reverse order. So the apply process will be in reverse. We can use -R parameter for this operation. In the example we will patch myapp_old.c rather than myapp.c $ patch -R myapp_old.c < myapp.patch As we can see that new changes are reverted back. 2 thoughts on “Patch Command Tutorial With Examples For Linux” Thanks for the writetup to help me to demystify the patching process. The hands on tutorial definitely helped me. The ability to reverse the patch was most helpful! very well and detailed explanation of the patch utility. Was able to simulate and practice it for better understanding, thanks for your efforts !
https://www.poftut.com/patch-command-tutorial-with-examples-for-linux/?replytocom=1289
CC-MAIN-2021-39
refinedweb
567
77.03
TODO: There is still some unneccessary duplication of code in the showVariables and showTypevariables methods that I might take care of sometime. package require Tk package require snit option add *background white snit::widget snitPane { option -label option -command option -open 0 onconfigure -open value { set options(-open) $value $self redraw } method open/close {} { $self configure -open [expr {grid $w.$o-name $w.$o-value -sticky news grid columnconfigure $w 1 -weight 1 } } method showVariables {w} { foreach v $specimen } } method showTypevariables {w} { foreach v $specimenType } } variable specimen variable specimenOpts variable specimenVars variable specimenTypeVars variable specimenNS variable nameLabelOpts {-anchor w -padx 15 -font {helvetica 10 bold}} variable valueLabelOpts {-anchor w -relief sunken} constructor args { $self configurelist $args set specimen [$self cget -specimen] # did we get a snit at all? if {$specimen eq {}} { tk_messageBox -icon error -message "No snit provided" exit } # if it's a snit, it should be able to tell us its type if {[catch {$specimen info type} result]} { tk_messageBox -icon error -message "Not a snit? $result" exit } # now find out some details about the snit # does it have options? set specimenOpts [$specimen info options] # does it have instance variables? set specimenVars [$specimen info vars] # does it have type variables? set specimenTypeVars [$specimen info typevars] # if it has instance variables or options, we can know its namespace set specimenNS [if {[llength $specimenVars] > 0} { namespace qualifiers [lindex $specimenVars 0] }] # exclude the 'options' variable from the instance variables set specimenVars [lmap v $specimenVars {expr {[regexp {::options$} $v] ? [continue] : $v }}] set w [frame $win.heading] label $w.name -anchor w -font {helvetica 16 bold} -text $specimen label $w.class -anchor e -font {helvetica 14 italic} -text [$specimen info type] pack $w.name $w.class -expand yes -fill x -side left pack $w -expand yes -fill x snitPane $win.options -command [mymethod showOptions] -label Options -open true pack $win.options -expand yes -fill x snitPane $win.vars -command [mymethod showVariables] -label {Instance Variables} pack $win.vars -expand yes -fill x snitPane $win.tvars -command [mymethod showTypevariables] -label {Type Variables} pack $win.tvars -expand yes -fill x label $win.fill pack $win.fill -expand yes -fill both pack $win -expand yes -fill both -anchor nw } } image create photo nav1rightarrow16 -data { R0lGODlhEAAQAIAAAPwCBAQCBCH5BAEAAAAALAAAAAAQABAAAAIdhI+pyxCt woNHTmpvy3rxnnwQh1mUI52o6rCu6hcAIf5oQ3JlYXRlZCBieSBCTVBUb0dJ RiBQcm8gdmVyc2lvbiAyLjUNCqkgRGV2ZWxDb3IgMTk5NywxOTk4LiBBbGwg cmlnaHRzIHJlc2VydmVkLg0KaHR0cDovL3d3dy5kZXZlbGNvci5jb20AOw== } image create photo nav1downarrow16 -data { R0lGODlhEAAQAIAAAPwCBAQCBCH5BAEAAAAALAAAAAAQABAAAAIYhI+py+0P UZi0zmTtypflV0VdRJbm6fgFACH+aENyZWF0ZWQgYnkgQk1QVG9HSUYgUHJv IHZlcnNpb24gMi41DQqpIERldmVsQ29yIDE5OTcsMTk5OC4gQWxsIHJpZ2h0 cyByZXNlcnZlZC4NCmh0dHA6Ly93d3cuZGV2ZWxjb3IuY29tADs= } snit::type dog { option -breed mongrel option -color variable weight variable numLegs 4 typevariable eats typevariable sound Woof! } dog Fido snitscope .s -specimen Fido after 1500 {Fido configure -color black} escargo 3 Jan 2004 - This new version of Snitscope no longer requires the BWidget tool kit. I did notice, after using wish-reaper to collect the code, that when running this code the variable weight and the typevariable eats are not displayed. This might be a Snit issue, since these variables might not yet exist, since they were declared but not assigned any values.I also think the handling of the down and right arrow might not be handled the way you intended. When I click on an arrow, it does not change shape. The code provides two images, and there is some logic for selecting between them, but in fact the shape does not change. If they are supposed to change, then something is a little wrong somewhere.PL: yes, undefined variables aren't displayed. Instance variables that haven't been assigned values don't even appear in the [$obj info vars] list. I'm still working (on and mostly off) on this, and I might do something clever about this some day: for now I just use this example to point out you won't see all that you get.The arrow problem should be fixed now.To think about: - Type variables can be listed even if they have no values; maybe I should include them in the viewer? - In theory, the snitscope could be used to edit option/variable values... Peter Lewerin (2004-01-03): the following comments were made on the previous version of the code.escargo 8 Dec 2003 - The demo proc is defined, but never called in this code.Peter Lewerin: yes, it's a "write-demo", not really a "run-demo".Is defining a method named list a possible problem? Conceptually, it might clash with the normal Tcl list command.PL: How? It's never used except as a subcommand to the object command. I use both in the internal code above. Anyway, the code is not very well-written, I should re-write it some time.WHD: No, there's no problem defining methods or typemethods with the same name as standard Tcl commands. That's why the form "$self methodname" is used to call method "methodname" within another method.escargo: I was not concerned with the software getting confused, only programmers. A too-casual reading of the source might lead to misunderstanding. (Or someone using grep or other searching tools might get a false hit looking for one list or the other.)WHD: I can only speak for myself, of course, but I often find it convenient to have methods with names like "list" and "set", and in reading my own code after a lengthy interval I've not found it confusing--simply because the method name is never the first token in a command.
http://wiki.tcl.tk/9764
CC-MAIN-2018-05
refinedweb
876
54.52
20 April 2012 10:46 [Source: ICIS news] LONDON (ICIS)--The European phenol and acetone market has been somewhat divided in relation to supply and demand during the first four months of 2012, despite major overhauls and unexpected production problems, market sources said on Friday. Although the European phenol and acetone market has been plagued by productions problems and planned outages over the past four months, some buyers do not feel supply for either product has been “seriously” tight. However, most consumers confirm that during February, when record low temperatures hampered production across the phenol chain, some orders were rescheduled, delayed or re-routed. Invariably, the largest consumers of phenol and acetone concede that they would probably be the last to feel the impact of supply problems because of long-term contractual agreements with their suppliers. But producers said that at times during the first quarter, buyers, no matter what their size, were frantically looking for volume. “Some of our [phenol and acetone] customers were begging us for volume. They didn’t care about a price they simply wanted the material,” said one European producer. In the spot markets, inventories clearly dropped to very low levels and prices surged as a result. While acetone sources confirm that at times, material was tight for spot volumes, phenol buyers say they have been able to get all the volume they need. When talking about supply, one major buyer of phenol and acetone said: “?xml:namespace> Despite the difference in ideas about the balance of the market, Spain-based CEPSA Quimica and France-based Novapex are both running, but INEOS Phenol has just started a four-week planned turnaround in An INEOS Phenol source described it stocks of phenol and acetone as “really tight”. Although perceptions differ about supply and demand, sources agree that the strong start to 2012 took them by surprise and this too has contributed to the tightness felt, particularly in the first quarter. Inventories were brought down to “dangerously low” levels on both sides. Indeed, the “Christmas” destocking started as early as September last year, as attention turned to cost. This remains the main focus as does strict inventory management across the petrochemical sector. Meanwhile, prices for acetone and phenol have started to erode as availability improves. This not only stems from the resumption of production but also the lack of export opportunities for phenol and acetone and their respective derivatives to the key Chinese market. “The arb [arbitrage] to Asia is firmly closed and there is nothing moving out of Europe or the “Asian demand for phenol and acetone is really very bad. Also demand is poor for derivative. There are no export opportunities which lead me to think that Looking ahead to May, INEOS Phenol is due to come back on stream and if demand in A solvent trader was not “too optimistic” about May. “In terms of activity, I am not too optimistic. In the south of Meanwhile, margin retention remains key for many market participants. One major buyer of both materials said: “It’s all about margin retention, forget [margin] recovery. Feedstock prices don’t look like there going to be coming down sometime soon.” Acetone spot is currently valued at a €1,100-1,160/tonne ($1,447-1,526/tonne) FD (free delivered) NWE (northwest Spot phenol is notionally assessed at €350/tonne over the April benzene contract price which settled at €890/onne FOB (free on board).
http://www.icis.com/Articles/2012/04/20/9552115/Europe-phenol-acetone-market-divided-on-supply-and-demand.html
CC-MAIN-2013-20
refinedweb
575
57.4
>>IMAGE." XML? that's so 1990 (Score:5, Insightful). Re:XML? that's so 1990 (Score:5, Informative) To see how clean YAML is to reads for humans and to parse by machine look at a Sample Document [wikipedia.org]. And here's something truly impressive, a Yaml Quick reference card [yaml.org] written entirely in YAML itself. Not only is it a marvelously short card, it's human and machine readable. It's a superset of JSON too. Re: (Score:2) Re: (Score:2, Informative) Interesting. How does YAML handle validation and user defined grammars? Multiple ways of varing stringency. For the simple case you can define types (.e.g. floats, ints, or user defined types). For the vast majority of uses that's all you need for validation. Now if you want to define a schema there are several different ones that are used. Kwalify and Rx are two. Finally, there are YAML 2 XML converters. So you can just convert the YAML to XML and use your favorite XML validator. Thus the validation itself other than the types is not baked into the definition and thus Re: (Score:1) Great for human readability. Terrible (due to some python-like indent rules) for humans to add content to. Meanwhile, XML might not be quite as nice as YAML for reading, but it is easier to figure out where you made a mistake, assuming you're pretty printing it (but the best thing is that pretty printing it is unnecessary). Re:XML? that's so 1990 (Score:5, Insightful) Great for human readability. Terrible (due to some python-like indent rules) for humans to add content to. Oh come on man. This is like the ancient discarded whitespace lament about python. I was once like you before I started writing python. Then I saw the huge huge light of why white space indenting is so great. I could explain but I'm not sure I could have convinced even myself before trying it. Bottom line. it's freakin easy to get the white space right and any decent editor with context sensitive tabs does it for you. emacs, vim, bbedit, eclipse. Is there any that don't? This is a NON ISSUE Meanwhile, XML might not be quite as nice as YAML for reading, but it is easier to figure out where you made a mistake, assuming you're pretty printing it (but the best thing is that pretty printing it is unnecessary). Ha! you make me laugh. So now we need special editors and printers for XML reading. Were we not just complaining about white space. Now you pretty print to put perfect white space in XML? Re: (Score:2) Notepad, which is so often used by the technically non-clueful. Of which, I seem to work with a few. Of course, you should use a real editor. This somehow doesn't prevent people from using notepad b/c they don't know better, or using vim but not knowing HOW to use vim and still we lose all indenting. and I never said you needed a special editor for XML. Not even that you need one for JSON or YAML. Pretty printing isn't MANDATORY for XML... which is really the point. With it NOT necessary, means you can fuck up Re: (Score:3) When is it ever desirable for indentation to not match the logical structure of a program? The only possible reason I can come up with is if you're intentionally attempting to obfuscate your code. Re: (Score:2) You're getting close, it's definitely to allow an intentional expression and it's going to be a bug for all people who use white space to express more than just the {}'ness. I wonder why a language has to enforce something that could have been enforced by the editor for those that value it. Strictness on this is what kept back so many perl coders and stopped python from ruling the world. But... I don't mind... and python-ites prefer white space to world domination, so thats good too! Re: (Score:1) bullshit, idiot. indentation is simple. Re: (Score:2) I'm with you on the python whitespace thing, but for YAML it's different. We're not talking about writing code here. It can be tricky to get the whitespace right but it's a damn sight easier than learning and reading XML syntax. Remember that 99% of the time machines process these files and we only care to make reading easy (where YAML whitespace is a non-issue) and human editing easy, where it isn't too bad. Composing from scratch by hand isn't really something you're going to be doing with YAML (or XML). Re: (Score:1) Great for human readability. Terrible (due to some python-like indent rules) for humans to add content to. Apparently you are not aware that YAML, being a superset of JSON, can be written entirely in JSON, or a mixof the two. in JSON you don't need to use white space. So you use the white space in YAML when it makes sense (nearly always) and when you get into absurd edge cases then you toss in a little JSON syntax when apropos. So sorry, you just don't have a case to make here unless you want to say something bad about JSON as well. Re: (Score:2) I use JSON (and occasionally YAML), but only for data interchange formats where I don't expect a human to need to modify it. Yes, I am aware that JSON and YAML are largely related. And I a few times tried to write up files in JSON, just as a mockup of my intended data structure. Yes, I used a real editor with proper tab indenting. It still got to be pretty unreadable. I use Data::Dumper whenever I want the data format to be as explict as possible, but only for debugging. But it's so much worse than that. XML Re: (Score:2) Does anyone else feel like they just looked at some COBOL source when looking at the YAML example? Re: (Score:2) [w3schools.com]", which is apparently (according to [yaml.org]) not possible in YAML. YAML is not for standards (Score:2) XML is perfectly suitable for long term data storage and exchange. You have namespaces, schemas, and a millions of tools to handle it. YAML is OK for storing configuration data. It's not even that good for anything else. Also anyone who "parses in ad hoc ways" deserves to be slapped in the face. Re: (Score:2) I'm perplexed why people continue to use XML when there is YAML. Can you point to me, please, to the reference on how one can define in YAML the equivalent of a schema? You know, to act as the "contract" for the data exchange protocol... extensions (to allow 3rd party custom data sections) and namespaces (to isolate the 3rd party extensions that I'm not interested in) would be a real bonus. Re: (Score:2) I'm perplexed why people continue to use XML when there is YAML... The real answer is: who cares? They're both easy [enough] to parse data formats. It's about as interesting as arguing about what your favorite editor is and why. Or your favorite database. Everyone knows the ins and outs, and nobody cares (except maybe you and the person you're arguing with). We all have libraries. We all have parsers. It really doesn't matter. The trivial answer to your question is: because YAML is very new in the grand scheme of things. And it's not so different that it's really in The First Time? (Score:2) Really? [sourceforge.net] Re: (Score:2) Re: (Score:1) Re: (Score:1) [naa.gov.au] Re: (Score:1) Re: (Score:1) British Commonwealth Apples & Oranges (Score:3) Australia is openly embracing census data and enhancing it's availability. Canada's government is going out of its way to prevent census data collection. Re: (Score:1) Seems logical - as a Tax Payer, the data should be available to me. Although I hope its not leveraged too heavily by the commercial sector. Re: (Score:1) Take action to change that! [liberal.ca] The Liberal Open Government Initiative will: * Immediately restore the long-form census; * Make as many government datasets as possible available to the public online free of charge at opendata.gc.ca in an open and searchable format, starting with Statistics Canada data, including data from the long-form census; Re: (Score:1) Australia is openly embracing census data and extending it's availability. Canada's government is going out of its way to extinguish census data collection. FTFY Re: (Score:2) but the govt still thinks sharing is bad This is why an Australian invented Wikileaks... I mean... "information wants to be free" and such... and open source you share your code freely to help everyone Hey, where does it say that they'll share the code? TFA quote: with the ABS directing software developer Space-Time Research to utilise the standards for both input and output of all data collected next year. So: ;) ) 1. it is the data that will be shared (govt takes preemtive - still legal - actions against Wikileaks? 2. the guys that are doing the software is Space Time Reseach [spacetimeresearch.com] - the way I know, a bit far from a open source establisment (note: I have no affiliation with them) Re: (Score:2) it looks like they want all data up, the only data not collected is names and addresses, you can use any of the questions to define your sets. "DDI and SDMX are good at describing things, and we're testing the very notion that you can actually consume this stuff and make it discoverable metadata for your search engines." "We definitely want to see who's keen, who's interested in statistics and metadata, open data, data linking and what people can do with it as well." Meanwhile, in other agencies and private (Score:2) Closed file formats are an "innovation" of Microsoft and similar companies. It's really any different from the bastards that write unreadable code in an attempt to provide job security. hopefully in the future some of the practices of elements of Microsoft and man 74% of people don't believe in statistics anyway (Score:1) We should find out what percentage of the population thinks that this is a good idea.... Hope they've studied Munich's woes... (Score:2) ...and here's why: It's official - Munich Linux migration is "dead - abandoned in all but name." - Linux Yes, you read right: "Dead - abandoned in all but name". [fixunix.com] Actually open source seems fine in Munich (Score:3) Munich Linux migration is "dead - abandoned in all but name." Last I heard it was a migration to open source and they were successfully using open source desktop applications. The operating system may be Windows rather than Linux but this still seems to be a victory for open source. On the desktop the applications are far more important than the operating system. Re: (Score:2) Open source standards, no open source code. Very different issue. Open source, or open standards? (Score:1) There is some difference. I'm not clear from the summary exactly what's going on. Re: (Score:2) I'm curious to see.. (Score:2) How many Jedi's currently live in Australia. Re: (Score:2) How many Jedi's currently live in Australia. None: for the moment, Assange is retained by the dark side of the force and too dry Australia is for master Yoda. YAML is not the answer (Score:1) As the author of the Perl module YAML::Tiny, and the current maintainer of the original YAML.pm I call troll on the parent. YAML as a specification is way more complex than XML and it's way harder to implement. And who in their right mind is going to read the raw census statistical quads directly? The point is moot. XML is ideal for machine to machine communication. It's easily machine readable, and easily debuggable by nerds (which is the bit of "readable" that really matters here). And machine readable is wh Incorrect Summary (Score:1) The census will become the first time the open standards are used by an Australian Federal Government agency. What the hell are you talking about? We use a variety open standards every day of every minute across every department with any modern IT assets, I think what you meant to say was the first time that open standards are being used by an Australian Federal Government agency to communicate with the general public. Even then, it's not exactly news, it was going to happen eventually.
https://news.slashdot.org/story/10/12/17/020229/australian-stats-agency-goes-open-source?sdsrc=nextbtmprev
CC-MAIN-2018-09
refinedweb
2,152
73.88
Memory Store Definition. More... #include <FXMemoryStream.h> Memory Store Definition. Open memory stream. When reading from the data buffer, the size parameter is optional. If not given, the reader will need to know when to stop reading by some other means, like end-of-file markers in the data. When writing, the size parameter must be set to reflect the actual buffer size, and should be at least 16. If the owned flag is true, the stream becomes the owner of the data buffer; otherwise, the stream will not delete the buffer. Passing NULL for the data buffer will cause the stream to allocate a buffer of the given size. Reimplemented from FX::FXStream.
http://fox-toolkit.org/ref/classFX_1_1FXMemoryStream.html
CC-MAIN-2017-22
refinedweb
114
67.55
Is there something like Matlab's procrustes X = [0 1; 2 3; 4 5; 6 7; 8 9]; % first shape R = [1 2; 2 1]; % rotation matrix t = [3 5]; % translation vector Y = X * R + repmat(t, 5, 1); % warped shape, no scale and no distortion [d Z] = procrustes(X, Y); % Z is Y aligned back to X Z Z = 0.0000 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.0000 9.0000 X = arange(10).reshape((5, 2)) R = array([[1, 2], [2, 1]]) t = array([3, 5]) Y = dot(X, R) + t Z = ??? d I'm not aware of any pre-existing implementation in Python, but it's easy to take a look at the MATLAB code using edit procrustes.m and port it to Numpy: def procrustes(X, Y, scaling=True, reflection='best'): """ A port of MATLAB's `procrustes` function to Numpy. Procrustes analysis determines a linear transformation (translation, reflection, orthogonal rotation and scaling) of the points in Y to best conform them to the points in matrix X, using the sum of squared errors as the goodness of fit criterion. d, Z, [tform] = procrustes(X, Y) Inputs: ------------ X, Y matrices of target and input coordinates. they must have equal numbers of points (rows), but Y may have fewer dimensions (columns) than X. scaling if False, the scaling component of the transformation is forced to 1 reflection if 'best' (default), the transformation solution may or may not include a reflection component, depending on which fits the data best. setting reflection to True or False forces a solution with reflection or no reflection respectively. Outputs ------------ d the residual sum of squared errors, normalized according to a measure of the scale of X, ((X - X.mean(0))**2).sum() Z the matrix of transformed Y-values tform a dict specifying the rotation, translation and scaling that maps X --> Y """ n,m = X.shape ny,my = Y.shape muX = X.mean(0) muY = Y.mean(0) X0 = X - muX Y0 = Y - muY ssX = (X0**2.).sum() ssY = (Y0**2.).sum() # centred Frobenius norm normX = np.sqrt(ssX) normY = np.sqrt(ssY) # scale to equal (unit) norm X0 /= normX Y0 /= normY if my < m: Y0 = np.concatenate((Y0, np.zeros(n, m-my)),0) # optimum rotation matrix of Y A = np.dot(X0.T, Y0) U,s,Vt = np.linalg.svd(A,full_matrices=False) V = Vt.T T = np.dot(V, U.T) if reflection is not 'best': # does the current solution use a reflection? have_reflection = np.linalg.det(T) < 0 # if that's not what was specified, force another reflection if reflection != have_reflection: V[:,-1] *= -1 s[-1] *= -1 T = np.dot(V, U.T) traceTA = s.sum() if scaling: # optimum scaling of Y b = traceTA * normX / normY # standarised distance between X and b*Y*T + c d = 1 - traceTA**2 # transformed coords Z = normX*traceTA*np.dot(Y0, T) + muX else: b = 1 d = 1 + ssY/ssX - 2 * traceTA * normY / normX Z = normY*np.dot(Y0, T) + muX # transformation matrix if my < m: T = T[:my,:] c = muX - b*np.dot(muY, T) #transformation values tform = {'rotation':T, 'scale':b, 'translation':c} return d, Z, tform
https://codedump.io/share/uCZXwhig1Rif/1/procrustes-analysis-with-numpy
CC-MAIN-2017-47
refinedweb
534
66.03
A situation that arises while solving many algorithmic problems or while development is determining when a String is empty, i.e., has size 0. To determine this, the String class (Java.lang.String), since the issue of JDK 1.6, has an in-built method isEmpty(). This method, as mentioned above, checks whether a String is empty or non-empty. Java String isEmpty() Content Overview Java string isEmpty() method checks if this string is empty or not. It returns true if the length of the string is 0 otherwise false. In other words, true is returned if the string is empty otherwise it returns false. Internal implementation public boolean isEmpty() { return value.length == 0; } Syntax: public boolean isEmpty() This method will return true if the string is empty and will return false otherwise. The following examples demonstrate the use of this method: See the following code. public class Example1 { public static void main(String[] args) { String str1 = "abc"; System.out.println(str1.isEmpty()); } } Output In the above example, the object of Class String – str1, has been initialized to contain the value “abc”, therefore, it has size 3 and is non-empty. So when the isEmpty() method is used, it returns false. On the contrary, consider the following example where the reverse happens. public class Example2 { public static void main(String[] args) { String str1 = ""; System.out.println(str1.isEmpty()); } } Output In the above example, str1 has been initialized as an empty String, and therefore, when the isEmpty() method is called, it returns true. The next example demonstrates the use of the isEmpty() method in the context of control flow statements: See the following code. public class Example3 { public static void main(String[] args) { String str1 = ""; String str2 = "abcd"; if (str1.isEmpty()) { System.out.println("String 1 is empty."); } if (str2.isEmpty()) { System.out.println("String 2 is empty."); } } } Output In the above example, the condition in both of the if statements will evaluate to true only if the said String is empty. Therefore, since the only str1 is empty and not str2, the first if block is executed while the second is skipped. Conclusion Java String isEmpty() String method checks whether a String is empty or not. Finally, Java String isEmpty() Function Example is over. Related Posts Java String lastIndexOf()
https://appdividend.com/2019/11/25/java-string-isempty-function-example/
CC-MAIN-2019-51
refinedweb
379
66.74
Incorrect name lookup occurring in class defined inside of a function. Sorry, but I can't really supply a direct runnable test case that is going to trigger the bug, as the problem only manifests at some point after the JIT kicks in in some way. As such, it only triggers when run as part of a larger test suite we run under tox. At least that it relates to the JIT kicking in is all I can think of as to why when run in isolation there is no problem. Anyway, the test program is shown below. I can't pair it back any further as when I start taking more out, even under our larger test suite it starts working okay, so is the minimal I can get such that still creates the problem. It needs pytest and wrapt to be installed. import pytest from wrapt import transient_function_wrapper def override_application_name(name): class Application(object): @property def name(self): print('locals()', locals()) print('type(name)', type(name)) print('repr(name)', repr(name)) print('type(Application.name)', type(Application.name)) print('repr(Application.name)', repr(Application.name)) return name @transient_function_wrapper(__name__, 'function_1') def _override_application_name(wrapped, instance, args, kwargs): def _bind_params(application, *args, **kwargs): return application, args, kwargs application, _args, _kwargs = _bind_params(*args, **kwargs) application = Application() return wrapped(application, *_args, **_kwargs) return _override_application_name def function_1(obj): return obj class Application(object): name = 'yyy' @pytest.mark.parametrize(('a',), [(1,)]) def test_bug_many_3(a): @override_application_name('xxx') def test_bug(): obj = function_1(Application()) print('type(obj)', type(obj)) print('obj.name', obj.name) assert isinstance(obj.name, str) test_bug() So when run standalone using pypy 2.4.0, 2.2.1 and 1.9.0 this test works fine. But when run as part of a larger test suite under tox it fails. The output we get is: test_pypy_bug.py::test_bug_many_3[1] FAILED ======================================= FAILURES ======================================= __________________________________ test_bug_many_3[1] __________________________________ a = 1 @pytest.mark.parametrize(('a',), [(1,)]) def test_bug_many_3(a): @override_application_name('xxx') def test_bug(): obj = function_1(Application()) print('type(obj)', type(obj)) print('obj.name', obj.name) assert isinstance(obj.name, str) > test_bug() test_pypy_bug.py:42: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .tox/pypy-without-extensions/site-packages/wrapt/wrappers.py:517: in __call__ args, kwargs) .tox/pypy-without-extensions/site-packages/wrapt/wrappers.py:800: in _execute return wrapped(*args, **kwargs) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ @override_application_name('xxx') def test_bug(): obj = function_1(Application()) print('type(obj)', type(obj)) print('obj.name', obj.name) > assert isinstance(obj.name, str) E assert isinstance(<property object at 0x000000010a232410>, str) E + where <property object at 0x000000010a232410> = <test_pypy_bug.Application object at 0x000000010a207de0>.name test_pypy_bug.py:41: AssertionError --------------------------------- Captured stdout call --------------------------------- ('type(obj)', <class 'test_pypy_bug.Application'>) (>') ('obj.name', <property object at 0x000000010a232410>) (>') ============================== 1 failed in 19.40 seconds =============================== ERROR: InvocationError: '/Users/graham/Work/python_agent/tests/agent_features/.tox/pypy-without-extensions/bin/py.test -v test_pypy_bug.py' _______________________________________ summary ________________________________________ ERROR: pypy-without-extensions: commands failed For this code, when looking up the 'name' attribute from inside of the 'name' property method of the Application class which is nested inside of a function, it should be finding the 'name' argument of override_application_name(). As I said, this works fine as standalone test, but in larger test suite, the behaviour changes, and rather than return the 'name' argument of the outer function, it is using the 'name' property method. This is regardless of the fact that 'self' was not used and so it should not have been doing that. I have added debug in so even if you can't manage to get it to trigger by filling the test file with lots of other code which is run first and so enables the JIT, that you can see that the lookup is wrong and so work from that. The obvious workaround for this is not to use 'name' as the name of the outer function argument at the same time as calling the property method 'name'. So changing the outer argument to 'app_name' and making the return statement use that as well, then all works fine. Issue is only when the names for argument and property method are the same. Can you try to run with pypy --jit off? It should tell us if the problem is with the JIT or not. Can't reproduce this. If possible, we would need to get the complete test case. We don't mind if it's a lot of code, requires installing more stuff, and so on. The difference between doing all this installation work and having nothing is the same as the difference between an annoying and a very hard problem (which would actually be impossible if we can't ask you questions that you can try out). It is a part of a proprietary test suite unfortunately. So would need to see if can toss out most stuff and still get it. Is there a way to disable the job besides giving the option explicitly to pypy? Can it be done by an environment variable? Since the problem arises in a py.test executed under tox I am having trouble finding where I can add the command line option. I actually tried to disable the jit when first found the issue but wasn't confident that what I was doing was disabling it. Otherwise, how can you tell whether it is disabled or not? The way I was trying to disable it was to modify the #! line of py.test itself to add the --jit off option at the end after pypy interpreter path given. It wasn't showing it as part of sys.argv though which from prior times I have used such a fiddle for other reasons, I thought it would show. Actually you can turn off the JIT at any point: so you can put these for example at the very start of py.test itself. About sys.argv: it's normal that pypy --jit off x.pyshows only sys.argv = ['x.py']; it's similar to how for example python -i x.pydoesn't show the -iin sys.argv. Another thing to try: download a nightly build of pypy translated without any JIT, and with slightly different internal optimizations, from (e.g. pypy-c-nojit-latest-linux64.tar.bz2). Using pypyjit.set_param("off") in the conftest.py in the tox test directory doesn't cause it to go away, thus suggesting it isn't the JIT, but then also makes it more strange as to why it needs a large amount of code to have been loaded before the problem arises. I will keep trying to come up with a separate test which demonstrates it which doesn't depend on proprietary code. Maybe the problem is not that nameis looked up from the wrong place, but that the nameargument of 'override_application_name()' has got its value overridden at some point by the namefrom the class body. Then we're looking at the wrong place by wondering why print(repr(name))in the property body doesn't find nameas a string. To check if this is the case, try this: That does indeed look like it might be the case: This yields: A possible hack to figure out where this name is changed: Ah, so it's early, around the class creation time. Then maybe you don't need the sys.setprofile()hack, and instead you can call check_name()manually at various points: This one is going to drive me mad. The location changes. Code is: Most of the time when run this generates a traceback of: which is particularly unhelpful. Occasionally, but not reproducible in any sane way I can work out, it produces: I tried removing the __pycache__directory with the byte code files and changing the file after the byte code existed, but nothing was able to yield the latter. It just seemed random whether one would get the one where it pointed at line 27. Even getting it was hard as was quite rare. In the end I changed the test program such that it had sleep calls just prior to doing the checking. It would then reliably reproduce the problem at the same point, always pointing at: Is pypy doing stuff in background threads???? Our test suite has background threads running as well, but when I try and take this into a standalone test harness there isn't. Not sure if that is going to matter. Any other suggestions? :-( The traceback you get most of the time doesn't make sense, btw. Is that really the traceback printed by traceback.print_stack()? Why doesn't it end in the line that contains traceback.print_stack()??? No, PyPy doesn't run background threads. It makes no sense that time.sleep()should change anything, except if you have your own background threads that mess things up. But I don't see how it should be possible to mess up the class construction from a different thread... Yes, the traceback does in those cases really end with: I couldn't make any sense either of why it was doing that. Time to sleep and ponder another day. Thanks for looking at it so far. (In case it helps: I would be willing to debug it over ssh on your machines, with gdb over debug versions of pypy. Your company will have to trust me not to disclose your sources.) Can you try removing all .pycfiles around? In pytest, in your app, etc. If it doesn't help, try to reproduce on a different machine with a freshly downloaded pypy... (I'm unsure it would help because you report problems with multiple versions of pypy already.) Sorry, didn't see this last followup. Only found it while trying to get inbox back under control. Two of my colleagues were able to reproduce on their own laptops and our tests when run under tddium continuous integration service were also tripping it. That is why already knew affected multiple versions. Am trying to catch up with backlog, but will try the .pyc files when get a chance. News! Krono reported, which looks like it is the same bug, and helped me reproduce it. Resolved in bbb6a5825c32. Thanks Krono for the test case! (Graham, I'm rather sure it was the same bug, but just in case, please reopen.) Issue #2225was marked as a duplicate of this issue.
https://bitbucket.org/pypy/pypy/issues/1928/incorrect-name-lookup-occurring-in-class
CC-MAIN-2018-26
refinedweb
1,797
64.61
Hi, After running a python script that sets the usertext of an object, hitting the Undo does not change the usertext back. I tried to make an example script and I need to do something else in order to get anything in the Undostack for else there isn’t even an entry for undoing the script. I noticed that if I move the object in the script Undo does revert the old usertexts So if only the usertext of an objetect is changed this does not get stored into the Undostack it appears. does this explanation make sense? import rhinoscriptsyntax as rs id = rs.GetObject('get something') print 'before script : usertext "testing" = ',rs.GetUserText(id, 'testing') rs.SetUserText(id, 'testing', 'VALUE') rs.AddLine([0,0,0],[1,1,1]) # add something to get an undostack print 'after script : usertext "testing" = ',rs.GetUserText(id, 'testing') -Willem
https://discourse.mcneel.com/t/edited-usertexts-not-in-undo/74801
CC-MAIN-2018-51
refinedweb
145
66.84
Composite pattern The composite pattern allows complex tree-like structures to be built from simple components. Composite objects are simply container objects, where the content may actually be another composite object. Traditionally, each component in a composite object must be either a leaf node (that cannot contain other objects) or a composite node. The key is that both composite and leaf nodes can be treated identically. The UML diagram is very simple: This simple pattern, however, allows us to create very complex arrangements of elements, all of which satisfy the interface of the component object. As an example, here is one such complicated arrangement: The composite pattern is commonly useful in file/folder-like trees. Regardless of whether a node in the tree is a normal file or a folder, it is still subject to operations such as moving, copying, or deleting the node. We can create a component interface that supports these operations, and then use a composite object to represent folders, and leaf nodes to represent normal files. Of course, in Python, once again, we can take advantage of duck typing to implicitly provide the interface, so we only need to write two classes. Let's define these interfaces first: class Folder: def add_child(self, child): pass def move(self, new_path): pass def copy(self, new_path): pass def delete(self): pass class File: self.name = name self.contents = contents def move(self, new_path): pass def copy(self, new_path): pass def delete(self): pass For each folder (composite) object, we maintain a dictionary of children. Often, a list is sufficient, but in this case, a dictionary will be useful for looking up children by name. Our paths will be specified as node names separated by the / character, similar to paths in a UNIX shell. Thinking about the methods involved, we can see that moving or deleting a node will behave in a similar way, regardless of whether or not it is a file or folder node. Copying, however, will have to do a recursive copy for folder nodes, where copying a file node is a trivial operation. To take advantage of the similar operations, let's extract some of the common methods into a parent class. Let's take that discarded Component interface and change it to a base class: class Component: self.name = name def move(self, new_path): new_folder =get_path(new_path) del self.parent.children[self.name] new_folder.children[self.name] = self self.parent = new_folder def delete(self): del self.parent.children[self.name] class Folder(Component): def add_child(self, child): pass def copy(self, new_path): pass class File(Component): self.contents = contents def copy(self, new_path): pass root = Folder('') def get_path(path): node = root for name in names: node = node.children[name] return node Here we've created the move and delete methods on the Component class. Both of them access a mysterious parent variable that we haven't set yet. The move method uses a module-level get_path function that finds a node from a predefined root node, given a path. All files will be added to to this root node or a child of that node. For the move method, the target should be a currently existing folder, or we'll get an error. As with many of the examples in this book, error handling is woefully absent, to help focus on the principles under consideration. Let's set up that mysterious parent variable first; this happens, of course, in the folder's add_child method: def add_child(self, child): child.parent = self self.children[child.name] = child Well, that was simple enough. Let's see if our composite file hierarchy is working properly: $ python3 -i 1261_09_18_add_child.py >>> folder1.add_child(folder11) >>> folder11.add_child(file111) >>> file21 = File('file21', 'other contents') >>> folder2.add_child(file21) >>> folder2.children {'file21': <_main_.File object at 0xb7220a4c>} >>> folder2.move('/folder1/folder11') >>> folder11.children {'folder2': < main_.Folder object at 0xb722080c>, 'file111': <_main_ .File object at 0xb72209ec>} >>> file21.move('/folder1') >>> folder1.children {'file21': <_main_.File object at 0xb7220a4c>, 'folder11': <_main_ Yes, we can create folders, add folders to other folders, add files to folders, and move them around! What more could we ask for in a file hierarchy? Well, we could ask for copying to be implemented, but to conserve space, let's leave that as an exercise! The composite pattern is extremely useful for such tree-like structures, including GUI widget hierarchies, file hierarchies, tree sets, graphs, and HTML DOM. It can be a useful pattern in Python when implemented according to the traditional implementation, as the example earlier demonstrates. Sometimes, if only a shallow tree is being created, we can get away with a list of lists or dictionary of dictionaries and do not need to implement custom component, leaf, and composite classes as we did earlier. Other times, we can get away with implementing only one composite class, and treating leaf and composite objects as one class. Alternatively, Python's duck typing can make it easy to add other objects to a composite hierarchy, as long as they have the correct interface.
https://www.pythonstudio.us/object-oriented-programming/composite-pattern.html
CC-MAIN-2019-22
refinedweb
840
55.24
This action might not be possible to undo. Are you sure you want to continue? k t • Richmond Publishing 19 Berghem Mews Blythe Road London W14 OHN UK © David Bolton and Noel Goodey, 1997 Published by Richmond Publishing@ First Published 1997 All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in any form, electronic, mechanical, photocopying, recording or otherwise, without the prior permission in writing of the publishers. ISBN: 84-294-5065-3 Deposito legal: M. 19.015-1997 Printed in Spain by Huertas S: A. Design and layout Mike Cryer, eMC Design Cover design La Pot Illustrations Philip Bannister, Kathy Baxendale, Greg Becker, Peter Cornwall, Stephen Dew, Mark Duffin, Richard Duszczak, Debbie Ryder, Clyde Pearson, Kath Walker 1 The present simple: She wears glasses 6 8 2 The present continuous: The phone's ringing 3 4 He s smoking The present continuous OR OR the present simple? He smokes? 10 14 16 The present continuous and the present simple with future meaning 5 The past simple: He was late for work. He arrived at 9.15 6 7 8 9 The past continuous OR the past simple? I was waiting for the bus OR I waited for the bus? The present perfect: I've lost my job 18 22 20 ever, never, before The present perfect with already, yet,just, The present perfect (other uses) OR 24 10 The present perfect They've left London OR They left London? the simple past? 26 28 30 11 The present perfect continuous: He's been waiting for hours 12 The present perfect continuous OR the present perfect simple? 13 The past perfect and the past perfect continuous: He had taken/He had been taking 14 The future: will/won't, 32 34 36 40 38 shall/shan't 15 Going to OR Will? Its going to rain. He'll be 20 tomorrow 16 The future continuous and the future perfect 17 The passive (1) Forms and main uses: He was taught by his parents 18 The passive (2) Other constructions 19 20 21 22 42 Have/Get something done: He had his car serviced Questions 46 Question tags: Its cold, isn't it? 48 44 Who, what, which? Do you know who/what/if? etc. 52 50 23 I think so, I hope so, etc. So do I, Neither do I, etc. 24 '25 . 26 27 Auxiliary verbs used alone: She likes cheese, but I don't 54 57 Can, could, be able to Must/mustn't Must, can't Should/ought 56 58 60 to have 66 64 62 Can, could, may, would in requests, offers and invitations Have to/don't have to Must have done, can't have done ,28 30 29 May (have), might (have), could (have) to Had better Should have/ought 68 31 Have got/Have: I've got £200. She's having a bath 32 Phrasal verbs: I got up and turned off the light a few All/every/each 130 Whole 126 122 124 128 everybody/everyone 66 All (of). smell + adjective OR 70 34 Look. notice. seem OR as if/as though 72 35 like 74 There is/There are: Is there a bank here? . 67 (Very) little. etc.. taste. smell. sound. most (of). Having said goodbye. none 65 All/everything. Both (of). hear.33 Verbs of perception: see. many. : J wish you'd stay. Youdon't need to come Ifsentences (lst and 2nd conditional) 80 82 36 Used to: J used to smoke 37 38 39 40 76 77 object: J gave the man some money 78 41 lfin past situations (3rd conditional) 42 44 45 46 47 Unless In case Provided/providing Purpose: to/in order to So as not to + infinitive + infinitive (that). no. some (of). commands. J feel like crying Do you mind + -ing? I don't mind + -ing I can't help It's no use/There's no point + -ing 100 + infinitive with -ing 101 52 Like.. these.. watch. any. as long as If 84 43 I wish .: He asked me what J wanted The definite article the (1): Which car do you like? . hate 53 to OR -ing: J hate flying.. taste. He let her go 49 50 51 97 98 + Preposition + -ing: I'm afraid of flying. plenty 64 Some.The black BMW The definite article the (2) 114 The indefinite article: a. I'd love to come 102 104 -lng clauses: They sattalking. that. those . ') He said his name was Jack Reported questions. etc. an and the plural some Nouns (singular and plural) Countable and uncountable 118 nouns 120 116 63 Much. Ieel. there are two 75 Get used to/Be used to: I'm getting used to English weather Verb + indirect object/direct The verb need: I need a friend. we left Verbs + infinitive with to 54 I prefer to read/I prefer reading 55 56 57 58 59 60 61 62 OR I'd prefer to stay/I'd rather stay OR -ing: Remember to do remember doing 108 110 112 106 Reported speech: ('My name is Jack.Yes. She promised not to be late Verb + object + infinitive: He wants me to leave 90 92 94 96 Adjective + infinitive with to: I'm pleased to meet you Verb + -ing: J enjoy eating 48 Make and let: Youmake me laugh. 88 only J had a car 86 + clause So that/so Verb + infinitive with to: I want to come. either (of) Demonstratives: this./If only . neither (of). feel. a lot of. love. (very) few A little. that The relative pronouns where. you 136 138 Whose? Myown 140 144 73 One/Ones 74 75 76 77 78 79 80 81 82 83 142 (I): He's taller than me. etc. best. More. near. at: Prepositions 165 166 in. until/till 95 Like and as As if/as though 96 Although. It isn't big enough 84 Even: Even my father was there. in future sentences: When I get home. bigger and bigger. the most money 148 150 152 Adjectives ending in -ed and -ing: I'm bored. today. pretty. here Adverbs of manner and degree: He listened carefully. during. yet Any more/any longer/no longer 160 162 164 Too and enough: Its too small. 172 174 Prepositions used for travel and transport: I travelled by plane 91 For.68 Reflexive and emphatic pronouns: myself. etc. Special uses of it. etc. mine. what Defining and non-defining relative clauses Clauses with -ing OR a past participle With in identifying phrases . 132 69 Someone. better. though. since/as. themselves. a bit. they. somewhere. so 186 188 190 192 94 By. Prepositions of movement: up. on. by the time. etc. etc. since. My life is so boring Adverbs of frequency. at: in June on Thursday at 5 o'clock 168 170 in my bag on the table at the traffic lights of place: under. I'm extremely tired 154 Quite. much. etc. as soon as. next to. etc. opposite. ago 93 176 178 92 For. She didn't even speak to me 85 Else: Do you want anything else? -No. whose. 134 etc. even though 97 98 99 100 184 Relative clauses with who. on. 70 71 72 Possessive forms: my brother's car the roof of the house a friend of mine Possessive adjectives and pronouns: My. fairly. which. while When. thanks 86 87 88 89 90 Time prepositions Prepositions of place in. time and place: often. She s the tallest (2): The use and position of adjectives Comparatives and superlatives Comparatives and superlatives 146 as tall as. 158 Still. down. nothing else. something. most. I'll have a shower 180 181 182 In spite of Because. rather So and such 156 Adverbs of degree: a lot. but they at 7. • things that are generally or always true. 1 22% of British families 2 The average British woman 3 British teenagers 4 The average British teenager 5 A typical British man 6 British people 7 The average British person 8 Over 6 million British families 9 The average British person 10 British women to Spain for their holiday. Note that we don't add -s to the verb that follows doesn't. Does it rain a lot? . Does this radio work? . a bath twice a week. Do you smoke? Does he smoke? Note that we don't use Do/Does to form questions with the verb be.) • We form questions with Do . on average. ? in the third person singular).. his or her teeth for only 20 seconds.Yes. He starts work before 8. it does. 6 . 1 usually get up at 7. 1do.. Waler boils at IOO°C. .No. 76 years. 62 kilos. 1don't smoke.15. Are you English? (NOT Do you be English?) • Short answers: Are you English? . (NOT She doesn't smokes. Do you speak English? . a dog. ? (Does . • In the third person singular affirmative the verb has a final-so The manager arrives first. to the dentist twice a year.Yes. it doesn't. 1 Form true sentences not read using the verbs in the box.Yes. six cups of tea a day. • We form the negative with don 'I (doesn 'I in the third person singular). much. they do. [am. She likes white wine.Yes. on average. Do they live in London? .. She doesn't smoke.20.. his hair each time.1 We use the present simple to talk about: • habits or regular activities and situations. television for over 19 hours a week. 11 rains a 101 in Wales. but he . drink have (x2) not wash go (x2) get up live watch weigh brush Example: The average British h1Qnsleeps 8 hours 10 minutes a night. 45 21./ X X X Spanish.40 09.50 - London (paddington) Reading Bristol Taunton Exeter Plymouth 09.15 10. ? I go shopping about twice a week.20 14.10 20.I .02 - 10. It London at . she usually spends more.49 10./ .08 13./ using the verb speak./ 2 He German X X X X .40 12.15 09. shopping? She goes about once a week. 4 But they Spanish.15 train from London stop at Exeter? the last train Plymouth? It London? It .15 14. Write the questions for his answers.15 and 10.27 12. .18 20.22 1 What time 2 3 What time 4 5 6 7 8 What time 9 What time the first train leave London? it stop in Bristol? it reach Exeter?' It .06 - 10.38 21. I am.15 trains both stop at Bristol? they stop at Taunton? the 10. the 09. French or German. . French and Arabic. 4 A young 1 man is being interviewed married? outside a supermarket. .08 13.01 11.15 - in the timetable.30 11. about the same? ? I pay by credit card. ./ X X . ? I spend about £20. English or Spanish. 18.05 14.15 20./ German or Arabic. she doesn't. 6 He 3 Complete the questions and answers using the information 08. .2 Look at the table and complete the sentences. Yes. English Alain Marta Anna Ahmed 1 Alain 3 Marta and Anna 5 Ahmed . different supermarkets? to this supermarket? No. Arabic X X X . 7 No./ French . .23 23.45 17.51 12.01 18. .35 19. Spanish .50 15. after work. I don't.15 00. I always go to this one. She goes to one near her office. No.05 - 14.15 - - 13.06 11.30 train stop at Taunton? the 14.08 22. 2 How often 3 When 4 How often 5 How much 6 7 How 8 9 wife ? I usually go in the evening. . remember. .... Alison/come How long you/go for? (8) ADAM: JAKE: ADAM: JAKE: ADAM: JAKE: We/not stay for very long... own.. these days? (3) my job at the moment. She/train Well. + -ing..... it/get late. seem.. understand..2 Quick f'Bfel'ence We form the present continuous Affirmative I'm listening You're listening He's listening • for something with the present tense of the verb be Questions Am I listening? Are you listening? Is he listening? Etc.. this time? .. notice. • for arrangements we've made for the future.. The most common are: agree.. with me... mean.. at this moment. I'd better go... (9) What/Alison/do these days? (10) to be a teacher.... (12) Yes. hear...... Bye! 8 ...... I/not/enjoy JAKE: ADAM: JAKE: We/go to Greece. • BUT some verbs are almost never used in the present continuous. know.. hate.. I'm having a party next Saturday.. care........ Then I/go to the bank... be.. Complete the dialogue. Ilove you........... He's studying engineering at college... What about you? ............ want... I/get ready to go on holiday... • with always to complain or express surprise/irritation about something that happens frequently.......... believe.. (7) . forget....... (NOT I'm loving you. ? .. Negative I'm not listening You aren't listening He isn't listening that's in progress We use the present continuous: now.. mind...l/really/look forward to it. wish.. (5) You/always/go (6) on holiday! Where/you/go JAKE: ADAM: Well... (11) She's still at college. only a week. What/you/do (4) .. I'm going out with a boy called Gary..... in town? (1) ? .. They're always criticising her. belong. suppose...l/apply for jobs in advertising... • for a temporary activity or situation (which may not be in progress at the moment)........ ? ..... Look' It's raining.. love. like.. So I/think of changing it........) What does this word mean? (NOT What is this word meaning?) 1 Two friends JAKE: ADAM: have just met each other in the street. She doesn't get on well with her parents.. ? Hi! What/you/do (2) I/take these letters to the post office..... me too.. Mike's (11) a swim and the children (12) playing uolleyball. OK. fmma. myself now.. always (13 make) excuses and I particularly (74 hate) . uneJrlploymenl (6 rise) . I (11 dry) I (12 not care) (14 want) in there? a bath. . fired of hearing excuses... I (15 be) . 10 you because I (2 become) . two other people and you (6 have) I a bath! DAUGHTER: FATHER: as quick as I can. We already (6) severol good restaurants near the harbour. . always il (12 no! be) . your [aul]....... { (13) you were here with us. Ihal olkcr countries in Europe have gol similar problems and I (70 suppose) . Charles Forlescue. I (3 remember) .. Dear Prime Minister. crime (1 gel) ...worse and worse and you (8 do). You (9 know) being late for work. We really (5) Greekfood......Smylh 9 .. what you (13 do) you to hurry up! I just DAUGHTER: FATHER: 4 Put the verbs into the present continuous where possible... We're (3) . to shave. Prices (5 go up) ... tha).... action. I (16 wanl) . Use parts of the following verbs: like sit have (x2) know seem stay be (x2) drink wish play belong Dear Kate. Laue. But wka! (4 happen) .2 Read this holiday postcard and write in the word that fits each space. At the moment l' m (9) in a beach tauerl'!a on vromoltmnos beach and I (10) .. ... We (1) here on Skiathos and we're (2) a marvellous time. more and more worried about Ihe policies of Ihe present qovernmen).. . I (1 write) ..... You . drinking an iced coffee.45. some Ihings are outside your control. Yours sincerely. IAe promises you made when you came 10 power.. fIOlhing about ill I (9 hnow] . 7... ... because euerybody here (8) to be able to speak tnglish. . Write only one word in each space. I (7 be) But I (8 want) (10 hate) OK.. . . Bul you (11 say) . We (1) lucky. in a uilla which (4) to a rich British businessman. 3 Put the FATHER: DAUGHTER: FATHER: verbs in brackets into the present continuous What (1 do) I (2 have) I (3 not believe) (5 wait) OK. it! It (4 be) to use the bathroom where possible. . Look! It's raining. forget... that may not be in progress at the moment of speaking. The most common verbs are: believe. This egg is bad.. Be quieti The film's starting.. prefer. want.. understand. need. belong. • for general facts and permanent mean. with the present simple. see. 5 . like. seem. We use the present simple: • for repeated I'm not happy at work. we use the present simple. situations.... 2 . They live in London.. • with verbs which describe a state (a situation which stays the same) and not an action. never. 5 I'm giving up smoking next week. taste) can describe a state or an action. have. Youaren't listening to me.. I want a drink. actions and regular situations. When the verb describes a state. • for a present activity or situation • for future plans or arrangements.. remember. They often come late. She's having a shower. at the moment of speaking c) Future plan/intention Present simple d) Facts e) Habits/repeated actions 1 . 10 . The President is visiting China next month. The sun rises in the east. We often use the words always. know. This car has a sun-roof When the verb is an action. own. etc. love.. • Some verbs (think. She thinks she's beautiful. hate. What are you thinking about? You're being very silly. He's studying maths at college. contain. be. often. every week. I'm looking for a new job. Present continuous a) Present action b) Present situation that may not be happening 2 Smoking damages your health. You're reading the paper. smell. J smoke 20 cigarettes a day. we use the present continuous.30 this evening. 3 I'm smoking a lot nowadays. 3 . suppose. 4 I'm smoking. He sells second-hand cars. We're meeting at 8. 1 Match the five examples on the left with the various uses of the present simple and the present continuous on the right. exist.. I love you. 4 . hear.3 We use the present continuous: • for things that are in progress at the moment of speaking. realise.. He smokes. usual/y. He doesn 'f like her. me awake... 36 Philbeach Gardens....... 12 . b) [speak Italian and Dieter speaks German. a) In Athens. 11 . 3 A man is phoning the police... 5 7 ........ b) A book about the Classical period of Greek history.... 8 .. . 4 .. any notice. 13 ... Christos? 6 Where are you living? 7 Yvette and Helene. Marco and Dieter? 14 What language do you speak? 1 .. a) English.. [ (11 not complain) But tonight the noise is awful and it (12 keep) .. (1 Be) noise which (3 come) party and they (5 play) there (7 have) that the police? [ (2 ring) to complain about the a ............ The man who (6 live) a party every weekend. 3 .... a) What we're going to do after the class... 1 What are you reading. Maria? 13 What language are you speaking... b) Some chocolate... a) Vegetarian food..... Hello... Carlos? 4 What are you doing? 5 Where do you live. b) Lots of things. 2 ... Oh good. you (13 send) ? Oh. b) I'm finishing this exercise.. b) With friends in a house in Kensington. b) Not at the moment. a) I'm an engineer... 10 .... 14 ........ 6 .... a) Only in the wet season... Maria? 12 What are you eating. They (4 have) music .....very loudly... but usually boys.. Match her questions with their answers...... Where [(14 live) London W8.. Put the verbs in brackets into the present simple or the present continuous... And every weekend [ (8 ask) him to turn the music down but he (9 not take) . . Fabio? 10 Does it rain? 11 What do you eat. of course.. until 2 or 3 in the morning. 11 . from the flat above me. what are you talking about? 8 What do you talk about? 9 [s it raining.. a police car round..2 An English teacher in London is talking to her students. a) Books about ancient history.... 9 ....... Adriana? 2 What do you read? 3 What do you do.. And they (10 not leave) very often.. .... ............ b) b) b) b) ..... . ... 2 a) He plays tennis........ .. Look at the picture and write down four things he is doing and four things he does........ 2 3 4 S 6 7 8 ..... ....... b) Are the following statements about Matthew true or false? a) He's watching TV.. ... b) He uses a computer.... 3 a) He's using a computer. Use these verbs.4 Answer the questions about the boy in the picture... wear (x2) watch work play (x2) ride use read listen Examples: He's weariftg a T shirt... He watches TV..... ... b) He's riding a motorbike. a) Write eight sentences about Matthew... 4 a) He rides a motorbike.. a) 2 a) 3 a) 4 a) .. . .... ... b) He watches TV. 12 .. .. ... .... .... .... b) He's playing tennis.................. .. e) Yes. He smokes 60 Cigarettes a day. At the moment (1 (2 (3 (4 (5 (6 (7 (8 (9 (10 (11 (12 (13 (14 ) ) ) ) ) ) ) ) ) ) ) ) ) ) she goes out with that boy who's waiting to use the phone. He's getting married next month and he has his honeymoon the Seychelles.. 7 a) Write down Examples: three things you are doing now and three you are not doing.. 4 . 3 . If a line has a mistake in it.5 A boy and a girl are getting to know each other at a party. Look carefully at the text.. he thinks of giving it up. He want to become managing director. 5 . The man at the next table is Neil Wilson..30 and doesn't leave till 8. He's having his own space in the car park. tltglish. (get up at 7. Some people are thinking they're having an affair but I don't believe it. is telling her about the other people in the dining room..00 in the evening. r m writiltg in. She start work at 7. h) In a student hostel. b) I'm from Manchester.. put a tick (... 6 It is Tessa's first day at work. Then there's Emma Harrison. a girl she works with. (dOIt/t go to church. 8 . I am.30. The woman who sits opposite him is his secretary. 13 . Some of the lines are correct and some have a mistake.. Check your answers with a teacher.. What do you do? 2 What are you studying? 3 What's that you're drinking? 4 Are you enjoying the party? 5 Where do you come from? 6 Where are you living at the moment? 7 How are you getting home? 8 Do you want to dance? 1 .. r m not watchiltg teieotsto«. 7 . He's the chief accountant.. He works in the accounts in the marketing department this week but normally he works department. 6 .... If a line is correct. It is lunch time and Abby. Apparently.. The man over there who's putting on his jacket is the sales manager. 2 ... o Psychology. She stands by the door. but I don't think in he will.1) after it. OK. d) I'm walking. a) Yes. c) I'm a student. the marketing manager. The girl over there works in the accounts department... g) I don't know what it's called. Match the questions on the left with the answers on the right. underline the mistake and write the correction in the brackets. He's travelling a lot so we don't see him very often. b) Then write three things you normally do and three you do not normally do... . These are the arrangements made for his visit. . he 4 Where/he/meet/the He 5 Who/he/have/lunch He 6 he/be/free/at No.15 14. to London? . Meet the mayor 12. . 7 How/return He . with? . 14 . I've got the details from the travel agent. 7..15? . 1 The Prime Minister will be in Torquay tomorrow.15 Arrival at Torquay station Breakfast with local party officials Visit to Technicom electronics factory Town hall.30 8. . How/travel/to He 2 What/do/at He 3 he/do/anything Yes.00.00 16.00? .I'm playing tennis with Andy at 7. .00 9. schedule or programme of future events. • We use the present simple to talk about a timetable. '" at 9.30. mayor? .00? .15.) for the future. We check in at the airport at 7. 8..4 • We use the present continuous to talk about things we've already arranged What are you doing this evening? .00 1l. (NOT What do you do? I play tennis with Andy. 14. and we arrive in Barcelona at 10.30. he Torquay? .30 Lunch with a local family Open the new shopping centre Helicopter leaves Imperial Hotel that have been Complete the questions and answers about the Prime Minister's visit. The plane leaves at 8. .. Their train home (14 leave) .. Oft Oft Examples: I'm playiftg teftftis I'm not goiftg out Tuesday. near Naples... 2 Where are you going? 3 How long are you going for? 4 Who are you going with? 5 Where are you staying? 6 Where are you flying from? 7 Which airline are you flying with? 8 How are you getting to Gatwick? 1 .. e) Alitalia.. to a football match in London tomorrow.45...... 4 .. enough money with them to buy at 15.00 and it (13 finish) London at 18...... 5 . 3 A friend is going to a rock concert on Saturday... Iam. (how much?) 4 I want to know how you're getting there... James and Richard (11 take) lunch on the train. back in Bristol at 19.. The match (12 start) at about 16.. Example: I want to know when the concert starts.... England (2 play) James Dent (1 go) ....... g) Yes... You want to know something about it. The train (7 leave) .. using the word(s) in brackets.45........ (how?) (what time?) 4 Put in the correct forms of the verbs. It (8 be) anywhere. h) For two weeks.15......45.. They (15 arrive) ...... . with his friend Richard.. 5 I want to know when the concert finishes.. Use either the present continuous or the present simple.. It (10 arrive) ... 8 ... d) By train. They (4 not go) travelling by coach.. 3 . c) I'm going on my own..2 Match the questions about holiday arrangements 1 Are you going on holiday this summer? on the left with the answers on the right.. 2 . They Bristol at 12..... a fast train and (9 not stop) in London at 13.. Complete the second sentence so that it has a similar meaning to the first sentence..... 6 ... (where?) bands tickets the concert? ? ? there? the concert ? 2 I want to know which bands are playing............. by coach because James (5 not like) (6 go) ............... Colombia..... f) To the south of Italy..... He (3 go) ...... by train... 7 ... Check your answers with a teacher 15 ............ (which?) 3 I want to know how much tickets cost... Friday eueftiftg. 5 Write down three things you are doing next week and one you are not doing... a) I'm renting an apartment b) London Gatwick........ (when?) Wheft does the concert start? J want to know where the concert is..00. . . not just at one fixed moment. She met Tim. She had four children. . The programme started ten minutes ago. non-stop about Buddhism it for 50 metres in Tokyo in 1979. Yes.·. Negative He wasn't They weren't Question Was he? Were they? • We use the past simple of regular and irregular verbs to talk about something that happened and finished at a particular moment in the past. 2 Ann Miller went on a business trip to Canada last week. . I left school in 1995. get on eat Complete the sentences with verbs in the past simple. Yes. Complete the questions and her answers. 1 A Russian woman. and Rick was there too. It is understood. Did he go? . .No he didn't.5 Affirmative He was They were sim~~!. We usually say or know when the action happened. the bus every morning at 8. Amy went to a party yesterday. a completed action. for 159 hours. Yes. . to talk about a past situation. They lived in an old farm house. Feodor Vassiina (I 707-1782) 2 In 1993 Steve Meltzer of Brooklyn. • The forms of the past simple: Affirmative Regular verbs Irregular verbs He lived He went Negative He didn't live He didn't go Questions Did he live? Did he go? Note the short answers. She smoked 20 cigarettes a day. She danced We also use the past simple to describe: • something He caught that happened regularly or continually in the past. Yes. He died on Friday. 96 sausages in 6 minutes. No. 10. • Often we don't say when something happened. • a situation that existed in the past over a period of time.15 ~ ~~<~i~ • We use the past simple of the verb be (was/were) It was cold yesterday.' No. fOri ioork« He arrived at 9. it was. New York 3 In 1982-83 Timothy Roy 4 University lecturer Kapila Kumarasinghe 5 16 people the same bicycle and in a tree in California for 431 days non-stop.. with him all night. The shops were closed. Example: weather/good? 1 flight/OK? 2 weather/hot? 3 meetings/useful? 4 food/good? 5 things/expensive? 6 the trip/successful? 16 Yes Was the weather good? Yes. . 1 Odd records. . Choose from: speak ride have sit I 69 children.. . Complete what she says. He works in the prison kitchen. ? . till midday. Some of the lines are correct and some have a mistake. ? -I lived in Barcelona. 6 Read this newspaper story. till 3 a. he was in another prison yard! The other sacks of potatoes were for the prisoners in Wandsworth Prison. 3 He sleeps most of the day. A truck full of potatoes come into the prison yard. any. London! 17 . He couldn't believe it .No. ? . Last week he out every evening.he wasn't free. ? . If a line is correct put a tick (. If a line has a mistake in it. After half an hour the truck stopped and the driver gets out.3 Complete not know this newspaper lose ring story with verbs in the past simple. underline the mistake and write the correction in the brackets.Yes. while she to steal everything in 4 The mother of a teenage boy is complaining Last night he about her son. it wasn't well paid. Harris then hid among the sacks of potatoes which was still on the truck. Last Saturday night he 7 He leaves his room in a terrible mess. Yesterday he a whole loaf of bread when he came home. 1 He loses a lot of things. Then.I went in August. Yesterday he 8 He eats a lot. Look carefully at each line. Harris now thinks it was safe to come out.I) after it. her purse (11) he (13) anything about her purse. her flat as well as her purse. He took half the sacks of potatoes into the kitchen. The truck then left the prison. I got a job as an English teacher. . all his clothes on the floor. home the telephone (3) her purse while on a shopping and he (6) trip. But half an hour later she (9) the opportunity the phone call. Complete the questions for his answers. the reason - The man at the other end But the manager the manager of a local supermarket back to the supermarket. Last month he 5 He goes out a lot. London. ? . The driver tells him to leave the rest in the truck.I taught groups of teenagers.m.I found it through a friend. ? . 5 Rob Howell 1 When 2 Where 3 4 How 5 Who 6 lived for a year in Spain. One morning he saw a chance to escape. (1 (2 (3 (4 (5 (6 (7 (8 ) ) ) ) ) ) ) ) Carl Harris was in Brixton prison. She immediately the same thief who (10) at the supermarket. Choose from these verbs: steal make go be (x2) get understand say take have On Tuesday last week Mrs Hilary Fox (1) When she (2) (4) (8) (12) he (5) (7) her purse. Last week he 2 He does very little homework. Last Sunday morning he 4 He spends all his money on clothes. his watch and a jacket. over £100. 6 And he always comes home late. . seem. or what were Matthew and Andrea doing. at a certain • We often use the past continuous to describe a situation. At 8. Left home Got to bus stop Bus came Arrived in city centre Met Andrea Went into pub 8. and! was feeling depressed. I was doing the washing-up (past continuous) I .. (NOT I was knowing the answer...00 is what Matthew did yesterday evening. be... believe... like..40 he 3 At 7. Example: At At 7. at the following times? Choose verbs from the box.. wish... notice.. suppose..... remember. The neighbours were shouting at each other.. hate.00 yesterday evening I was having a drink with a friend...40 they '" '" '" a pizza.45 7...... We use The phone rang.15 8.. own.) 1 This 7.20 10.. a drink in a pub. My head was aching....6 • We use the past continuous to talk about an action that was already in progress time in the past. a film. The radio wasn't working. forget... I wait (x2) have watch walk go eat I for the bus. by bus to the city centre...30 11. . hear.. belong.25 10....27 2 At 7....10 they S At 9.) I didn't understand him.. (past simple) • Some verbs are almost never used in the past continuous. mean.. want. understand....45 Came out of pub Arrived at cinema Came out of cinema Went into pizza restaurant Got home What was Matthew doing.. 4 At 8. I had a terrible morning. have (possession). to give the background to a scene that happened in the past. ..... (NOT I wasn't understanding him....20 he was walkiftg to the bus-stop..25 7. that was in progress.. know...50 he 7.. '" . I was doing the washing-up when the phone rang... • We use the past continuous to talk about an action or a situation the past simple to talk about a completed action in the past..30 7.. mind..15 7... I knew the answer. It was raining.00 they 6 At 10. care..... {ave. The most common are: agree....55 8.. for Andrea... (was liuil1.! got up. Use your imagination. A boy (8 be) his shirt. underline the mistake and write the correction in the brackets. He (9 not wear) between his teeth. tables. Etc. music. to you recently. and some have a mistake in them. If a line is correct.the toast caughtftre. Put in the correct form of the verbs.. Sam and his friends (2 play) Some people (4 not listen) in the kitchen. While! was talking 011. Check your answers with a teacher 19 . They (5 be) cream.2 Sam had a party last night. If a line has a mistake in it. it was ra/~ng. and the sun shone. ( ( ( 4 Describe a series of events that happened . Describe what they found. Use Example: Whel1. While! was getting dressed. put a tick (. One girl (7 lie) sofa. if necessary. 5 I went to the toilet when I bumped into her table and spilt her drink. 6 I apologised to her and bought her another drink.g) 2 She was working at the Louvre and she was having a flat by the river. Read the text carefully. ( ( ( ( ( ) ) ) ) ) ) ) ) 7 While I was having my coffee. and he (10 have) under the stairs. Some of the lines are correct. They (6 eat) on the piano. 8 While we were talking. the phol1. A lot of people (3 dance) to the music. There (1 be) a lot of noise. Example: I I lived in Paris when I first met her. the past simple and the past continuous. His parents arrived home in the middle of the party. 9 But we didn't see him because we looked lovingly at each other. the waiter was coming with our bill. 3 We were meeting at a cafe where we were sitting at separate 4 It was a beautiful spring day. The dog (II hide) 3 Justin is telling a friend how he met his wife. the phol1.e. she came over and sat at my table.e rattg.I) after it. chips and ice asleep on the a rose very loud . 7 Oui.. enough of him! B B B B B B B B B B B happens? 's left has he go? haven't left 've rung haven't heard 've lost Has he left hasn't left 's he take not has taken B You have phoned B haven't B 's had C C C C C C C C C C C C C C did happen? leaves has he gone? hasn't leave 've rang haven't hear 's lose He has left hasn't 's he taken hasn't take Has you phoned not have 've had 1 A 's happened? 2 3 4 5 6 7 8 9 10 11 12 13 14 20 A A A A A A A A A A A A A left did he go? hasn't left 've ring not have heard 's lost Have he left hasn't leave he has taken hasn't taken Have you phoned haven't phoned 've have . John (2) me. He (4) an address or a telephone number. it hasn't.. A.... I've lost my keys..) . Just a few clothes. or C best fits each space.) The rain has stopped. Has the rain stopped? ..Yes..rNo. Qerif~f(I've lost my job ..) a at • We form the present perfect with forms of the verb have + a past participle. it has... he (9) . Where (3) ? I don't know. a note? No. • The present perfect connects the past and the present..ck reference ~~ ~. I (14) . I (5) . I (13) .... the police? No... from him so maybe he (7) his job.. Read the dialogue and decide which answer. What's the matter? What (1) . I haven't.. his office but they (6) .. What (10) with him? He (11) .... I don't want to find him. much. 1 Helen's KATE: HELEN: KATE: HELEN: KATE: HELEN: KATE: HELEN: KATE: HELEN: husband has left her. (12) .INo.Yes. haven't got my keys now. isn't raining now. Kate.I have... Affirmative Negative Questions I've (I have) started You've started He s (He has) started She's started Its started We've started You've started They've started I haven't started Youhaven't started He hasn't started She hasn't started It hasn't started Wehaven't started Youhaven't started They haven't started Have I started? Have you started? Has he started? Has she started? Has it started? Have we started? Have you started? Have they started? Short answers Have you started? . It refers to a past action. B. (8) ... She is talking on the phone to a friend. but we're more interested in the present results or effects of the past action.. Write three sentences explaining why.. ...2 Look at the picture and write sentences verbs and nouns in the box. . 4 6 .. c) Have they been handed in? . 4 I (put) my glasses down somewhere 5 [(pay) for three nights. using the j""U~: ).. 8 [(ring) for a taxi.. [ (lose) my umbrella 2 [(use) all the shampoo in my room .. using the present perfect. . Example: r In jeelif19 with the present perfect uf1happLj because rue lost hlLjjob... e) but it hasn't come. 8. Write the correct form of the verbs in brackets. 6. 4. 9. Check your sentences 21 .. 4 a) Imagine you are feeling unhappy. about what the student has or has not done.~. 9 I (find) this key. a) Can [ have some more? . 10 [think [ (break) my leg 1 ..).... with a teacher. 3 A number of hotel guests are talking to a receptionist. Then match the sentences on the left with those on the right... j) and it doesn't belong to me.... 3 5 7 . 3. g) so now [can't get in. i) Can you call a doctor? . 3 l Ileave) my key in my room.~. d) Can you lend me one? .. 10 .... h) Have you got an aspirin? . 6 l Iforget) my room number 7 [(have) a headache all day 0 Can you tell me what it is? . b) Then imagine you are feeling happy and explain why. .... . .. b) but [ only want to stay for two.. 7.. 5. 2. glass do breakfast have keys clean empty forget switch off the washing up shoes the lights break waste paper basket 2 .. . . between have/has and the main verb.... • We often use just (= a very short time ago) with the present perfect.. It goes in mid-position.. We use it to talk about what has or hasn't happened in the period up to this moment. I've done the kitchen and the living room.. I'm sure I've heard that song before... new car.. ... I've never eaten caviar before.... .... We usually put yet at the end of the sentence. • We sometimes use never and before in the same sentence... • We use yet in questions and negative sentences to say that something hasn't happened up to now. Has the train left yet? -No.. • We use already to emphasise that the action has happened before the moment of speaking.... • We often use ever with the present perfect to ask if something has happened at any time up to the present.. all her exams... Why don't you phone Dave? -I've already phoned him. Some exciting things have happened... usingjust and these verbs: buy......... in the National Lottery... new job.... 22 ......... pass..... I've never won a penny..8 Ollick referellH • The present perfect connects the past and the present. Look at the pictures and make sentences. start.. Why are you so happy? -I've just passed my driving test....... . win. We usually put it at the end of the sentence..... 4 George Trent . They .... Ever and never go in mid-position... • We often use before (= before now) with the present perfect. it hasn't left yet. Have you ever won the lottery? -No... I'm painting the flat at the moment.... 3 Gillian Trent .. but that we expect it to happen some time in the future... but I haven't finished the bedroom. 1 The Trent family are very happy today. 2 Beth .... ... ever..... but she hasn't decided how to tell him (13) 5 What things in your life have you not done? (But you hope to do them in the future.. 23 . 3 Jessica Dale is having an interview for a new job with a travel company.. 'Yes.......I 7 And you need a shave too...No.... ..... At the party Lauren asked him 'Have you ?' Ryan told her a lie and said. .. ... yet. using already. But he has not tidied his room.... he has not fed the dog... but I've phoned her three times today..... Example: rue fteuer rtdde« a motorbike...... I '" .... never.. using yet....... She's (12) ... .. the USA and Australia..jast...... What things in your life have you never done? Write three sentences.... I 8 Have you got your front door key? . He's (2) (4) (5) (7) seem to be interested been out with a girl (6) been out with a girl like you. a computer? seriously ill? German or Spanish? abroad? for a travel company? 4 Complete the text...I 2 Is your room tidy? ... She was at the had a girlfriend (3) Girls in him.........No.. driven round to decided she Ryan Briggs is very excited.' He's (8) but he hasn't been able to contact her (9) her house.. I 3 You must do the washing up..... . but I've worked as a tourist guide in London.... .. 3 I've never learnt German....... you must make your bed..... Example: rue already been to [urodisftey... He's (1) party he went to last night... . using already and yet.) Write three sentences...... . 5 Yes... he has finished his homework and he has had a bath.. What things in your life do you not want to do because you have done them once? Write three sentences. before. but I learnt Spanish at school..I 4 And you must finish your homework.I know.... Check your answers with a teacher.I 5 I want you to have a bath.. Italy.. met a beautiful girl called Lauren. I've been to Spain.... Lauren has (11) doesn't want to see him... So he's (10) seen him arrive. I've never been ill for more than a week.2 Harry's mother will not let him go out this evening until he has done certain things. Example: I haoen': been to the USA yet.. So far he has done the washing up. Yes. using already..... I use a computer all the time at home. Write Harry's replies. -I 6 And what about the dog? . His mother is talking to him.... using ever. I Before you go out.... 4 No..... ... ..... he has not shaved and he has not found his front door key... he has made his bed.... .... 2 No..... .... Write the interviewer's questions. etc. in Geneva. = He isn't there now. in central Africa. if1 a lot of expensive a lot of Ef1glish. when these periods aren't completed at the moment of speaking. He's gone to New York. etc. but he went there in the past. this morning. 2 Natalia is an Italian student at an English language school in England.I (4 haue) a lot of Ef1glish a lot of good frief1ds at the me a ouer £500. • Gone to and been to don't mean the same.) time and 1 This is this morning's TV news. Example: This morning the Prime Minister (go) to a UN conference A cholera epidemic (break out) people (die) 2 Police (arrest) 3 The Daily Star (apologise) her private letters. It's the most frightening experience I've had. He's been to New York. NOT the past simple.9 • We often use the present perfect with today. after It's the first (second/third. their first four matches this season and fans the manager he must go. this year. She has been there for a month. They (8 teach) mOf1ey twice this hlOf1th -/ (10 spend) / (9 rUf1 out of) Ef1glaf1d's expensive! / (11buy) restauraf1ts. My mother will . But / (13 not see) thif1k / (14 become) 24 a lot of clothes and / (12 eat) af1 atheist! the inside of a church once this mOf1th. two of that Princess Diana this morning to the Queen for publishing the same dress three times this month! its lowest rainfall for over 100 years. Complete the sentences with the right form of the verb.) • We use the present perfect. (This year hasn't finished. I've done a lot of work today. a mOf1th f1OW. = He's there now. Complete the headlines.000 drug dealers in Edinburgh this morning. I (6 make) SOme uery f1ice Ef1glish boys. She is writing to an American friend she met last summer. this week. (It's still today. two big international This morrtittg the Prime Minister has gone to a UN conference in Geneva. 1(1 f10t write) uery busy end I (3 be) lessons end I (Sleam) school end / (7 meet) lot of slaf1g . This summer I if1 Ef1glaf1dfor r (2 be) veru. It's the first time they've met.) He's written two books this year. And the Sun newspaper (wear) 4 This year Britain (have) 5 Manchester (tell) United (lose) (report) .m sorry. This week over 5.end swear words! to you this year . often after superlatives. Usa is driving Ben's car. Read the dialogue and decide which answer.This week! (15 110t feel) al1d today! (17 stay) uou. How do you like the weather? Any problems with England? It's the driest summer (4) . well so !(16 see) This (18 glue) the doctor a couple of times me the chal1ce to fil1lsh this letter to it! It twice this week.. here.! (20 fil1lsh) 3 Usa BEN: LISA: BEN: is a Swedish girl. Spain? . the food. No. She (2) else who (4) I'll try to connect you. He (1) Barcelona. Check your answers with a teacher. Now.. or C best fits each space.. Is this your first time in England? No it's the second time (2) . on the left. No. Natalia 111 bed... A. lunch.. Why are you nervous? Because it's the first time (1) . PAUL WILSON: RECEPTIONIST: Could you put me through to someone a meeting at our head office. It's the worst (6) ..... I'm sorry. Hey! Slow down.. Today's the hottest Yes. I hauef1't had a holiday. I've driven I'm I have we've had I know I've ever eaten I ever drive B B B B B B B I've drive I've been I had ever we had I've known I've ever eat I ever drove C C C C C C C I drive Iwas I've ever had we have I knew I've ever ate I've ever driven LISA: BEN: LISA: BEN: LISA: BEN: LISA: BEN: LISA: 1A 2A 3A 4A 5A 6A 7A 4 Paul Wilson wants to speak to somebody who knows about marketing in Spain... Complete the dialogue with have gone to/has gone to or have been to/has been to. Example: rue bought a f1ew car.. at losi.. The only other people who could help you (5) 5 Write down four things you have done so far this year and two you have not done. this century.. I'm sorry.. Can I speak to Mr Wainwright please? Mr Wainwright isn't here I'm afraid. day (5) . But Miss Philips is here. in this country. You're doing 95 mph! 95! That's the fastest (7) . B. It's just beautiful.! (19 start) Loue. Ben is an English boy. Miss Philips (3) a conference in to Spain a few times.... PAUL WILSON: RECEPTIONIST: Hello. Are you enjoying it? Yes it's the best holiday (3) . 25 .. I played squash yesterday.. Match the questions on the left with the a) b) c) d) Once. She (11 apply) Nick with her? They (14 not be) (16 find) Lucy me last night that she (18 not want) together now for a month. [ had some chips on Friday.. [ (8) (9 talk) Yes. The effect or the result of the action or situation isn't finished at the time of speaking. they (13 break up) Oh. ADAM: Oh. 9 . And (12 be) No. 4 ... (His leg's hurting now. I've never taken drugs. Yes. but I've stopped now. We use the past simple (not the present perfect) after When ... well. I haven't had any today.... she (17 tell) boyfriend at the moment..) • We use the past simple if the action or situation took place at a particular time in the past. 3 .. which is now finished. (7 see) . She (10 seem) ANNA: ADAM: ANNA: ADAM: ANNA: ADAM: ANNA: That's good. 6 ... 1 . 1 This 1 2 3 4 5 6 7 8 9 10 is a questionnaire answers on the right.... 8 .. ADAM: ANNA: ADAM: What (1 be) the party like last night? good... Why (3 not come) very busy. 7 . I've been twice. What's the matter? -I've hurt my leg. 0 g) h) i) j) I had glandular fever when I was eight. anyone else? another for a new job. No. I went three weeks ago. I drank two glasses of wine. I (5 have) u (2 be) J (4 have) week. What serious illnesses have you had? Have you ever smoked? Have you ever taken illegal drugs? How many times did you go to the doctor's last year? How many times have you been to the doctor's this year? When did you last go to the doctor's? How much alcohol have you had today? How much alcohol did you drink yesterday? How many times did you eat fried food last week? How many hours' exercise have you taken this week? 2 .. you to her? really happy.. so I (6 be) Yes. e) About two.. Put the verbs in the present perfect or the simple past... to find out how healthy you are. 26 . I went two or three times. 5 ... you you ? exams all this Lucy there? too much work to do last night..Quick reference • We use the present perfect to talk about the present results or effects of a past action or situation. 10 .. I (15 not know) No.. ? When did you hurt your leg? -/ hurt it yesterday during a basketball match. I might phone her in that case. 2 Adam is asking Anna about a party.... ..... ? We gave our first concert We got our first recording in a pub in Plymouth.........I). put a tick (..... When did you lose them? I've lost them this morning.. They don't seem to like our music in the States.................... Say what you times in the past. 2 JO: I left school when I was sixteen... underline the mistake and write the correction in the brackets........ using the present perfect or the simple past ........ She is talking to her neighbour..1 met the Pope i111994..... We sold over a million records last month! ? No. and some have a mistake in them. If the line has a mistake... When have you done that? I've done it this morning on a piece of glass.... and what you did or did not do at particular Examples: rue walked in the HimalQljas.... Sally Brice is having a bad day..... The dog's disappeared!? When has that happened? has stopped working and (1 (2 (3 (4 (5 (6 (7 (8 (9 (10 (11 (12 ) ) ) ) ) ) ) ) ) ) ) ) ) NEIGHBOUR: SALLY: NEIGHBOUR: SALLY: When I've let it out into the garden this morning............... ? We've made twelve albums so far. 27 ... Write her questions... I think......... Read the dialogue....... 3 JO: 4 JO: 5 JO: 6 JO: 7 JO: 8 JO: 4 It is 3 o'clock in the afternoon... we haven't been there yet... NEIGHBOUR: SALLY: (13 5 Write ten sentences have done or have not done so far.. Why has no-one come? Because the Telecom engineers went on strike...... Some of the lines are correct. ..3 Jo Thomas is a famous guitar player with the band 'Earthforce'.. ? I chose it........ using the present perfect and the simple past..... and the dog's disappeared. And worst of all. And I can't use my word processor because I've cut my finger... about your life. A journalist is asking him questions. ? We've sold about eight million.. JO: ? ? I started playing the guitar when I was nine........ the telephone nobody came to repair it.......... SALLY: NEIGHBOUR: SALLY: I can't use the car because I've lost the keys... Oh.. Check your answers with a teacher.. I thought 'Earthlorce' was a good name for a rock band................. If the line is correct. ? contract five years ago with Polygram Records.. 2 The woman . over a period of time up to now. which continued N~ _______________________________________________ 1 She's having a rest now. 4 The girls . Write four sentences. 28 . The men .. in the past. We often use it with for and since to say how long an action has been happening. Questions Have I been waiting? Have you been waiting? Has he been waiting? Have we been waiting? Have they been waiting? I've been waiting for ages. over a period.11 Quick reference We form the present perfect continuous with have/has Affirmative Negative I've been waiting I haven't been waiting You've been waiting You haven't been waiting He's been waiting He hasn't been waiting We've been waiting We haven't been waiting They've been waiting They haven't been waiting We use the present perfect continuous: • to talk about a temporary action that started in the past. ~T She's been doing some exercises. that has continued over a period of time and is still continuing now. NOW year. 1 Describe fish what has been happening swim collect dig in this picture. PAST NOW ----------------------------------------------~ + been + -ing. using these verbs. 3 The dog .. and has just • to talk about repeated actions which have continued 1 YEAR AGO January March June ----------------------------------------------~ I've been writing to him for a • to talk about an action which started stopped. 3 . is that right? That's right.... 6 She's worried about her father. He's still reading it.30 and started He to read a magazine.... money for months. 5 She's a bi-lingual secretary. In fact. . I suggest you try these pills. If a line has a mistake in it. 2 . a French girl. Some of the lines are correct and some have a mistake. Write sentences using the present perfect continuous + for. 3 Emily came home at 5.00. And I haven't slept. 2 Her English is very good. lives in London.... I've been feeling really ill.00 and switched He 6 A boy phoned at 5.15 and phoned Naomi. People are using them for years and I think they'll help you. 1 She's got a flat in south London....2 Claudine. She's still in the bathroom. 5 . How long have you been having these headaches? I had them since the beginning of the month. for a French firm for two years. a) They (go out) b) They (save) c) She (work) d) She (live) e) She (think) f) She (learn) g) He (have) 7 . Well. in it for a year. 6 . . 1 . I've only been wait for a few minutes. . He 5 Matthew got home at 5. He's still there .. 3 Four young men and two young women share a big house. It is 7 o'clock in the evening. of moving back to France... Have you been waiting long? No. it for eight years. Choose from these verbs: watch read get ready talk lie cook I for half an hour. 4 They're going on holiday next month.. He's still on the phone.. 7 She doesn't like being so far away. 4 .45 and invited Lucy to a party. on the TV... you haven't felt well. ... problems with his heart. . 3 She's got an English boyfriend. I had terrible headaches.. '" She went up to her bedroom for an hour. 4 Look carefully DOCTOR: PATIENT: DOCTOR: PATIENT: at this dialogue in a doctor's surgery.I) after it. Have you worried about anything? Yes.. She's still there 4 Toby came home at 6. underline the mistake and write the correction in the brackets. It's still on. giving the correct form of the verb together since last May. If a line is correct put a tick (.. (1 (2 (3 (4 (5 (6 (7 (8 (9 (10 (11 ) ) ) ) ) ) ) ) ) ) ) DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: 29 . in the second column. 2 Michael went into the kitchen at 6. Now.. I've been worrying about an exam.. Joel arrived home at 6. Match the sentences..30 with a headache. She and lay down on her bed. aren't used in the present perfect continuous. I've always lived in London. 'I'm sorry I'm late.) She's known him for a year. She's written to him five times. • for an action happening over a short period. I've been reading it all evening. . using the present perfect simple or the present perfect continuous. want. Laura. . . love. over a longer period. 2b She/drink/about four glasses 3a Mark Roland/ask/her/to dance/all . notice. I've only been waiting for a few minutes. believe. like. seem. remember.12 We use the present perfect continuous: • for an action happening over a period of time. We can't get into the house. • when we talk about how many things or how many times. • when talking about how long.' We normally use the present perfect simple: • for completed actions. belong.30.' 4b She/never/like/him/very much 5a It's late now and Laura/try/to phone for a taxi since 12.) 1 Write sentences. know. wine and lemonade. I've taken ten photos so far. own. (NOT I've been being ill. mind. evening. suppose. not an action. understand. 5b She/try/three 6 Mark/wait/for times this moment all evening. They've been talking for 20 minutes. thanks. How long have you been waiting?' 'Don't worry. I've been ill for two weeks. • for actions happening matter if it's finished or not. • Some verbs when they describe a state. Do you want a lift?' 30 . wish. 'I've got a car. 3b He/ask/her/several times 4a But each time Laura/say/ 'No. (NOT She's been knowing him. hate. evening. la It's nearly midnight and Laura/dance/all 1b She/dance/with 2a She/drink/white about five boys. but he hasn't replied once. For example: agree. It doesn't This book s very good. be. because she's lost the key. and he (14 take) his depression.... He (12 not feel) the doctor two or three times.... Jack's a tax inspector.... He (17 watch) a documentary television and he (19 see) ... But all the time he (9 get) working in the house........... only (6 do) bedrooms . While he (5 be) jobs around the house.......... b) What has David Hall been doing? . surrounded pills for two weeks now. like that for months.. He (13 see) (16 decide) (18 watch) ....... but he (4 have) out of work he all the ... What have the Hall family been doing? What have they done? Choose the correct question.2 It is midday on Saturday......... ............. 3 Complete the text.......... He asleep..... using the present perfect simple or the present perfect continuous. about being back in an office again...... and give the answer.... So far he (7 paint) and he (8 build) All his life he (IO work) .... Now at last he (20 fall) screens full of figures. . a) What has Harry done? (play) 2 a) What has Sarah done? (break) 3 a) What has David Hall done? (paint) 4 a) What has Louise Hall done? (buy) b) What has Harry been doing? football........ but he (I be) out of work for six months and he (2 try) for ten jobs.... 31 .. one interview.. He (3 apply) a new garden shed..... He (22 not smile) And for the last few minutes he (21 dream) by computer ... and he (II hate) recently... to get another job...... in an office well ....... but they (15 not cure) the news three times..... He's smiling in his sleep................. Check your answers with a teacher... 4 Write ten sentences and say what you have/have not done recently and what you have/have not been doing recently..... about unemployment not to get up. Today he in bed........ b) What has Louise Hall been doing? . b) What has Sarah been doing? .... more and more frustrated. a or b. Joanna had been revising for her exams all day. When I met him. he went to bed. and now she was tired. Write complete sentences using the past perfect.50. outback. we use the past perfect to say that something before a certain time in the past. he had been living in London for ten years.13 • We form the past perfect with had + the past participle. Mfirmative Negative Questions She had been waiting She hadn't been waiting Had she been waiting? • We use the past perfect continuous when we want to emphasise that something progress continuously up to a certain time in the past. After Simon had eaten his dinner. 1 The waiter showed them to their table.Yes it had/No. had been in 1 Rachel Gower left home when she was only 17 and went abroad. it hadn't. a truck driver. She smiled when he spoke to her.00. Choose from these verbs. The train had left at 9. She finally returned to England and got married when she was 39. (had) When . both her legs in a helicopter gold in Northern a lot of money but she some of the money to friends and they any children and she pilot and a journalist. They asked to see the menu. He ran away as soon as he saw me. the man she wanted to marry. Complete the third sentence so that it has a similar meaning to the previous two sentences. before the other • When one action is an immediate reaction to another we use the past simple for both actions. happened • When there are two actions and it's clear that the first action was completed action started we use the past perfect for the first action. • We form the past perfect continuous with had + been + -ing. live find spend not have fly have make break not pay not meet be lend Example: Rachel had lived ir: Brazil ond Australia. 32 . a helicopter helicopters in the Australian Australia. a sheep farmer. 2 Alexander and his wife went to a restaurant to celebrate their wedding anniversary. using the word given. 1 She 2 She 3 She 4 She 5 She 6 She 7 She 8 But she malaria and cholera. most of it. • If we're already talking about the past. It was 10. By that time she had done a lot of different things. Affirmative Negative Questions It had started It hadn't started Had it started? Short answers: Had it started? . crash. her back. they . .L'talk/to 'you/have/a 'Yes 1/-' (4) 'You/drink?' 'Yes..I/celebr ate/rny birthday... 1994. He still (11 not open) like Superman at a speed of 300 kph.. When he (9 realise) one of them. five skydivers down at the other skydivers her unconscious.. 4 Tom Bell was involved in a car accident a month ago. .. Thank you Mr Bell.. he his eyes off her until she that her parachute her.. .. a team of six skydivers . When he (5 look) took off from an airfield near Tucson. On 9 May. (eaten) ..000 metres. 1/-' (6) 'How long/you/drink?' 'l/drlnk/since party?' (3) 'I see. later. 'Mr Bell. He told them that service wasn't included! 3 Complete (1 climb) (3 jump) seconds the sentences. ........ using the past perfect continuous.... They finished their sweet.... their instructor... After they them five he (6 see) immediately that the this he his . .. her parachute was OK. what/you/do that evening?' (1) some old frienda. He finished his cigarette........ about 7 o'clock.. collide with another.2 He brought them the menu... Now he is in court. using past perfect + past simple OR past simple + past simple. he (14 put) cord.. (given) . Complete the dialogue. (had) . After 6 The waiter gave them the bill.'(2) .. out.. 3 Alexander took a sip of his wine.. ... As soon as he (16 pull) Once he (18 check) his own..' (8) 'I/have/a good tirne. The magistrate is asking him questions. He (20 not take) safely.. (taken) They ate half their chicken. (5) (7) .. Once the plane (2 jump) (4 follow) Greg Robertson.' 33 . Arizona. . he before 5 The waiter brought their coffee. He knew it was off....... ... Debbie Williams. after (had) . . He (7 see) impact (8 knock) (10 make) parachute (15 pull) (17 open) (19 open) (21 land) so he (12 dive) her parachute """""""""""'" an immediate decision. He As soon as 4 They suddenly After lost their appetite. at a height of 300 metres... ... to 4... When he (13 reach) her into a Sitting position and it. .... I~-----------------------------------------------------------------------1 Complete this conversation. . I'll buy the drinks. just sitting here. or a refusal..... thanks.. She is visiting an old lady of 90 who has got some problems. ----. I II ... he (2 not be) 'How long (3 he/have) 'They say it (4 be) 'He (5 not be able to) 'No. 1 won't speak to her again.. Example: 1 [don't want to watch television any more..-_.... (6) drive either. Two days perhaps...' go and see him.. please. we can use will or shall. In Helen's replies.' in hospital for long?' there for very long.. after lor we.' He's got his leg in plaster.. He (9 not like) all right. 'Really? (1 he/be) 'No. we can use won't or shan't. He'll be tired after his long journey....... 'The trouble is I (13 not be able to) 'Never mind.. I'm so bored. He's in hospital. so I won't get/shan't get to work on time tomorrow... Shall I carry your suitcase? I • We can use will CII) when we decide to do something at the moment of speaking and won't to express a sudden decision not to do something.' him at the hospital. but we normally use their short form '11. HELEN: Would you like me to clean them for you? for you? 34 . • We use Shall we? Shall I? to ask for suggestions What shall we do? Shall we go to the cinema? and to make a suggestion or an offer.. HELEN: Do you want me to turn it off? Shall Itum it off? look at a magazine together? 2 Yes.. 1 won't have a coffee.__------"-'---'------'---1 .' play football. n negative sentences.' 'l hope he (10 be) 'I'm sure he (11) . Won't is more common. and he (7 not be able to) go everywhere by bus.' They (12 look after) at home for the next week. I (14 not be) that. complete the second question so that it has a similar meaning to the first.. There's a bus strike. After lor we in affirmative sentences. using will 'Jack's broken his leg in a car accident.._. I My brother will be here soon. HELEN: Why don't we look at a magazine together? 3 [can't see properly.. (OR • We can use will to make a request.. You (15 see) 2 Helen is a social worker.. He (8 have to) he?' .' him when you get back. My glasses are dirty.14 1--. the plaster on?' about six weeks.. Will you lend me £9 Will you come with me? '/0 and won't/shan't. Sit down.. i Quick reference • We use will CII) to talk about a simple prediction of a future event or situation. I'll af1. Write what they say. HELEN: Would you like me to call the doctor? the doctor? 3 Steve is in a hurry. to send me a postcard! RACHEL: I RACHEL: I haven't told my mother I'm going to be away. Italians. But he has still got a lot of things to do. I'm really not feeling well. What (l have) I (2 have) You (4 write) Yes.4 I'm thirsty. but I (15 think) 5 a) Make some predictions about the year 2010. me from Rome? time. He is going away for a week and he is catching a train in half an hour. His neighbour Rachel is offering to help him. I 4 Tom and TOM: ZOE: TOM: ZOE: TOM: ZOE: Zoe are having a drink. using will and won't. . (12) before you go. I promise I (6 write) I (8 phone) (10 phone) TOM: ZOE: TOM: ZOE: TOM: to drink? anything alcoholic. Use these verbs. (14 you/marry) about it. I haven't fed the cat. answer Example: I STEVE: STEVE: STEVE: STEVE: RACHEL: tell STEVE: feed not forget close get RACHEL: Oh. . but I (11 send) Don't talk to any good-looking I (13 talk) I want to ask you something When (16 you/give) We (17 talk) ZOE: TOM: ZOE: Tom! I can't give you an answer now. a tomato juice. no! The phone's ringing. you? me? to anyone. The upstairs Remember RACHEL: RACHEL: 2 3 4 5 windows are still open. I think my train ticket's in the desk in the living room. 35 . using will or won't. 1 . How would you answer these questions? What will you have to drink? What will you have to eat? Check your answers with a teacher. Don't worry. HELEN: Do you want us to go for a walk? for a walk? 6 No. HELEN: Why don't I make you a cup of tea? you a cup of tea? 5 I must get out of the house more. Zoe is going to Rome tomorrow for three months. I Don't worry. Write five sentences. STEVE: I . I you from the airport because I (9 have) you from the hotel. . in Rome yet? it to you as soon as I know. b) You are at a party. (5) every week. me your answer? about it when I get back from Rome. you? I want to know that you've arrived safely. I think I (3 have) to me while you're away. so (7 you/phone) Do you know your address No. Complete the conversation.Swer it. visit write hire play sunbathe go snorkelling swim read take Example: He's goil1. Neil is going on holiday to Spain. -----~ -1 Why do you need your driving licence. . Look out' That tree's going to fall. I How long are you going to stay? [ 1 2 There's a big conference on in the hotel so we're going to be very busy. There won't be much traffic. but I didn • • 'f have your number. I'm sure you'll pass the exam.Because I'm going to hire a car We use going to to predict a future event which seems certain because of present evidence.-.. .15 .Yes. The things she says are all examples of: A intentions where we have already decided to do something. -/'11 open a window. Do you want a drink? . It's Sunday tomorrow.. It's hot in here. He is taking these things with him._ Quick reference • • We use going to to talk about future actions we have already decided to do. I'll have a beer.. .-------_. .'? . Use these verbs. C predictions of future events which seem certain because of present evidence. 2 A hotel receptionist is talking to a guest. 2 3 5 7 . I was going to phone you. We use will for intentions where we decide at the moment of speaking.. Read the sentences and then write A. B intentions where we decide at the moment of speaking. 4 6 8 . or plans we had in the past (but we've now • We use was/were going to to talk about intentions changed our plans). [l 36 .g to swim. Write sentences about what he is going to do. We normally use will/won't for simple predictions. B or C in the brackets.---> . ' (l (2 (3 (4 (S (6 (7 Example: I thif1k Italy will ioin the World Cup. for a taxi. 3 .3 Are you going to pay by credit card? 4 Can I have your passport please? I'll let you have it back tomorrow. ) ) ) ) ) ) ) 6 a) Write three simple predictions about the future. I'm going to come round at 8 and I'll bring a bottle of wine.... a) so it's not going to be easy... I'll see you then.. d) I'm not going to work. He is on the phone to a mend. 6 .' 'fine.' 'Why not come to my place and I'm going to cook us both something. 'Where will you eat tonight?' 'At home.. These are the things he says. S I'll see if I can find you a room with a view. 4 . ['m not going to see him again .. the window.. 2 But I've got no qualifications. Some of the lines of the dialogue are correct and some have a mistake.. 4 I've heard the weather forecast. I (sit) were heard at a party. it. I've finished with Ned. 4 G: The phone's red please.. D: I (open) down. 4 The following short conversations going to.. c) I'll ring you back. and sit next to you. b) It's going to be fine. 3 I'm free on Saturday. I (give) H: Don't worry. on the left and right.' 'Won't you see Ned this evening?' 'No. [ [ [ [ [ J [J 1 1 1 1 3 Jerome sentences works in a shop. Match the I I'm not enjoying this job. you a lift. S . underline the mistake and write the correction in the brackets. If a line has a mistake in it. I've got a new Indian cook book so I'll make a curry. 6 It's going to be fine tomorrow.ever. F: I (come) 1: Because I (phone) I: Don't bother. now you tomorrow. S We could meet at the river bridge at 9.. I've heard the weather forecast. If a line is correct put a tick (. 2 .' 'OK.. f) ['I! bring two fishing rods.. 6 Someone's 1 . [ (ring) 5 Two mends are leaving work together.00. e) I'm going to look for a new one.. I (answer) S [: Why do you need the phone') 6 K: I (leave) L: OK. b) Write three sentences Example: about your plans or intentions r h1 90if19 to study law at uf1iuersity_ 37 Check your answers with a teacher. Put the verb into the future with will or 2 C: It's very hot in here. just come in.I) after it.. . 1 A: Red or white wine? B: I (have) 3 E: I'm tired. ringing.. 7 Are you going to have dinner in our restaurant? 8 I'll find a porter to take your luggage. for the future. or b) it has been planned.___ . We use the future perfect (will have/won't have + (or not happening) at this past participle): • to talk about something that hasn't happened yet. happened (or not happened) by now. DO. we could meet for lunch a bit later. .00 Drif1k with Lee at the Red UOf1 13..week's shoppif1g 12. shall I come round to your place at about 3. What will you be doing at 9. shopping. I'll be watching the match on television.. She'll be having her lunch. tomorrow? -I'll be sitting in my office.30? That's not possible. He'll have arrived in Rome by now. as usual.15 LUf1ch with Emily 14. Game with Jerry. [won't be here. what about 1O. JENNY: MARK: JENNY: MARK: JENNY: MARK: JENNY: MARK: JENNY: 38 . These are Mark's arrangements for next Saturday: 9.---- 16 Quick reference (will be/won't be + We use the future continuous -ing): • to say that something will be or won't be in progress at a certain time in the future. but that will be (or won't be) completed before a certain time in the future. I've got the message! at the optician's.IS? 1can't. when we say what has probably It's eight o'clock.eye test 11. Example: 'Hi. (4) I Well. (6) I with Jerry.30? No. (2) I Well.00? No. OK. They won 'Ihave repaired it till Thursday.00 Opucion' s . The car won't be ready tomorrow. I can't come at 8. (S) I How about a drink at the pub at S. with Emily. JENNY: MARK: Well.30 Squash club. that's not possible. (1) I the week's JENNY: MARK: What about lunch at about 12. He's just come out of hospital. when we say what is probably happening moment. I'll be hauil1g Q swim at the Sports Centre at f1if1e.. I'm free at about 4. I'll have finished reading this book by tomorrow evening. Shall I ring you then? No. (3) I Well. because a) it is part of a normal routine. in town.15 Supermarket .00 Swim at Sports Centre 10. DO. using the future continuous.30? No. He won't be feeling very strong. Can we meet at nine on Saturday morning?' {' m afraid not. Say 1. _j _ L • to talk about the present. Complete Mark's replies. Jenny is talking to him on the phone.45 Yoga lesson if1 tOWf1 16. Mark.00. at the Red Lion. • to talk about the present. Don 't phone Anna now. . On June 15th he will be starting work as a chef in a restaurant. Melanie is talking to Camilla on the phone. What will you have done by the end of next year? Write three sentences.m.15Towork. What will he have done by the end of June? Example: 1 By the end of JUf'1e he'll haue toke« his college exalt1S. it is also 8 a.2 Between June 5th and June 8th Nick will be taking his college exams.05? up. 18. This will be the first time they have met.15? He'll be gettif'1g And at 8.35? 6 At 19. . This is what Nigel does every day. What's she thinking at 8.30 Home.30 Dinner. 23. his wife.00 To bed.00 TV news. in London.20? 5 At 18. I won't have slept at all. 7.35? 7 At 21. . to bed.30 train from London Paddington. I'll have had lunch on the train. dinner. On June 29th he will be getting his exam results. (I) CAMILLA: MELANIE: CAMILLA: MELANIE: CAMILLA: MELANIE: CAMILLA: MELANIE: CAMILLA: on the plane? ? ? and a bag.35? 4 At 13. ? ? me. 8. On June 11th he will be moving into a new flat. using the future continuous and the future perfect.00? He'll haue jif'1ished his breakfast. 21. lunch. Example: What is Sophie thinking at 7. She knows his habits very well. I expect you'll be tired when you arrive in London.m.15? 2 At 9. No. lunch. I'm afraid. (2) I'll be catching the 11. I can never sleep on planes. 12. 19. 4 Melanie MELANIE: Wright is meeting her cousin Camilla from Australia at the station on Saturday. 745 Breakfast. 3 Nigel is at home in London. Check your answers with a teacher. Complete her thoughts. On June 10th he will be leaving college. is in Accra on business.15 Lunch.05? 8 At 23.00? 3 At 12. 39 . to work work. home. (5) I'll be wearing a red jacket. Write Melanie's questions. I'll be bringing two big suitcases (4) Yes.30-13. Sophie is thinking about Nigel. the news. (3) Quite a lot. When it is 8 a.15 He gets up. in Accra. so you should recognise 5 What will you be doing this time next year? Write three sentences. using the future continuous and the future perfect. Sophie. 2 3 4 . (begin) of the tunnel. for example modal verbs (can.. (construct) during the construction in 1994. (open) and several 3 Work on the present Channel tunnel by many people. expect to.. under the Channel in half the time by rail. o form the different tenses in the passive. (Informal) A letter will be sent to you. (put forward) 2 A tunnel 4 Two tunnels 5 Seven people 6 It 8 Nowadays the tunnel 9 The sea crossing .---~ •. . Active: The cat killed the mouse.. etc.. But passengers. That shouldn't be allowed.have/has been + past participle.. My bike's been stolen.. Note that we also use the passive infinitive construction after verbs like want to...--. we use a passive infinitive (be + past participle)."" Present continuous: Past simple: Past continuous: Present perfect: Past perfect: Future will: Future going to: Modal (present): Modal (past): the verb be (is/was/has been... Ten people were killed ... or isn't known.. hope to.. .-Ol "1!1_"~_ssire.. Your room should have been cleaned.. 7 The first trains were unreliable in 1878 but it side by side....)... Compare: We'll send you a letter... (prefer) (transport) 40 .. · We use the passive when the person or thing doing the action isn't important..~i1 sim pie: P'roo"""... The house was bought by a local businessman. (delay) by thousands of people every day... would. You might have been hurt. Passive: The mouse was killed by the cat. She wants to be liked. All tickets must be shown.. should. Note the past form of the passive infinitive . etc. I • The object of the active sentence becomes the subject of the passive sentence.) + the past participle.-- - 1 Put the verb in brackets into the passive. will.. • Some verbs are followed by an infinitive.. (Formal) Note that in a passive construction we can mention the person or thing that does the action (the agent) after the word by... must. • A passive sentence is usually more formal than an active sentence. When these verbs are used in a passive construction.. (use) cars and freight 1 The idea of a tunnel between England and France century. agree to.. at the beginning of the 19th (start) (not complete) in 1987... (kill) by many hours.~ -. or is understood. They agreed to be photographed. Active Passive He teaches He is taught He is teaching He is being taught He taught He was taught He was teaching He was being taught He has taught He has been taught He had taught He had been taught He will teach He will be taught He is going to teach He is going to be taught He may teach He may be taught He might have taught He might have been taught The tense of i I II . l .. etc. . Complete the text by putting these verbs into the past simple passive or the present perfect passive: add..... 4 In which city are they going to hold the next Olympics? in which country. ought to have offered them longer holidays. using a passive construction. 3 Put a tick (... A man in a red Ford Escort was talking to her in St Andrews Road. [1 [1 [J [J [1 [J [J [1 [1 [1 [1 [1 4 Read the questions in this general knowledge quiz...... to pay them more to consult them about changes.. 41 . A black T-shirt and jeans were being worn by her. ? ? ? ? . the next football World Cup 6 How many times have astronauts visited the moon? How many times the moon.I) after the 1A B 2A B 3A B 4A B 5A B 6A B better or more natural of the two alternatives. She has been heard from by none of her friends...... Example: They don't want the management 1 They want the management 2 They want the management 3 They think the management 4 The management to treat them like machines. Someone last saw her on Tuesday evening.... using a passive infinitive. at the moment? 3 Who invented dynamite? Who dynamite... Complete the second question so that it has a similar meaning to the first. .) The workers at an engineering company are very worried. She was last seen on Tuesday evening. She was wearing a black T-shirt and jeans... A reward is being offered for any information useful to the police. install.2 Here are the details The house (1) of a house for sale. the next Olympics '" 5 In which country will they play the next football World Cup? In which country ... rebuild.. She was being talked to by a man in a red Ford Escort in St Andrews Road.. Change the following sentences from active to passive..... Someone is offering a reward for any information useful to the police. A missing girl is being looked for by the police. buy. It (2) completely A new bedroom The roof (6) and a shower room (5) less than year ago... modernise. None of her friends have heard from her.. . Since then it (3) heating (4) .... by the present and central also owners in 1980. in the 18th century. Police are looking for a missing girl... Example: Where do they speak Dutch? Where is Dutch spoken? 1 In which country do they make the most bicycles? In which country the most bicycles ? 2 ln which country are they producing the most oil at the moment? In which country the most oil.... ~ They dOI1't tooni to be treated like machil1es. should have told them about the company's problems... build... say. [couldn't stand . A new car was given to her. The photograph was shown to me. We aren't supposed to smoke. We use being + a past participle. find. I don't like being told what to do. tobacco. consider.) __ . offer. • We can also use a perfect infinitive (to have hac!) in this construction. send.18 r I I I ---.00 They're said to be very rich. . (Active: Somebody showed me the photograph. . tell. owe.) Passive: I was shown the photograph. who were very strict with her. .------. feel. stand ' 2 They always gave her boring jobs to do. it's possible to have two passive sentences: give. we can use the construction passive verb + infinitive with to: believe. announce. teach. intend. sell. . • With the following verbs. b) Something should happen because it's the rule or the plan. fear. hated it._- Quick reference • We can use the -ing form in the passive.. promise. -I l. expect. say. The robbers are said to have stolen £1. • We can use It + a passive verb + a that clause to talk about what people in general say. report. . It's reported that 20 people died in the crash. understand. know. know. fear. I hated beil1g treated like a child. feel. at her when she did something wrong. (This isn't permitted. suggest. .. We can use this construction with these verbs: agree. think or feel about a situation.ction is more commo_n_. It was felt that he was too old for the job.. • Note the two meanings of be supposed to. I hated 5 They always shouted 'hated 6 They criticised I couldn't -'-2 . . (Active: Somebody gave her a new car.) • When the following verbs have two objects (indirect and direct). I got tired of 3 They always sent her to the shop to buy her grandfather's I got fed up with 4 They treated her like a servant. 'Impulse' is supposed to be a very good film. think. report. expect.) Passive: She was given a new car. find. using a passive construction. Add what Sally says. her all the time. show. lend. She Example: They always treated her like a child. . think.. decide. They always told her to make her bed. (The fir~_t_co_nst:.000. understand. You're supposed to wear a seatbelt. He's expected to arrive at 11. a) Something is the general opinion of most people. 1 When Sally was 14 she often had to stay with her grandparents. I enjoy being given presents. pay. 4 'I haven't had any exercise this week. using a passive construction.2 Amy Wyn lives alone. She 2 Reports suggest that she's got a priceless collection She 3 (The other day the police stopped her for speeding. The dogs 2 They've promised him compensation. . . The water here is supposed to be polluted. . (thought) . . of antique jewellery. (reported) . Use forms of supposed to to remind him. She (found) . Then rewrite Example: I had a small glass of water yesterday. people say sugar gives you energy..' ' But you're supposed to drin« 1 litre. Write the following sentences in a different way. ' ' ' ' ' .' 'But 'Well. (said) She 5 People believe that she played at Wimbledon. No sugar. George is not taking the doctor's advice. his reply in a different way. He 43 .' 'But 'Well. They say they'll find the dogs new homes.tthree letters of comploird. Plenty of exercise.. Complete the second sentence similar meaning to the first. people say tea's good for you. This is his advice: No coffee or tea. 1 litre of water a day. People say the water here is polluted. 3 George Foster is 55 and has had a heart attack. He 3 A man offered him a gun to shoot the dogs.' ' 3 'I had two fried eggs for breakfast. 'I fancy a nice cup of tea. people say eggs provide protein. Not much is known about her. she had £25.000 in her 1 People think she made a lot of money selling antique furniture. Example: The authorities have sent him three official letters of complaint. He's been sel1. (believed) so that it has a She's believed to be about 80. Example: People believe she's about 80. He 4 Someone has sent him threatening letters.) They discovered handbag.' ' 4 Bill Graham keeps 15 dogs in his small house.' ' 2 'And I'll have two spoonfuls of sugar in it. She (believed) . His doctor has told him that he must change his life-style if he wants to avoid another attack. 4 People say she was a very good tennis player when she was young.' 'But 'People say too much exercise is dangerous. His neighbours want him to get rid of the dogs.' 'But 'Well. using the word given. No fried foods. ' . . l 1 • when something unpleasant happened to someone. (broken) in a pub.. 2 On Thursday On Thursday someone I took my wife's passport broke my glasses in an argument in an argument stole my video camera. And he (5 repair) he (3 not install) the software Complete these sentences fix it himself so he had it repaired by a in a garage.. by a building firm. Get suggests a clear intention.) . get instead of have.. When he bought a at the shop. broke into our car. with the correct forms of have something done.... (taken) our bags for drugs. I had my haircut.... j .. (= We had have + object + past participle had the TV repaired. I'm not enjoying my stay. We had the house painted._ _ -. Do not change the word given. on Sunday. He had his nose broken. 3 On Friday someone On Friday my wife from our hotel room.. but not everything.. using the word given... He washes the car himself but normally he (1 service) cleans the windows himself but he (2 paint) new computer himself. to tell you the truth. _ ---- -. someone And finally...19 ! Q~ick reference We use the construction have something done: usually because we can't... have had their passports stolen. He's quite good at small building jobs but next month he (4 build) . On Tuesday someone On Tuesday..._ . the carpet cleaned.•. She had her bike stolen.. ---_--- . we us and they searched us and we for drugs. He always by a decorator. in a pub. on Sunday. I feel safe there' ._-_.. 0) . Example: His central heating system broke down. 2 An American tourist is talking to a Scotsman in a hotel in Glasgow.. He did it a new garage the roof of his house .. • The word order is: Subject + a) We b) They In informal English we sometimes use We got the carpet cleaned... (had) 4 On Saturday the police stopped On Saturday the police stopped 5 And finally. I can't wait to get back to New York. into. Complete the second sentence so that it has a similar meaning to the first. (broken) So. I l I ! I I I .. . • when we don't do the job ourselves.-- - - -'-"--- Peter is practical and does a lot of things himself. He couldn't heating engineer. . 9 Once a month an astrologer tells her fortune. 4 Every week a garage washes and polishes her car. She does very little for herself.. Why don't you (5 install) . When did you last (1 cut) The cooker doesn't work. His mother is visiting him for the first time. .. Check your answers with a teacher. MOTHER: Your hair's too long. 5 This month a dressmaker .... 10 And four times a year a dog beautician shampoos 4 Justin is a student living away from home. . 45 .. Every day a woman cleans and tidies her apartment. . 5 Write sentences in which you describe two things you normally have done for you and two things you had done last week or last month. . ... Why don't you (2 repair) And look at this carpet! You should (3 clean) I can smell gas.. 2 Last month a decorator redecorated the whole apartment.. 7 That was only a week after a plastic surgeon had remodelled her nose. . 3 A carpet fitter has just laid new carpets in every room. 6 Last week a dentist straightened her teeth. .. Example: Once a week her hairdresser cuts and styles her hair Ol'lce a week she has her hair cut end styled... Complete the dialogue using the construction have something done.... her poodle... .... You should (4 check) I worry about you. JUSTIN: Because I haven't got any money. Replace the words in italics with the structure have something done.... .. Last week I had my hair cut. ? ? the gas fire a telephone .3 Charlotte Montagu-Smith has a lot of money and a lot of spare time.... Justin... . ? it it it .. . 8 Next week an artist is going to paint her portrait. is making her a new collection of summer clothes. Examples: I haue my eyes tested once a year. . .... " . I did.." .. I quite like answering questions............" . 5 ? ? Yes. Why won't you Why don't you in exclamations... is asking her ." No..." here for the first time? 2 No..... would.."" . Complete the researcher's questions ....... I have......) before the subject......".... I'm not.. the preposition remains attached to the verb/adjective in a question. do) or a modal verb (can.." .... and did in the past simple. Don't you like chocolate? 28 days in February? or to make a suggestion..20 Quick ref~rence • To make a question we put the auxiliary verb (be. ? 4 Yes. Who's she talking to? What are you good at? I _j I 1 Amy Price is at the new Shopping Centre in her local town. ..?How? thinking? What are you last? How long does the film We use negative questions: • • • to show surprise. Present simple: Does the train stop at Exmouth? Do people like her? Past simple: Did she arrive yesterday? • We often begin questions with the question words What? When? Where? Which? Who? Why... I've bought a lot of things this morning...."".. there is something I'd like to change. 7 Yes. Aren't there with Why? to show surprise or frustration.". I come every week... A market researcher what she thinks about the new centre. I always do my shopping here now.. etc.. I came twice last week.. will.. have.... 3 ? Yes. Don't Isn't they the view • • If we use a verb or an adjective + a preposition. help have look me? a holiday? stupid! wonderful' when something seems very probable. 6 . does to make questions..... Auxiliary/Main Are Have Can verb Subject you the children you Main verb staying been speak here long? abroad? Arabic? • In the present simple we use do........ I wish they wouldn't play this music...."".." ." .". I don't mind.. .............. we did. 3 She's obviously thinking about something 4 She was talking to someone at the station.............. "7 7 ? 7 ? "7 4 Zoe is talking to her friend Chris...........? 3 Emma is hoping to buy a second-hand computer.... we realised we'd paid for two bottles! 5 Tom's friend Sue has been acting very strangely..2 Uwe wants to get to know Pia.. l~~~~~~~_~......... but after we'd left... And the manager was very rude.. you recommended wasn't very good..... ? ? ? . _ .................. a girl in his English class.......... he did........ Complete the negative questions Chris uses to show his surprise. ZOE: CHRIS: The restaurant Not very much. 47 ....... Where 2 when she arrived in England 3 how many times she's been to England ? 7 4 how long she's been learning English 5 what she likes doing 6 what she's doing this evening..... but the wine was terrible.. She has seen an advert in the paper.. ? ? '1 ? Example: She's worried about something.......... (1 you/not Iike/it) (2 the food/not be/very good) The food was OK. (3 you/not complain) (4 he/not give/you/another bottle) _. 7 if they can have dinner together.......... ......... you ? 1 He wants to know: where she comes from.. What are you worried about? _........ Write the questions he wants to ask her.......... Example: IBM PC or Macintosh? 1 Model? Which 2 Printer type? What 3 Age? How 4 Cost? How 5 Reason for sale? Why 6 Possible to see it? Can _. she is writing down the questions she wants to ask the person who is selling the computer.. 1 She's angry about something 2 She seems afraid of something.. 7 ZOE: Yes.............Write the questions he asks her.. 1 J Before she makes the phone call.. _ Is it an IBM PC ora Macintosh? _.__ Computer (including monitor) and printer) for sale.............. ZOE: CHRIS: ? ZOE: CHRIS: 7 ZOE: CHRlS: Yes.... ........ ? Oh dear...... Write her questions.............. A.7 They've got lovely gardens. 3 They lost 3-0...... the question Positive Negative It's cold. 2 Some tourists are going round the Oxford university colleges. haven 't they? There's a problem...-. ? They must get fed up with tourists like us.. This is your new computer. a) has he') b) are they? c) did they? e) is it? f) didn't they? g) won't they? h) can they? i) isn't he? 6 .. are there? Positive does he? did they? has she? am t? has she? can you? should we? • We can use a positive tag after a positive statement to express interest. is it? Positive Negative Negative He smokes. did you? surprise or I .. is it? You've got a headache. The verb be: She's got a car. There are lots of colleges. hasn't she? She hasn't got a car. ? They're beautiful inside. Read what they say and decide which answer. shouldn't we? We shouldn't have waited.. or C best fits each space. Let's go. (5) . 8 . doesn't he? He doesn't smoke. aren't I? I'm not right. sarcasm. 2 And they didn't play well last week. (2) . (4) . sympathy.. 4 Their defence isn't very good.- Quick reference • We use question tags at the end of a sentence person agrees or not. shall we? Open the door. quite good.... though. Present perfect: I'm right. If we say something negative. isn't it? • to ask if what we said is true or not.... will you/can you? Everybody came.. 2 . they can't score goals. 4 . 5 But the new goalkeeper's 6 The problem is. didn't they? Somebody has stolen it.. (6) ? _:_8 . Have got: You can come. or if the other tag is usually negative. hasn't she? She hasn't left.I '-- 21 --. Negative Positive It isn't easy. didn't they? They didn't win. isn't there? There aren 't any tickets.._ _j I 1 Two men are watching a football match. (3) .'_ ".. 3 ... 7 The students look bored. 7 .. the question tag is positive.. 5 ... 7 They'll have to sack the manager. Match the two parts of each sentence... (1) 7 But you can't see anything from the outside. 8 He hasn't done very well. • If we say something positive. ... Modal verbs: We should have waited. B. have you? You had too much to drink. Present simple: They won. Past simple: She's left. I They're not playing well. 1 . can't you? You can't come. I think. '!' speaks English nowadays. (6) . using question tags. correct question tags.1 2 3 4 5 6 A A A A A A aren't there can't you are they haven't they got don't they must they B B B B B B isn't there can you they are haven't they aren't they they must C C C C C C is there you can't aren't they have they do they mustn't they 3 Two people are watching a film on television. Complete the dialogue.' 'He looks really evil. (11) money in that restaurant pesetas. (15) last night. because we've missed our train. (14) 7 ? And that was your idea. (13) 7 You said it was only 400 pesetas.' 'I said they would.000 7' 49 she said. (3) 'Yes. 'I've no idea where the station is. (9) Look after my suitcase (3) (5) (7) 7' ? I told you.' 'But we haven't got enough money for a taxi. . (7) ?' ?' ?' '1' ?' 4 Two English people are lost in Barcelona. for me. '1 You can understand Spanish. (8) 7 So I'll go and ask that woman over there 'Don't be so sarcastic! I think we'd better get a taxi. I understood 'So you understood (10) everything she said. 'It's not a very good film (1) 'It's OK. (4) 'Yes. (6) 'Shut up! You can never keep quiet. They are arguing. Add the ?' 7' 'Those two cars are going to crash. I can see that. er no. (2) 7 Let's ask a policeman. We go straight on. (2) 'I don't know. then we turn right. (4) '1' 7' 7 And we can't speak Spanish. (I) 'Well. ?' 'Well. it doesn't matter now.' everything ?' 7 We shouldn't have spent all our 7' but it was 4.. then we. (18) .' 'We should have bought a map.. you chose the wine.' One of them likes to talk at the same time. left. we'll have to ask someone.' 'That man's got a gun. at the lights. what did she say?' 'No problem. (17) . (5) 'I don't know.' 'He's not going to shoot her. er. you did. (12) That wasn't my fault. 'But there aren't any policemen. (16) 'Well. 'But everyone (Later) 'Well. .. we use if or whether. ..00? ? ? ? ? ? ? ? ? 9 (phone) She phoned the electricity 50 company. A few seconds later there was another violent flash and the television exploded.. Where are my shoes? > Do you know where my shoes are? Do.05 the phone rang. 5 (phone) The neighbour. What languages does she speak? > Can you tell me what languages she speaks? Where there is no question word. ? OR Can/Could you tell me. followed by a lamp on the living room table._--_. 6 (ring) It rang at 10.~---. . Does she eat < > Do you know if/Wheth:_s~e:ts fish? . Lisa rang the electricity company to ask when the power would be restored. Which one is yours? Which of those people do you know? ? . At 10._. _. Complete the questions that give the following answers._Quick reference • When we use Who.22 . Lisa screamed. I I I I 1 Peter and Lisa were at home yesterday when there was a violent thunderstorm. 8 (disconnect/first) The CD player. What clothes (OR Which clothes) are you going to wear? But Which is more common with people... did are replaced by the affirmative form of the verb.00 the centre of the storm was right over the house. Who did you phone this morning? (NOT Who you phoned this morning") • We can use What and Which before a noun. we use do. or _ . At 10._.. The meaning is often the same. Peter immediately disconnected the CD player and then the video. There was a terrific flash of lightning and the lights went out.?/What?/Which? as the subject of the sentence. 7 (disconnect) The CD player and the video. does. 2 (explode) The television and a lamp on the living room table. Peter picked it up carefully. does. we don't use do. does. and What when there's a large or unlimited choice. . Which tennis player has won the championship three times? (Which + a person) Which leg did he break? (limited choice) What books do you read? (large choice) • We can use Which + one/ones and + of. When the storm had moved away.---.. I I I • We often begin indirect questions with Do you know . It was their neighbour asking if they were all right. We normally use Which when there's a limited choice of possibilities.05. did with the verb. 1 (happen) The lights went out. or at 10. did with the verb._. 4 (do) She screamed. . 3 (explode/first) The television.. Who phoned this morning? (NOT Who did phone this morning?) When we use them as the object of the sentence. There are two books here. '(3) 'I'll have those. you can get a bus.' 'How far is it? (2) Have you any idea 'It's about 15 miles from here.' 'Have you got any goat's cheese?' 'I've got a French one or one that's produced '(8) 'Fine.' 3 Read the dialogue and complete the second question so that the meaning is similar to the first. (7) 'The ones from Spain. (5) '(6) 'I've got some English ones or some from Spain. but there's a reduced service on Sundays. I'm afraid.' 'How much does it cost? (7) Could you tell me 'I'm not sure.' 'Good.' 'Can I get a train? (3) Do you know 'No.' 'What time does it leave? (5) Could you tell me 'I think there's one every two hours. there are no trains. Now.' 51 . (2) ones are cheaper?' of these avocado pears are ripe?' sort of cheese have you got?' sort would you like? There's a big choice.' locally. these two are OK.' 'How long does it take? (6) Have you any idea 'It takes about 45 minutes. on the hour. (1) Could you tell me how r get Example: 'How do I get to Snatchwood? 'Snatchwood? to Sf1Qtchwood?' is?' You need to go towards Oxford.' 'Do the buses run on Sundays? (8) Do you know ?' ?' ?' ?' ?' 7' 'Yes.' 'Is there a bus? (4) Do you know 'Yes. 1prefer the local one personally.' '(9) 'Urn.' would you prefer?' 'I've only got orange. using what or which. (4) 'Er. (10) 'That'll be fine. Um. would you like?' please.2 Complete '(1) the dialogue. (11) else would you like?' fruit juice have you got?' do lowe you"?' do you recommend"?' 'Well.' would you like?' 'I'd like some tomatoes. . seem. • With all of the above verbs except guess. ..It seems so.. + subject. we use do... guess.. • Is it going to rain? -! hope not. f) So would I. hope. 5 .) • We can use both forms with believe.Neither did I.. suspect. I understand most of the grammar. But we must use not after guess. 7 . . 3 . will they'? -! don't expect so.So do I I've got a headache.. 3 I've never eaten Thai food. . we often use negative forms with so. we often express agreement with so after the following verbs: believe. . 4 . 1 can ski. 2 Maria is Spanish and Pascal is French. PASCAL: (1) PASCAL: PASCAL: . They won't win. does or did after So/Neither/Nor. I'm hungry. 52 . 2 But I don't like very hot curries.. • Note that when the present simple or the past simple is used in the first statement. presume. imagine. using So '" I and Neither I. . tvIARIA: And I sometimes MARIA: I've never been to England.. b) Neither can l. a) So have l. (4) (5) . . They have just met in a bar in Rome. c) So do l... . d) Neither am l. hope. 1suppose so. 7 I can't use chopsticks. (2) (3) PASCAL: PASCAL: I've been learning it for a long time. They must have a lot of money. be afraid. I didn't wan! to go. 1 . MARIA: MARIA: MARIA: MARIA: I'm learning English. presume. . • When we want to say that we do the same or feel the same as someone else.Yes. 5 But I've eaten Vietnamese. presume.. • After negative statements we use Neither or Nor + auxiliary verb I don't like English beer. suppose. OR! expect not.So do we. We live in Manchester.23 Quick reference • In short answers. didn't she? -/ don't think so. g) Neither have I. we can use the short answer So + auxiliary verb + subject after positive statements.So have I. think. reckon. suspect. PASCAL: (8) . 2 . But I don't find speaking English very easy.Neither do I/Nor do I. be afraid. e) Neither do l. .. \1ARlA (7) Let's have something to eat. 6 .. 1 I like Indian food. She passed the exam.. . (NOT I don't hope so. Complete Pascal's part of the dialogue.... 4 I'd like to try it some time.Neither am I/Nor am l. can't understand people.. suspect.. . I'm not enjoying this. PASCAL: PASCAL: \OIARL'" I'd like to go one day. 1 Match the replies on the right with the sentences on the left. hope. 6 I'm not very keen on Chinese food. (6) ... And they like to spend it. expect and suppose.So can I He works hard . be afraid. ZOE: TIM: 5 Answer these questions using I hope so/I don't think so/I expect not. Complete Tim's answers. Will you live till you are 80? Will you stop work when you are 60? Will you ever use your English outside the classroom? Will you always live in your own country? Will there ever be another world war? 53 . ZOE: TIM: You've got our boarding cards. Zoe does not like flying. . Use only one word in each space. that won't ZOE: SARAH: It takes about three and a half hours to Athens. SARAH: You don't ZOE: like ilying. won't ZOE: I suppose (1) . think so. etc. Read the dialogue and think of the word which best fits each space. No. Check your answers with a teacher. etc. do you? . this evening. isn't it? (be afraid) (7) We won't be there till 8 o'clock (be afraid) (8) . . it? SARAH: It'll be hot there in July. (expect) ZOE: TIM: Will they call our flight? (expect) (4) . haven't you? (hope) (5) Can we change our money here? (imagine) (6) There's a bank over there. ZOE: TIM: ZOE: TIM: It's quite a long flight. Have we got time for a coffee? (think) ZOE: TIM: ZOE: TIM: Our flight hasn't been delayed. has it? (think) SO (2) It doesn't say 'Delayed' on the board. I'm afraid (5) 4 Zoe and ZOE: TIM: Tim are at the airport. SARAH: Are you going on holiday this summer? Yes. doesn't ZOE: Yes. on their way to Naxos. it? [suppose they'll speak English in the hotels. will we? . (3) . SARAH: What about the language? Can Tim speak any Greek? ZOE: J (2) I hope (3) SAIV\H: Well. (1) It's only ten to four. I'm (4) so. we won't have to wait long. be a problem. using J think so.3 Sarah ZOE: is asking Zoe about her holiday plans. Tim and I are going to Naxos in JUly. . All my friends went to Sally's party. . f don't eat meat. . I didn 't buy that car. . I I • We often use an auxiliary verb (be.I . .My sister has.Yes. . • • • --------.I wouldn't. We use the full form of auxiliaries when they're affirmative. have. but f would have if I'd had enough money.) on its own to avoid repeating the main verb. . . would. Look at the chart and answer the questions.I . Example: Who likes sport? Zoe does. we normally repeat only the first. using the correct auxiliary verb. they will.I but but but but but but but but but but . but f haven't. . I've cut my finger._. It was too expensive.. They won't have finished lunch yet. If the main verb has two auxiliaries. on its own in reply questions to show interest or surprise.24 _.I .I . ..I .I . Have you seen their new baby? . might. but my brother does.I .I . I'm not going to the match. • • But we use two auxiliaries We use an auxiliary if we change the verb form. etc. Zoe and Anna are sisters.I ._---------------Quick reference Most of my friends are going abroad this summer. It's quarter past two. but their lives are very different. . but I'm not.I 1 Who was born in England? 2 Who lived for a time in the USA? 3 Who's got long hair? 4 Who's had a serious illness? 5 Who plays a musical instrument'? 6 Who enjoys horse-riding? 7 Who will be on holiday in Florida next week? 8 Who can swim? 9 Who's got a boyfriend at the moment? 10 Who's looking for a job? 54 . but Sue oru: Af'lf'1Qdon't: Anna Zoe Sue Born in England Lived in USA Long hair Serious illness Musical instrument Horse-riding Sport Florida holiday Swim Boyfriend Looking for a job ..I . (NOT Tom's) We use forms of do if the preceding main verb is in the present simple or past simple. . ..Have you? He drank the whole bottle. f would have bought that video camera. but I didn't. but Tom is.I .I .Did he? 1 Sue. . can. .. It's his handwriting... We should have asked him why.. A. d) Hasn't he? 4 They think it's a big concession to the rich. would 55 . Match the statements on the left with the reply questions on the right.. 9 . f) Has he? 6 The price of petrol's going up.... Write five sentences. But he doesn't (A hasn 't 't B haven 't C have) B should have C must have) want us to know where he's gone.... {shouldf1. {should have. Example: {don't like shoppif1. but my brother does. (A did B was C wasn't) I (8) . (A must have B would have C can't have) He was acting very strangely this morning.... but { was lazy.... Examples: {didf1. Who knows? (A must have B might have C could) Do you think he'll telephone? He (5) ... depressed.. using auxiliary verbs on their own. a) Didn't he? 1 The Chancellor's reduced income tax by 2%.. 1(1) .. but we haven't got her number. either.g. Shaun and Neil live in the same flat as Sam... e) Won't they? 5 He should have given more money to the Jow-paid. c) Haven't you? 3 But low-paid people won't benefit. if he'd wanted us to know. because it isn't here.'t work hard at college. i) Should he? 9 I've never known a more selfish budget. I ...g Check your answers with a teacher. Two people are talking about it. I don't know where he is. at my sister's party.. I haven't seen Sam all day. but I didn't have time.... B or C best fits each space. but {wasjeelif1. Write five sentences about things you wanted to do but that you did not do because of circumstances.. 2 .. 10 .... Alice... 5 . 4 Compare members of your family.2 Sam's SHAUN: NEIL: SHAUN: NEIL: girlfriend. or about things that you did. 4 .'t have..... j) Did he? 10 1reckon it's a budget for the rich... {got drunk.. Decide which answer.. I'm not sure.... (A won Has he taken his car? He (6) . (A don Who left this note? Sam (2) . but that you regret now... (A can 't 't B couldn 't C might) B could C won't) 3 The Government has just announced its budget for next year. He (3) ... 3 . g) Do they? 7 But he hasn't increased the tax on wine and spirits... the other has not.... (A would have B would C couldn't) Can't we phone Alice? We (9) . He obviously doesn't (A would have B would C hasn 'f) Do you think he's gone to Scotland to see Alice? SHAUN: NF:IL: SHALlN: NEIL: SHAUN: NEII_: SHAUN: NEIL: SHAUN: NEIL: SHAUN: He (4) .. One has heard the news. b) Do you? 2 He said this would help the economy. 7 . Use the auxiliaries have or should haoe/shouldn 't have on their own. I know he (7) ... SHAUN: NEIL: say where he's gone.. h) Is it? 8 He didn't increase spending on education. 8 .. has just gone to live in Scotland. 6 . The only thing you (3) were able to/could do was go for a walk or go to church... when we want to emphasise the future time. J won't be able to remember your phone number for ability/inability. not be able 10. Underline the better alternative. write. J (4) . And you (2) weren 't able to/couldn 'I do anything either. not can. so my second book took much longer to buy a word processor.. When she's 18. understand how to use it and I lost a whole chapter of my book! [ (6) . I can't ski...25 We use can • • • • + infinitive without to and be able to + infinitive: J can speak Spanish. J don't know her address.. (NOT I wasn't able to believe it. find it for me and he said he (8) teach me how to use a word processor properly. write to her. so we don't use could) J couldn't believe it when she said she was 20. J can speak Spanish. At first.. on Sundays. Complete the sentences with can/can't could/couldn't or (not) able to. get a job ... you (1) weren't able to/couldn't buy anything except a newspaper. But in the negative couldn't is more common than wasn 't/ioeren 'I able 10. Last Sunday I (5) was able to/could go shopping at the supermarket. Jcan't J can meet you at the station. At the moment he's studying Japanese and by the end of next year he (2) with a Japanese company.. He '1/ be able to drive soon. I got my first royalty cheque and I (2) typewriter. only speak four languages. I'd like to (4) speak English and I (6) at the moment but I (7) really speak that very well! I'm going to French evening classes go every week because I've been too busy. 3 In Britain Sunday used to be a special day.. my son and j (6) were able lo/couldwatch a professional football match. 2 Robert Collingwood has been a writer for 30 years.) 1 Complete My brother the sentences using can/can't (1) or the correct form of be able to.... A few years ago. (NOT I'm able to) In the future we use will/won't be able 10. for possibility/impossibility. But recently the law has changed and people (4) have beef/ able to/ could do much more. Then. afternoon. a friend... But I (3) only type with two fingers. In the present.. who was an expert on computers. A buy a year after the book was published. speak five languages and he (3) speak two languages! [ (5) . He could write with either his left or right hand (a general ability) J didn't have any money yesterday... in the 56 . (7) anywhere on my computer. but a friend was able to lend me some. find it . 1(5) . she '1/ be able to drive to school. When I started writing books I (1) type so I wrote my first book with a pen and paper. (a particular situation. we usually use can. • In the past we normally use could for a general ability and was/were able to for a particular action or situation. 1'1/ be able 10 leaoe early tomorrow. When I got my second royalty cheque.. Fortunately. ... Could is a little more polite than Can..9 . We don't know where it is. You can stay till midnight.. 4 We want to leave very early tomorrow... some? show you how it works? borrow mine? lend you some money? meet them? invite her round for a meal? come? 57 a lift? . 5 We need to contact our bank. f) Could we have breakfast at 7. 2 Manuela has just arrived in London to study English at a language school. ?/Would you like to '" ?/Would you like me to '" ? I I'll be driving past your language school this morning 2 I've just made some coffee 3 This is our microwave 4 You haven't got an umbrella. May is very formal.. You may leave now. Can you._- ---_Quick reference We use can. Complete their offers and invitations. Can I get you a drink? Can we help you? May I make a suggestion? • To give permission we usually use can.3 . 2 .... She is living in a flat with a group of English girls who are very kind and helpful... 6 We need a film for our camera... have you? 5 I'm afraid the bank doesn't open tiI19. Match their needs with their requests.6 . They ask the owner for help. Can / come? Could / have a drink? Could / open a window? May / smoke? • • We can use Would you. Would you is more formal than Can you and Could you and is less common. 8 We're all going to a party tomorrow night.30? g) Can we use the phone? h) Would you tell her we'll ring her back? i) Can you give us a key? 8 Ilike a cigarette after dinner. May is more formal and less common than Can.. and for permission to do things.30 6 There are two very nice boys living in the flat upstairs 7 I know a Spanish girl at work.4 . Would you like some tea? Would you like me to get you a ticket? Would you like to stay the night? 1 Michelle and Jean-Claude are staying at a bed and breakfast in England. Could you (NOT May you) to ask someone to do something. Use Would you like . 1 Where can we leave the car? 2 We want to visit Castle Drago.... Can you help me? Could you pass me the salt? Would you get a taxi for me? • We use Can lor May I when we offer to do something. please? b) May we park in front of the house? c) May I smoke in the dining-room? d) Can you tell us where we can buy one? e) Could you lend us a map? 3 We'll be back late tonight. and to invite someone to do something.. a) Could we have some....26 (--.. (formal) • We use would like to offer something or to offer to do something.. 7 We like bread with our meals. May is more formal than Could.8 . 9 A friend might phone from Paris. could and may to ask for things or for permission.5 .7 .. 27 -_ • • • • .. Quick reference _--------, we normally use Do l/you, etc. have to? I Must and have to sometimes mean the same - that something is necessary or obligatory. I must go now OR I have to go now. In informal speech we can also use have got to. It usually means the same as have to. I've got to go now. To ask if something is necessary or obligatory, Do you have to be over 18? Do I have to come with you? There is sometimes a difference in meaning. Must: obligation coming from the speaker. You must read this book. I think it's good. Have to: obligation coming from the outside. They have to wear a uniform at school. I didn't have to wear a uniform when I was at school, but I had to have short hair. Mustn't and don't have to do not mean the same. Mustn't, You have no choice. You mustn't walk on the grass. Don't have to: You have a choice. You don't have to eat the soup if you don't like it. • 1 Two people are on a day-trip to France. Complete the second sentence so that it has a similar meaning to the first sentence, using the word(s) given. It was necessary for us to be at Dover at 10.15. (had) We at 10.15. The ferry left at 10.45. 2 It wasn't necessary for us to queue. (didn't) We queue. The ferry was half empty. 3 It wasn't necessary to take any seasick pills. (have) 1 pills. The sea wasn't rough. 4 Normally it's necessary to show your passport when you enter a foreign country, but when we got to Calais it was unnecessary. Normally got to Calais we . (have) (have) (didn't) passport when you enter a foreign country but when we 5 Every time J go to France I need to remind myself to drive on the right. Every time I 6 Some British drivers find this difficult. ........................................................ it. 7 The last ferry to Dover left at 11.00 so it was important The last ferry to Dover left at 11.00 so to drive on the right. But it's essential not to forget it. (You) to be at Calais by 10.30. (we) by 10.30. 58 2 Look at these signs and complete the sentences using forms of must and have to. Example: I NO TALKING IN THE LIBRARY I You musini talk in the library. r------__, BUY NOW, PAY LATER 7 ACE RENT-A-CAR For drivers over 25 with full British driving licence. KEEP OFF THE GRASS MINIMUM AGE 18 You 2 You 3 You 4 You 5 You 6 You pay now. footpath. 18 to get into the club. pay tickets. home. pay for parking after 6 pm. 8 9 10 7 You . You You You you 1 I G SERVICE INCLUDED DRESS: JACKETS & TIES. NO JEANS OR T-SHIRTS over 25 and you a full British licence. walk grass. pay for service. wear a jacket and tie and wear jeans or a T-shirt. 3 One person is in a hurry, the other is more relaxed. Which sentences on the right match the ones on the left? We must hurry. 2 We don't have to panic. 3 We mustn't miss the train. 4 We must leave enough time to buy tickets. 5 We must call for a taxi. 6 We don't have to go by taxi. 7 We mustn't forget to set the burglar alarm. 8 We don't have to worry about the house. 1 .... 2 .... 3 .... 4 .... 5 .... 6 .... 7 .... 8 .... a) John will give us a lift. b) It's too far to walk. c) The neighbours will keep an eye on it. d) The house will be empty for three weeks. e) We've got plenty of time. f) We haven't got much time. g) There might be a queue at the ticket office. h) There isn't another one till much later. 4 Put the following pieces of advice in the correct columns. ADVICE TO VISITORS TO THE USA A) have a valid passport B) stay in motels C) visit New York D) work unless you've got a work permit E) have an American Express credit card F) stay longer than your visa permits G) drive on the right H) have enough money for the duration of your stay I) drive at more than 55 mph on most roads J) have air conditioning in your car K) have alcohol, in a bottle or can, in your car You must/have to You mustn't You don't have to 59 28 1Quick reference We use: • must + infinitive without to or must be + -ing when we feel certain something is true. He must live here. That's his car outside. The television's on. He must be watching TV Note the short answers. Is he in'?- He must be. Does he know we're herer=He must do. I told him we were coming at 8.00. • can't + infinitive without to or can't be + -ing when we think something is impossible. She's just lost her job. She can't have much money She can't be feeling very happy. • must have in the past. + a past participle or must have been + -ing when we feel certain something was true The video's disappeared. Burglars must have taken it. They must have been watching the house when I went out. - Did they get in through a window'? - They must have done. • can't have + past participle or can't have been + -ing when we think something was impossible. He hit a motorcyclist. He can't have seen him. He can't have been watching the road. Was he driving carefully? - He can't have been. 1 Claire has got a maths exam soon. Her parents are talking about her. Complete the second sentence so that it has a similar meaning to the first, using the word(s) given. Example: I'm sure it's a difficult time for her. (must) 'I'm sure she's feeling worried.' (must) It must be Q difficult time for her. worried. (1) 'Do you think she's feeling nervous?' 'I'm sure she is.' (must) (2) (3) She be. . 'I'm sure she isn't sleeping well.' (can't) '1don't suppose she likes all this hard work.' 'I'm sure she doesn't.' (can't) (4) do. 'I'm sure she thinks she's going to fail the exam.' (must) (5) She 'Yes, I'm sure that's the problem.' (must) to fail the exam. (6) Yes, that (7) She . that. 'But she's good at maths. I'm sure she knows that.' (must) 'l'rn sure she isn't feeling very confident, that's all.' (can't) (8) She very confident, that's all. After the maths exam Claire comes horne, looking miserable. Her parents are talking about her again. 'I'm sure the exam was difficult.' (must have) (9) The exam difficult. very well. 'It looks as if she didn't do very well.' (can't have) (10) She 60 . I forgot to tell you. (3 cost) It ... using must have or can't have + past participle.. Look at the pictures. I think I've lost my credit card.. Imagine how people felt and make deductions. it (2 be) expensive.. Well. I bought myself a new mobile phone. 1 was trying to ring you on my new phone. But I had it when I bought the phone. (4 drop) I somewhere. I wasn't going fast. It's one of the best you can buy. (8 go) You too fast.. Look! JENNY: ANDY: JENNY: (1 be) It No.. (9 concentrate) you the car. Answer the questions.. Example: They must haue been uery excited.. or must have been/can't have been + -ing.. it there.2 Andy ANDY: Caswell has been shopping in town. (5 leave) you (6 leave) I at the shop. cheap if it's the best you can buy... Oh. I got it at a special price. it JENNY: ANDY: Well.. because I used it to buy some petrol on the way home. Complete the sentences... Check your answers with a teacher. She can't have been/She can't have done. Jenny... Example: They caVl't hove had much to eat... 3 The police are looking for Meg Sharp. No.. Well. .. I hit a tree... He is talking to his wife. using the short answers: She must have been/She must have done... nearly.... By the way.. 61 ... I was concentrating. and make your conclusions... at least £200! ANDY: Well.... Write three sentences using must have + past participle.. JENNY: ANDY: JENNY: ANDY: (7 damage) You No. Did she take her car? 2 Was she planning to be away for a long time? 3 Was she feeling weJI? 4 Has she gone abroad? 4 Think of an important time in the past... I had a small accident in the car. Write three sentences using can't have + past participle.. might be.) • Note the negative forms may not have/might not have. could be + -ing to talk about a present possibility._ - .29 --.ick reference • We use may. He didn't answer the phone. Dry.--. • We use the negative forms may not/might not to talk about possibility.' . It may/might/could rain this afternoon. reach the south till the 1 Complete All parts of the country will have rain tomorrow evening. He's got a British passport. I may not/might not see you tomorrow. He couldn't be American.She might have gone to town already. Complete what his friends are saying about him. could have been talk about a past possibility. • We often use a continuous form: may be. might have or could have + a past participle to say that something was possible in the past. The police could have caught him.) • 1 I L. but not couldn't. Temperatures the west and (3) but the rain (1) reach 25°. might have been.' get better medical 'This is a very good hospital. + -ing to _ ----.) • Couldn 'f means something is impossible. He never did any work. He (5) 'The other car was on the wrong side of the road._. (= They didn't catch him.) • Couldn't have means that something was totally impossible.this weather forecast. I may not have remembered to lock the door.' been killed. (= It wasn't possible. The driver been drunk. He might have been having a bath. using each of these verb forms. • Could have can also mean that something was possible but didn't happen. Winds will increase from be as be better really. couldn't may have may not could may might have 'He (1) 'He (2) 'But it (3) treatment (6) 62 anywhere be in hospital for weeks. He (4) else. might or could when we say that something future). They could be waiting for us to ring • We can use either may have. She could have left early.---. It will be quite warm. We often use the continuous form may have been. 2 This man is in hospital. And the forecast for the weekend? It (5) sunny for both Saturday and Sunday._-is possible (in the present or the Qu.' recover completely. She may be lying. (NOT I couldn't see you tomorrow. using may/might/could (2) or may not/might --not/couldn't. warm and reach speeds of 45 mph on the coast but they (4) strong inland.' be worse. (= It's possible I didn't remember. He couldn't have passed the exam. Where is she'? . Two firefighters are discussing the situation. two or three alternatives may be correct. ( (.' might have may not couldn't have may could be more have got everybody inside. ( ( ( ) ) you earlier because I couldn't 3 I may be as much as an hour late. underline the mistake and write the correction in the brackets. Some of the lines are correct and some have a mistake. couldn't 'We (1) people trapped 'We (4) 'I wonder what started 'It (6) the fire. to come and repair the car. all its planes . The heat's too intense. 4 He a) couldn't have done anything b) may not have done anything c) could have done nothing about his dreams but in fact he contacted Washington . If a line is correct put a tick (. 2 He a) couldn't have b) might not have c) may not have lied about his dreams after the crash. He had the same dream for seven nights. I couldn't 2 I mightn't have contacted get to the meeting on time. find a phone. On 22 May he told aviation officials in Washington about it. On 25 May American Airlines flight 191. 5 But I may not have known that my car was going to break down. 5 American Airlines a) couldn't have b) mightn't have c) may not have grounded 6 The plane a) might not have b) couldn dream . 't have c) may not have crashed if Booth hadn't had his 63 .I) after it. Now she is phoning her office. I smelt gas when we first arrived. Which of the alternatives are correct? (One. Complete the dialogue using each of these verb forms. 3 The dream a) may not have b) couldn't have c) might not have been clearer and he had the same dream seven times .) Booth a) may have b) could have c) might have had powers to see into the future . There (2) still be alive in there. a DC 10 with three engines. because the interview was recorded .' 5 On 15 May 1979 David Booth of Cincinnati dreamed that he saw a three-engined American Airlines plane crashing. 6 This delay wouldn't have happened at a worse time. But they (3) out of the building. crashed shortly after take-off at O'Hare Airport. Chicago. They interviewed him and wrote down the details of his dream but did nothing more.' ' got here sooner. My car's broken down. ) ) ) ) ) ) (. 4 I might have left home earlier. killing 273 people. We came as soon as we (5) been a gas leak. If a line has a mistake in it.3 Helen Goodman was driving to an important meeting when her car broke down. ( (. 4 An office building is on fire. 7 [may have to wait for hours for someone 8 I might leave my car here and take a taxi. With the other she is eating a pizza. She is very tired and she is doing 160 k. • should/shouldn't and ought to/oughtn 'I to to talk about how probable something is.. She only gets home from the office at 9 p.. 2 3 4 5 6 And now 7 8 work so hard... . She works at least 12 hours a day. Is Stephanie doing the right thing? What do you think? Write eight sentences.. He should have been watching the trattic.. She smokes a lot. iI..p. It's late. We use it with you or he.J I 1 Stephanie Reed works for a computer software company. using should/ought to + infinitive and should/ought to + be + -ing (or their negative forms) . + be + -ing to say that something should (shouldn't) be watching teleoision. he was using his mobile phone.. have been + -ing when we talk about something that moment ill the past.:~:k~~C:• should/shouldn't. We use it with I and we to talk about an immediate intention. so fast. You'd better not drive. 00. I gave her a map.. I should have worked harder. she. 10 a past participle the exam. I don 'I have 10 work late today.Fd better go... You ought to be working. so she shouldn't gel lost .. She is a workaholic. You oughtn't to smoke. both hands on the steering wheel. We'd better not touch it. She'd better slay in bed • should hone/ought I didn 'I pass You've had 100 'I 10 much have 10 + drink. This liquid may be poisonous.h. • had Cd) better (not) + an infinitive without 10 to say that something is (isn't) the right thing to do. • shouldtn't) have been or ought( n't) should(n't) have been in progress at a particular When he was knocked down.. more time with her family. on the motorway. • should/shouldn 'lor ought to/oughtn '110 + infinitive to say something is or isn't the right thing to do... so I should be home by 6. to say that to haoe/shouldn 'I haue/oughtn something in the past was a mistake.._. She looks ill. He oughtn't to have been using his phone. She has got one hand on the steering wheel..m.. 30 ~-1 be in progress now. I oughtn't to have been so lazy. they when we're giving advice or a warning about the present or the immediate future... so much junk fooel. She does not spend much time with her family.. home earlier. You should go 10 the dentist's. She eats a lot of junk food... smoke so much. or what we expect to happen in the future. a pizza when she's driving. At the moment she is driving home from work.. 64 . You shouldn't etc. . we could. 8 3 Match what one person says on the left with the replies of the other on the right. have finished work by 4. e) Yes. be able to meet you in town at 5. 2 3 4 5 6 7 . She did not look at the bus timetable and when she arrived at the bus-stop she found there were no buses. at about 4... She walked alone along the dark road that led to the pub. be able to catch a bus at about 4. Complete the second sentence so that it has a similar meaning to the first. 1 The travel agent said the hotels on Anguilla get full very quickly. She tried to get into the concert without paying. She did not tell her parents where she was going. 6 .15.. 5 It's going to cost us twice as much as last year's holiday. 3 . but we'd better decide quickly. He would not apologise. you'd better.... c) Well. Her mother tried to calm things down. 2 ... 1 '" . 65 2 So I'll probably So I There 4 So I'll probably So I 3 There probably won't be much traffic at that time. Write eight sentences about what you think Lucy and her father did wrong. She went up to the group and tried to kiss the lead singer. She decided not to get a taxi. 4 Tom is telling I'll probably I a friend that he can probably meet him later. by 4.. But Lucy would not listen. at 5.15.. 4 ..30. at that time. . The doorman told her to leave and got her a taxi..... We can't afford that as well.. Use should(n 't) have or ought(n 't) to have + past participle.00. . a) Is it? Perhaps we'd better go somewhere cheaper. 1 .. we'd better not.. f) Well.. Her mother told her to come in and they would talk about it the next day. b) Yes. d) We'd better book straight away then.2 Last night Lucy Cage went to a country pub near her home to listen to a new Australian group. When the taxi arrived at her house. 7 . Lucy said she would not come into the house until her father had apologised. she refused to pay the driver.00. but the doorman saw her and made her pay. Her father was angry with her and called her an idiot. 7 We could spend less money on the house and on clothes. 2 When shall we go? 3 I'm not sure when I can get two weeks off work. . using forms of should. .. I'd better not buy that new suit. g) I don't know. .30. you'd better find out. During the evening she behaved very stupidly. 5 . 6 And we were going to change the car this year. 4 I'll ask my boss tomorrow. We've had a long walk. Most of them are people like me who (20) a girlfriend back home in Manchester since I've been here. a lot of any serious too late that I (24) six more weeks' work . She's having a swim. It's two days off since I started work here. but 1didn't have a moustache. she has. My friends at home think J (10) hard work. Has she got a flat? . • In the past simple we use had/didn't have. Illnesses: l'oe got a cold. Last week I (23) only holidays for young people between the ages of 18 and 30. so I (22) a cup of coffee and a bread roll. Relatives: She's got two brothers. • Note that we don't include got in these forms: Future: When the baby is born. clothes. an interview in London last May. (American English) • Note the short answers Yes. It's a good thing I (8) my 18-30 uniform (a T-shirt with the company logo on it) and some jeans a four-month holiday but it's not like that at all. I get up at about 9. the sentences with forms of have got where possible or. • We use have for actions or activities. five or six hours at the most. I (15) I sometimes (17) (18) a good time.Yes. • Note that we don't use contractions with have when it's describing They have two holidays a year. a shower and . an action. • In American English we rarely use have got in questions or negatives. but they're less common. where not possible. For breakfast I just (14) My job is to make sure our customers 1(21) relationships any insurance. Infinitive: He might have malaria. a short siesta. they haven't. I (19) much sleep. I hope 1(26) 66 some money in my pocket!' . When 1was 20. But in informal English we normally use have got rather than have when we talk about: Possessions: I'oe got a motorbike. 1 have/No. jobs with holiday companies.) 1 Complete of have. with forms a job with a company called Club 18-30 which specialises any qualifications It (6) in This year Tom Carter (1) 'I (2) Torremolinos. I (9) but that's about all. (British English) We don't have a video.31 quick refen!nce • Have got and have mean the same. Personal characteristics: He's got blue eyes. etc. We haven't got a video. 1had long hair. I (3) Now I (5) but they a many offered me the job. We can use had got/hadn't got. 1(11) 1(12) lunch -I (16) a shave. they'll have four children. food poisoning and I remembered The medicine cost me half a week's wages! I (25) here and then I go back to England. Present perfect: l'oe had this cold for a week. Then I (13) time! In the afternoon friends here. I (4) bed and a chair but it (7) a week's training in London and then they sent me out here to a room in a small flat above a restaurant. How often do you have a bath? They had an argument. (NOT They've two holidays. any other furniture. I think these pills might help. less than that. rue got three brothers.! hauel1't got a driver's licence.. but lately I (IS) .. one? On Monday. at the moment? DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: PATIENT: DOCTOR: Yes I (3) . r m goil1g to haue a party. Well. plenty of problems enough money for holidays! a holiday this year. using four sentences with have got and four with have.. any children? Yes. three. a job? (13) No... I see. (12) . a holiday recently? No. but! hoven': got al1y sisiers. I'm afraid we can't afford one. Example: rue got blue eyes al1d lOl1g.. any particular ones. B B B B B B B B B B B B B B B B B B B I have You have have had got Got you I've got not have Have you got I got Have you got Ido Have he got hasn't have you got I've had Have you got don't have haven't got I got C C C C C C C C C C C C C C C C C C C I've been having Have you had got had You have I'm having not got You have I'm having Did you have I have Have he doesn't have you I had Have you had aren't having aren't having I've got 1 A I've got 5A 6A 7A 8A 9A 10 A 11 A 12 A 13 A 14 A 15 A 16 A 17 A 18 A 19 A 2 A Have you got 3 A had 4 A have Have you got I got haven't got Do you got I've got You have I got Has he got hasn't got do you have I've got Did you have haven't got haven't had Ihad 3 Describe yourself or a person you know well.....2 Read this dialogue.. (16) . or C best fits each space.. (5) ..... When was the last time you (4) .. Check your answers with a teacher.. What's the problem? 1(1) (2) a lot of headaches a headache recently... (10) .. (19) ...... a husband? Yes...... 67 . (6) .. so r m hauil1g driuil1g lessons at the moment: Wh€l1! pass my driuil1g test... B.. any particular (8) .. he .. (9) . ? About seven hours a night normally....biond hair... Well.. A.. How much sleep (14) . you (18) No.. lots of patients like you. Decide which answer. (II) . we (17) SO problems at the moment? but I (7) . )'~i~ ~ orntfl~.... Replace the words in italics with the correct forms of these phrasal verbs. [ turned on the radio........ [don't get on with them..< • adverbial particle): go out.. Put it on... He collected his girlfriend border... run out of.. had a bad relationship with (1) set off get away from come up to talk over his parents.. • We can use different particles with the same verb.... 32 Quick reference • Phrasal verbs are usually two-word verbs (verb + . [got up at 7. etc. Two hours later a man approached driver.... (NOT Why don't you throw the clothes you don't wear any more away.. an American teenager..... Here... They suddenly had no more (10) were they going to do? They discussed it (11) started (13) no-one stopped sun was sinking (15) .. • But if the object is a pronoun...... but he got away.. from them... His voice wakened them (18) It was a truck ...... He . .......... the pronoun always goes before the particle.... or would he let the police have them (19) 68 ... He said to himself he with (6) wanted to escape (2) would never return (5) .............) • 'Long' objects go after the particle.... (NOT Put on it...light" .......... Brad removed at 3 a.. a girl who was also unhappy and they started their journey (9) for several days before he finally decided to leave (4) .~~~... One night he got out of bed for the Mexican petrol in the middle of Texas. (8) .. The object can usually go before or after the particle. The meaning changes. ~J}~.. . (= escaped) • Most phrasal verbs can take an object. + preposition): get on with. (7) . at home....... and finally they for hours in the hot sun. but The nearest town was 25 miles away and the They stretched out on the ground (16) (17) them... give up.... They tried to get a lift.. the object must go after the preposition..... He took his father's car..... OR J turned the radio on.00 this morning (= got out of bed) The police arrested the thief.. .. 1 A girl is describing the first episode of a TV series she has just watched.. Why don't you throwaway the clothes you don't wear any more. J don't get on with my parents....... to the police? to walk They continued (12) to take them (14) his shirt so Donna could put it over her head... Here's your coat.... Would he take them to Mexico. What for a long time.m. pick up (x2) think over get out hand over come back get up wake up run out of go on go down get on with lie down go out with take off Brad.. put on....... He considered it (3) He was having a relationship Donna. by the side of the road and fell asleep.: ......) • Some phrasal verbs are three-word verbs (verb + particle etc.... Replace the words in italics with a pronoun (it. he wants the opposite. but to be honest I really can't him for much longer. 3 Why are you wearing that old sweater. 1 You watch too much television. he wants to (5) he's wearing.) and rewrite the sentence. Use the word given in capitals at the end of each line to form a phrasal verb that fits in the space in the same line. I can't put up with your laziness any more. it doion. he (4) to bed early. I'm really looking forward to the day when you get a job. 2 Why are you smoking? You should give up smoking. 69 . him. He might have a job for you. etc. 5 Your room's full of old magazines. When she wants something. Example: When I turn up the television Sometimes when I switch the television When I want to go out. he (1) When [ get a When I put up a nice When I want to go When I say I like the shirt When I say I want him to stop talking. look up his number in the telephone book! 12 One day you might get a job. Why don't you throwaway the old magazines? 6 In fact your room's in an awful mess. he wants to (2) drink out of the cupboard. Her mother is talking to her. Take off that old sweater! 4 You've left your clothes all over the floor. Why don't you 10 What about the manager of the new supermarket? ring up the manager? 11 You don't know his telephone number? Well. them. he automatically late. he (3) because I can't hear it. He thinks I like him. TURN SWITCH STAY PUT TAKE STAY TAKE CARRY GET PUT picture in the living room. 8 You owe me £10.2 Doris Griggs has got a very difficult husband. he (6) he just (7) (8) (9) 3 Helen is 20 but she is still living at home. Turn the television off. You haven't paid the £10 back yet. 9 What about this job application form? You haven't filled in this job application form. Clear up the mess! 7 You're so lazy. When I ask him to come home early. Put your clothes away. hetuntS on. hard mattress on his bed. • But we use the infinitive without to when we talk about a completed action or event that we saw. • We use the -ing form after these verbs when an action or an event is or was in progress. 2 Katherine and James are on holiday. 1(1) some people down by the swimming pool.he's in the room below us J think. they got very excited. I can smell gas. There's a good-looking to me but I (2) boy down by the pool. . smelf) in the present. feel. I could hear the noise of the traffic. I don't hear you. Suddenly. A. 2 3 . It's a man Singing but I (4) quite hot out here . unwashed bodies of other prisoners. I can see our hotel.33 • We normally use can and can't with the verbs of perception (see. C C C C C am seeing can't hear hear can't seeing can feel D D D D D do see don't can hear do hear am not seeing can feeling 2 3 4 5 70 A don't hear A can hear A don't see A am feeling B B B B B can see am not hearing am hearing can't see feel . Katherine is on the balcony of their room. talking to him.I (5) 1 Asee the warmth of the sun on my face. . He can still see hear feel taste smell the the the the the awful prison food. I can hear somebody singing. but he cannot forget what it was like.) • In the past we use could and couldn't with these verbs when we talk about a continuing perception. 4 5 . I saw him smoking. I can 'f hear you. We use these verbs in the past simple if the perception was momentary. (NOT I see our hotel. sound of the prison guards shouting. I heard him sing that song in 1975. He's saying something (3) what he's saying . Write complete sentences. I'm smelling gas. I him . heard or felt from beginning to end. We don't normally use the present continuous or the present simple with these verbs. B. She watched him get into his car and drive away. matching the verbs with the other part of the sentence. 1 Harry McCann was in prison for ten years. Cor D best fits each space. He is out now.he's too far away. Read the text and decide which answer. She watched them playing. When the children saw the sea. James is still in bed. hear. I heard a noise. four walls of his prison cell. but I couldn't see the sea. taste. . The plane was shaking..... where you . !can/can t see .. anyone talking now. I (1 hear) and I (2 see) the engines running smoothly. the plane fall a woman behind me . or could/couldn't think it is preferable.I was on the Two minutes later the fire engine the ladder off the fire engine and then to burn through the door of my bedroom! it up against the building.. burn slam using the verbs in the box in the -ing form or the infinitive without to. was normal... that one of the ambulance his lips moving . at this moment. hear. were serving lunch. We were flying over the Pyrenees.. ! can/can t smell. notice. smell.. hear... I watched (10) and nearer and [ felt heat (6) (7) the firefighters (9) third floor! [ heard the sound of a siren (8) (3) I could hear some people (2) downstairs. 1can hear someone/I can 't hear anyone . I (6 hear) drop her food tray... watch. He (3) to him . 71 . Check your answers with a teacher. b) Write four sentences in which you describe something which you saw happen or happening recently. 1can/can 't feel .but he (5) disinfectant.. 5 Complete approach these sentences. and everyone was very quiet. come get explode shout jump begin take put I woke up when I heard a door (1) Seconds later I heard something (4) a woman suddenly arrived. I was flying from London to Barcelona..... He (6) blood. I (5 feel) . [ looked out of my window and saw from her first floor balcony. Suddenly we flew into some severe turbulence. we were all very relieved when we (8 hear) we had left the turbulence behind. Then I smelt something . Use these verbs + the -ing form or the infinitive without to: see. I (7 not hear) the captain say Then.. five minutes later.he (4) trying to say something (7) him through the bandage that covered his ears.3 A motorcycle He (1) (2) rider was involved in a road accident. hear... Complete the sentences + see.. The flight attendants coffee.. taste. the . But [ couldn't jump .... As I climbed out of the window and onto the ladder [ could see flames (11) 6 a) Write sentences about what you can or cannot see. I (3 smell) and 1(4 feel) a sudden panic. the sound of the siren and through the window of the ambulance its blue light flashing. could/couldn't feel. and on his lips he his right leg. several metres... snow-covered mountain On the plane everything + infinitive without to.. nearer The house was on fire! [ listened to the sound of flames (5) up through the floor. smell. tops. using he men was . But what alarmed him most was that he (8) 4 Use the past simple to complete the text. etc.. I spoke to James. 1 Gemma terrible. This cup tastes ofwashing-up liquid. It looks as if its going to rain. your face (2 look) (3 sound) (4 seem) What do I look like? And you've almost lost your voice. It sounds as if he isn't coming to the party. (NOT terribly) This soup tastes good. (3) What (4) lt Shake it. + That music sounds • We use like a noun after these verbs to say what someone She looks like her mother. Ugh! It (6 not smell) What does it taste like? Mmm! It (7 taste) 2 Kate has just given Amy a present. (1) What (2) It Feel it. Complete the sentences using the verb in brackets and each of these adjectives/adjectival phrases once: quite good. after taste and smell when there's a particular taste or smell on something. taste. What that noise? -It sounds like thunder. He sounded as if he had a cold. worse. smell. Look at the pictures and complete Kate's questions and Amy's answers. with the meaning 'It seems as if/as though'. You look as though you've seen a ghost. AMY: KATE: AMY: KATE: AMY: 72 . s or something is similar to. (5 sound) What (6) It like? a book. (NOT weJl) • For visual appearance She sounded l of things. not an adverb. awful. seem to talk about our impression adjective after them. These gloves smell of petrol. • We can use as if/as though + a subject and a verb after these verbs to describe As ifand as though mean the same. You look happy. very nice. feel. The children looked frightened. • We often use the impersonal it with look. KATE: Look at it. • We use of. today. + as if/as though. . Look at those clouds. RICK: GEMMA: RICK: is ill. very well. ? chocolates. • We use sound to talk about the things we hear. I feel as if I'm going to be sick. sound. '1 a box. We use an I we use look. I feel terrible. hot. tired on the phone. . She wants Amy to guess what it is before she opens it.34 Quick refel'ellCe • We use look. You I thought you were getting better yesterday. not like. Have you got a temperature? (5 feel) . Her boyfriend Rick has come to see her. my forehead Try this medicine. our impressions. but you GEMMA: RICK: GEMMA: RICK: GEMMA: Yes. sound. feel. How do you feel? I (1 not feel) Well. pale. It we'll have to go to the pub. hit me over the head. using the word given. I don't think we've got any wine. it's as if someone's you've had a bad day. Complete the second sentence so that it has a similar meaning to the first. 1 There's Lisa. She doesn't look 2 She says she feels 3 But I feel 4 She looks 5 It's Nathan...y.. who's got boyfriend problems. She is talking to her husband Paul. Oh no.. Ugh! This cup tastes (3) 'There's some sugar in that jar. It looks 6 He doesn't sound 7 I saw him in town with Zoe..' 'Are you sure this is sugar? It tastes (4) 'Oh. 2J PAUL: 3 Oh. Phew! I'm tired! You give me the impression Yes. (feel) over the head... Would you like one?' 'Oh. Oh.' varnish. I'm going to have a cup of tea. bod do. (feel) I could go out again this evening. e) as if he's found another f) like someone g) very happy today... 1think. girlfriend. 8 . h) sure she isn't telling the truth.' 'What do I smell (1) 'You smell (2) 'I've been varnishing 'Yes. c) as if she's treating Lisa very badly. [don't think [ could go out again this evening.. no. (look) we've got any wine. And it looks 8 And Zoe is Lisa's best friend. It seems 1 . thanks. 3 . sorry.. Give me another salt.3 Complete the dialogue with like or of.. they look good. 1 Yes.. Well. b) like a very nice boy. ? varnish.' 'Ugh! You smell awful..d 0. 4 . 6 . I 5 Match each item on the left with the correct one on the right... 1think go to the pub. 73 . (looks) 4 It HELEN: 5 Oh.' a chemical factory. (feel) a whole bottle...' 'Now.. a) as though he hasn't told Lisa. why don't you go and change your clothes? You smell (5) 4 Helen HELEN: PAUL: has just arrived home after work.. d) fine. I PAUL: HELEN: What about a glass of wine? J think J could drink a whole bottle. (sound) Example: HELEN: You sound as if (as though) you' ue ho..' one. Here's the sugar.. 2 . 5 . 7 ... What have you been doing'?' the kitchen cupboards. • to introduce a piece of information. • We use There is or There are when we mention something for the first time. (7) '(9) 'No. underline the mistake and write the correction in the brackets. we use It's and They're.' three. If we then want to give more information about it.' only one bathroom 'And how many bathrooms much noise from traffic?' quite a lot of traffic. • Singular: There's (is) a man at the door. and some have a mistake. Are there any buses? There aren't any taxis. There's a fly in my soup. Look. There are on the south coast where there are several good beaches. (4) In the summer they're usually very full because there's dozens of hotels on the (5) island.35 Quick refere"ce We use There is/There are: There's a new teacher at college. ( ) ) ) ) ) ) ) ) (1) It isn't a very big airport . (10) '(12) 'Yes.' any people living in the house at the moment?' So. (. 74 people left on the . There's a book. (13) '(14) 'No. There are two letters. (. (15) of there is/there are to complete this telephone conversation between an estate agent and a person interested in buying a large three-storey house in London. I I I I I '----------_. I can show you round the house at any time.' station nearby?' 2 Read the text below about a Greek island and look carefully at each line. Is there a bank here? There isn 't a park here. There's only a few hundred (8) island and they are mostly old people. If a line has a mistake in it. If a line is correct put a tick (/) after it. 'How many bedrooms (1) (3) on the top floor?' ?' on the top floor but (5) another on the first floor. (2) There are only one real road on the island and it's only 18 kilometres (3) There's buses which go backwards and forwards along this road every half an hour. • We use There is before a list of things if the first item is singular. • to describe what we can see. a newspaper and some magazines on the table. Some of the lines are correct.' usually plenty of parking spaces in the street.' much noise. if you're interested. Example: Two kilometres from the only big town on the island. It's red. But in the (7) winter it's very different. They're both for you. there are an airport.it's only got one very short runway. (is) ( long. ( ( ( (. but (8) room to park a car?' But (11) an underground two in fact.1 Use forms '(2) '(4) '(6) 'Well. Plural: There are two cars outside. There's a car outside. (6) Every summer there are thousands of tourists from Northern Europe. My father used to be a professional footballer. (never go abroad) 4 I've got a lot of friends. . make me feel . Example: I live in London now. And I often (9) with the opposite sex very embarrassing. 3 Have your tastes and habits changed? Write five sentences about things you used to do and that you do not do now. . She never used to drink it. (not travel/much) 3 I often go abroad now. 75 . I did. All my friends (5) (7) Yes.. r (8) speak to them for days. SUE: NEIL: SUE: My parents were the same. but I don't now. They never (1) Didn't they? What (2) Whenever (4) No. past with used to. Check your answers with a teacher..36 Quick reference • We use used to + infinitive to talk about a habit or a regular activity in the past that doesn't happen now (or that might or might not happen now). they didn't.Does she? She didn't use to/used not to like it. (Manchester) 1 I'm a professional actor now. Did you use to eat frogs' legs when you lived in France? Did your parents use to criticise you a lot when you were young? • Note the negative forms didn't use to or used not to and never used to + infinitive. I (12) talk about them. They are talking about the time when they were teenagers. . and five sentences about things you did not use to do and that you do now. be/interested in me) Now they ask for my autograph! 7 (MyoId pupils/not 2 used to to complete their conversation. they (3) let you go out with boys? go out with boys. do? ask me where I was going. I (6) get angry? have arguments with them. SUE: NEIL: Neil and Sue are both 30. • Note the question form did I/you/eic: use to + infinitive. but I read a lot I'IOW. Examples: I used to smoke a loi. I used to smoke. My parents were very strict. . (history teacher) 2 I travel a lot now. They (11) get very angry with them sometimes. . envy them.! didl1't use to read much. I used to liue il1 Mal1chester. work) Now I enjoy it. up in the morning) Now I look forward to each day. SUE: NEIL: I went out. (not have/many) 5 (never like/getting 6 (not like/hard Complete the sentences about his . NEIL: Use forms of trust me. Laura drinks beer now. They found relationships They (10) guilty if I wanted to go out with a girl. 1 Oliver Stratton is telling a journalist how his life has changed. . .... He wasn't used to sleeping in a tent. not yet. That wasn't difficult.. ~.. not strange to me... I don't do it now.. I can't get used to speaking English. 76 . • We use get used to something or get used to doing something when we talk about the process of becoming accustomed to something. (having) a small refrigerator. (It's still strange to me. 1 He sees police officers without guns every day.. ---' 1 An American journalist from Washington has been living in London for six months. (live) in this big house? that. • Note the difference between the verbs used to and be used to.. . at first.) I've got used to speaking English. Complete the second sentence so that it has a similar meaning to the first sentence...) L . I'm used to the job. others he is accustomed to....-:?- ' weather . (= It's familiar. (live) in a small flat again... that isn't a problem. (seeing) He 2 He finds it normal that he gets free medical treatment... using the words given. (get up) early when I had a job...00. He 3 He normally travels by public transport He 4 He still finds it strange to have a small refrigerator... They were used to an easy life.. (= It was my habit in the past. I soon (6) from all my friends. JOURNALIST: MAGGIE: I don't have to go to work but I can't (4) JOURNALIST: MAGGIE: Oh yes.) I'm used to eating seafood. Some things he still finds strange. I'm trying (2) What's the biggest problem? 1(3) (5) you : is interviewing JOURNALIST: all this money.. • 4:. He still 5 He still isn't accustomed He still to living in a city centre.. becomes familiar and normal.. (spend) as much as I like in the shops. . (It isn't a problem now.: '"... now. (is) travelling by public transport... ..) • We use be used to something or be used to doing something when we say that we are(n't) or we were(n't) accustomed to something.~ '<..... A journalist her.. And there's another .. But I (8) thing I'll never (9) I don't think I'll ever (10) bargains and special offers in the supermarket. (used) living in a city centre...37 r--------Quick referellce .. but it isn't easy. Something that was strange or unfamiliar... Now (stay) in bed till 9. I don't think I could ever (7) ( be) so far I still look for . . 2 A month MAGGIE: ago Maggie Sullivan won half a million pounds on the lottery.) I'm getting used to speaking English.. police officers without guns.. (It's becoming less strange..". (used) free medical treatment. (1) : you (be) rich yet? No.. Complete the text using forms of be used to or get used to + noun or -ing.. I used to eat seafood. ) 1 Every year Doris Slocornbe/her 2 Last week she/the card/to her husband 3 Two days later Mary/a letter/sent/to 4 She told/some 5 The postman 6 He told/the shocking news/her Doris. . • We put the object that gives more important information What did you give your ioite? .Snails in the post box have eaten the other half of the card. • We use to or for when we want to emphasise He left his London apartment I've saved this seat for you.f gave her some flowers. Indirect object Direct object f sent He lent my brother her a postcard his car. (NOT She left to her children all her money. the editor 3 Buya packet of cigarettes 7 Take this reel of film 77 .30 my assistant. a) Complete the sentences with to or for. we normally use to or for with the indirect object. reason/Mary . (.) I've posted it for you.') 2 A film director is telling his actors and technicians what he wants them to do. . the indirect object. She left all her money to her children. sister Mary/a birthday George/gave. Show it to him. • An indirect object with to or for goes after the direct object.) • If the direct object is a pronoun. card/sends. . (NOT I've posted you it. the producer me at Doyle's Bar me for 6. everyone . He made a meal for all the family. . Who did he give the flowers to? . to his son and his villa in Monte Carlo to his daughter. had only given/half the card/her. (NOT Show it him. second. b) Then rewrite the sentences without to or for. (She asked him to post it.38 Quick reference • An indirect object normally refers to a person and comes before a direct object.He gave them to his wife. Fetch me my glasses. me . . .) 1 Put the following sentences in the right order. Example: Fetch my glasses 1 Make some coffee 2 Send this fax 4 Book a table 5 Order a taxi 6 Give this note for me. But it isn't always She didn't need to take an umbrella.) infinitive She's very ill. • Need has two negative forms: don 't/doesn 't need and needn't. The mechanic told me I needed two new lyres on my car. 00. • In the negative. Needn't can never be followed by a noun. . It's raining. . • We use needn't have + a past participle when someone did something that wasn't necessary.) • We use didn't need to + infinitive clear if it was done or not. . • We use need + (NOT You needn't a ticket. (Perhaps she took an umbrella.. infinitive with to OR needn't + infinitive It's only II. because it didn't rain. 2 3 4 5 6 7 8 78 . and this Italian woman is going to England to do an English language course. note the difference between didn't need to and needn't have. OR You don't need to leave yet. The meaning is the same. She needs to see a doctor. Use the verb need. + with to to talk about a necessity in the present or the future. She is packing her suitcase. . She needn't have taken her umbrella. when it wasn't necessary to do something.39 Quick reieren£e • We use need + a noun when we talk about the things it's necessary to have. I can't stay any longer. Look at the pictures and write what things are necessary or not necessary.) 1 It is November. Perhaps she didn't. You need an umbrella. In the past. It was a waste of time or effort. You don't need a ticket to get in. we can use either don 't/doesn 't need without to. . You needn't leave yet. She'll need a visa to go to the States. (But she took it. I need to go now. . . But at the time they didn't know this. because the weather forecast was good. He just walked in... .he would sell her one 3 Then he told the woman sitting next to him that she .... A. because while he was waiting a friend stopped Dan wasn't there. 8 . 4 Dan Price went to a concert last night to see an American blues band. His wife is asking him about it.. The last time I went I (2) already booked one..50. The evening cost him nothing. I don't think so.30.... that's all. 5 After the concert he phoned for a taxi... because he found one on his seat. He used the £2. to get up early in the morning. I need 2 . 6 The taxi driver arrived. '(1) book a hotel room in Paris?' to......' any French currency?' go to the bank.. the money. 3 .' 'You might (12) 'Oh. 5 . a) b) c) d) e) to go into work. me next week. I just (3) 'What train (4) 'I (5) 'Yes... in a queue because he already had a ticket.. his own money. I just (11) a raincoat.. I (13) 'I'm going into town this afternoon.2 Peter Clegg is going to Paris for a business meeting next Monday.. and gave him a lift home. B.. 2 He bought a programme for £2..' 'I don't think so. but he .... g) a holiday for months. Put in the correct form of the verb need. 6 .. He . 7 . He .. 4 At the interval he had a drink.. It's great.' one the last time I went. Read the text and decide which answer..' catch?' catch an early one. because 1A 2A 3A 4A 5A 6A for £5. h) a week's holiday.50.. o 1 . I'll get some at the airport. but he . but you (8) 'What clothes (9) 'I (10) underwear.. I needn't So I don't need I told my boss I needed He said he didn't need So I didn't need I won't be paid. 4 ....' my suit and a change of be at the airport till 18. go to work tomorrow.. but he ... but I don't really need I've needed I'm going to North Africa. I (6) (7) take?' take many.. 3 Complete 1 2 3 4 5 6 7 8 the sentences by matching the items in the two columns.. C or D best fits each space. £5 for a programme needn't stand didn't need to do needn't have paid needn't have used needn't have needn't have come B B B B B B didn't need needn't do didn't need didn't need needed not didn't need to stand to pay to use come C C C C C C needn't have stood needn't done needn't to pay needed not to use didn't need to didn't need to come D D D D D D needn't to stand needn't have done didn't need pay needed not use needn't to needn't come 79 . because the company had check that they've booked one this time. to feel the sun on my face. What will I do if 3 The interviewer might not like me. should. __ . It is very hot. • To talk about something that's always true. Jfyou found £100 in the street.. If the weather gets better. 2 Anna is going to London for an interview for her first job. 2 3 4 5 . ? Example: J might not get there on time. What willI do if 2 I might not be able to get a taxi. • We use the 2nd conditional if + a verb in the past simple + would/wouldn't. his body. 1 Jack Rice is in a hotel room in Saint Lucia. could. We shouldn't be late. • In addition to the future will. If public transport was better. hypothetical or imaginary. you can catch a bus. Phone me if you want anything. I always get carsick. Write sentences his problem. he'll be too hot.. ought to. he'll have mosquito bites allover he might drown. (NOT If the weather will get better. + present simple. What will J do 80 . She is thinking of possible problems.is door open. What willi do ? ? ? 4 She might ask difficult S They might not offer me the job. we'll go for a walk. must or an imperative in the main clause. Jfyou want to go to London. might to talk about an action or situation in the present or the future which is improbable. .) OR We'll go for a walk if the weather gets better.40 Quick reference • We use the 1st conditional (if + a verb in the present simple) to talk about a possible future action or situation. the mosquitoes will get into the room. What will I do if questions. we can also use can. if the train's on time. Make sentences with What will J do if . might.. If/travel by car._. it'll be too noisy. what would you do with if? ----.. She is very worried. He cannot sleep._--. we use if + present simple If you heat plastic. Example: (Leave his door open) 1 (Leave the window open) 2 (Close the window) 3 (Take off his pyjamas) 4 (Not take off his pyjamas) 5 (Try to sleep in a cold bath) about Ifhe leaves h. The if clause is often followed by a main clause with will/won't. using /fand choosing the correct main clause from the list on the right. it melts. there'll be no fresh air in the room. there would be fewer cars on the road You might feel better if you took some of these tablets. may. What will / do if/don't get there 01'1 time f ? ? 1 My train might be late. you'd ieor« a lot ofSpal1ish. that was all right. 81 . I could get there in three hours. If there were (2) more buses.. Example: (worry a lot/be late for something) 1 (I/get embarrassed 2 (I/not feel good 3 (anyone/criticise 4 (my boyfriend/not me listen to me I worry a lot if r m ioie for something. Example: (1) If I went to London next Saturday. I'll have to drive for three hours. Example: Try to go for at least a month. I'd catch it. (go for a month/learn a lot of Spanish) lJyou wel1tfora month. If they stop that (4) early morning bus service. put a tick (.. means of travel. I'll have to hitchhike. a lot of people won't be able to travel. But there's only one bus a day and that leaves (3) at 5.1J Igo by plane.30 in the morning.. If it leaves a bit later. (6) public transport If I would have a car. If a line has a mistake in it. and she is thinking of going to Spain. Write five b) Imagine you are going to England. simple + would/wouldn't. (It/be better/go on your own) 2 (go with a group of English friends/not speak much Spanish) 3 (go on your own/not be able to speak English) 4 Stay with a Spanish family. If the mistake (go) ( ) ) ) ( ( ( ( ) ) will get any worse. (learn the language quickly/stay with a family) 5 Find a Spanish boy. there'll be no way of getting to London by (5) public transport. Example: Would you be angry if Icriticised you? Check your answers with a teacher. using If . I get al1gry. Examples: If Igofrom Santander. underline and write the correction in the brackets. write five general truths about yourself and your opinions. a restouroni. 6 a) Using if + present simple + present simple.3 At the interview (see Exercise 2) Anna was asked to talk about herself. nice things about me) people/say l/not be wearing smart clothes) I/feel guilty) it/make me angry) 4 Emily is learning Spanish.I). A friend is giving her some advice.. ifll cost a lot more. (have a Spanish boyfriend/soon speak Spanish well!) 5 Read the text. Use if + past c) Write five questions you would ask someone you were thinking of marrying. She said some general things (general truths) about herself. using if + present simple + will/won't. Talk about the alternative sentences. Complete her sentences. Example: Ifpeople smoke in. If a line is correct. Make sentences with If . it was so cold in Scotland. They have just got back and they are talking about it.. We (1) .. Read the dialogue and decide which answer... You weren't concentrating. If + past perfect + would have/could have/might have If Jack had worked hard. you would have seen that the traffic lights were red.. raining...... out more.. we (6) . He isn't living in luxury now.. We use the past conditional in the main clause..41 • We use the past perfect in the if clause to talk about something that didn't happen or a situation that didn't exist in the past. + • We sometimes link the past with the present by using would or would be If + past perfect + would or would be + -ing If I hadn't lost my lottery ticket. C or D best fits each space.) If Sue had taken a taxi.. we (8) .. B. She was late for work.. much more of Scotland.. I'd (would) be rich now. he would (could/might) have passed the exam.. if it (3) . (NOT If Sue would have taken) • We sometimes use the past perfect continuous (would have been + -ing) in the if clause. And if your car (7) . the front door key of the guest house we were staying at..) Note that we don't use the past conditional in the if clause. And what about Saturday night? If you (9) . we (4) the whole time. some warm clothes. sleep in the car! 1 A would have enjoyed 2 A wouldn't have rained 3 A stopped 4 A could have gone 5 A would have known 6 A might have take 7 A didn't break down B B B B B B B enjoyed hadn't rained would have stopped can have gone know might to take hadn't broken down C C C C C C C had enjoyed didn't rain had stopped had gone knew might have taken doesn't break down 8 A had seen 9 A wouldn't have lost 10 A wouldn't have had to B mightn't have seen B haven't lost B wouldn't have to C could see C hadn't lost C didn't have to would enjoy wouldn't rain has stopped went had known might take wouldn't have broken down D could have seen D didn't lose D hadn't to D D D D D D D 82 ... (= She didn't take a taxi.. He isn't rich now. If you'd (had) been concentrating. she wouldn't have been late for work.. the weekend if it (2) Yes. -ing. A. I'd be living in luxury. (= He didn't work hard.. He didn't pass the exam.) 1 Becky BECKY: POLLY: BECKY: POLLY: BECKY: and Polly went to Scotland for the weekend. we (10) . (= He lost his ticket. And it was cold! If we (5) . .... .. so I hit the car in front.I . '" more clothes........ I could ..... Complete their stories..... using if + past perfect continuous + would(n't) have and would(n 't) OR would(n 't) be + -ing. Example: I didn't have any brothers If r d had brothers or sisters..I .. I could more clever..... fifty metres from where I was standing.... My parents were poor.... 4 I didn't pass any exams..2 An old man is thinking about his past life.. If my parents 2 I missed a lot of school lessons. If I'd been born a boy/girl .. If 6 I worked on a farm. ADAM: I applied for a job in Australia... If I 3 I wasn't very clever. Write sentences with If + past perfect + would have or wouldn't have.r .. or sisters... I (hit) tired. 2 If I'd chosen my own name . I never had any children.. ... I didn't fight in the war. ... 2 CARLA: If I (stand) killed.. At the interview I was feeling tired and they didn't offer me the job. 4 If I'd lived in the last century . more... I (be) ferry.. I never got a well-paid job. 83 . they (offer) in Australia now. I didn't do very well at school.. . I (be) here now. better at school.. Check your answers with a teacher. 3 Four people 1 ANDY: are talking about big events in their lives. In a recent storm.. that car... I wasn't watching the road....... lightning struck a tree. under the tree. If I (watch) the road. I wouldft't have had such a ionelu childhood.. I didn't have many clothes. . If If 5 I was shy. I might friends..... . ..... I (surf) ...... If 7 I didn't leave this village..... I never got a better job... If If 8 I never got married.. I might . I first met my husband could help me. I didn't have many friends..... If I (feel) to me. And we (live) Larry on a cross-Channel 3 4 LOUISE: When I had my accident.. If I (feel) I (be) me the job.. 4 Complete these sentences about yourself.. . on Bondi Beach.... he (speak) together now... . I had a lonely childhood.. I was feeling ill and he asked me if he ill....... I didn't learn a lot. 3 If I'd been born ten years earlier . 2 She won't go to the cinema with him if he doesn't let her pay for herself. provided (that). unless you come ioith me (= if you don't come with me) • We use as long as. f won't go to London. she won't go out with him if he doesn't stop smoking. so take some tablets as a precaution. (= You can borrow my CD player. as long as. (See Unit 40. You can borrow my CD player.42 '. as long as you give it back to me tomorrow. italics. so I'll take an umbrella as a precaution. Complete the sentences providing.. 2 Look at these notices. They're stronger than if. (= You might not feel well on the boat. provided you give it back to me tomorrow.) Take some sea-sick tablets in case you don't feel well on the boat. . and they all mean only if. providing (that) to talk about a condition. 5 If she asks him questions.) 1 Anna has got some very strict rules for her boyfriends. The meaning would be the same. providing (that). 3 When he's away she isn't happy if he doesn't phone her every day. (= It might rain. she gets angry if he isn't prepared to talk about them. only if you give it back to me tomorrow. 4 If they have problems. 1 ENTRANCE FOR TICKETHOLDERS ONLY You can go in that explain them. You can borrow my CD player. • We use in case to talk about the precautions we take because something might happen. . provided (that). . she isn't satisfied if he doesn't answer her honestly. I'll take an umbrella in case it rains. In the sentences rewrite the clause in 1 If a boy smokes. using as long as/provided/ . using unless. 2 SWIMMING POOL: UNDER 7s MUST BE ACCOMPANIED BY AN ADULT Under 7s can swim 3 PARKING FOR RESIDENTS ONLY You can park in the street 4 NON-SMOKING COMPARTMENT You can travel in this compartment 84 . in case are followed by the same tenses as ifin the 1st and 2nd conditional.O:UCk :'~nCe I Unless + an affirmative verb = If + a negative verb.) We could use provided (that) or providing (that) here. -.) • Note that unless. Note that we often leave out that after provided/providing. 4 Katie Wain is going to Copenhagen tomorrow on a business trip. 6 I'll book a taxi now. 5 I'I! take Andrea's phone number. Example: I'll put my passport rtl put my passport in my bag now. The Danish company is sending Andrea to meet her at the airport. morning. I might not have time tomorrow 2 I'll take my hairdryer. There shouldn't you keep to the rules and behave sensibly. 4 I'll phone to confirm my hotel booking. 5 On what unless. Make the two sentences into one. I'll be angry (1) unless you've got a very good excuse. would you take and why? Write f wouldl1·t take the job unless they gaue me lOl1gholidays. She is telling them what they can and cannot do. d say goodbye to all my friel1ds il1. If you're late. You You can go into every day. Examples: conditions would you accept ajob in Alaska? Use provided/providing/as long as or r d take the job as lonq as they offered me a uery good salary. She is taking a group of young students to Paris. The hotel won't be responsible you leave them in the hotel safe. r d take my cat il1 case f got lOl1ely.3 Jenny Railton teaches French in an English school. stereos (3) you don't play them too loudly on the coach. Write the word(s) that best fit(s) each space. (8) You can bring your personal In Paris on your free evenings you can go out (4) can't go out in the evening (5) cafes (6) to come (7) the hotel (9) valuables (11) (10) you don't drink alcohol. you tell me where you're going. I might forget it tomorrow il1my bag 110W ir: case f forget it tomorrow morning. Which of you are vegetarians'? Vegetarian food will be available for you at be any problems you let me know before we leave. case f didl1·t come Check your answers with a teacher. Katie is preparing for her trip. It might be cold in the evening. They might not have got my letter. I'll pack my case now. I'll expect you all you try to speak as for your you're with at least two other students. There'll be an excursion you're ill. You can wear any clothes you like (2) as lOl1gas you look reasonably smart. Examples: back.30.. 3 I'll take my winter coat.00 tomorrow. Examples: The coach leaves school at 7. The trip won't be a success much french as possible. using in case. what precautions five sentences using in case. . 85 . mOr/1il1g. She might not be at the airport to meet me. If you were going to sail round the world alone. There might not be any available at 8. There might not be one at the hotel. . It often means we're feeling impatient or annoyed.. (but you didn't come earlier.' • We use could after I and we to talk about a regret about a present or future inability. He is feeling stressed. • We don't use would have after wish/if only. (wish) 2 1want my brother to stop playing his music so loudly.43 Quick reference • We use wish or If only + would to say that we want something to change. I wish we could have a holiday. I wish she was my girlfriend. (wish) 4 1don't want her to worry so much. Complete the second sentence so that it has a similar meaning to the first sentence. I wish l could come with you. If only the train had been on time. Note that we can't say 'I wish I would . • We use wish or If only + the past simple or the past continuous when we talk about a regret we have about a present situation.) 1 Luke is revising for an important exam.. or that we want someone to do something.. If only it wasn 't raining. • We use wish that happened I wish you'd I wish I hadn or if only + the past perfect when we talk about a regret we have about something or didn't happen in the past. Example: The phone's ringing . I wish it would stop raining.) 't said that.' or 'I wish we would . 1want my sister to turn the television down. (wish) 6 I don't want to have to do the exam. Of only) 5 I want to know what the exam questions are. NOT If only you would have worked harder. Of only) 3 1don't want my mother to keep coming up to my room. [fonly he'd (would) be quiet.why doesn't someone answer it? (wish) The phol1e's ril1gil1g -/ wish somebody would al1Swer it. I wish I had more money. using the words given. Of only) 86 . (had) come earlier. (NOT I wish I would have seen it. in the country. Check your answers with a teacher. b) Write three sentences about things you wish you had or had not done in the past. marry + the past have (x2) learn go travel read stay Example: / wish 1 2 3 4 5 6 7 r d (had) stayed at school lonoer. a foreign language. 3 If only 5 I wish more money. 2 I wish 4 If only 6 I wish raining. Use these verbs. to more foreign countries. 87 . my raincoat. so many things. a more interesting job. more books. Examples: / wish / was Of'! a beach if'! the SUf'!. at al1 earlier age. not forget stop not buy only + would/wouldn't or live have come Example: 1 / wish my bus would come./ wish / wasf'!'t studyif'!g Ef'!glish grammar. the first girl I fell in love with. He is thinking back over his life. 3 Complete what the people in the picture are saying. to university. using wish/if wish/if only + the past simple or the past perfect of these verbs. Complete what he says using I wish perfect. 4 a) Write three sentences about the regrets you have about the situation you are in at present. a son as well as three daughters. Example: I wish t' d started to leor« Enclish. / wish / could go Of'! holiday.2 Albert Street is 85. tel1. (= She stopped/she looked. 2 She wants to go out with a friend. couldn't. (l/he) She hung her key round her neck. we can also ~~-. uiouldn'ty if there is a different subject in each part of the sentence. The insurance company said they would reduce the cost of his insurance if he bought an alarm system. I'll phone my father so that (OR so) he can come and pick us up. The alarm system cost so much money that he had to sell some of the valuable things he owned. or if the purpose of an action is negative. .) In order to + infinitive is more formal than to + infinitive. won't. 3 Only her cat keeps her company. . Now he can only get into the house by remembering a special alarm code. And he has to shut the dog in the kitchen. (He wants to talk to someone) He's looking for someone to talk to. She wants someone 88 . so he bought a dog. And when the verb has an object. so that (OR so) she wouldn't lose it. . 1'1/ buy a magazine to read on the train. where the II • We use to + infinitive (NOT in order to) to talk about the purpose or use of a thing or person. I went to London to buy some new clothes. use so as not to + infinitive. giving the purpose of the actions. so as not to lose it. So he bought one. of an action. I must find someone to help me. . • Note that the preposition stays with the verb. can't.eto talk to. This year the cost of insuring the contents of his house was very high. could.ts of his house. She hung her key round her neck. Complete the second sentence so that it has a similar meaning to the first._---- ----- - I 1 Burglars broke into James Hart's house three times last year. would. • If the purpose is negative and the subject is the same in each part of the sentence. because it is the only way he can stop it activating the alarm! Answer these questions. . 2 Melanie Wright has just moved to an isolated part of the country. Example: 1 She wants to talk to someone.) Can I have a bag to put my books in? • We use so that or so (usually followed by can. (= I went/I bought) She stopped in order to look at the map. I Why did James buy a dog? 2 Why did he buy an alarm system? 3 Why did he have to sell some of his valuable things? 4 Why does he need to remember a special alarm code? 5 Why does he shut the dog in the kitchen? . . James also needed a way of protecting his property. She ioonis SOlneOf1. will. . 5 She wants to share her life with sorneone. She wants a friend She's only got her cat There's nowhere 4 She can't spend her money anywhere. . She is lonely and unhappy. the preposition comes after the object. Example: Why did James have to pay a lot this year? To insure the cOl1.--j - --- --_. . (l want to put my books in a bag.44 Quick reference • We use to + infinitive and in order to + infinitive to talk about the purpose subject of each part of the sentence is the same. . He checks the origin of all the things he buys (8 he wants to make sure) they were produced locally in Britain............ (I He wants to reduce his energy costs) heating system in his house... Sometimes there is more than one possible answer. using to + infinitive.... 4 Violet Horn is an eccentric old lady of 80.......... . . using to. b) in order to + infinitive. .. he has asked his office manager if he (7 he wants to communicate) .............. and.............. ... He has bought a computer ... (5 by doing so they will reduce air pollution) (6 He intends to travel less) can work at home...... (9 He doesn't intend to waste anything) away.. hurt their feelings..... using a) to + infinitive..... so that/so or so as not to.. (2 He doesn't want to lose any heat) he has insulated the roof and the walls of his house.. He keeps all his vegetable waste (10 in this way it can be used on the garden) When he goes shopping he always keeps the plastic bags ......... in order to....... Read the text and replace the words in brackets with a clause..... uses public transport.. he doesn't throw things .. he has installed a solar . Examples: To saue moneu Isometimes walk to work instead oJtakil1g the bus....... Check your answers with a teacher... make them taste sweeter... in order to.......3 Stewart Price does everything he can to save energy.............. h! wil1ter loftel1 wear socks il1 bed so that myfeet dOI1't get cold. so that/so or so as not to + infinitive. when he travels long distances.... Complete the sentences......... He keeps all his waste to the recycling ..... ... he uses his bicycle a lot......... with his office bye-mail.. .... He'sgot his own web-site on the Internet and he uses it (13 he wants to tell the world) about his ideas on energy-saving methods. she can use them again.. (3 He intends to keep fit) ................... spoil them..... She puts salt on her strawberries 2 She puts sugar on her tomatoes 3 She reads by candlelight 4 She talks politely to her plants 5 She never wears her best clothes 6 She always empties the bags from her vacuum cleaner they don't taste too sweet...... d) so + clause.... ............ he always . save electricity.............. c) so that + clause.... .. He feels a lot of energy is wasted by importing and exporting goods. ..... (4 this means he can leave his car at home) He also advises his friends to stop using their cars.. 5 Say why you do certain things. (11 in this way they can be used again) paper in a big box (12 in this way he can take it) factory at the end of every month.... He thinks that world trade is a bad thing........... Write five sentences.. 89 .......... e) so as not to + infinitive. She told me that the problem was her Bristol accent. tell.. decide. fail. play. help.. At first she seemed (5) because we'd decided (6) She refused (7) me. I didn't decide. ask. tend. pretend. He decided not to go. • With some verbs we often use a question word + the infinitive with to. not understand.. And now she's even threatening football? it It's the only thing I can do. not have. because she didn't want (9) (10) Everybody (12) JOURNALIST: RICHARD: to me about it. She got a job children for a few years. Past: I didn't dare (to) look. intend. deserve. Two days later they offered (3) to London? (2) me in a match on over £4 million for me. Verb + question word + infinitive I don't know He explained / can't decide what how where to do. • Note the negative form of the infinitive.. I'm hoping (18) much less company for a month. . let. hope.. 1 Richard Yates. be. 90 . They arranged to meet. expect. give up 2). wish. The most common are: afford. She worked for an insurance the same thing happened SO are you intending (15) No. at work laughed at her when she spoke. London? happy in London. A London journalist is interviewing him..... refuse. ex ex JOURNALIST: RICHARD: Why did you decide (1) TV. Complete the interview. see.. change. from Bristol in the west of England. train... I daren't (17) (16) me and go back to Bristol on her own. forget. plays football for a top London team. But she wasn't happy. choose... want. hesitate.45 Qu. He promised to write. hurry.. offer. demand. arrange. pay.. prepare. She pretended not to listen to him. talk. He promised not to laugh. We intend to sell it. promise.icl( reference • Many verbs can be followed by the infinitive with to. But finally she agreed (11) .. happen. Present: I daren 't look OR I don't dare (to) look. agree. earn. plan. that she was unhappy.. come. using these verbs: leave 2). her. togo. mean (= intend). seem.. worry. But (14) . manage. learn... She didn't dare (8) me. She learned to swim. • The verb dare.. JOURNALIST: RICHARD: for a Bristol team and I'm prepared money as long as my wife is happy. I helped to make dinner. They pretended her answer the phone! So she decided (13) in the next job. attempt. But he is Dot happy. But they refused . OR I helped make dinner. threaten. appear.. jobs. Questions: Do you dare (to) look? Did you dare (to) look? • The verb help. The manager of Arsenal happened SO why have you decided (4) It's my wife. admit. to use the machine... remember. to catch a bus to the centre of London . S I don't dare ... aren't sure He doesn't get a taxi. Write the two sentences as one. 1 Next weekend I want ..they to ask... 91 . to buy. it yet. wondering. There are a lot of things she is not sure about. Use only one word in each space. 3 What time should I get up in the morning?/She 4 How do I use the dishwasher?/She hasn't discovered S How much are they going pay mer/They haven't discussed 6 How do I cook food in a microwavei'/She's 7 Where can I go to learn more Englishr/She's never learned... doesn't understand.. 3 In five years' time I hope '" 4 I've decided .. Example: What shall I call Mrs Harveyr/She Where shall I put my dirty clothesr/She 2 How do I set this alarm clockr/She doesn't know. using an infinitive with to.. in the souvenir shop. I don't know who . S What shall I do on my day off?/She hasn't decided. Now they don't know 6 A German businesswoman's London. She can't decide desk are discussing 7 Two French girls at the Tourist Information 4 Complete these sentences about yourself with an infinitive. hotel to stay at in 2 A Frenchman's 3 A businessman's 4 A group of Australians can't find the bus stop.... yet. 2 I can't afford . 6 7 S 9 10 I sometimes I understand I've discovered help . wants to know. doesn't know.. She doesn't knou: what to call Mrs HarueLJ. know to use an English telephone. S A woman from Nigeria wants to know to contact the Nigerian embassy. 3 Some tourists have just arrived at London Airport. Check your answers with a teacher. Read the text below and think of the word which best fits each space. I often forget when . 1 A porter's helping two Americans wondering having problems.2 Carina has just got a job as an au pair girl with an English family called the Harveys. S They've asked three people and they didn't know. how . where ..... to leave his luggage while he goes to the toilet. (NOT [don't to come? to listen to me. would like.) • Note the negative infinitive. We use it: + infinitive with to when we say or • with verbs like: advise. to stay. help. must help with the cooking and the cleaning. can choose what they want to do. object me her the doctor people you + infinitive with to to do? (NOT What do you want that I do?) to know. (force) do homework. and respect for others. 1 Manworth school is different from conventional schools. would prefer. using the word given. Example: The students It isn't necessary We 2 Students We 3 Students We should have self-respect can call us by our first names. persuade. would hate. (teach) self-respect don't have to do homework. 'f ioon: you to relax. expect. etc.46 Quick reference We often use the construction verb + object (noun or pronoun) do something to influence somebody else. ask. (expect) attend all the lessons. invite. I advise Verb I don't want Would you like I'd like I'd prefer They asked him + • with the verbs want. Say a) What does he/she want? and b) What does he/she say? Example: A doctor's examining a patient who is very tense. te//. recommend. Look at these situations and write two sentences each time. would love. force. remind. teach. to post this letter. What do you want want that she knows. not to smoke. Complete the second sentence so that it has a similar meaning to the first. (ask) with the cooking and the cleaning. A teacher is telling a parent about it. Verb I persuaded Remind + object my father me you + infinitive with to to lend me the car. We allow students to call us by our first f1Qmes.' 92 . I'd prefer you not to say anything. for students 4 Students We 5 All students We 2 Some people's jobs are often difficult. (encourage) choose what they want to do. warn. (allow) to attend all the lessons. allow. to go by train. encourage. and respect for others. He waf'lts the poiieni to relax. get. . but I (6 prefer/you/ask) 'Well.. and some have a word that should not be there....... what he said to her. but I can't... Rick.......' 'You see.. I don't like parrots.' '(9 you/like/me/show) 'No......' do?' here. who has only eaten a little of her lunch... Hey! Where are you going? Come back!' 93 . ) ) ) ) 2 3 4 5 6 7 JENNY: RICK: JENNY: ) ) ) ) 8 me to keep music as a hobby.' (12 you/want/me/show) In case you see him .' round to the back of the house?' this letter me.. say) you how to make the noise?' I haven't got time. Amy... 'Excuse me... I(1 like/you/help) 'Your parrot? What (2 you/want/me) 'I (3 like/you/stand) look for him there... She is training to be a teacher.' ' ' in her class aren't listening... and now she is telling her boyfriend.. talking to a very young patient who's keeping her mouth closed.... He told me [ to talk to my teachers to say the same thing............ If a line has a word that should not be there.. b) 'I ' Iunch... before midday. And I (4 want/you/make) 'I (5 hate/you/think) .. please. put a tick (..... And anyway.. write the word in the brackets. My husband (8 want/me/post) someone else.... He escaped from his cage about five minutes ago.... but she also plays the drums...... He warned me not to make any quick decisions. using want or would like. He told me to get as many qualifications about it.. 'Oh dear. b) 'I b) '[ b) '1 has just turned left instead of right...... I wouldn't..... RICK: What did he tell to you to do? He told me for to think about it for a while.... I've lost my parrot.. Complete the dialogue....... he can you a photo of him? .. 4 A driving instructor's 3 Jenny Kite is at college....... would prefer..... If a line is correct. If he hears you..... 4 An old man has stopped someone outside his house..' that.... I'm sorry. I (10 want/someone/help) me find him. I'm in a hurry. She wants to be a professional musician.. I'm worried. '(7 you/prefer/go) 'No. Amy annoyed because the students the students the patient annoyed because his student his student Iunch. Read the dialogue. I (11 prefer/you/not be very aggressive... Some of the lines are correct.. She talked to her drum teacher....A mother's a) She 2 A teacher's a) She 3 A dentist's a) He a) He talking to her child.. What did he tell you to do about college? He advised that me not to give up my studies. He of my teachers ( ( ( ( ( ( ( (. while I go round to the back of the house to this noise: "Skreeeeeeee!'" that I'm being unkind...I)..... thank you.. would hate + object + infinitive. He expected recommended as possible... rare. (advisable) . lucky. important. . Do not change the word given. you to come and see me. Complete the second sentence so that it has a similar meaning to the first sentence. kind. expensive. ready. clever. safe. common. amazed. him not to laugh. using the word given. usual. Example: You'll easily find places to stay. impossible. to meet you. polite. careless. She is telling them what they must do. of of of + Some other adjectives used in this construction: noun/pronoun + infinitive with to your brother to do that. (sensible) It would be 5 You must walk along the cliffs. Staying in a bed and breakfast is less expensive It's 2 Hiring a car isn't cheap in July and August. necessary. wonderful. disappointed. essential. (disappointed) know that . wrong. . easy. silly. interesting. mean. generous. dangerous. (expensive) .47 Quick 'fJierellCe Note these three constructions. possible. terrible. Adjective It's It was impossible difficult + for for for + noun/pronoun me Some other adjectives Adjective It was It's silly nice used in this construction: + infinitive with to to say. in your car. hard. (silly) You'd 7 Don't leave valuables It's 8 Unfortunately. exciting. . (wonderful) It's 6 You must visit Land's End. cheap. good. It's 3 Parking is difficult in the town centres. unusual. unnecessary. not to forget your ticket. sensible. . Adjective It isn't I'm It's easy pleased important + infinitive with to to find a job. (cheaper) in a bed and breakfast. + normal. You'll be 94 I won't be here in July. stupid. unkind. difficult. nice. good. . (easy) It's easy to fll1d places to stay. (easy) It 4 Buya map of the area. surprised. than staying in a hotel. Some other adjectives used in the construction: advisable. 1 Some Greek friends of Claire Long are coming to visit the area where she lives. It was wrortg of the oovetnmeni to increase taxes last year... using adjective + for + object + infinitive.. The following week he saw her again.. Alan Badger recently gave £20 to a woman in the street who said she hadn't had nowhere to live.. RYAN: LOUISE: RYAN: LOUISE: RYAN: LOUISE: RYAN: LOUISE: And it was (2 nice/you/phone) yesterday.... Hi. using the three constructions you have practised in Exercises 1..... 2 and 3. . eaten for three days and a job..' a lot of freedom.. It's (5 hard/not Yes....' until you have children of your own. you I just don't understand '(1 common) MARIE: '(2 rare) MARJE: '(3 important) MARIE: '(4 difficult) 3 Read the text and make sentences..... How's the leg? Painful. Ryan..... laugh) really. Would it be (7 possible/you/scratch) my right foot? It's itching and I can't reach it.. is there anything I can do? I'm always (6 happy/help) you can do. .. Example: MARIE: MARIE: son.. she was homeless....... 1 (generous) 2 (dishonest) 3 (stupid) It was 4 (silly) It was 5 (wrong) It was 4 Louise LOUISE: Betts is in hospital with a broken leg. Examples: It was silty of me not to leorn to playa musical instrumeni cohen / was uounq.2 Marie is complaining to a friend about her sister's three-year-old replies....' . she just laughed at Example: It was good of Alart to help the It was It was wo/tWrt.... She wasn't homeless and she had money on things she didn't need.' sometimes. She spent his asked him for some more buying drinks for her him..(not easy) young children children 'It tsn': easy for childrert to sit still for lortg. Check your answers with a teacher........ The next day Alan saw her in the pub friends.....' everything you give them. has come to see her... Complete the friend's 'He just can't sit still. He doesn't eat what she gives him........ Alan handed her another £20.... Three days. That child has too much freedom! young children why she doesn't control him better.. 95 ...... why she wanted the money. perhaps.. She money. It's (1 good/you/come) ..... It isn't (3 easy/me/walk) How long will you be here? It's (4 difficult/say) How did it happen? I tripped over the dog. ...' He seems to shout all the time.. £20... Complete the dialogue. she didn't need. 5 Write five sentences giving your opinion of the way you or other people have behaved... using adjective + of + object + infinitive..... Ryan.. But this wasn't true. there is something Well.. When he told her she hadn't told him the truth. laugh at him. ..... Her friend. .. using the word given.... It is followed by the infinitive with to. passengers smoke. (oo cause) • Make can also be followed by object + + Make You • Let (meaning make allow) + object me adjective."...... 48 Quick reference le!fpergo ' "'. make can mean 'force' or 'cause'. (let) ""." . to go out with a man ten years older than her.... He's very funn§ He always (llaugh) (2 happy) fashioned." . --------. using make or (not) he ..".. He also so slowly! I want to And when I'm feeling miserable sometimes. old jeans. (oo force) The seafood made me feel ill. He (7 wear) (8 impatient) shake him sometimes 96 " to (9 hurry) sometimes .rr ".." "". And he always tries to (6 wear) smart clothes when we go out..... . "~'--"-"-----------------------... The children were made to go to bed..he does everything .. (let) with a man ten years older than her... (let) anything they like on television.... (make) They don't make the younger ones go to bed at a reosonoble time... They allow them to go to bed when they like." ... (made) They allow them to stay at horne if they want to. They allow them to watch anything they like on television. They aren't forced to go to school.. if they want to. 1 Brian and Ann Price do not approve of the way their neighbours are bringing up their children. to school... Passengers are made to show their passports. for myself when we go out. • We can use make in the passive.. when they like. He never (4 decide) But he also (3 angry) Complete what she says. Example: BRIAN: ANN: They don't force the younger ones to go to bed at a reasonable time.".---------~--... Make + object + infinitive without to His mother makes him work hard. what we're going to do and he (5 pay) He's very old- . + object + infinitive without to me borrow the car. . Let My father They don't let let is used in this construction.""" "" ... (let) They allow their eldest daughter 1 They ANN: 2 They BRIAN: 3 They ANN: 4 They BRIAN: 5 They """""""""""""'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 2 Stephanie is telling her mother about her boyfriend. • In the following construction. let with the verbs in brackets. adjective angry... . Complete the second sentence so that it has a similar meaning to the first. The manager risked losing his job.. 3 3 Complete teacher. Check your answers with a 1 I enjoy . whatever computer their teeth. 6 I dislike . miss. postpone.. involve. consider.. 4 . 5 I regret . 2 .. practise. enjoy. games even when they were adults. because they jobs because they were bored at work.rence • If these verbs are followed by another verb.. detest. 29% of drivers said they delayed (4) 27% of Americans enjoyed their jobs.. escape. up their cars with petrol for as long as possible.. 23% said they were considering 21 % said they disliked (7) last moment. Do you want to come sailing? Shall we go swimming? :J 1 These are some of the results of a recent survey in the USA in which Americans were asked about their likes and dislikes. up in the morning and admitted (8) was on. deny. 2 I hate . fancy..49 Quicl( rel. 4 I fancy . go on. He went shopping. • We use go and come + -ing when we tal k about sports or free-time activities outside the home. risk. these sentences about yourself using the verb + -ing form. to playa musical instrument. 2 What are the people in this picture doing? 1 They're going sailing. it to the imagine not (5) (6) 38% of American husbands (2) 32% said they hated (3) it regularly.. no matter how rich they were. recall. Read the text below and think of one word which best fits each space. regret. I avoided meeting her. finish.. keep. dislike. imagine. mind. 3 I avoid .. . delay.. we use the -ing form of the second verb: admit. 97 . 63% said they enjoyed (1) to sleep at night. They finished arguing. fancied the idea of dating other women but only 13% admitted the dirty dishes and pans after a meal. suggest.. 19% said they didn't mind just (9) 17% of Americans went on (10) not (11) (12) 15% said they regretted 5% said they detested couldn't in front of the TV. avoid. jl gave English lessons. Example: You don't want to look stupid when you meet that new girl.~e Preposition + -ing Before going to bed. bad at./lieft school. Write the questions. by and without + -ing. 3 In India I paid for my food and accommodation.zl didn't know what I was going to do. fond of. congratulate someone on. good at. Verb I feel I don't approve + preposition like of + + -ing going to the cinema. people smoking in restaurants. Some other verbs + object + preposition: blame someone for. I studied physics at university. suspect someone of. keen on. after. Adjective She's Are you interested afraid + preposition in of + -ing learning foreign languages. preposition -ing for helping her.. clever at. 2 I started work. (Afraid?) Are qou afraid of looking stupid tohen uou meet that new girl? You haven't got a girlfriend./1 spent a year travelling in Asia. + Some other common verbs Verb She thanked They accused + preposition: object me me apologise + insist on. fed up with. prevent (or stop) someone from. Make the two sentences using before. approve of. proud of. into one. worried about. I fed the cat. I got into the house by breaking a window. not getting a job? Some other common adjectives + preposition: angry about. She left without saying goodbye. I got a job. 4 I got back to England last month. excited about.50 I/Iuick refere. forgive someone for. think of/about. for. (Fed up?) Are you fed up 2 Do you want to improve your chances? Are you keen 98 (Keen?) ? ? . After leaving college. 2 This is some publicity for a new book for men called 'How to get on with girls'. dream of. talk about. 1 Katie Stevens is telling her new boyfriend about her life so far. of not trying hard enough. using the construction adjective + preposition + -ing. decide against. .. ( ) ) 5 What frightens you? What makes you angry? What do you do well? What do you do badly? What interests you? What do you really enjoy? Answer these questions. (Worried?) Are you worried 4 You lost that last girl because you said something Are you angry 5 Do you want to know all the answers? Are you interested (Interested") ? ? wrong.. C or D best fits each space. intolerant. Some have a mistake in them. I don't approve (1) . (Angry?) ? 3 Simon Welch is talking about his likes and dislikes and his habits.. Examples: r In afraid oflosil1g Inyjob .. r In bad at spellil1g.. a mistake. and I'd like to prevent people (8) . put a tick (.. suspect all politicians (7) . B. I never believe people who accuse me (6) .. hypocrites.!get al1gry about 110t beil1g able to play the guitar well... early on Monday morning. l' In good at speokino £l1glish... Some of the lines are correct. Write two answers for each question.I).. If a line is correct.3 You don't want to say the wrong thing.. too slowly on I motorways. Read the text.. I always insist (5) .. A. r In «ee« 011 playil1g volleyball. Oh. using the construction adjective + preposition + -ing. I don't like people who never apologise (2) . underline the mistake and write the correction in the brackets.... 1 A of women smoking B of smoking women B for to make B like get up B to the postman come B on to drink B for being B for being 2 3 4 5 6 7 8 A to have made A like to get up A to the coming postman A to drink A of being A to be A of driving B from driving C for women to smoke C for make C like getting up C to the postman coming C to drink C of be C of being C from drive D of women to smoke D for making D like to get up D to the postman D on drinking Dto be D being D to drive 4 This is an advertisement for Sun Villas in the Seychelles. Are you bored about living an ordinary life? Are you afraid of spending ( ( ) 2 the rest of your life in the same place? Are you tired of do the 3 same thing every day? Does your job stop you from being the person you 4 want to be? Do you ever blame yourself with being unadventurous? 5 you only talk about changing your life? Do you ever dream of get 6 away from it all? Have you ever thought of owning your own house in 7 paradise? Why not buy a Sun Villa in the Seychelles? 8 Then you'll thank us for save your life! Do ) ) ) ) ) ( ( ( ( (. r In interested in lnakil1g lnol1ey. 99 Check your answers with a teacher. in the street. Read the text below and decide which answer. I never feel (3) .. If a line has a mistake... in the morning. I always look forward (4) . white wine ice-cold. ... the woman she works for. Can't stand + (noun or pronoun) + -ing I can't stand fighting They can't stand people smoking... not a cleaner! 3 Look at what these airline passengers are saying and think of one word which best fits each space. There's no point (in) asking. in the hotel safe. the kitchen floor? light housework and last week 1(6) .. I (5) . When it is followed by a • It's no use (OR It's no good)/There 's no point/It's (not) worth are followed by the -ing form of the verb... I'm sorry Jane...... But I'm an au pair.. 2 She wants him to leave his passport 4 He wants her to put his travellers 5 He wants her to order him a taxi 3 She wants him to fill in the registration cheques 2 Annika is an au pair girl.... that's fine.. using (not) mind + the -ing form of these verbs. There's nothing to see except cloud.. . we always use the -ing form. but I can't help (2) to the toilet now...... we always use the -ing form.. There's a long queue. all the meals when you were ill.. It's not worth trying... you I'm sure ANNIKA: JANE: ANNIKA: her a bedtime story for a change.... It means 'hate' or 'detest'. It's no use (3) 'There's no point (4) 'That meal wasn't worth (5) 100 . mind + (noun or pronoun) + -ing Do you mind waiting? I don't mind Katie coming.. Emily this evening? We're going to the theatre.' scared. . .... It's no use crying.... • We use can't stand to show strong dislike. I (3) And (4) No. in this evening. Do you mind and Would you mind are polite ways of asking someone to do something... They don't mind me wearing jeans at work.. I know it's very safe really.' 'I can't stand (I) 'Stay in that seat.51 Oukk refel'eDCe • When mind is followed by a verb.... Write what they say using Would you fniftd + -ing? .' It didn't taste of anything. 1 A hotel receptionist is talking to a guest.......... verb.. I can't help laughing.' by the window.. Complete the dialogue between her and Jane Forsyth. I've been out twice this week.. clean do stay cook look after read JANE: (1) Emily (2) """'''''''''''''''''''''''''''''''''''''''''''' No. card with her 1 She wants him to show her his passport.
https://www.scribd.com/doc/49933614/Richmond-Grammar-Practice-in-context
CC-MAIN-2017-09
refinedweb
39,747
88.13
java.util.EventObject. Event, such as OverdraftEvent. 1 package com.artima.examples.account.ex4; 2 3 import java.util.EventObject; 4 5 /** 6 * Event that indicates an overdraft has either been loaned to a client or 7 * repaid by a client during a withdrawal or deposit transaction on an 8 * <code>Account</code>. 9 */ 10 public class OverdraftEvent extends java.util.EventObject { 11 12 private long overdraft; 13 private long amount; 14 15 /** 16 * Constructs an <code>OverdraftEvent</code> with the passed 17 * <code>source</code>, and <code>overdraft</code>. 18 * 19 * @param source the source of the event 20 * @param overdraft the current amount of overdraft outstanding in the 21 * <code>OverdraftAccount</code> 22 * @throws IllegalArgumentException if either of <code>overdraft</code> 23 * or <code>amount</code>, passed as parameters to this constructor, 24 * are less than or equal to zero. 25 */ 26 public OverdraftEvent(OverdraftAccount source, 27 long overdraft, long amount) { 28 29 super(source); 30 31 if (overdraft <= 0 || amount <= 0) { 32 throw new IllegalArgumentException(); 33 } 34 35 this.overdraft = overdraft; 36 this.amount = amount; 37 } 38 39 /** 40 * Returns the current overdraft, the amount of of overdraft after the 41 * transaction that caused this event to be propagated. 42 * 43 * @returns the current overdraft 44 */ 45 public long getOverdraft() { 46 return overdraft; 47 } 48 49 /** 50 * Returns the amount of money either loaned to the client or repaid to 51 * the bank during the transaction that caused this event to be 52 * propagated. 53 * 54 * @returns the amount loaned or repaid 55 */ 56 public long getAmount() { 57 return amount; 58 } 59 } java.util.EventListenerand contains a method declaration for each event (of that category) that will trigger an information propagation from the event generator to its listeners. Listenerfor Eventin the event category class name. For example, the listener interface for OverdraftEventwould be OverdraftListener. OverdraftEventthat was triggered by an overdraft occurring would be named overdraftOccurred(). overdraftOccurred()method would be: void overdraftOccurred(OverdraftEvent e); 1 package com.artima.examples.account.ex4; 2 3 import java.util.EventListener; 4 5 /** 6 * Listener interface for receiving overdraft events. 7 */ 8 public interface OverdraftListener extends EventListener { 9 10 /** 11 * Invoked when an overdraft has occurred. This method will 12 * be invoked on listeners whenever the bank loans money 13 * to a client that has requested a withdrawal of more funds 14 * than is available in the account's balance. 15 */ 16 void overdraftOccurred(OverdraftEvent e); 17 18 /** 19 * Invoked when some or all of the outstanding overdraft 20 * that a bank has loaned to a client is repaid. 21 */ 22 void overdraftRepaid(OverdraftEvent e); 23 } Listenerin the listener interface name with Adapter. For example, the adapter class for OverdraftListenerwould be OverdraftAdapter. 1 package com.artima.examples.account.ex4; 2 3 /** 4 * An abstract adapter class for receiving overdraft events. The methods in 5 * this class are empty. This class exists as convenience for listener 6 * objects. 7 */ 8 public abstract class OverdraftAdapter implements OverdraftListener { 9 10 /** 11 * Invoked when an overdraft has occurred. This method will 12 * be invoked on listeners whenever the bank loans money 13 * to a client that has requested a withdrawal of more funds 14 * than is available in the account's balance. 15 * 16 * @param e the overdraft event object 17 */ 18 public void overdraftOccurred(OverdraftEvent e) { 19 } 20 21 /** 22 * Invoked when some or all of the outstanding overdraft 23 * that a bank has loaned to a client is repaid. 24 * 25 * @param e the overdraft event object 26 */ 27 public void overdraftRepaid(OverdraftEvent e) { 28 } 29 } add<listener-interface-name>()and the remove method remove<listener-interface-name>(). For example, the listener add and remove methods for a OverdraftEventwould be named addOverdraftListener()and removeOverdraftListener(). 1 package com.artima.examples.account.ex4; 2 3 /** 4 * Represents a bank account with overdraft protection. Instances of this 5 * class are instantiated with a specified maximum overdraft. If a client 6 * attempts to withdraw more than the current account balance, the bank may 7 * loan the amount in excess of the balance to the client. The overdraft 8 * maximum passed to an <code>OverdraftAccount</code>'s constructor is the 9 * maximum amount the bank will lend to the client in this manner. When a 10 * client makes a deposit, the bank will pay itself back first before 11 * increasing the account's balance. 12 * 13 * <p> 14 * Money is stored in this account in integral units. Clients can use this 15 * account to store any kind of value, such as money or points, etc. The 16 * meaning of the integral units stored in this account is a decision of the 17 * client that instantiates the account. The maximum amount of units that can 18 * be stored as the current balance of an <code>OverdraftAccount</code> is 19 * Long.MAX_VALUE. 20 */ 21 public class OverdraftAccount implements Account, OverdraftEventGenerator { 22 23 /** 24 * Helper back-end <code>BasicAccount</code> object 25 */ 26 private BasicAccount account = new BasicAccount(); 27 28 /** 29 * Helper back-end <code>OverdraftEventManager</code> object 30 */ 31 private OverdraftEventManager eventMan 32 = new OverdraftEventManager(); 33 34 /** 35 * The maximum amount the bank will loan to the client. 36 */ 37 private final long overdraftMax; 38 39 /** 40 * The current amount the bank has loaned to the client which has not yet 41 * been repaid. This value must at all times be greater than or equal to 42 * zero, and less than or equal to <code>overdraftMax</code>. If this 43 * value is greater than zero, then the balance of the helper 44 * <code>BasicAccount</code> (referenced from the <code>account</code> 45 * instance variable) must be exactly zero. 46 */ 47 private long overdraft; 48 49 /** 50 * Constructs a new <code>OverdraftAccount</code> with the passed 51 * overdraft maximum. 52 * 53 * @param overdraftMax the maximum amount the bank will loan to the 54 * client 55 */ 56 public OverdraftAccount(long overdraftMax) { 57 this.overdraftMax = overdraftMax; 58 } 59 60 /** 61 * Returns the current overdraft, the amount the bank has loaned to the 62 * client that has not yet been repaid. 63 * 64 * @return the current overdraft 65 */ 66 public long getOverdraft() { 67 return overdraft; 68 } 69 70 /** 71 * Returns the overdraft maximum, the maximum amount the bank will allow 72 * the client to owe it. For each instance of 73 * <code>OverdraftAccount</code>, the overdraft maximum is constant. 74 * 75 * @return the overdraft maximum 76 */ 77 public long getOverdraftMax() { 78 return overdraftMax; 79 } 80 81 /** 82 * Gets the current balance of this <code>OverdraftAccount</code>. 83 * 84 * @return the current balance 85 */ 86 public long getBalance() { 87 return account.getBalance(); 88 } 89 90 /** 91 * Withdraws the passed amount from this <code>OverdraftAccount</code>. 92 * If the passed amount is less than or equal to the current balance, all 93 * withdrawn funds will be taken from the balance, and the balance will 94 * be decremented by the passed amount. If the passed amount exceeds the 95 * current balance, the bank may loan the client the difference. The bank 96 * will make the loan only if the difference between the passed amount 97 * and the balance (the shortfall) is less than or equal to the available 98 * overdraft. The available overdraft is equal to the current overdraft 99 * (the amount already loaned to the client and not yet repaid), 100 * subtracted from the overdraft maximum, which is passed to the 101 * constructor of any <code>OverdraftAccount</code>. 102 * 103 * <p> 104 * If the passed amount is less than or equal to the current balance, the 105 * <code>withdraw</code> method decrements the current balance by the 106 * passed amount and returns the passed amount. If the passed amount is 107 * greater than the current balance, but the passed amount minus the 108 * current balance is less than or equal to the available overdraft, the 109 * <code>withdraw</code> method sets the current balance to zero, records 110 * the loan, and returns the requested amount. Otherwise, the passed 111 * amount minus the current balance exceeds the available overdraft, so 112 * the <code>withdraw</code> method throws 113 * <code>InsufficientFundsException</code>. 114 * 115 * Subclasses must withdraw at least the passed amount, but may 116 * effectively withdraw more. For example, if a subclass includes a 117 * notion of a withrawal fee, the subclass's implementation of this 118 * method may charge that fee by decrementing it from the account at the 119 * time of withdrawal. 120 * 121 * @param amount amount to withdraw 122 * @return amount withdrawn from the <code>OverdraftAccount</code> 123 * @throws InsufficientFundsException if the 124 * <code>OverdraftAccount</code> contains insufficient funds for the 125 * requested withdrawal 126 * @throws IllegalArgumentException if requested withdrawal amount is 127 * less than or equal to zero. 128 */ 129 public long withdraw(long amount) throws InsufficientFundsException { 130 131 if (amount <= 0) { 132 throw new IllegalArgumentException(); 133 } 134 135 long bal = account.getBalance(); 136 if (bal >= amount) { 137 138 // Balance has sufficient funds, so just take the 139 // money from the balance. 140 return account.withdraw(amount); 141 } 142 143 long shortfall = amount - bal; 144 long extraAvailable = overdraftMax - overdraft; 145 146 if (shortfall > extraAvailable) { 147 throw new InsufficientFundsException(shortfall 148 - extraAvailable); 149 } 150 overdraft += shortfall; 151 account.withdraw(amount - shortfall); 152 153 OverdraftEvent event = new OverdraftEvent(this, overdraft, 154 shortfall); 155 eventMan.fireOverdraftOccurred(event); 156 157 return amount; 158 } 159 160 /** 161 * Deposits the passed amount into the <code>OverdraftAccount</code>. If 162 * the current overdraft is zero, the balance will be increased by the 163 * passed amount. Otherwise, the bank will attempt to pay off the 164 * overdraft first, before increasing the current balance by the amount 165 * remaining after the overdraft is repaid, if any. 166 * 167 * <p> 168 * For example, if the balance is 0, the overdraft is 100, and the 169 * <code>deposit</code> method is invoked with a passed 170 * <code>amount</code> of 50, the bank would use all 50 of those monetary 171 * units to pay down the overdraft. The overdraft would be reduced to 50 172 * and the balance would remain at 0. If subsequently, the client 173 * deposits another 100 units, the bank would use 50 of those units to 174 * pay off the overdraft loan and direct the remaining 50 into the 175 * balance. The new overdraft would be 0 and the new balance would be 176 * 50. 177 * 178 * Subclasses may effectively deposit more or less than the passed amount 179 * into the <code>OverdraftAccount</code>. For example, if a subclass 180 * includes a notion of funds matching, the subclass implementation of 181 * this method may match some or all of the deposited amount at the time 182 * of deposit, effectively increasing the deposited amount. Or, if a 183 * subclass includes the notion of a deposit fee, the subclass's 184 * implementation of this method may charge that fee by decrementing it 185 * from the account at the time of deposit, effectively reducing the 186 * deposited amount. 187 * 188 * @param amount amount to deposit 189 * @throws ArithmeticException if requested deposit would cause the 190 * balance of this <code>OverdraftAccount</code> to exceed 191 * Long.MAX_VALUE. 192 * @throws IllegalArgumentException if requested withdrawal amount is 193 * less than or equal to zero. 194 */ 195 public void deposit(long amount) { 196 197 if (amount <= 0) { 198 throw new IllegalArgumentException(); 199 } 200 201 if (overdraft > 0) { 202 203 long amountRepaid = 0; 204 205 if (amount < overdraft) { 206 amountRepaid = amount; 207 overdraft -= amount; 208 } 209 else { 210 long diff = amount - overdraft; 211 amountRepaid = diff; 212 overdraft = 0; 213 account.deposit(diff); 214 } 215 216 OverdraftEvent event = new OverdraftEvent(this, overdraft, 217 amountRepaid); 218 eventMan.fireOverdraftRepaid(event); 219 } 220 else { 221 account.deposit(amount); 222 } 223 } 224 225 /** 226 * Adds the specified overdraft listener to receive overdraft events from 227 * this <code>OverdraftAccount</code>. If <code>l</code> is 228 * <code>null</code>, no exception is thrown and no action is performed. 229 * If <code>l</code> is already registered as a listener, no action is 230 * performed. 231 * 232 * @param l the <code>OverdraftEventListener</code> to add 233 */ 234 public void addOverdraftListener(OverdraftListener l) { 235 236 eventMan.addOverdraftListener(l); 237 } 238 239 /** 240 * Removes the specified overdraft listener so that it no longer receives 241 * overdraft events from this <code>OverdraftAccount</code>. This method 242 * performs no function, nor does it throw an exception, if the listener 243 * specified by the argument was not previously added to this component. 244 * If <code>l</code> is <code>null</code>, no exception is thrown and no 245 * action is performed. 246 * 247 * @param l the <code>OverdraftEventListener</code> to remove 248 */ 249 public void removeOverdraftListener(OverdraftListener l) { 250 251 eventMan.removeOverdraftListener(l); 252 } 253 } 1 package com.artima.examples.account.ex4; 2 3 import java.util.Set; 4 import java.util.Iterator; 5 import java.util.HashSet; 6 7 /** 8 * A class that manages registration and unregistration of 9 * <code>OverdraftListener</code>s and the firing of 10 * <code>OverdraftEvent</code>s. 11 * 12 * @author Bill Venners 13 */ 14 class OverdraftEventManager { 15 16 /** 17 * Unsynchronized <code>HashSet</code> to which listeners are added and 18 * removed via the synchronized methods <code>addOverdraftListener</code> 19 * and <code>removeOverdraftListener</code> methods. 20 */ 21 private HashSet listeners = new HashSet(); 22 23 /** 24 * Clone of the <code>listeners</code> <code>HashSet</code>, which is 25 * used by the <code>fireOverdraftOccurred</code> and 26 * <code>fireOverdraftRepaid</code> methods to propagate events. This 27 * <code>HashSet</code> always contains a most recent snapshot of the 28 * <code>listeners</code> <code>HashSet</code>, but this 29 * <code>HashSet</code> is never modified, only replaced. Because this 30 * <code>HashSet</code> is never modified, the fire methods can iterate 31 * through the set without synchronization. This implementation approach 32 * is geared towards providing optimum performance for the expected run 33 * time usage in which adding and removing listeners happens less 34 * frequently than firing events to those listeners. 35 */ 36 private Set listenersClone = new HashSet(); 37 38 /** 39 * Constructs a new <code>OverdraftEventManager</code>. The 40 * <code>OverdraftEventManager</code> starts its life with an empty 41 * listeners list. 42 */ 43 public OverdraftEventManager() { 44 } 45 46 /** 47 * Adds the specified overdraft listener to receive overdraft events. If 48 * <code>l</code> is <code>null</code>, no exception is thrown and no 49 * action is performed. If <code>l</code> is already registered as a 50 * listener, no action is performed. 51 * 52 * @param l the <code>OverdraftEventListener</code> to add 53 */ 54 public synchronized void addOverdraftListener(OverdraftListener l) { 55 56 listeners.add(l); 57 listenersClone = (Set) listeners.clone(); 58 } 59 60 /** 61 * Removes the specified overdraft listener so that it no longer receives 62 * overdraft events. This method performs no function, nor does it throw 63 * an exception, if the listener specified by the argument was not 64 * previously added to this component. If <code>l</code> is 65 * <code>null</code>, no exception is thrown and no action is performed. 66 * 67 * @param l the <code>OverdraftEventListener</code> to remove 68 */ 69 public synchronized void removeOverdraftListener(OverdraftListener l) { 70 71 listeners.remove(l); 72 listenersClone = (Set) listeners.clone(); 73 } 74 75 /** 76 * Fires overdraftOccurred events to registered listeners. 77 * 78 * @param event the <code>OverdraftEvent</code> to propagate 79 */ 80 public void fireOverdraftOccurred(OverdraftEvent event) { 81 82 Iterator it = listenersClone.iterator(); 83 while (it.hasNext()) { 84 OverdraftListener l = (OverdraftListener) it.next(); 85 l.overdraftOccurred(event); 86 } 87 } 88 89 /** 90 * Fires overdraftRepaid events to registered listeners. 91 * 92 * @param event the <code>OverdraftEvent</code> to propagate 93 */ 94 public void fireOverdraftRepaid(OverdraftEvent event) { 95 96 Iterator it = listenersClone.iterator(); 97 while (it.hasNext()) { 98 OverdraftListener l = (OverdraftListener) it.next(); 99 l.overdraftRepaid(event); 100 } 101 } 102 }
http://www.artima.com/javaseminars/modules/EventGen/index.html
CC-MAIN-2016-40
refinedweb
2,608
52.39
Quote: I want help with this ... This is the code, and i have taken 4 questions initially... and applied the input method to only question 1 ... i want the input scanner variable of question 1 to be stored in a variable with automatic numbering as the for loops runs till 10 my variable name changes so that i could later call the same question again and compare the answers with if condition ! for example i'm taking 10 inputs for "write 10 colors names" : i want those inputs.. to be used later again lets look at it step by step.. 1. Show randomly 1 question out of 10. 2. The question's answers should be 10, for example .. write 10 colors, write 10 countries! 3. when the user enters all 10 answers,the program should again display the same question and ask the user to repeat the answers which he/she entered earlier ! 4. If the user manages to write the answers in correct sequence in which he entered earlier, the program should add +10 score for each correct sequence answer. Code : import java.util.Scanner; public class Game { public static void main (String arg[]) { java.util.Random r = new java.util.Random(); int a = r.nextInt(4); int abc[] = null; if (a==0) { System.out.println("Write 10 color names: "); Scanner question = new Scanner(System.in); for(int i=0; i<10; i++) abc[i] = question.nextInt(); } else if (a==1) { System.out.println("Write 10 city names: "); } else if (a==2) { System.out.println("Write 10 contry names: "); } else if (a==3) { System.out.println("Write 10 vegetable names: "); } for (int g=0; g<10;g++) System.out.println(abc[g]); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/23643-memory-test-game-program-printingthethread.html
CC-MAIN-2015-35
refinedweb
283
68.77
In the previous tutorial, we discovered and tested the MH-Z19 sensor which allows to measure the CO2 concentration without calibration. We saw how to read the CO2 concentration returned on the sensor PWM pin in MicroPython and then publish it on a Domoticz server via the HTTP / JSON interface. In this new tutorial, I propose to do the same thing with Arduino code. The code is compatible with the ESP8266 and the new ESP32. For that, it will be necessary to install the Espressif SDK by following this tutorial for the ESP8266 development bards and this one for the ESP32 boards. If you have not read the previous article, the Winsen MH-Z19 sensor is more accurate than the MQ135 environmental sensor. It is much more expensive (about $24 / 20€) but measuring the CO2 level does not require a “hack” mathematical. The value expressed in ppm is retrieved directly from the PWM pin or from the serial port. Components used The code works on ESP8266 as well as on ESP32. For this tutorial, we will use the PWM output of the MH-Z19. Only one entry on the ESP8266 / ESP32 board will be required. Presentation of the CO2 sensor MH-Z19 The MH-Z19 is a self-calibrated sensor, ie the measurement sent by the sensor does not require any mathematical treatment. In other words, the CO2 content expressed in ppm (parts per million) is recovered. The MH-Z19 has a PWM output and a UART digital interface (serial port). For this tutorial, we will already start by exploiting the PWM output. The PWM signal is proportional to the CO2 concentration. It will therefore be necessary to measure the time during which the signal remains at the high level. Then, the following formula allows to deduce the CO2 rate. - Cppm represents the concentration of CO2 in the atmosphere in ppm - Th, the time during which the signal remained high - Tl, the time during which the signal has remained low For a 0-5000ppm sensor, simply replace 2000 by 5000 in the formula. The complete documentation is available here. Prepare virtual appliances on Domoticz Go to the Domoticz server to create two virtual devices of the temperature type and get the Idx of each probe. Follow this tutorial to learn how to do it. Cabling the MH-Z19’s Serial Port to an ESP8266 Although an Arduino Uno can be used to perform CO2 concentration measurements, the ESP8266, which incorporates a WiFI module, is much better suited for this project. We can move the probe in the house and why not add a small monochrome OLED screen SSD1306. In order for the CO2 concentration measurement to be correct, the MH-Z19 must be permanently powered. As you can see in the technical data, wait at least 2 minutes before the measurement is correct. Battery operation is not suitable for this type of project. The ESP8266 has 2 UART serial ports. UART0 port (RXD0 / TXD0) and reserved for communication with the IDE. The port numbered by mistake # 1 (TXD1) is incomplete. There is only the TXD1 pin. It is reserved to flash the memory of the ESP8266. Here we will use the RXT2 / TXD2 serial port. Pin RX is located on pin D7 of the ESP8266. The TX pin is on pin D6. We will therefore wire the serial loan by crossing the pins as usual. The RX pin of the MH-Z19 on the D6. The TX pin of the MH-Z19 on the D7. The MH-Z19 can be powered with a voltage between 3.6 and 5.6V. Connect the MH-Z19’s Win Pin to the 5V Pin of the ESP8266. Close the circuit by connecting the GND pins. Serial communication with the MH-Z19 I adapted the source code from the previous tutorial that read several Dallas DS18B20 temperature probes. Here is what is particular. To communicate via the serial port with another device, another serial port must be opened. It is the SoftwareSerial.h library that takes care of it. To open a serial port on the RXD2 and TXD2 pins, you must instantiate a SoftwareSerial object that takes the serial port pins as parameter. In the setup(), we start the serial port. Here, it is ported at a speed of 9600 bauds according to Wesen specifications: - Baud rate: 9600 - Data byte: 8 byte - Stop byte: 1 byte - Parity: no Here, we have 2 open serial ports. The first at 115200 baud communicates with the serial monitor of the Arduino IDE (for example), the second communicates with the MH-Z19. #include <SoftwareSerial.h> #define MH_Z19_RX D7 #define MH_Z19_TX D6 SoftwareSerial co2Serial(MH_Z19_RX, MH_Z19_TX); void setup() { Serial.begin(115200); co2Serial.begin(9600); //Init sensor MH-Z19(14) } For the rest of the code, it’s already seen.. Then change the following parameters in the code - wifi_ssid, WiFi network - wifi_password, WiFi password - host, IP address of the Domoticz server - port, default 8080 - IDX_mhz19, Idx of the Domoticz virtual appliance that will receive the CO2 concentration < //#include <Wire.h> #include <SoftwareSerial.h> // For Arduino or ESP32 (Espressif SDK must be installed) //#include <WiFi.h> //#include <HTTPClient.h> // Pour une carte ESP8266 | For ESP8266 development board #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <PubSubClient.h> #define INTERVAL 5000 #define MH_Z19_RX D7 #define MH_Z19_TX D6 long previousMillis = 0; SoftwareSerial co2Serial(MH_Z19_RX, MH_Z19_TX); // define MH-Z19 // Parametres WIFI - WiFi settings #define wifi_ssid "********" #define wifi_password "********" // Paramètres HTTP Domoticz - HTTP Domoticz settings const char* host = "***.***.***.***"; const int port = 8080; #define IDX_mhz19 26 HTTPClient http; void setup() { Serial.begin(115200); // Connexion au réseau WiFi, connexion aux sondes // Start WiFi connexion and probes setup_wifi(); // Démarrer la communication série avec le MH-Z19 - Start UART communication with MZ-Z19 sensor unsigned long previousMillis = millis(); co2Serial.begin(9600); //Init sensor MH-Z19(14) } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis < INTERVAL) return; previousMillis = currentMillis; Serial.print("Requesting CO2 concentration..."); int ppm = readCO2(); Serial.println(" PPM = " + String(ppm)); // Format JSON à respecter pour l'API Domoticz - Domoticz JSON API // /json.htm?type=command¶m=udevice&idx=IDX&nvalue=PPM // String url = "/json.htm?type=command¶m=udevice&idx="; url += String(IDX_mhz19); url += "&nvalue="; url += String(ppm); sendToDomoticz(url); } //Connexion au réseau WiFi void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connexion OK "); Serial.print("=> Addresse IP : "); Serial.print(WiFi.localIP()); }(); } int readCO2() { // D'après le code original de | From original code byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // command to ask for data byte response[9]; // for answer co2Serial.write(cmd, 9); //request PPM CO2 // The serial stream can get out of sync. The response starts with 0xff, try to resync. while (co2Serial.available() > 0 && (unsigned char)co2Serial.peek() != 0xFF) { co2Serial.read(); } memset(response, 0, 9); co2Serial.readBytes(response, 9); if (response[1] != 0x86) { Serial.println("Invalid response from co2 sensor!"); return -1; } byte crc = 0; for (int i = 1; i < 8; i++) { crc += response[i]; } crc = 255 - crc + 1; if (response[8] == crc) { int responseHigh = (int) response[2]; int responseLow = (int) response[3]; int ppm = (256 * responseHigh) + responseLow; return ppm; } else { Serial.println("CRC error!"); return -1; } } Save the sketch and upload it to the ESP8266. If all is correct, you must receive a response with the status OK for each HTTP request. <Connecting to 192.168.1.24 Requesting URL: /json.htm?type=command¶m=udevice&idx=26&nvalue=410 Domoticz response { "status": "OK", "title": "Update Device" } closing connection The virtual device displaying the CO2 content in the room updates after a few seconds on Domoticz. -
https://diyprojects.io/publish-co2-concentration-mh-z19-sensor-domoticz-arduino-code-compatible-esp32-esp8266/
CC-MAIN-2021-49
refinedweb
1,279
57.98
Using pre-trained models in MXNet¶ In this tutorial we will see how to use multiple pre-trained models with Apache MXNet. First, let’s download three image classification models from the Apache MXNet Gluon model zoo. * DenseNet-121 (research paper), improved state of the art on ImageNet dataset in 2016. * MobileNet (research paper), MobileNets are based on a streamlined architecture that uses depth-wise separable convolutions to build light weight deep neural networks, suitable for mobile applications. * ResNet-18 (research paper), the -152 version is the 2015 winner in multiple categories. Why would you want to try multiple models? Why not just pick the one with the best accuracy? As we will see later in the tutorial, even though these models have been trained on the same dataset and optimized for maximum accuracy, they do behave slightly differently on specific images. In addition, prediction speed and memory footprints can vary, and that is an important factor for many applications. By trying a few pretrained models, you have an opportunity to find a model that can be a good fit for solving your business problem. import json import matplotlib.pyplot as plt import mxnet as mx from mxnet import gluon, nd from mxnet.gluon.model_zoo import vision import numpy as np %matplotlib inline The Gluon Model Zoo provides a collection of off-the-shelf models. You can get the ImageNet pre-trained model by using pretrained=True. If you want to train on your own classification problem from scratch, you can get an untrained network with a specific number of classes using the classes parameter: for example net = vision.resnet18_v1(classes=10). However note that you cannot use the pretrained and classes parameter at the same time. If you want to use pre-trained weights as initialization of your network except for the last layer, have a look at the last section of this tutorial. We can specify the context where we want to run the model: the default behavior is to use a CPU context. There are two reasons for this: * First, this will allow you to test the notebook even if your machine is not equipped with a GPU :) * Second, we’re going to predict a single image and we don’t have any specific performance requirements. For production applications where you’d want to predict large batches of images with the best possible throughput, a GPU could definitely be the way to go. * If you want to use a GPU, make sure you have pip installed the right version of mxnet, or you will get an error when using the mx.gpu() context. Refer to the install instructions # We set the context to CPU, you can switch to GPU if you have one and installed a compatible version of MXNet ctx = mx.cpu() # We can load three the three models densenet121 = vision.densenet121(pretrained=True, ctx=ctx) mobileNet = vision.mobilenet0_5(pretrained=True, ctx=ctx) resnet18 = vision.resnet18_v1(pretrained=True, ctx=ctx) We can look at the description of the MobileNet network for example, which has a relatively simple yet deep architecture print(mobileNet) Let’s have a closer look at the first convolution layer: print(mobileNet.features[0].params) The first layer applies ``16`` different convolutional masks, of size ``InputChannels x 3 x 3``. For the first convolution, there are ``3`` input channels, the R, G, B channels of the input image. That gives us the weight matrix of shape ``16 x 3 x 3 x 3``. There is no bias applied in this convolution. Let’s have a look at the output layer now: print(mobileNet.output) Did you notice the shape of layer? The weight matrix is 1000 x 512. This layer contains 1,000 neurons: each of them will store an activation representative of the probability of the image belonging to a specific category. Each neuron is also fully connected to all 512 neurons in the previous layer. OK, enough exploring! Now let’s use these models to classify our own images. All three models have been pre-trained on the ImageNet data set which includes over 1.2 million pictures of objects and animals sorted in 1,000 categories. We get the imageNet list of labels. That way we have the mapping so when the model predicts for example category index 4, we know it is predicting hammerhead, hammerhead shark mx.test_utils.download('') categories = np.array(json.load(open('image_net_labels.json', 'r'))) print(categories[4]) Get a test image filename = mx.test_utils.download('', fname='dog.jpg') If you want to use your own image for the test, copy the image to the same folder that contains the notebook and change the following line: filename = 'dog.jpg' Load the image as a NDArray image = mx.image.imread(filename) plt.imshow(image.asnumpy()) Neural network expects input in a specific format. Usually images comes in the Width x Height x Channels format. Where channels are the RGB channels. This network accepts images in the BatchSize x 3 x 224 x 224. 224 x 224 is the image resolution, that’s how the model was trained. 3 is the number of channels : Red, Green and Blue (in this order). In this case we use a BatchSize of 1 since we are predicting one image at a time. Here are the transformation steps: * Read the image: this will return a NDArray shaped as (image height, image width, 3), with the three channels in RGB order. * Resize the shorter edge of the image 224. * Crop, using a size of 224x224 from the center of the image. * Shift the mean and standard deviation of our color channels to match the ones of the dataset the network has been trained on. * Transpose the array from (Height, Width, 3) to (3, Height, Width). * Add a fourth dimension, the batch dimension. def transform(image): resized = mx.image.resize_short(image, 224) #minimum 224x224 images cropped, crop_info = mx.image.center_crop(resized, (224, 224)) normalized = mx.image.color_normalize(cropped.astype(np.float32)/255, mean=mx.nd.array([0.485, 0.456, 0.406]), std=mx.nd.array([0.229, 0.224, 0.225])) # the network expect batches of the form (N,3,224,224) transposed = normalized.transpose((2,0,1)) # Transposing from (224, 224, 3) to (3, 224, 224) batchified = transposed.expand_dims(axis=0) # change the shape from (3, 224, 224) to (1, 3, 224, 224) return batchified Testing the different networks¶ We run the image through each pre-trained network. The models output a NDArray holding 1,000 activation values, which we convert to probabilities using the softmax() function, corresponding to the 1,000 categories it has been trained on. The output prediction NDArray has only one row since batch size is equal to 1 predictions = resnet18(transform(image)).softmax() print(predictions.shape) We then take the top k predictions for our image, here the top 3. top_pred = predictions.topk(k=3)[0].asnumpy() And we print the categories predicted with their corresponding probabilities: for index in top_pred: probability = predictions[0][int(index)] category = categories[int(index)] print("{}: {:.2f}%".format(category, probability.asscalar()*100)) Let’s turn this into a function. Our parameters are an image, a model, a list of categories and the number of top categories we’d like to print. def predict(model, image, categories, k): predictions = model(transform(image)).softmax() top_pred = predictions.topk(k=k)[0].asnumpy() for index in top_pred: probability = predictions[0][int(index)] category = categories[int(index)] print("{}: {:.2f}%".format(category, probability.asscalar()*100)) print('') Fine-tuning pre-trained models¶ You can replace the output layer of your pre-trained model to fit the right number of classes for your own image classification task like this, for example for 10 classes: NUM_CLASSES = 10 with resnet18.name_scope(): resnet18.output = gluon.nn.Dense(NUM_CLASSES) print(resnet18.output) Now you can train your model on your new data using the pre-trained weights as initialization. This is called transfer learning and it has proved to be very useful especially in the cases where you only have access to a small dataset. Your network will have already learned how to perform general pattern detection and feature extraction on the larger dataset. You can learn more about transfer learning and fine-tuning with MXNet in these tutorials: - Transferring knowledge through fine-tuning - Fine Tuning an ONNX Model That’s it! Explore the model zoo, have fun with pre-trained models!
https://mxnet.apache.org/versions/1.7/api/python/docs/tutorials/packages/gluon/image/pretrained_models.html
CC-MAIN-2022-33
refinedweb
1,398
55.64
26/06/2011 at 14:17, xxxxxxxx wrote: Hy there, I have the indexes of the selected Edges of a Polygon. How can I figure out the corresponding Point values of the Edges or the Point Indexes of the Edges ? I couldn't find any Methods on the PolygonObject/PointObject that would give me that information ... Maybe I can convert the Edge selection to a Point selection (but it must not destroy the actual Point Selection on the object)? Thank you, maxx On 26/06/2011 at 15:42, xxxxxxxx wrote: Check out the Neighbor class in the utils module. Cheers, Seb On 26/06/2011 at 16:18, xxxxxxxx wrote: yes I found the Neighbor class, but it is not really useful in this case. What do I miss? I got for example a Polygon-Object and I know that point 5 and 7 is selected. How to get the Point indexes so I can retrieve the point-coordinates? Neighbor.GetNeighbor( a , b , poly ) Gets the polygon opposite to poly with respect to the edge from point a to b. -> Can't use this method for this, got no polygon upfront Neighbor.GetNeighbor Neighbor.GetPointPolys( pnt ) Get the polygons that are attached to the given point index. -> Can't use this method for this, would have to match two sets of polys and find correlating edges, much too complicated for what I want, right ? Edit: actually It is also not possible, as the two sets have no common edge indexes ... Neighbor.GetPointPolys Neighbor.GetEdgePolys( a , b ) Get the polygons that neighbor the given edge: -> Can't use this method either. Now I've got two polygons. Each Polygon has its own edge-indexes. Or do I need to match the correlating point-coordinates? So many calculations just to get the coordinates of a selected edge ? Neighbor.GetEdgePolys Neighbor.GetEdgeCount() -> ... Neighbor.GetEdgeCount Neighbor.GetPolyInfo( poly ) Neighbor.GetPolyInfo Get a dict that contains neighbor information about the given polygon. One can use this to browse through all available edges using the following code: -> Here the same, I would need to retrieve the two polygons and go through all the point-coordinates and match them up .. There must be a simpler way? On 26/06/2011 at 18:47, xxxxxxxx wrote: What if you use the SendModeling Command to select the points inside your selected edges like this: import c4d from c4d import gui,utils def main() : obj = doc.GetActiveObject() bc = c4d.BaseContainer() bc.SetData(c4d.MDATA_CONVERTSELECTION_LEFT, 1)# ConvertSelection's Left "Edges" option in memory bc.SetData(c4d.MDATA_CONVERTSELECTION_RIGHT, 0)# ConvertSelection's Right "Points" option in memory bc.SetData(c4d.MDATA_CONVERTSELECTION_TOLERANT, True)# Select the selection->ConvertSelection's "Tolerant" option in memory utils.SendModelingCommand(c4d.MCOMMAND_CONVERTSELECTION, list = [obj], mode = c4d.MODIFY_ALL, bc=bc, doc = doc) c4d.EventAdd() if __name__=='__main__': main() Then use a "for loop" to cycle through those selected points and pick up their ID's and positions? -ScottA On 26/06/2011 at 22:03, xxxxxxxx wrote: Hy Scott, >> Maybe I can convert the Edge selection to a Point selection (but it must not destroy the actual Point Selection on the object)? Thank you for the code. If I can't find another way, I will do it in a similar way. As I want to preserve the actual Point-Selection on the Object, I will need to store the Selection and re-apply it after I read out the points (as also reapply the edge selection). But I am heavily surprised. Such an elementary task needs involving a Command, retrieving a selection, reading it out (and possibly loop again to do so), retrieve the points, writing back the initial selections ... hugh .. what an act There must be a better way ... Cheers, maxx On 28/06/2011 at 13:15, xxxxxxxx wrote: I am afraid, but the solution with converting the selection is no option either. Once it has been converted, I cannot know which Points belong to an edge ... There must be a way to do this ?? For each selected edge I need the two points (with coordinates) which define them. Such a difficult problem ? Thanks, maxx On 28/06/2011 at 15:09, xxxxxxxx wrote: In the C++ docs. There are some edge functions like EdgeIndex(). This might be what you need. But unfortunately these functions are part of the N-GON class. Which is not supported by Python. So All I can offer is work- arounds. If the SendModeling "convert" code isn't the ticket. What about creating a spline based on the selected edge using: c4d.CallCommand(1009671)# Edge to Spline? The new spline will have the same point locations as your edge. So you can get the positions from that spline using the spline class functions...Then delete it afterwords. It's clumsy. But it might be the only way to do it. Without the N-GON class. I don't know if there is any way to directly get at the verts. of edges with Python. On 28/06/2011 at 15:35, xxxxxxxx wrote: Hey Scott, inventive, I must admit Probably I'll go this way, desperate measures, making some knots into the snake But if there really is no way, there is something missing in the Python API. No structure around holding Edge information ? On 28/06/2011 at 15:51, xxxxxxxx wrote: I know it sounds hard to believe. But no. I don't see any built in functions to handle edge points directly with Python yet. There's still lots of things that haven't been ported over from C++ yet. Python in C4D is still very new(has it even been a year yet?). I think Sebastian has done a great job getting so much converted. In such a short period of time. In fact..I've been known to ask him to stop adding new stuff. And work on the docs for a while. On 28/06/2011 at 16:51, xxxxxxxx wrote: Yes, I also appreciate Sebastians work greatly. I'd never blame him But Maxon could give him another developer, at least, now, where the integration is official Btw. here is a script from nophoto (on the c4dnetwork) which uses the relation between the polygon and edge-indexes to create a point-selection. In this way I can also determine which point belongs to which edge. import c4d import math def main() : EdgeS = op.GetEdgeS() # Alle selektierten Kanten als 'c4d.BaseSelect' maxEdgeCnt = op.GetPolygonCount()*4 # Die maximal zu erwartende Anzahl von Kanten # Eine Liste mit den Indizes aller Selektierten Kanten erstellen EdgeInd = [] for i in xrange(maxEdgeCnt) : if EdgeS.IsSelected(i) : EdgeInd.append(i) Polygons = op.GetAllPolygons() PointS = c4d.BaseSelect() for edge in EdgeInd: PolyInd = int(edge/4) # Der Index des Polygons, zu welchem die Kante mit Index 'edge' geh\rt PolyEdgeInd = edge-4*(PolyInd) # Der Index der Polygonkante #print str(edge) + ' = Polygon #' + str(PolyInd) + ' > Polygonkante #' + str(PolyEdgeInd) Polygon = Polygons[PolyInd] if PolyEdgeInd is 0: PointS.Select(Polygon.a) PointS.Select(Polygon.b) elif PolyEdgeInd is 1: PointS.Select(Polygon.b) PointS.Select(Polygon.c) elif PolyEdgeInd is 2: PointS.Select(Polygon.c) PointS.Select(Polygon.d) elif PolyEdgeInd is 3: PointS.Select(Polygon.d) PointS.Select(Polygon.a) PointS.CopyTo(op.GetPointS()) if __name__=='__main__': main() On 28/06/2011 at 20:52, xxxxxxxx wrote: Very cool. I love to see how that kind of stuff is done by hand. Thanks for sharing that one.
https://plugincafe.maxon.net/topic/5825/5883_get-points-of-a-selected-edge
CC-MAIN-2021-39
refinedweb
1,240
67.04
Implementing Apache Camel Context and Camel Routes Using Spring Context Implementing Apache Camel Context and Camel Routes Using Spring Context Join the DZone community and get the full member experience.Join For Free Part 1 – Enabling Camel Context We can easily start a Camel context in Spring configuration file. Assuming you have a working Spring configured application. Add below code snippet in your Spring context xml. <CamelContext id = "CamelContext" xmlns= <!-- Define all camel routes within this context --> </CamelContext> When we start the Spring context, camel context will be automatically enabled. Camel context has a field ‘autoStartup’ which can have value either true or false. This value can be read from a properties file. In order to use above code, we need to add camel namespace in the spring file. Part 2 – Implementing Camel routes (Camel timer component) Define all your routes within the camel context. Code snippet added below. <CamelContext id = "CamelContext" xmlns= <route id="route_email" startupOrder="1"> <from uri="timer://detectir?fixedRate=true&period=12h" /> <to uri="bean:emailService?method=sendEmail" /> </route> </CamelContext> Here we defined one route called ‘route_email’. This route uses camel timer component which runs at a fixed interval. Above route will run every 12 hours and invoke the method ‘sendEmail’ in ‘EmailService’ class. You need to define ‘EmailService’ class in the Spring xml. Code snippet given below. <bean id="emailService" class="com.cameltutor.email.EmailService" > <!-- Define properties for this bean if you have any --> </bean> package com.cameltutor.email; public class EmailService { public void sendEmail(){ // Implement email sending logic within this method } } Above description will give a head start to configure Apache Camel with Spring and enable Camel routes. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/implementing-apache-camel
CC-MAIN-2019-26
refinedweb
294
59.19
A site map is a list of a website's content designed to help both users and search engines navigate the site. A site map can be a hierarchical list of pages, an organization chart, or an XML document that provides instructions to search engine crawl bots. XML Sitemaps are important for SEO because they make it easier for Google to find your site's pages—this is important because Google ranks web PAGES, not just websites. There is no downside of having an XML Sitemap and having one can improve your SEO, so we highly recommend them. The sitemap for this blog can be found at . Create a file Create two different classes in sitemap.py file, one for static pages and another for Dynamic URLs. Let's assume your website sell some product where product details are stored in the database. Once a new product is added to the database, you want that product page to be searchable by search engines. We need to add all such product pages/URLs to sitemaps. Define a class StaticSitemap in your sitemap.py file. Define the mandatory function items in it which will return the list of objects. These objects will be passed to the location method which will create URL from these objects. from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse class StaticSitemap(Sitemap): def items(self): return [ 'myapp:terms_and_conditions', 'myapp:contact_us', 'myapp:about_us' ] def location(self, item): return reverse(item) Here in items function, we are returning appname:url_name which will be used by the location method to convert into an absolute URL. Refer you app's urls.py file for URL names. Similarly, we will create Dynamic sitemap by fetching values from DB. from mystore.models import ProductDetailsModel class ProductSitemap(Sitemap): def items(self): return ProductDetailsModel.objects.all() def location(self, item): return reverse('myapp:product', args=[item.product_id]) Here we are getting all products from the database and generating URLs like http:example.com/product/12. Now add these sitemap class in URLconf. Edit the project's urls.py file and add below code in it. from mystore.sitemap import StaticSitemap, ProductSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'pages': StaticSitemap, 'products': ProductSitemap, } urlpatterns += [ url(r'^sitemap.xml$', sitemap, {'sitemaps': sitemaps}) ] Now reload your server and go to localhost:8000/sitemap.xml and you will be able to see your sitemap there. Reference : Host your Django App for Free.
https://pythoncircle.com/post/686/how-to-create-sitemap-of-django-website/
CC-MAIN-2021-43
refinedweb
407
58.89
an joing tow files with inner join. I want all the fields from the first file and only two fields from the other file. I defined an external DS for the first file then included that DS in another DS with the two fields from the other file but program will no compile. Will not read the last DS in...Thanks! We'll email you when relevant content is added and updated. Fetch element using getElementsByTagName excluding the namespace I have an XML code which fetches a node from one xml and creates a new xml out of it. the code is as follows, parser = new DOMParser(); parser.parse(new StringReader(xml)); xmlSrcDoc = parser.getDocument(); xmldoc.setXmlVersion("1.0"); // new xml doc xmldoc.setEncoding("UTF-8");...
http://itknowledgeexchange.techtarget.com/itanswers/tag/fetch/
CC-MAIN-2014-15
refinedweb
126
67.04
. The essence of project hosting services is that you have the files associated with a project in the cloud. Many people may share these files. Every time you want to work on the project you explicitly update your version of the files, edit the files as you like, and synchronize the files with the "master version" in the cloud. It is a trivial operation to go back to a previous version of a file, corresponding to a certain point of time or labeled with a comment. You can also use tools to see what various people have done with the files throughout the history of the project. Greg Wilson's excellent Script for Introduction to Version Control provides a detailed motivation why you will benefit greatly from using version control systems. Here follows a shorter motivation and a quick overview of the basic concepts. The simplest services for hosting project files are Dropbox and Google Drive. It is very easy to get started with these systems, and they allow you to share files among laptops and mobile units with as many users as you want. The systems offer a kind of version control in that the files are stored frequently (several times per minute), and you can go back to previous versions for the last 30 days. However, it is challenging to find the right version from the past when there are so many of them and when the different versions are not annotated with sensible comments. Another deficiency of Dropbox and Google Drive is that they sync all your files in a folder, a feature you clearly do not want if there are many large files (simulation data, visualizations, movies, binaries from compilations, temporary scratch files, automatically generated copies) that can easily be regenerated. However, the most serious problem with Dropbox and Google Drive arises when several people edit files simultaneously: it can be difficult detect who did what when, roll back to previous versions, and to manually merge the edits when these are incompatible. Then one needs more sophisticated tools, which means a true version control system. The following text aims at providing you with the minimum information to started with Git, the leading version control system, combined with project hosting services for file storage. The mentioned services host all your files in a specific project in what is known as a repository, or repo for short. When a copy of the files are wanted on a certain computer, one clones the repository on that computer. This creates a local copy of the files. Now files can be edited, new ones can be added, and files can be deleted. These changes are then brought back to the repository. If users at different computers synchronize their files frequently with the repository, most modern version control systems will be able to merge changes in files that have been edited simultaneously on different computers. This is perhaps one of the most useful features of project hosting services. However, the merge functionality clearly works best for pure text files and less well for binary files, such as PDF files, MS Word or Excel documents, and OpenOffice documents. The installation of Git on various systems is described on the Git website under the Download section. Git involves compiled code so it is most convenient to download a precompiled binary version of the software on Windows, Mac and other Linux computers. On Ubuntu or any Debian-based system the relevant installation command is Terminal> sudo apt-get install git gitk git-doc This tutorial explains Git interaction through command-line applications in a terminal window. There are numerous graphical user interfaces to Git. Three examples are git-cola, TortoiseGit, and SourceTree. Make a file .gitconfig in your home directory with information on your full name, email address, your favorite text editor, and the name of an "excludes file" which defines the file types that Git should omit when bringing new directories under version control. Here is a simplified version of the author's .gitconfig file: [user] name = Hans Petter Langtangen email = hpl@simula.no editor = emacs [core] excludesfile = ~/.gitignore The excludesfile variable is important: it points to a file called .gitignore, which must list, using the Unix Shell Wildcard notation, the type of files that you do not need to have under version control, because they represent garbage or temporary information, or they can easily be regenerated from some other source files. A suggested .gitignore file looks like # compiled files: *.o *.so *.a # temporary files: *.bak *.swp *~ .*~ *.old tmp* .tmp* temp* .#* \#* # tex files: *.log *.dvi *.aux *.blg *.idx *.nav *.out *.toc *.snm *.vrb *.bbl *.ilg *.ind *.loe # eclipse files: *.cproject *.project # misc: .DS_Store You should be critical to what kind of files you really need a full history of. For example, you do not want to populate the repository with big graphics files of the type that can easily be regenerated by some program. The suggested .gitignore file above lists typical files that are not needed (usually because they are automatically generated by some program). In addition to a default .gitignore file in your home directory, it may be wise to have a .gitignore file tailored your repo in the root directory of the repo. Large data files, even when you want to version them, fill up your repo and should be taken care of through the special service Git Large File Storage. Go The ordinary GitHub URL of image files can be used in web pages to insert images from your repo, provided the image files are in the raw format - click the Raw button when viewing a file at github.com and use the corresponding URL in the img tag. Most Mac and Linux users prefer to work with Git via commands in a terminal window. Windows users may prefer a graphical user interface (GUI), and there are many options in this respect. There are also GUIs for Mac users. Here we concentrate on the efficient command-line interface to Git. You get started with your project on a new machine, or another user can get started with the project, by running Terminal> git clone git@github.com:user/My-Project.git Terminal> cd My-Project ls Recall to replace user by your real username and My-Project by the actual project name. The typical work flow with the "My Project" project starts with updating the local repository by going to the My-Project directory and writing Terminal> git pull origin master You may want to do git fetch and git merge instead of git pull as explained in the section Replacing pull by fetch and merge, especially if you work with branches. You can now edit files, make new files, and make new directories. New files and directories must be added with git add. There are also Git commands for deleting, renaming, and moving files. Typical examples on these Git commands are Terminal> git add file2.* dir1 dir2 # add files and directories Terminal> git rm file3 Terminal> git rm -r dir2 Terminal> git mv oldname newname Terminal> git mv oldname ../newdir When your chunk of work is ready, it is time to commit your changes (note the -am option): Terminal> git commit -am 'Description of changes.' If typos or errors enter the message, the git commit --amend command can be used to reformulate the message. Running git diff prior to git commit makes it easier to formulate descriptive commit messages since this command gives a listing of all the changes you have made to the files since the last commit or pull command. You may perform many commits (to keep track of small changes), before you push your changes to the global repository: Terminal> git push origin master It is recommended to pull, commit, and push frequently if the work takes place in several clones of the repo (i.e., there are many users or you work with the repo on different computers). Infrequent push and pull easily leads to merge problems (see the section Merging files with Git). Also remember that others (human and machines) cannot get your changes before they are pushed! You should run git status -s frequently to see the status of files: A for added, M for modified, R for renamed, and ?? for not being registered in the repo. Pay particular attention to the ?? files and examine if all of them are redundant or easily regenerated from other files - of not, run git add. .gitignorefile. The simplest way of adding files to the repo is to do Terminal> git add . The dot adds every file, and this is seldom what you want, since your directories frequently contain large redundant files or files that can easily be regenerated. You therefore need a .gitignore file, see the section Configuring Git, either in your home directory or in the root directory of the repo. The .gitignore file will ignore undesired files when you do git add .. A nice graphical tool allows you to view all changes, or just the latest ones: Terminal> gitk --all Terminal> gitk --since="2 weeks ago" You can also view changes to all files, some selected ones, or a subdirectory: Terminal> git log -p # all changes to all files Terminal> git log -p filename # changes to a specific file Terminal> git log --stat --summary # compact summary Terminal> git log --stat --summary subdir Adding --follow will print the history of file versions before the file got its present name. To show the author who is responsible for the last modification of each line in the file, use git blame: Terminal> git blame filename Terminal> git blame --since="1 week" filename A useful command to see the history of who did what, where individual edits of words are highlighted ( --word-diff), is git log -p --stat --word-diff filename Removed words appear in brackets and added words in curly braces. Looking for when a particular piece of text entered or left the file, say the text def myfunc, one can run Terminal> git log -p --word-diff --stat -S'def myfunc' filename This is useful to track down particular changes in the files to see when they occurred and who introduced them. One can also search for regular expressions instead of exact text: just replace -S by -G. Occasionally you need to go back to an earlier version of a file, e.g., a file called f.py. Start with viewing the history: Terminal> git log f.py Find a commit candidate from the list that you will compare the present version to, copy the commit hash (string like c7673487...), and run Terminal> git diff c7673487763ec2bb374758fb8e7efefa12f16dea f.py where the long string is the relevant commit hash. You can now view the differences between the most recent version and the one in the commit you picked (see the section Replacing pull by fetch and merge for how to configure the tools used by the git diff command). If you want to restore the old file, write Terminal> git checkout c7673487763ec2bb374758fb8e7efefa12f16dea f.py To go back to another version (the most recent one, for instance), find the commit hash with git log f.py, and do get checkout <commit hash> f.py. If f.py changed name from e.py at some point and you want e.py back, run git log --follow f.py to find the commit when e.py existed, and do a git checkout <commit hash> e.py. In case f.py no longer exists, run git log -- f.py to see its history before deletion. The last commit shown does not contain the file, so you need to check out the next last to retrieve the latest version of a deleted file. Often you just need to view the old file, not replace the current one by the old one, and then git show is handy. Unfortunately, it requires the full path from the root git directory: Terminal> git show \ c7673487763ec2bb374758fb8e7efefa12f16dea:dir1/dir2/f.py Run git log on some file and find the commit hash of the date or message when want to go back to. Run git checkout <commit hash> to change all files to this state. The problem of going back to the most recent state is that git log has no newer commits than the one you checked out. The trick is to say git checkout master to set all files to most recent version again. If you want to reset all files to an old version and commit this state as the valid present state, you do Terminal> git checkout c7673487763ec2bb374758fb8e7efefa12f16dea . Terminal> git commit -am 'Resetting to ...' Note the period at the end of the first command (without it, you only get the possibility to look at old files, but the next commit is not affected). Sometimes accidents with many files happen and you want to go back to the last commit. Find the hash of the last commit and do Terminal> git reset --hard c867c487763ec2 This command destroys everything you have done since the last commit. To push it as the new state of the repo, do Terminal> git push origin HEAD --force The git pull command fetches new files from the repository and tries to perform an automatic merge if there are conflicts between the local files and the files in the repository. Alternatively, you may run git fetch and git merge to do the same thing as described in the section Replacing pull by fetch and merge. We shall now address what do to if the merge goes wrong, which occasionally happens. Git will write a message in the terminal window if the merge is unsuccessful for one or more files. These files will have to be edited manually. Merge markers of the type >>>>>, ======, and <<<<< have been inserted by Git to mark sections of a file where the version in the repository differ from the local version. You must decide which lines that are to appear in the final, merged version. When done, perform git commit and the conflicts are resolved. Graphical merge tools may ease the process of merging text files. You can run git mergetool --tool=meld to open the merge tool meld for every file that needs to be merged (or specify the name of a particular file). Other popular merge tools supported by Git are araxis, bc3, diffuse, ecmerge, emerge, gvimdiff, kdiff3, opendiff, p4merge, tkdiff, tortoisemerge, vimdiff, and xxdiff. Below is a Unix shell script illustrating how to make a global repository in Git, and how two users clone this repository and perform edits in parallel. There is one file myfile in the repository. #!/bin/sh # Demo script for exemplifying git and merge rm -rf tmp1 tmp2 tmp_repo # Clean up previous runs mkdir tmp_repo # Global repository for testing cd tmp_repo git --bare init --shared cd .. # Make a repo that can be pushed to tmp_repo mkdir _tmp cd _tmp cat > myfile <<EOF This is a little test file for exemplifying merge of files in different git directories. EOF git init git add . # Add all files not mentioned in ~/.gitignore git commit -am 'first commit' git push ../tmp_repo master cd .. rm -rf _tmp # Make a new hg repositories tmp1 and tmp2 (two users) git clone tmp_repo tmp1 git clone tmp_repo tmp2 # Change myfile in the directory tmp1 cd tmp1 # Edit myfile: insert a new second line perl -pi -e 's/a little\n/a little\ntmp1-add1\n/g' myfile # Register change in local repository git commit -am 'Inserted a new second line in myfile.' # Look at changes in this clone git log -p # or a more compact summary git log --stat --summary # or graphically #gitk # Register change in global repository tmp_repo git push origin master cd .. # Change myfile in the directory tmp2 "in parallel" cd tmp2 # Edit myfile: add a line at the end cat >> myfile <<EOF tmp2-add1 EOF # Register change locally git commit -am 'Added a new line at the end' # Register change globally git push origin master # Error message: global repository has changed, # we need to pull those changes to local repository first # and see if all files are compatible before we can update # our own changes to the global repository. # git writes #To /home/hpl/vc/scripting/manu/py/bitgit/src-bitgit/tmp_repo # ! [rejected] master -> master (non-fast-forward) #error: failed to push some refs to ... git pull origin master # git writes: #Auto-merging myfile #Merge made by recursive. # myfile | 1 + # 1 files changed, 1 insertions(+), 0 deletions(-) cat myfile # successful merge! git commit -am merge git push origin master cd .. # Perform new changes in parallel in tmp1 and tmp2, # this time causing hg merge to fail # Change myfile in the directory tmp1 cd tmp1 # Do it all right by pulling and updating first git pull origin master # Edit myfile: insert "just" in first line. perl -pi -e 's/a little/tmp1-add2 a little/g' myfile # Register change in local repository git commit -am 'Inserted "just" in first line.' # Register change in global repository tmp_repo git push origin master cd .. # Change myfile in the directory tmp2 "in parallel" cd tmp2 # Edit myfile: replace little by modest perl -pi -e 's/a little/a tmp2-replace1\ntmp2-add2\n/g' myfile # Register change locally git commit -am 'Replaced "little" by "modest"' # Register change globally git push origin master # Not possible: need to pull changes in the global repository git pull origin master # git writes #CONFLICT (content): Merge conflict in myfile #Automatic merge failed; fix conflicts and then commit the result. # we have to do a manual merge cat myfile echo 'Now you must edit myfile manually' You may run this file git_merge.sh named by sh -x git_merge.sh. At the end, the versions of myfile in the repository and the tmp2 directory are in conflict. Git tried to merge the two versions, but failed. Merge markers are left in tmp2/myfile: <<<<<<< HEAD This is a tmp2-replace1 tmp2-add2 ======= This is tmp1-add2 a little >>>>>>> ad9b9f631c4cc586ea951390d9415ac83bcc9c01 tmp1-add1 test file for exemplifying merge of files in different git directories. tmp2-add1 Launch a text editor and edit the file, or use git mergetool, so that the file becomes correct. Then run git commit -am merge to finalize the merge. Branching and stashing are nice features of Git that allow you to try out new things without affecting the stable version of your files. Usually, you extend and modify files quite often and perform a git commit every time you want to record the changes in your local repository. Imagine that you want to correct a set of errors in some files and push these corrections immediately. The problem is that such a push will also include the latest, yet unfinished files that you have committed. A better organization of your work would be to keep the latest, ongoing developments separate from the more official and stable version of the files. This is easily achieved by creating a separate branch where new developments takes place: Terminal> git branch newstuff # create new branch Terminal> git checkout newstuff Terminal> # extend and modify files... Terminal> git commit -am 'Modified ... Added a file on ...' Terminal> git checkout master # swith back to master Terminal> # correct errors Terminal> git push origin master Terminal> git checkout newstuff # switch to other branch Terminal> git merge master # keep branch up-to-date w/master Terminal> # continue development work... Terminal> git commit -am 'More modifications of ...' At some point, your developments in newstuff are mature enough to be incorporated in the master branch: Terminal> git checkout newstuff Terminal> git merge master # synchronize newstuff w/master Terminal> git checkout master Terminal> git merge newstuff # synchronize master w/newstuff You no longer need the newstuff branch and can delete it: Terminal> git branch -d newstuff This command deletes the branch locally. To also delete the branch in the remote repo, run Terminal> git push origin --delete newstuff You can learn more in an excellent introduction and demonstration of Git branching. It is not possible to switch branches unless you have committed the files in the current branch. If your work on some files is in a mess and you want to change to another branch or fix other files in the current branch, a "global" commit affecting all files might be immature. Then the git stash command is handy. It records the state of your files and sets you back to the state of the last commit in the current branch. With git stash apply you will update the files in this branch to the state when you did the last git stash. Let us explain a typical case. Suppose you have performed some extensive edits in some files and then you are suddenly interrupted. You need to fix some typos in some other files, commit the changes, and push. The problem is that many files are in an unfinished state - in hindsight you realize that those files should have been modified in a separate branch. It is not too late to create that branch! First run git stash to get the files back to the state they were at the last commit. Then run git stash branch newstuff to create a new branch newstuff containing the state of the files when you did the (last) git stash command. Stashing used this way is a convenient technique to move some immature edits after the last commit out in a new branch for further experimental work. You can get the stashed files back by git stash apply. It is possible to multiple git stash and git stash apply commands. However, it is easy to run into trouble with multiple stashes, especially if they occur in multiple branches, as it becomes difficult to recognize which stashes that belong to which branch. A good advice is therefore to do git stash only once to get back to a clean state and then move the unfinished messy files to a separate branch with git stash branch newstuff. The git pull command actually performs two steps that are sometimes advantageous to run separately. First, a get fetch is run to fetch new files from the repository, and thereafter a git merge command is run to merge the new files with your local version of the files. While git pull tries to do a lot and be smart in the merge, very often with success, the merge step may occasionally lead to trouble. That is why it is recommended to run a git merge separately, especially if you work with branches. To fetch files from your repository at GitHub, which usually has the nickname origin, you write Terminal> git fetch origin You now have the possibility to check out in detail what the differences are between the new files and local ones: Terminal> git diff origin/master This command produces comparisons of the files in the current local branch and the master branch at origin (the GitHub repo). In this way you can exactly see the differences between branches. It also gives you an overview of what others have done with the files. When you are ready to merge in the new files from the master branch of origin with the files in the current local branch, you say Terminal> git merge origin/master Especially when you work with multiple branches, as outlined in the section Git working style with branching and stashing, it is wise to first do a get fetch origin and then update each branch separately. The git fetch origin command will list the branches, e.g., * master gh-pages next After updating master as described, you can continue with another branch: Terminal> git checkout next Terminal> git diff origin/next Terminal> git merge origin/next Terminal> git checkout master git diffcommand The git diff command launches by default the Unix diff tool in the terminal window. Many users prefer to use other diff tools, and the desired one can be specified in your ~/.gitconfig file. However, a much recommended approach is to wrap a shell script around the call to the diff program, because git diff actually calls the diff program with a series of command-line arguments that will confuse diff programs that take the names of the two files to be compared as arguments. In ~/.gitconfig you specify a script to do the diff: [diff] external = ~/bin/git-diff-wrapper.sh It remains to write the git-diff-wrapper.sh script. The 2nd and 5th command-line arguments passed to this script are the name of the files to be compared in the diff. A typical script may therefore look like #!/bin/sh diff "$2" "$5" | less Here we use the standard (and quite primitive) Unix diff program, but we can replace diff by, e.g., diffuse, kdiff3, xxdiff, meld, pdiff, or others. With a Python script you can easily check for the extensions of the files and use different diff tools for different types of files, e.g., latexdiff for LaTeX files and pdiff for pure text files. Occasionally it becomes desirable to replace all files in the local repo with those in the repo at the file hosting service. One possibility is removing your repo and cloning again, or use the Git commands Terminal> git fetch --all Terminal> git reset --hard origin/master Say you have two branches, A and B, and want to merge a file f.txt in A with the latest version in B. To merge this single file, go to the directory where f.txt resides and do Terminal> git checkout A Terminal> git checkout --patch B f.txt If f.txt is not present in branch A, and if you want to include more files, drop the --patch option and specify files with full path relative to the root in the repo: Terminal> git checkout A Terminal> git checkout B doc/f.txt src/files/g.py Now, f.txt and g.py from branch B will be included in branch A as well. In small collaboration teams it is natural that everyone has push access to the repo. On GitHub this is known as the Shared Repository Model. As teams grow larger, there will usually be a few people in charge who should approve changes to the files. Ordinary team members will in this case not clone a repo and push changes, but instead fork the repo and send pull requests, which constitutes the Fork and Pull Model. Say you want to fork the repo. The first step is to press the Fork button on the project page for the somebody/proj1 project on GitHub. This action creates a new repo proj1, known as the forked repo, on your GitHub account. Clone the fork as you clone any repo: Terminal> git clone When you do git push origin master, you update your fork. However, the original repo is usually under development too, and you need to pull from that one to stay up to date. A git pull origin master pulls from origin which is your fork. To pull from the original repo, you create a name upstream, either by Terminal> git remote add upstream \ if you cloned with such an https address, or by Terminal> git remote add upstream \ git@github.com:somebody/proj1.git if you cloned with a git@github.com (SSH) address. Doing a git pull upstream master would seem to be the command for pulling the most recent files in the original repo. However, it is not recommended to update the forked repo's files this way because heavy development of the sombody/proj1 project may lead to serious merge problems. It is much better to replace the pull by a separate fetch and merge. The typical workflow is Terminal> git fetch upstream # get new version of files Terminal> git merge upstream/master # merge with yours Terminal> # Your files are up to date - ready for editing Terminal> git commit -am 'Description...' Terminal> git push origin master # store changes in your fork At some point you would like to push your changes back to the original repo somebody/proj1. This is done by a pull request. Make sure you have selected the right branch on the project page of your forked project. Press the Pull Request button and fill out the form that pops up. Trusted people in the somebody/proj1 project will now review your changes and if they are approved, your files are merged into the original repo. If not, there are tools for keeping a dialog about how to proceed. Also in small teams where everyone has push access, the fork and pull request model is beneficial for reviewing files before the repo is actually updated with new contributions. An annoying feature of Git for beginners is the fact that if you clone a repo, you only get the master branch. There are seemingly no other branches: Terminal> git branch * master To see which branches that exist in the repo, type Terminal> git branch -a * master remotes/origin/HEAD -> origin/master remotes/origin/gh-pages remotes/origin/master remotes/origin/next If there is only one remote repo that you pull/push from/to, you can simply switch branch with git checkout the usual way: Terminal> git checkout gh-pages Terminal> git branch * gh-pages master Terminal> git checkout next Terminal> git branch gh-pages master * next You might need to do git fetch origin to see new branches made on other machines. When you have more than one remote, which is usually the case if you have forked a repo, see the section Team work with forking and pull requests, you must use do a checkout with specifying the remote branch you want: Terminal> git checkout -b gh-pages --track remote/gh-pages Terminal> git checkout -b next --track upstream/next Files can be edited, added, or removed as soon as you have done the local checkout. It is possible to write a little script that takes the output of git branch -a after a git clone command and automatically check out all branches via git checkout. Although the purpose of these notes is just to get the reader started with Git, it must be mentioned that there are advanced features of Git that have led to very powerful workflows with files and people, especially for software development. There is an official Git workflow model that outlines the basic principles, but it can be quite advanced for those with modest Git knowledge. A more detailed explanation of a recommended workflow for beginners is given in the developer instructions for the software package PETSc. This is highly suggested reading. The associated "quick summary" of Git commands for their workflow is also useful. git ls-files is the command: Terminal> git ls-files # list all tracked files Terminal> git ls-files -o # list non-tracked files Terminal> git ls-files myfile # prints myfile if it's tracked Terminal> git ls-files myfile --error-unmatch The latter command prints an error message if myfile is not tracked. See man git-ls-files for the many options this utility has. The command git gc can compress a git repository and should be run regularly on large repositories. Greater effect is achieved by git gc --aggressive --prune=all. You can measure the size of a repo before and after compression by git gc using du -s repodir, where repodir is the name of the root directory of the repository. Occasionally big or sensitive files are removed from the repo and you want to permanently remove these files from the revision history. This is achieved using git filter-branch. To remove a file or directory with path doc/src/mydoc relative to the root directory of the repo, go to this root directory, make sure all branches are checked out on your computer, and run Terminal> git filter-branch --index-filter \ 'git rm -r --cached --ignore-unmatch doc/src/mydoc' \ --prune-empty -- --all Terminal> rm -rf .git/refs/original/ Terminal> git reflog expire --expire=now --all Terminal> git gc --aggressive --prune=now Terminal> git push origin master --force # do this for each branch Terminal> git checkout somebranch Terminal> git push origin somebranch --force You must repeat the push command for each branch as indicated. If other users have created their own branches in this repo, they need to rebase, not merge, when updating the branches! Sometimes you accidentally remove files from a repo, either by git rm or a plain rm. You can get the files back as long as they are in the remote repo. In case of a plain rm command, run Terminal> git checkout `git ls-files` to restore all missing files in the current directory. In case of a git rm command, use git log --diff-filter=D --summary to find the commit hash corresponding to the last commit the files were in the repo. Restoring a file is then done by Terminal> git checkout <commit hash> filename Working.
http://hplgit.github.io/teamods/bitgit/Langtangen_github.html
CC-MAIN-2020-10
refinedweb
5,483
58.72
THE HARBINGER - 35By Luke The first sign - the first seal - the first horse? Thoughts on Matt 24, Rev 6 and the White Horse In recent time among friends there's been a fair amount of discussion presenting different views or interpretations on the possible identity of the White Horse of Rev 6 and it's rider. Over the years while studying the history of the first century church, the "evolution" of Christianity and David's writings about the history of the Church System, I began to formulate an alternative view. Although I don't hold to an absolute opinion on the subject I'm more inclined to believe and I personally feel there's more plausible evidence both scriptural and historical to be found in the following articles, as opposed to the more generally accepted views, that the White Horse of Rev 6 represents either the Antichrist, or Jesus Christ himself. Below there's also a "food for thought" article and youtube clip about Mitt Romney. "The Free Bible Society" - and Matthew 24:5 "As we look around Christendom today, we find many denominations and groups proclaiming their particular brand of Christianity to be the "one," way. Which one is correct? Because ancient Greek form was without punctuation, punctuation was later added by those who translated the original writings. This leaves the door to error open. But why do we have so many denominations today? The answer may just be found in Matthew 24:5. If we remove quotation marks from around the phrase, "I am the Christ;" the line takes on new meaning. Christ, then, may have been declaring that many will come and say that He is the Christ, and will lead many astray. This does not mean that they will lead people astray on purpose, but that they will lead them astray nonetheless. Hence, there would be many denominations, with many diametrically opposed to each other, or nearly so." The Free Bible Society This interpretation can be debated on many levels, among scholars and students alike, but History clearly speaks for itself. "Left Behind" - One of the biggest deceptions ever fostered upon the multitude of professing Christians, in these modern times, by the vast majority of Christian theologians and preachers, the many who will come in Jesus' name professing, Jesus is the Christ, is the false pretrib rapture doctrine. A deception that has totally hoodwinked the masses into a state of spiritual unpreparedness, to confront "a time of trouble" the Lord warned was to come, before His return at the end of the age. Left Behind however is just one, of a multitude a false doctrines, hitherto unknown to the original first century followers of Christ (the called out ones), now being promulgated by the vast and overwhelming majority of modern Christian theologians, preachers, missionaries and evangelist, of every church denomination, both Protestant and Catholic, the many who come in Jesus' name. For which modern Christianity bares little, if any resemblance at all, to the"faith that was once delivered unto the saints." And why now more than ever the Lord's followers during these last days, "should earnestly contend for that faith" without compromise. The same faith that lived in David Brandt Berg since the birth of The Family. (see and) In answering his disciples it may be that the Lord was not implying that many would come "in his name" saying that "they are Jesus or Christ", but that many Christian preachers, teachers and evangelist "would come in his name" claiming Jesus is the Christ. And these very same people, we so often hear today, from their pulpits, TV and radio shows, books and magazines, would be the very ones who would deceive many about the signs, and the - timing - of the Lord's return, such as the pre-trib rapture doctrine? The shoe seems to fit quite well. On another occasion Jesus said, "Many will say to me in that day, Lord, Lord, have we not prophesied in thy name? and in thy name have cast out devils? and in thy name done many wonderful works?" (Matt 7:22) But the Lord didn't commend them with a "Well done thou good and faithful servant." Jesus was clearly speaking to Christian leaders, preachers and evangelist, for only Christians do these wonderful works "in His name." (PLEASE NOTE:) I took the liberty to edit the articles below removing any doctrinal differences which I do not personally agree with, however, some of these same folks, in my opinion, do hit certain things spot on at times, even if I disagree with their eventual conclusions and many of their doctrines. These articles are very condensed for clarity. The Four Horsemen (Part Two): The White Horse by Richard T. Ritenbaugh "Now months—even years—for—or communicated—to men through the Word (John 1:118;—he goes out "conquering and to conquer." He is the one who commences— some white—without considering the mainly negative aspects of the other symbols. A bow is a purely offensive weapon, even more so than a sword, and is highly effective from long range. Thus, the foremost idea behind this biblical symbol is powerful, penetrating, deadly accuracy with an intimation of distance. In addition, whereas the sword symbolizes the Word of God (Ephesians 6:17; Hebrews 4:12)—His truth—the€”a truthâ€, was forced to flee to the relative safety of frontier lands and wilderness areas where its members could practice their biblical beliefs more freely. It was not until the age of the Protestant Reformation, when the power of the Catholic Church began to wane. Even so, Protestantism—its various denominations merely rebellious daughters of the Universal Church—has not been entirely sympathetic to the (another) gospel about the person of Jesus rather than proclaiming the true gospel of the Kingdom of God (Mark 1:15). In addition, as God maneuvers events in preparation for His Son's second coming, a great deal of prophetic speculation—which many call outright heresytime, prayer, and enduring to the end (Matthew 24:13; Luke 21:36; I Thessalonians 5:4-8; I Peter 3:10-18).. The White Horse – ―Many Shall Come in My Name…‖ BY DAVID C. PACK! Author’s Note: This booklet is part of a unique series covering the subject of the Four Horsemen of the Apocalypse..........., reflecting the sequence described in Revelation 6 and Matthew 24: The White Horse – ―Many Shall Come in My Name…‖ The Red Horse – ―You Shall Hear of Wars…‖ The Black Horse – ―There Shall Be Famines…‖ The Pale Horse – ―There Shall Be Pestilences…‖ Sometimes God chooses to use common experiences or activities as symbols or analogies in His Word. This is done to help human minds comprehend what is being described. God‘s‘s mane. As we begin the subject of the Revelation 6 horses (with horsemen), fix in your mind this animal‘s physical prowess. Bear in mind that for much of history, including the age of the writing of the New Testament, horses were man‘s preferred means of transportation—for rapid travel, communication and, in the case of armies, invasion and conquest. The horse and rider are virtually inseparable from a place within every picture of history. For the past 2,000 years, millions have sought to understand the socalled ―Four Horsemen of the Apocalypse‖ described in Revelation 6. Much written about, and seen in Hollywood films, none grasp their true significance. Religionists have crafted their own explanations, but have all ignored important clues in properly understanding what these symbolize.‘ prophecies have been accurate. Did He speak the truth to His disciples about events preceding His Return? But at this point, another question arises—and it is also big! Are the first four seals of Revelation still closed, or has Christ unsealed them? In other words, are they in effect today? Before continuing, something else must be grasped in order to set up the subject. Deception Everyone hates having been deceived—lied to—especially by those they have known and trusted. The reader has probably experienced this. In every case, it is painful and disillusioning. The shock of betrayal can shake one to the core of his being. For a moment, in your mind‘s. A Specific Counterfeit ―another Jesus‖ ―spiritual‖ and thoroughly organized. It appears to be wellestablished, with centuries-old ―roots‖ reaching back to the original apostles. To the undiscerning, this ―Jesus‖ and his teachings look, sound, feel and seem like the genuine article. But they are not the Christianity of the Bible—the one taught by the true Jesus Christ. We will see that this false religious system is a counterfeit of God‘s true Church! Almost immediately after Jesus founded His Church, Satan devised a counterfeit to keep the masses unaware of the message the true Church was proclaiming after Jesus‘ death. Satan‘s purpose has been to deceive mankind about God‘s truth, and he has done this through his counterfeit religious system, masquerading as genuine Christianity. Matthew 24 Reveals More Jesus foretold the confusion and misunderstanding that would surround this rider‘s identity! He disclosed events that would occur prior to His Second Coming. The first event is synonymous with the white horse. Answering His disciples‘ question pertaining to the sign of His coming and of the end of the age, Jesus first warned of religious deception in the sequence of what would occur. Let‘s read this all-important element of Jesus‘ Olivet Prophecy to now set a larger stage: ―Take heed that no man deceive you. For many shall come in My name, saying, I am Christ; and shall deceive many‖ (Matt. 24:4-5). Only after this did He proceed to mention war, famine and pestilence. The ―many‖ are the vast majority of thought-tobeChristian ministers who say that Jesus Christ is Christ (the Messiah), but who do not believe or teach what Christ taught, nor do they come with His authority. Later in the same chapter, Jesus expanded upon these verses: ―And many false prophets shall rise, and shall deceive many‖ (vs. 11). According to this and related prophecies, not only would false prophets arise to deceive the great majority, but they would also infiltrate the true Church, causing many of God‘s servants to fall away. Matthew 24 also mirrors the time sequence of the two riders of the white horses. The real Christ does not return (as shown in Revelation 19) until the time of the seventh and last trumpet (Matt. 24:27-31). The sequence of events in both accounts (Revelation 6 and Matthew 24)white‘‘s Return. (Realize that John did not record the Revelation until about 65 years after Jesus spoke to the apostles in Matthew 24. He would certainly not introduce things sealed that had already been unsealed long before!) So then, the absolute explosionof these things—these conditions—in the last days is such that Jesus is telling us (in Revelation 6 and Matthew 24) that the tremendous increase of these things is the opening of the seals! Warnings from the Apostles Before examining some history of this counterfeit Christian system, let‘s: ―Beloved, believe not every spirit, but try [test] the spirits whether they are of God: because many false prophets are gone out into the world‖ (I John 4:1). ―Beloved,‖ (Jude 3-4). Briefly referenced earlier, the apostle Paul‘s admonition to the Corinthians defines how effectively these early false teachers misled the unsuspecting: ―Buthim [or ‗put up with it‘]‖ (II Cor. 11:3-4). In verses 13-15, Paul singles out ministers who appear to represent the truth and the true Christ, but are actually led by ―another‖ spirit: ―.‖ Can you comprehend the gravity of this passage, viewed in an endtime context? Most do not recognize false ministers because they appear to be ministers of light—just as the ―god of this world‖ appears to be the true God. The devil is an effective counterfeiter! He counterfeits true ministers with false, true doctrines with false and the true God with the false god—himself! Peter added to Paul‘s warning with a similar one: ―There shall be false teachers among you, who privily [craftily, secretly] shall bring in damnable heresies…And many shall follow their pernicious ways‖ (II Pet. 2:1-2). Paul also warned that this condition will worsen at the end of the age: ―This know also, that in the last days perilous times shall come…evil men and seducers shall wax worse and worse, deceiving, and being deceived‖ (II Tim. 3:1, 13). Deceit is not new to planet Earth. But Paul warns of deceivers— ―seducers‖—growing worse ―in the last days‖! ―daughters‖), and there is simply no escaping directly identifying this system. Growth of Counterfeit Movement Parallels True Church: ―Christian churches had scarcely been gathered and organized, when here and there men rose up, who, not being contented with the simplicity and purity of that religion which the apostles taught, sought out new inventions, and fashioned religion according to their own liking‖ (Institutes of Ecclesiastical History, Ancient and Modern, Vol. 1). Author Jesse Hurlbut called this period after the time covered by the book of Acts ―The Age of Shadows.‖ He wrote, ―...of all periods in the [Church‘s] history, it is the one about which we know the least…For fifty years after St. Paul‘s‖ ―magician‖ or ―sorcerer‖)‘ successors were equally zealous in sowing the seeds of heresy to counter the true apostles‘ work. His followers included Menander, Nicholas, Cerinthus and Marcion.. Notice again in Matthew 24 that the many are deceived, not the few: ―For many shall come in My name, saying, I am Christ; and shall deceive many‖ (vs. 5). Both the ―manys‖ here—ministers and lay members—represent the overwhelming majority, as demonstrated by history. By the middle of the second century, the true followers of Christ were a small minority! The counterfeit movement openly denounced those who remained loyal to the teachings of the original apostles. Leaders such as John‘s successor, Polycarp, and Polycarp‘s disciple, Polycrates, were among the very few holding to the full truth in the Greco-Roman world. The Time of Constantine, ―By this sign you will conquer.‖ Constantine believed that the meaning of the letters was symbolic of Christ and therefore felt indebted to Christianity for his victory, despite being a devout sun-worshipper. One of Constantine‘s first acts as emperor was to issue the Edict of Toleration in AD 311. It legalized Christianity in the empire, ending 10 years of severe persecution against the true Church. However, the edict sped up false Christianity‘s ―persecuted‖ became the ―persecutors.‖ This counterfeit false church‘s goal had now been achieved, and it now vengefully pursued the true people of God., the true Church, among many others. 2000 Years of Deception and Error, Part 2A Constantine & Augustine Constantine ―Christian,‖ or they would not agree with his ―Christian‖‘s writings have formed a major belief system for both the Reformed Church and the Roman Catholic Church. Augustine justified Constantine‘s unscriptural marriage between church and state with the false doctrine he wrote in The Visible and Invisible Church. According to Augustine, the church could use violence to convert people or force people back to the church‘s thinking. He encouraged the idea that the church replaced Israel. He changed toam‘s. Romney and the White Horse Prophecy A close look at the roots of Romney's -- and the Mormon church's -- political ambitions / THE ROMNEY RISING - The White Horse Prophecy of MORMONISM Being Fulfilled? When Mitt Romney received his patriarchal blessing as a Michigan teenager, he was told that the Lord expected great things from him. All young Mormon men — the ―worthy males‖‘s founding 12 apostles—Mitt Romney had been singled out as a destined leader. From the time of his birth — March 13, 1947 — through adolescence and into manhood, the meshing of religion and politics was paramount in Mitt Romney‘s life. Called ―my miracle baby‖‘s side, attended strategy sessions with his father‘s political advisors, and interned at his father‘s office during all three of. ―If not Mitt, then who?‖ was the ubiquitous slogan within the elite organization. The pious world of BYU was expected to spawn the man who would lead the Mormons into the White House and fulfill the prophecies of the church‘s founder, Joseph Smith Jr., which Romney has avidly sought to realize. Romney avoids mentioning it, but Smith ran for president in 1844 as an independent commander in chief of an ―army of God‖ advocating the overthrow of the U.S. government in favor of a Mormon-ruled theocracy. Challenging Democrat James Polk and Whig Henry Clay, Smith prophesied that if the U.S. Congress did not accede to his demands that ―they shall be broken up as a government and God shall damn them.‖ Smith viewed capturing the presidency as part of the mission of the church. He had predicted the emergence of ―the one Mighty and Strong‖ — a leader who would ―set in order the house of God‖ — and became the first of many prominent Mormon men to claim the mantle. Smith‘s insertion of religion into politics and his call for a ―theodemocracy where God and people hold the power to conduct the affairs of men in righteous matters‖ created a sensation and drew hostility from the outside world. But his candidacy was cut short when he was shot to death by an anti-Mormon vigilante mob. Out of Smith‘s national political ambitions grew what would become known in Mormon circles as the ―White Horse Prophecy‖ — a belief ingrained in Mormon culture and passed down through generations by church leaders that the day would come when the U.S. Constitution would ―hang like a thread as fine as a silk fiber‖ and the Mormon priesthood would save it. Romney is the product of this culture. At BYU, he was idolized by fellow students and referred to, only half jokingly, as the ―One Mighty and Strong.‖ He was the ―alpha male‖ in the rarefied Cougar pack, according to Michael D. Moody, a BYU classmate and fellow member of the group. Composed almost exclusively of returned Mormon missionaries, the club members were known for their preppy blue blazers and enthusiastic athletic boosterism. Romney, who had been the assistant to the president of the French Mission where he was personally in charge of more than 200 missionaries, easily assumed a leadership position in the club.. They held monthly ―Fireside testimonies‖ —. Such regular testimonies encouraged the students to live devout lives and to resist the encroaching outside influences overtaking the nation at large. ―It helps them cope with such external pressures as evolutionteaching professors and cranky anthropologists who expect answers that conflict with LDS teachings,‖ according to James Coates, author of ―In Mormon Circles.‖ They traditionally hosted frat-like parties (Greek fraternities were banned from the campus) to raise a few thousand dollars for the college‘s sports teams. But Cougar president Romney drove the young men to aim higher, orchestrating a telethon that raised a stunning million dollars. Romney‘s position as head of the club was widely seen as a calculated steppingstone for a career in national politics. So it seemed disingenuous to his former club mates when, in a 2006 magazine interview, Romney denied his longtime political aspirations. ―I have to admit I did not think I was going to be in politics,‖ he told the American Spectator. ―Had I thought politics was in my future, I would not have chosen Massachusetts as the state of my residence. I would have stayed in Michigan where my Dad‘s name was golden.‖ Michael Moody says political success was an institutional value of the LDS church. ―The instructions in my [patriarchal] blessing, which I believed came directly from Jesus, motivated me to seek a career in government and politics,‖ he wrote in his 2008 book. Moody recently said that he ran for governor of Nevada in 1982 because he felt he had been divinely directed to ―expand our kingdom‖ and help Romney ―lead the world into the Millennium. Once a firm believer but now a church critic, Moody was indoctrinated with the White Horse Prophecy. Like Romney, Moody is a seventh-generation Mormon, steeped in the same intellectual and theological milieu. ―We were taught that America is the Promised Land,‖ he said in an interview.‖The Mormons are the Chosen People. And the time is now for a Mormon leader to usher in the second coming of Christ and install the political Kingdom of God in Washington, D.C.‖ In this scenario, Romney‘s candidacy is part of the eternal plan and the candidate himself is fulfilling the destiny begun in what the church calls the ―pre-existence.‖ Several prominent Mormons, including conservative talk-show host Glenn Beck, have alluded to this apocalyptic prophecy. The controversial myth is not an official church doctrine, but it has also arisen in the national dialogue with the presidential candidacies of Mormons George Romney, Sen. Orrin Hatch, R-Utah, and now Mitt Romney. ―I don‘t think the White Horse Prophecy is fair to bring up at all,‖ Mitt Romney told the Salt Lake Tribune when he was asked about it during his 2008 presidential bid. ―It‘s been rejected by every church leader that has talked about it. It has nothing to do with anything.‖ Pundits and scholars, rabbis and bloggers, have repeatedly posed the question during Romney‘s run: Is a candidate‘s religion relevant? With a startling 50 percent increase ofrecently polled American voters claiming to know little or nothing about Mormonism, another 32 percent rejecting Mormonism as a Christian faith, a whopping 42 percent saying they would feel ―somewhat or very uncomfortable‖ with a Mormon president, and a widespread sense that the religion is a cult, the issue is clearly more complicated than religious bigotry alone. Judging from poll results, Americans seem less prejudiced against a candidate‘s faith than concerned about the unknown, apprehensive about any kind of fanaticism, and generally uneasy about a religion that is neither mainstream Judaic nor Christian. Just as the Christian fundamentalism of former GOP candidates Michele Bachmann and Rick Perry informed their political ideology — and was therefore considered fair gamein the national dialogue — so too does Mormonism define not only Mitt Romney‘s character, but what kind of president he would be and what impulses would drive him in both domestic and foreign policy. Romney‘s religion is not a sideline, but a crucial element in understanding the man, the mission and the candidacy. He is the quintessential Mormon who embodies all of the basic elements of the homegrown American religion that is among the fastest growing religions in the world. Like his father before him, Romney has charted a course from missionary to businessman, from church bishop to politician — and to presidential candidate. The influence that Mormonism has had on him has dominated every step of the way. The seeds of Romney‘s unique brand of conservatism, often regarded with intense suspicion by most non-Mormon conservatives, were sown in the secretive, acquisitive, patriarchal, authoritarian religious empire run by ―quorums‖ of men under an umbrella consortium called the General Authorities. A creed unlike any other in the United States, from its inception Mormonism encouraged material prosperity and abundance as a measure of holy worth, and its strict system of tithing 10 percent of individual wealth has made the church one of the world‘s richest institutions. A multibillion-dollar business empire that includes agribusiness, mining, insurance, electronic and print media, manufacturing, movie production, commercial real estate, defense multinational percent of his personal fortune, is among the church‘s wealthiest members. And like his father, grandfather and greatgrandfathers before him, Mitt Romney was groomed for a prominent position in the church, which he manifested first as a missionary, then as a bishop, and then as a stake president, becoming the highestranking Mormon leader in Boston — the equivalent of a cardinal of the Roman Catholic Church. Called a ―militant millennial movement‖ by renowned Mormon historian David L. Bigler, Mormonism‘s. So it is not the LDS cosmology that is relevant to Romney‘s candidacy, but whether devout 21stcentury Mormons like Romney believe that the American presidency is also a theological position. Since his first campaign in 2008, Romney has attempted to keep debate about his religion out of the political discourse. The issue is not whether there is a religious test for political office; the Constitution prohibits it. Instead, the question is whether, past all of the flip-flops on virtually every policy, he has an underlying religious conception of the presidency and the American government. At the recent GOP presidential debate in Florida, Romney professed that the Declaration of Independence is a theological document, not specific to the rebellious 13 colonies, but establishing a covenant ―between God and man.‖ Which would suggest that Mitt Romney views the American presidency as a theological office. eoa Published on Feb 27, 2012 Thoughts on Matt 24, Rev 6 and the White Horse By Luke
https://issuu.com/audioactivated/docs/the_harbinger_35
CC-MAIN-2017-43
refinedweb
4,192
58.32
A Beginner’s Guide to Styled Components in React 💅 Styled-components allows us to create a normal React component that has styles bound to it. There are many benefits to implementing styled-components in your React app: - CSS becomes easier to maintain and update when you no longer have to search through multiple files and folders to find the styling for a particular element. - Allows for dynamic rendering of elements based on a component’s props. - It makes removing CSS easier because you don’t have to worry about other elements using the same className. - Styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically. You only need one line in your terminal to get things up and running! To install styled-components with npm, simply run: Or, if you’re using a package manager like yarn: The docs also highly recommend adding styled-components to the ‘resolutions’ field in your package.json if you’re using yarn. Once you’ve got everything installed, it’s time to get to styling. Here we’re creating a component, Title, that will render a styled <h1> element. ** Don’t forget to import styled from 'styled-components' at the top of your component! Easy, right? With styled-components we can style any html element: divs, sections, buttons, anything! Styled-components gets even more fun and interesting to use when an element’s style changes based on its props. Another great thing about styled-components is the ability to extend one component’s style to another. Here we have a styled div Block whose CSS is extended to RedBlock with one small change. So there you have it! A beginner’s guide to React styled-components!
https://leahschlackman.medium.com/a-beginners-guide-to-styled-components-in-react-88e3ecefbde2?source=---------0----------------------------
CC-MAIN-2021-21
refinedweb
293
55.34
C has a very weak form of data encapsulation that is provided via the generic void * pointer and the ability to declare that a struct is local to a file. Suppose I want to declare a Stack data type in C and I want to hide its implementation, including its data structures, from users. I can do this by first defining a public file called Stack.h that contains my generic Stack data type and the functions that the stack data type supports: Stack.h: typedef void * Stack; Stack stack_new(int size); void stack_free(Stack s); void stack_push(Stack s, int value); int stack_pop(Stack s);Note that I have prefaced all my function names with the "stack_" prefix so that I can avoid name conflicts with user selected names. C++ and Java have ways to avoid these name conflicts and they will be discussed later. Next I create my stack.c file that contains the implementation for my stack data type: #include "stack.h" #include <stdlib.h> typedef struct { int size; int *data; int top; } myStack; Stack stack_new(int size) { myStack *newStack = (myStack *)malloc(sizeof(myStack)); newStack->size = size; newStack->data = (int *)malloc(sizeof(int) * size); newStack->top = 0; return (Stack)newStack; /* cast myStack to a (void *) */ } void stack_push(Stack s, int value) { myStack *stack = (myStack *)s; if (stack->top == stack->size) return; /* should really do error handling */ stack->data[stack->top] = value; stack->top++; } ...Since myStack is declared locally and is not declared extern in the stack.h file, its scope is limited to stack.c. Hence only the functions in stack.c can manipulate the myStack data structure. The user is handed a (void *) which effectively hides a stack's implementation because there is no way for the user to cast the (void *) to a myStack. Whenever the user wants to manipulate the stack the user passes a (void *) to the appropriate stack function. The stack function can cast this (void *) to a myStack struct and manipulate the stack in any way it wishes. This form of data encapsulation using void *'s is fairly kludgy but it does allow several files to share their implementation, as long as each file declares its local data structures in exactly the same way. For example, I could spread the stack implementation over two files by declaring a myStack struct locally in both files. The obvious drawback to this approach is that instead of having one central declaration for the stack's data structures I have one declaration per file, which makes it much more difficult and error-prone to change the data structures. A positive aspect of the void * implementation is that you can hand a binary implementation to a third party without divulging any proprietary implementation knowledge because the third party will only see the void * in the .h file. Hence the third party will not even know what data structures you are using. The public, protected, and private accessors in C++ provide a way to control access to the implementation of a class. Unfortunately, these accessors are "all" or "nothing" accessors, they either let everyone access the implementation or only subclasses to access the implementation. They do not provide a way to say "let classes A, B, and C have access to each other's implementation, but exclude everyone else." C++'s developers partially address this problem by providing the friend keyword. A class can declare that other classes are its friends, which allow the other classes to examine the protected and private instance variables of the class. For example: class ListNode { friend class List; ... };This declaration gives any method in List the ability to examine any variable in ListNode and to call any method in ListNode, regardless of whether or not the access protection is public. Friendship has a number of klunky disadvantages. First it is not two way. When you declare List to be ListNode's friend, ListNode does not become a friend of List. List must explicitly declare ListNode to be a friend before the friendship becomes two way. Second, subclasses do not inherit a superclass's friendship status. For example, suppose you have the following subclass declaration: class DList : public List { ... }DList is not considered a friend of ListNode, despite the fact that it is a subclass of a friend of ListNode. These restrictions are incredibly annoying and really limit the effectiveness of friends in C++. First, if you want classes A, B, and C to share their implementation, you must ensure that all the classes mutually refer to each other as friends. Second, if you want their subclasses to also be friends, which invariably you do, then you have to make sure that the subclasses mutually refer to each other as friends. In general, if you want n classes to be friends, you will need n(n-1) friend declarations. In addition, if you add a new class to the system that should be included amongst the friends, then you must remember to add 2n more friend declarations. What a mess! The second module-related concept in C++ is that of namespace's. The namespace keyword allows a programmer to specify that a certain set of variables, functions, and classes belong to the same library or "module". For example, a programmer might write: namespace ibm { class Stack { ... }; class List { ... }; class ListNode { ... }; class Consult { ... }; ... } namespace apple { class Stack { ... }; class List { ... }; class ListNode { ... }; class Cut { ... }; ... }Notice that the same set of names have been re-used, but since they are in two different namespaces, that is ok. There are three common ways to access members of a namespace: ibm::Stack *s = new ibm::Stack(); using ibm::Stack; Stack *s = new Stack(); using namespace ibm; Stack *s = new Stack(); If you import conflicting names into the same namespace it is problematic only if you try to use that name: using namespace ibm; using namespace apple; Consult *c = new Consult(); // ok--no name conflict Stack *s = new Stack(); // compiler error because of a name conflictNamespaces can span one or more files, so you can still place declarations in a .h file and definitions in a .cpp file. For example, to declare the methods for ibm's Stack class one could use any of the following three styles in an ibm.cpp file: C++ implements its standard template library using the std namespace. This library provides a number of pre-defined data structures, such as vectors and lists. Namespaces solve another of C's problems, which is that all variable, function, and class names end up in the same global name space. This common grouping can create problems when you combine third party software from two different vendors, who duplicate one or more names, as shown above. Unfortunately C++'s developers did not create true modules with the namespace keyword. Unlike Java's packages, C++'s namespaces do not provide a way to share implementation among members of the namespace. If ListNode and List are declared in the same namespace, they still cannot access one another's members without using the friend keyword. It would have been nice if they also added the concept of package-level access so that one could truly create modules in C++, but they didn't. As a result Java has a much more powerful module mechanism than C++. class ListNode { friend class List; ... }; class DList : public List { ... }then DList is not considered a friend of ListNode. This restriction is incredibly annoying and really limits the effectiveness of friends in C++
http://web.eecs.utk.edu/~bvz/teaching/cs365Sp17/notes/modules.html
CC-MAIN-2017-51
refinedweb
1,248
60.75
An advantage of using a headless CMS is that it allows you to have a single data source. You can use Contentful’s REST APIs to serve content to multiple devices, such as web, mobile, and IoT devices, or different tech stacks on the client side. Contentful is an integrated, API-first content platform that enables you to create and deliver engaging digital experiences quickly and efficiently. This article demonstrates how to set up a project on Contentful, create a space, add data, and publish this data. Then, it goes through how to pull the data and display it on your web app using Vue. Vue is a frontend framework that allows you to implement web applications while improving scalability quickly. It abstracts low-level functionalities, letting you manage and display data properly. It also allows you to reuse code using components, meaning you can reuse a user interface without repeating code. In this demo, you’ll use the Content Delivery API to get ecommerce data and display it within a reusable Vue component. Specifically, you’ll build an ecommerce store that allows you to select and display bags and add them to a cart. You can view the complete project code on GitHub. Getting started To get started, create your free Contentful account. When you sign up, you’ll automatically get your first space. You can think of a space as a project within Contentful. For this tutorial, you can either rename the space that was created automatically or create a new one. Next, create a content model and content type. Consult the beginner’s guide to Contentful for step-by-step instructions. Your content type needs a name that describes your collective data entries. Since this demo is an ecommerce store for bags, name the content type “Bags.” Next, create fields in your content model. For your bag store, you need three fields: Title, ImageUrl, and Description. Be sure that the imageUrl points to a valid image or else the display will not work properly. Click + AddField and add a new field. Now, click the Content tab and add some example entries using these fields. Make sure to publish each entry once you add it. For example, below is a listing for a brown messenger handbag, including a title, description, and URL. After a few entries have been added and published, you’ll be ready to pull your data from a RESTful API. Using Contentful’s Content Delivery API Contentful makes it possible to access your data using the Content Delivery API. This REST API allows you to access the data in your space through a single request. Contentful provides a GraphQL endpoint, but this demo will focus on the REST API. Now that you’ve added all your data to the dashboard, you can pull the data into your Vue application using the Content Delivery API. To proceed, make sure you have the following: Space ID — This is a unique ID associated with each space. Content Delivery API access token — This is a token used when interacting with the Content Delivery API. You can find both by clicking Settings in the top-right of the dashboard and selecting API Keys. Add the following endpoint on Postman, and it will return all our field entries:{SPACE_ID}/environments/master/entries?access_token={ACCESS_TOKEN} Your data is now returned from Contentful’s endpoint. Your next task is setting up your Vue code and pulling the data. Installing Vue CLI To initiate your Vue app, you need to install Vue CLI globally on your machine. If you already have it installed, you can skip this step. npm install -g @vue/cli Once it’s installed, you’ll use Vue CLI to initiate your project. Initiate a new project using this command in your terminal: vue create vue-ecommerce-site Within your terminal, you’ll have to manually select your preferred options for your project until the appropriate Vue boilerplate code is ready. Please select Vue 2, as that is what this tutorial is based upon. We suggest you deselect both Babel and Linter, as they can cause complications. Proceed with the installation. Once the installation is completed, you can navigate to your project’s folder: cd vue-ecommerce-site Now, let’s install vue-router. Please install the following version: npm i vue-router@3.5.4 Also, install axios. You’ll use this popular HTTP client to make your API request to Contentful: npm i axios Then, start the server: npm run serve It should fire up your project, and you should see this in the browser: Go into the components folder and create two new components called ContentfulComponent.vue and CartComponent.vue. ContentfulComponent.vue displays the list of bags, while CartComponent.vue will display our cart. Now, let’s make use of our vue-router. Create a router folder inside our src and within the router, we can now add index.js. Now, go into your main.js and import the router. Then, go into your App.vue file, which is automatically created in the boilerplate, and import the component for use. Do not remove the styling. Now, go into the ContentfulComponent.vue file and implement your data. First, declare the theBags array under data: Next, add a new function called getBags under methods: This pulls your data and assigns it to the theBags array you’ve declared earlier. You need to import axios using the following command: import axios from "axios"; Finally, to fully implement your business logic, you’ll add a mounted lifecycle that executes on load. Add this.getBags(); so it can trigger the function once the page loads. Within the <template>, you’ll loop over the theBags array and display its elements. Find the full code for the component below. Be sure to add your own space ID and Content Delivery API access token. You can also add the following styling: And here’s what this code looks like in action: Letting shoppers add items to their cart Next, you’ll create a cart feature for your online bag store. This lets your shoppers select the bags they need and add them to their cart. Return to your ContentfulComponent.vue file and add a new method under methods called addToCart. Add the code below to this method. With this code, you create a cart item in local storage, allowing your application to store the specific item you want to save to the cart. Then, to enhance user experience, you add an alert to notify users when they have successfully added an item to the cart. You also need to add a button to trigger this addToCart function. You’ll add this to the "indi__item" class under <template>: Here’s what your demo now looks like: Creating the cart component Now that you’ve added the option to add an item to the cart, you need to give shoppers access to view their carts. So, it’s time to create a cart component that displays all the items in a shopper’s cart. This component will loop through the cart’s local storage and display the cart list. Plus, users can remove individual items they don’t want from their cart. To build the cart component, add a script tag, where you’ll add an empty cart array into data. Next, add a method that gets your cart from the local storage and assigns it to the cart array above: Then, add a beforeMount lifecycle to trigger the getCart method on load. The final method you need to add is the removeFromCart method, which allows you to remove a particular item from the cart array in the local storage. It receives the imageUrl from the item and uses findIndex() to return the index of that specific item in the array. Then, it uses that index to remove the item from the array using splice() and saves the updated array in the local storage cart item. Your template now looks like this: This code loops through the cart array and displays individual items. For each item, there is a button that can be used to remove the item by firing removeFromCart. Here’s the full component code: And, here’s your cart: Wrapping up Using a bag ecommerce store as an example, this tutorial explored how to add data to Contentful and display it in a Vue application. You can find all the relevant code in this repo on GitHub. A key advantage of building an Vue app using Contentful is that you’ll be working alongside an active community of avid users. So, if you come across any challenges, you can join the Contentful Community to seek help from fellow developers. To expand on everything you’ve learned in this tutorial, start building with Contentful for free today — no credit card required.
https://www.contentful.com/blog/2022/08/18/vue-tutorial/
CC-MAIN-2022-40
refinedweb
1,475
64
# An Easy Way to Make Money on Bug Bounty ![Рисунок 2](https://habrastorage.org/r/w1560/getpro/habr/post_images/f93/d5b/c8c/f93d5bc8c06339907e9dfc5d56508be8.png) Surely you've heard the expression «bug hunting» many times. I dare to assume, you won't mind earning one or two hundred (or even thousand) dollars by finding a potential vulnerability in someone's program. In this article, I'll tell you about a trick that will help analyzing open source projects in order to find such vulnerabilities. Bug Bounties on Free and Open Source Software — what is it? ----------------------------------------------------------- Bug Bounty is a common name for various programs, where website and software developers offer cash rewards for finding bugs and vulnerabilities. In addition to well-known Bug Bounty programs from such large corporations, as Apple or Microsoft, there are also programs for searching vulnerabilities in open source projects. Many of them can be found on HackerOne, but perhaps the largest is FOSSA — Free and Open Source Software Audit. It's a program on searching vulnerabilities in various open source projects, sponsored by the European Union. The total prize fund is an impressive sum — as much as 850,000 euros! How to take part? ----------------- First, you need to register on [HackerOne](https://www.hackerone.com/). We'll need only open source projects. There is a [whole list](https://hackerone.com/directory?asset_type=SOURCE_CODE&order_direction=DESC&order_field=started_accepting_at) on HackerOne. If you'd like to take part in Bug Bounty from the European Union, the list of projects, participating in this program, can be found [here](https://juliareda.eu/2018/12/eu-fossa-bug-bounties/). For most projects, it will be enough to be registered on HackerOne, but many of listed programs are also on the intigriti.com website. To participate, you have to choose an appropriate project for yourself and then carefully read the terms of participation. If you agree with them, go to a practical part. To find a vulnerability and get your money, you'll just need to download a project (or clone it from GitHub) and thoughtfully analyze each code line, examining each expression for potential errors. If you find something, that can affect program security — make a report and send to developers. If they rate your finding as worthy to be rewarded — you have your money in your pocket :). But where is the simplicity? ---------------------------- The simple part is that you don't have to analyze the code only manually. There are tools that let you search for errors in code automatically. For example — static code analyzers. I prefer using our tool — [PVS-Studio](https://www.viva64.com/en/pvs-studio/). PVS-Studio analyzer is able to find errors in code, written in C++, C# and Java, as well as has a user-friendly interface. In addition, there are several options of its free usage. Anyway, there are other various [code analyzers](https://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis). Of course, static analyzers can reveal not all errors. Never mind! After all, we have a purpose to find errors quickly and easily, and not to find them all. Once the project is downloaded and built, it will take only a couple of clicks to start the analysis. The result will be a report with some (usually considerable) number of warnings generated by the analyzer. In PVS-Studio, they are classified into three levels of certainty. You should start with the first level of warnings, so the orange and yellow levels can be weeded out from the analysis result. ![Рисунок 1](https://habrastorage.org/r/w1560/getpro/habr/post_images/266/5fd/fa9/2665fdfa9ca9485ead28643cdbe068d9.png) An example of filtering the results of the analysis. Thus, you'll only need to look though the rest warnings and choose the places that may pose the greatest danger. It is worth checking whether it is possible to reproduce any of them directly when running the program. If you manage to do it — it will not only increase the chances that developers will accept the report, but also certainly increase the amount of payment. In this case, visibility is your best friend. It's also worth considering whether the bug you found affects the security of the program. After all, in this case, the amount paid to you will be several times more :) The screenshot shows the Visual Studio interface. However, don't let it mislead you. The analyzer can be used not only as a plugin for Visual Studio, but also on its own, including the [Linux and macOS](https://www.viva64.com/en/m/0036/) environments. Pros of this Approach --------------------- First, using a static analyzer is one of the easiest ways to find bugs. You don't have to have any special knowledge to use code analyzers: you just need to understand the language in which the code is written. Secondly, analyzers are attentive. They don't get tired and don't lose their vigilance, unlike a human being. Therefore, they can be used to analyze as large code bases as you like with almost minimal cost. Third, analyzers often have more knowledge than humans. What does it mean? Let me explain my thoughts with the example from the Android kernel code: ``` static void FwdLockGlue_InitializeRoundKeys() { unsigned char keyEncryptionKey[KEY_SIZE]; .... memset(keyEncryptionKey, 0, KEY_SIZE); // Zero out key data. } ``` It would seem, where's an error here? It turns out, that a compiler, seeing that an array isn't used anywhere else, can optimize the code and remove the call of the *memset* function from it. And it'll do it only when building the release configuration. Everything would be fine, but only the encription key will remain in the RAM uncleared for some time, this way it can be obtained by an intruder. A real security breach! In addition, it can be hardly found by yourself: in the debugging mode the call of *memset* works fine. Tests also won't be of help… The only thing that remains is to be aware and remember about this feature yourself. What if the project developers don't know about this feature? What if you don't know about this feature when you search for bugs? As for the analyzer, it has the [V597](https://www.viva64.com/en/w/v597/) diagnostic, so you'll definitely find out about this feature when viewing the report. Finally, the fourth point. One of the most useful advantages of using static analysis when chasing for Bug Bounty is speed. It's true that you can check two, three, four project in one evening — but that's not all. The main thing is that you can be the first. While the award is offered for finding bugs in any project, the project continues to be refined and developed. Developers ship new releases and new features along with new code and new space for errors. When using the approach I've described, you'll be able to targetedly consider new errors and potential vulnerabilities in the very first day they're released. ![Рисунок 4](https://habrastorage.org/r/w1560/getpro/habr/post_images/c76/705/69c/c7670569cb98c751b48be3ddad9eb97e.png) Potential Vulnerabilities ------------------------- An attentive reader may be puzzled: *Wait, wait! On the one hand, you're saying about searching for errors in code in programs, on the other hand — you're mentioning potential vulnerabilities. Vulnerabilities are more interesting in terms of Bug Bounty. Please, clarify what you mean!* The fact of the matter is that errors and potential vulnerabilities are basically the same thing. Sure, only a few errors/potential vulnerabilities prove to be real vulnerabilities in further research. However, a harmless blunder and crucial vulnerability might look exactly the same in code. The article "[How Can PVS-Studio Help in the Detection of Vulnerabilities?](https://www.viva64.com/en/b/0514/)" gives several seemingly common bugs that are now known to be vulnerabilities. By the way, according to the report by National Institute of Standards and Technology (NIST), about 64% of vulnerabilities in applications relate to software errors, not issues directly related to security. So grasp the nettle, get PVS-Studio and start searching for errors and safety flaws! Classification according to the [CWE](https://www.viva64.com/en/cwe/) will be of great help here. Conclusion ---------- Hopefully, I helped a reader in his searching for that very bugs that will bring him honoring and monetary reward. I'm sure that static analysis will help in this! Remember that developers usually don't have time to analyze bugs in detail, so you'll have to prove that your finding can actually affect the program. The best way is to visually reproduce it. And remember: the more the bug destructs security — the more you'll get paid for it. Well, that's it. Good luck in searching for a reward!
https://habr.com/ru/post/464553/
null
null
1,460
56.96
Introducing the .NET MAUI Community Toolkit (Preview) The Community Toolkit team is excited to announce the first pre-release two new .NET Multi-platform App UI (.NET MAUI) Toolkits: As announced last month, these libraries are the evolution of the Xamarin Community Toolkits. They contain .NET MAUI Extensions, Advanced UI/UX Controls, Effects, and Behaviors to help make your life as a .NET MAUI developer easier. These features are contributed by you, our amazing .NET community, and maintained by a core set of maintainers (see “Focus On Community”, below). And – the best part – the features you add to the .NET MAUI Toolkit may one day be included into the official .NET MAUI library! We leverage the Community Toolkits to debut new features and work closely with the .NET MAUI engineering team to nominate features for promotion. What to Expect in .NET MAUI Toolkit The .NET MAUI Toolkit does not yet include all of the amazing community contributions from the Xamarin Community Toolkit. We are actvely porting them from Xamarin.Forms to .NET MAUI and they will be available in upcoming releases (see “Schedule”, below). The .NET MAUI Toolkit will not contain the MVVM features from Xamarin Community Toolkit, like AsyncCommand. Going forward, we will be adding all MVVM-specifc features to a new NuGet Package, CommunityToolkit.MVVM. What to Expect in .NET MAUI Markup Toolkit The .NET MAUI Markup Toolkit allows developers to continue architecting their apps using MVVM, Bindings, Resource Dictionaries, etc., without the need for XAML: - Fluent C# UI Extensions - Create your .NET MAUI UI in C# using MVVM (no XAML) The .NET MAUI Markup Toolkit contains all of the C# UI extension methods from the Xamarin Community Toolkit. Here are examples from my open-source HackerNews app: Docs We have teamed up with the Microsoft Docs team to find a new home for all of the Community Toolkit documentation. Stay tuned for future updates when we announce the new location of the Community Toolkit docs on docs.microsoft.com. Getting Started Both MauiCompat libraries are available as a NuGet package that can be added to any .NET 6 project targeting net6.0-ios and net6.0-android: - Open a .NET MAUI project in Visual Studio - In the Visual Studio Package Manager Console, enter the following command: Install-Package CommunityToolkit.Maui or Install-Package CommunityToolkit.Maui.Markup - To add the namespace to the toolkit: - In C#, add the following: using CommunityToolkit.Maui; or using CommunityToolkit.Maui.Markup; - In XAML, add the following: xmlns="" xmlns:behaviors="clr-namespace:CommunityToolkit.Maui.Behaviors;assembly=CommunityToolkit.Maui" xmlns:converters="clr-namespace:CommunityToolkit.Maui.Converters;assembly=CommunityToolkit.Maui" xmlns:effects="clr-namespace:CommunityToolkit.Maui.Effects;assembly=CommunityToolkit.Maui" xmlns:views="clr-namespace:CommunityToolkit.Maui.Views;assembly=CommunityToolkit.Maui" Focus on Community While these libraries are built in collaboration with the .NET team at Microsoft, it is truly a community effort. The core team, Andrei Misiukevich, Pedro Jesus, Gerald Versluis, Javier Suárez, and (myself) Brandon Minnick, are here mostly to move things forward. Your help and input is very much required. Whether that is through triaging issues, updating Docs, participating in discussions or adding actual code, we will need your help! Starting in November, following the first offical release (aka non pre-release) of .NET MAUI Community Toolkit, we encourage you to open Feature Requests and Proposals to add your favorite .NET MAUI extensions to the toolkit: Once your proposal has been approved, you will be welcome to submit a Pull Request adding your own feature to the toolkit! Schedule The .NET MAUI Community Toolkit will GA alongside .NET MAUI and .NET 6 in November 2021. Summary The .NET MAUI Community Toolkits are still a work in progress, but we wanted to share our progress with you today! As you begin your journey in .NET MAUI, try out the Toolkits, open proposals on our GitHub repositories, join the discussions and help us make the best Toolkits for the community! When can we expect a DataGrid for Maui from Microsoft? If you guys don’t already have an answer for this, someone is dropping the ball. I don’t think I’m alone when I say, I won’t adopt a new Microsoft platform until they release a DataGrid for it. And no, I won’t use Telerik, or any other 3rd party SDK EVEN IF IT’S FREE. The only way to find out if you are not alone in this is to see if there is already an issue on the .NET MAUI repository and if not; open one so we can gauge interest. We make all our decisions based on data that comes from a variety of sources. I can say with certainty it will not be part of the first release as we are working for parity with Xamarin.Forms, but there will definitely be new things in the future. For what it’s worth, the third-party controls are very good and I think that is also why there isn’t a big ask to add it as a first-class citizen. I would be very curious why you are so against the vendor controls. Third-party controls are great, until all of a sudden they’re not supported. Dunno how many times v.Next was released and it was like a vendor wasn’t even aware that new versions were possible. Another aspect is, if Microsoft isn’t shipping a DataGrid, generally speaking, the project isn’t ready for prime time. UWP is a perfect example. It was like they took Silverlight / WPF code, hired the a bunch of HTML hacks, smashed their heads with hammers, and then said, “We’d like you to do the worst port in the history of software.” Boom, UWP. As to Maui third party controls, what’s the link to the NuGet package for Telerik? What no link, I have to download it??? Whoa, and now’s there’s a registration form?????? I’ve already completely lost interest. Silverlight, WPF, and even UWP have a DataGrid. Is Microsoft strapped for cash? It should have been developed IN PARALLEL. The missing DataGrid is a dealbreaker for me too, for the same reasons as @Jack Bond mentions. IMO It’s a huge oversight, and a missing native Open Source DataGrid, will stop me from even trying out MAUI, because I know we will be needing it. Where did the ObservableObjectgo? It wasn’t exactly a big class, but we used it quite a lot because it’s just convenient. Very Good Hey Thomas! For the .NET MAUI Toolkit we have to reevaluate all the things we currently have, especially if they touch things that look like MVVM. Since we now work together with the other toolkit(s), we don’t want to have duplicate things. This preview release has a minimal set of things we managed to port already. That something is not in there doesn’t mean it won’t come. However, it also doesn’t mean that it will come. We might need to put it in a different place for things to make more sense. Of course our goal is to take nothing away from what you can currently use. Thanks for the explanation. I’m taking that as a hint to start using some MVVM library I suppose 🙂
https://devblogs.microsoft.com/dotnet/introducing-the-net-maui-community-toolkit-preview/
CC-MAIN-2022-27
refinedweb
1,217
66.94
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. perform particular action after 5 minutes Hello every one, Here i want perform a particular action, after 5 minutes. please let me know, is there any way to ahieve this? and i tried this import time import datetime print "Loop Started" while time.sleep(5) print "loop is running" Thanks in advance.... 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/perform-particular-action-after-5-minutes-53402
CC-MAIN-2017-51
refinedweb
107
58.89
Difference between revisions of "Draft Downgrade/cs" Revision as of 19:26, 17 February 2014 Popis Tento nástroj degraduje vybrané objekty různými způsoby. Není-li vybrán žádný objekt, budete vyzvání k výběru objektu. Použití - Select one or more objects you widh to downgrade - Press the Draft Downgrade button or press D then N keys Options The selected objects are modified Example Scripting The Downgrade tool can be used in python scripts and macros by using the following function: downgrade (objects [delete], [force]) - Downgrades the given object(s) (can be an object or a list of objects). - If delete is True, old objects are deleted. - The force attribute can be used to force a certain way of downgrading. It can be: explode, shapify, subtr, splitFaces, cut2, getWire, splitWires. - Returns a dictionnary containing two lists, a list of new objects and a list of objects to be deleted Example: import FreeCADGui,Draft selection = FreeCADGui.Selection.getSelection() Draft.downgrade(selection)
https://www.freecadweb.org/wiki/index.php?title=Draft_Downgrade/cs&diff=69009&oldid=69007
CC-MAIN-2019-47
refinedweb
157
50.06