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
Operations Management Archive: Questions from May 04, 2013 - 3 answers - A car rental agency uses 96 boxes of staples a year. The boxes cost $4 each. It costs $10 to order staples, and carrying costs are $0.80 per box on an annual basis. Determine: (A) the order quantity t1 answer - Susan Gilbert, a purchasing agent for Wisconsin Plastic Inc (WSI) is reviewing quotations from suppliers for a new plastic gear. Susan plans to either place an order for 12000 gears from a supplier wi1 answer - 3 answers - You are the manager of the Gander Mountain store in Frogtown, Illinois. Recently, a customer mentioned that they believed your prices for ammunition were lower than the prices of Gander's primary comp1 answer - Practical Application Scenario 2 Your love of golf has brought you back to the range as the new product manager for UniDun's "Straight Flight" (SF) line of golf balls. The company's research and deve1 answer - ) Who originally owned the rights to the computer Steve Wozniak made, and why did they not take advantage of it? 2) What was the first computer that Bill Gates and Paul Allen tried to write software2 answers - Type your question here Susan Gilbert, a purchasing agent for Wisconsin Plastic Inc (WSI) is reviewing quotations from suppliers for a new plastic gear. Susan plans to either place an order for 120001 answer - 1 answer - Should the applicants be selected primarily on the basis of their ability or personality or fit? How can fit be assessed?1 answer - In general, under what conditions might a firm favor a level production plan over a chase plan? A chase production plan over a level plan?1 answer - 2 answers - The harvest of cane sugar in Australia is highly mechanized. The sugar cane is immediately transported to a sugar house in wagons that run on a network of small rail tracks. The sugar content of a wag1 answer - 1) Define and discuss the advantages and disadvantages of functional and matrix structures.<?xml:namespace prefix = o 2) Define and discuss the1 answer - Harley Davidson sells motorcycle X and Y. Motorcycle X sells for $10,000, has variable cost (labor and material) of $2,000, and requires 10 hours of use of machinery to produce. Motorcycle Y sells for2 answers - Assume XYZ stock’s last dividend was $3. The dividend growth rate is expected to be constant at 5% for 3 years, after which dividends are expected to grow at a rate of 6% forever. XYZ’s1 answer - A large electronics superstore sells a popular handheld computer. The store presently manages its inventory of this item with the following process: When the number of computers in stock drops to 20,2 answers - 0 answers - Mars Inc. is considering the purchase of a new machine that will reduce manufacturing costs by $5,000 annually. Mars will use the MACRS accelerated method to depreciate the machine, and it expects to2 answers
https://www.chegg.com/homework-help/questions-and-answers/operations-management-archive-2013-may-04
CC-MAIN-2018-26
refinedweb
491
59.74
Anthony Liguori wrote:> Gregory Haskins wrote:>> We add a new virtio transport for accessing backends located on vbus. >> This>> complements the existing transports for virtio-pci, virtio-s390, and>> virtio-lguest that already exist.>>>> Signed-off-by: Gregory Haskins <ghaskins@novell.com>> > Very interesting...> > I'm somewhat confused by what you're advocating vbus as. I'm trying to> figure out how we converge vbus and virtio and become one big happy> family :-)> > What parts of it do you think are better than virtio?I see them as distinctly different, and complimentary: virtio isprimarily a device-interface. vbus is primarily a bus-model.While its true that vbus has a rudimentary "device interface" (aladev->call(), dev->shm(), etc), it will typically be layered with a morerobust device model (such as virtqueue based virtio-net, or IOQ basedvenet).This is akin to raw PCI. PCI has the basic mechanics (MMIO, PIO,interrupts, DMA), but generally devices overlay higher layer constructs(such as tx/rx rings for ethernet). vbus is similar in that regard.virtio, on the other hand, is a fully fleshed device model, but it needsto be paired up with some other bus-model (such as qemu+pci viavirtio-pci, or linux+vbus via virtio-vbus) to be complete.> Should we forget> about venet and just focus on virtio-net on top of virtio-vbus assuming> that we can prove venet-tap/virtio-vbus/virtio-net is just as good as> venet-tap/vbus/venet?I think going forward, I would love to see some community weight behindvirtio-vbus and the standardization of the virtio-X drivers (net, blk,console, etc) as the default core IO device model for vbus. If thatwere to happen, I would not be inclined to create any new native vbusdrivers for where there is overlap with virtio (net, disk, etc).I *will*, however, likely use the native vbus interfaces for some of thedevice models in the pipeline (such as the real-time controller, andOFED) because there isn't a virtio equivalent for that, and the vbusdevice model was written with them in mind.And regardless of the final outcome of virtio-vbus as a viable virtiotransport model, I will probably continue to support the native vbus"venet" protocol for AlacrityVM indefinitely only because I have peoplethat are using it today (AlacrityVM being one example, but others are inthe works), it is simple, and it works extremely well.> > If we can prove that an in-kernel virtio-net> backend/virtio-pci/virtio-net does just as well as> venet-tap/virtio-vbus/virtio-net does that mean that vbus is no longer> needed?vbus is primarily about the bus model and resource-containers. It istherefore so much more than just 802.x networking and/or KVM. So no,obtaining equal network performance with virtio-net sans vbus does notinvalidate vbus as a concept. It would perhaps purely be disincentivefor anyone to chose venet over virtio-net within a KVM guest who doesn'thave a vested interest in the venet ABI.> > If you concede that the transport mechanisms can be identical, are you> really advocating the discovering and configuration mechanisms in vbus?The problem is that they are not truly identical, and they cannot easilybe made identical.One of the design goals is to create a re-useable, in-kernel devicemodel with a thin-shim transport between the guest and the bus. Thetransport (called a "vbus-connector") in question must convey a verysmall verb namespace (devadd/drop, devopen/close, shmsignal, etc) to usethis bus. So you have a driver for this transport (e.g. vbus-pcibridge)but the bus-model itself, device-models, and guest drivers are all reusable.Another design goal is to create a high-performance, low-latency,software-to-software optimized IO subsystem. PCI was designed forsoftware-to-hardware, so it has assumptions about that environment thatsimply do not apply in software-to-software. Most of these limitationscan be worked-around with KVM surgery and/or creative guest development,but they are (at best) awkward to express in PCI.For example, creating a high-performance, synchronous, in-kernel "call"in PCI is fairly complicated, awkward, and requires a bit of per-deviceheap to pull off. Yet, I need this functionality for things like RTsupport (scheduler state changes, etc).As another example, the PCI model is somewhat resource rigid andtherefore awkward for creating dynamic software objects in response toguest actions on demand, such as IPC sockets, due to the way MSI works.As a third example, the PCI device model makes assumptions aboutsignal-path delivery (MSI to APIC) which may or may not be the optimalpath (e.g. see my priority+aggregation thread with Arnd).I am open to suggestions on ways to write the "connector" codedifferently. I am sure that some things could be addressed at adifferent layer (such as the conversation with Arnd regarding the PVinterrupt controller).I think, however, that the motivations to PCI'ize the x86-KVM world aredriven more by inertia (its already in qemu and many guests know it)than by intentional selection (its model is the best to express theneeds of virt). Therefore, I am trying to put a stake in the ground toredirect that inertia towards a path that I believe is more amenable tovirt in the long term. Consider it a long-term investment in the platform.My approach to date is more akin to how something like USB wasintroduced. The USB designers were not trying to artificially constraintheir design so that it looked like PCI just to avoid needing an OSdriver. They (presumably) designed a bus that best achieved theirgoals, and then people wrote adaption layers (ala PCI-to-USB bridges) tosupport them on the OS's/arches that cared. Eventually most did.I admit that, as with any new bus (e.g. USB), there will undoubtedly besome lumps during the initial roll-out phase since it is not yetuniversally supported. But the long term vision is that (assuming itsucceeds as a project) that eventually vbus would be ubiquitous (alaUSB) and it makes for a better bus-model choice for things likelinux-based hypervisors (pci-based kvm (x86/ppc), s390-kvm, lguest, UML,openvz, and even something like Xen-Dom0, etc), as well as applicationsand even some specialized physical systems (Blade systems, clusters, etc).> Is that what we should be focusing on? Do you care only about the host> mechanisms or do you also require the guest infrastructure to be present?I see it as a tightly integrated portion of the stack that sits rightbelow the virtio layer.> > I think two paravirtual I/O frameworks for KVM is a bad thing.So hopefully after reading my reply above you can see that I don't thinkthis is indeed what is being proposed.> It duplicates a ton of code and will very likely lead to user unhappiness.I totally agree and I hope we can work together to find a solution thatmakes the most sense and eliminates as much duplicate effort as possible.Kind Regards,-Greg[unhandled content-type:application/pgp-signature]
http://lkml.org/lkml/2009/8/10/221
CC-MAIN-2013-20
refinedweb
1,176
53.31
Hi, Each state has it's own laws about (1) who must file (2) whether you are a resident or not and based on that (3) whether you file a resident tax form and a non-resident (usually having the extent NR) from or not Also, as in the case of GA, you may not have earned ENOUGH (there's usually an exempion amount) to have to file Either way, you generally do the non-resoient state first and then there will be a CREDIT for taxes paid to other states on your resident tax form Let me see if I can find NC's definition of residency OK, here's what NC dep of revenue says ... let me give you this in two pieces: (1) You are considered a nonresident if you are legal resident of another state. A nonresident is required to report income received from services performed in North Carolina or from tangible property located in this state. (2). What they're prbaly trying to do isn put you in one of those two categories Now, let me give you one more piece from them (this is from here, by the way:) Part-year residents who receive income from sources in another state or country while they are North Carolina residents which is taxed by another state or country may be eligible to claim a tax credit. Nonresidents are not entitled to tax credits for taxes paid to another state or country. SO it may make more sense to argue that you are part year resident (IF YOU PAID SIGNIFICANT AMOUNT TO WV) so that you can get a credit for than on the return TO answer you question, you will need to file in both WV and NC (but again, may do best by filing as a PART YEAR in NC) . Now ... the last piece here is to assess your residency and need to file in WV Who Must FileFull-year residents of West Virginia must file a tax return, even if only to receive a refund, unless the following exception applies: Resident This is any person who meets the following requirements: here's an excellent resource for Figuring out the WV piece (remember NC says that the way THEY assess residency is BASED ON whether you are a resident of another state) ... whereas West Virgina provides a much more specific way: How does Ga assess residency? Just a sec ... also another area that may apply to that is did you earn enough in GA to have to file at all? ... let me check Really quickly" there are also some exclusion of person income for NC state income tax purposes ST & Loc Govt (in or out of state): 4,000 single, 8,000 jointly ... Federal Civil Service is the same .... Military is the same ... and they have what they call a private pension exclusion of 2000 single and 4000 marriedl filing jointly Now GA Lets start here: GA: However, for NON-RESIDENTS, which you are .. for GA purposes If you are a legal resident of another state, you are not required to file a Georgia income tax return if your only activity for financial gain or profit in Georgia consists of performing services in Georgia for an employer as an employee when the compensation for services performed does not exceed the lesser of five percent of the income received in all places during the taxable year or $5,000. The question was how does Ga assess residency" Whether ot not you are a legal resident of another state ... just showed you that (very much like NC) WV is the one that gives you numbers of says, etc sorry "days" from above "If you are a legal resident of another state, ..." How much did you earn in GA? The reason I ask was in Ga with intent to locate there perm. Was there 5 weeks. At this point, I'm fairly certain GA is the Di minimus issus ((very possibly no need to fle) Here's what is probably the most efficient way to handle this... But was I a legal resident in Ga. Get a 2009 copy of turbotax re- do (if you don't already have that) you federsl ... then (the way TT handles state taxes, is is simply flows everything to the state(s) return) IN waht way? you were at most a part-year resident This is very dificult. I was in Ga for 5 weeks with intent to locate there perm. Did this make me a Ga residenct. If so according to NC I am not a residenct. I never met there WV requirements. For tax filing purposes, you were a part year resident, further the personal exemption and standard is aorund $5000, so if you didn't have that much GA income .... Ahhh you said you were there 6 months 183 days makes you a resident for WV purposes All income is from pension, 401k, and SS. This all has to do with filing a return where you are require and then getting a credit from the states that provide on for taxes paid to other states each state has it's own (as they are all separate taxing authorities) definitions of who must file, who is resident vs part year vs non-resident as well as exemption for taxing pensions I think as I was about to type before yyour most efficient solution is the following: (hang with me a minute here) Thats what I am asking you to sort out for me. this is what a tax preparer would probably do for several hundred dollars ... I am working for a one time payment of $15 Now let me tell you what I think is your best. most cost effective solution .... I will pay you more. NC intents to assess me for full year Was only there for 5 months. (1) Get a 2009 copy of turbotax (2) do (or re-do) your federal return (3) do three states, beginning with Ga and ending up with the bstate where you think you are most likely to be a resident ... ... turbotax will automatically flow the federal information to each state return and the ask several follow-up questions about where the income was earned, etc then you'll have what you should have paid NC File that as your answer to NC Did you not pay any state taxes to WV either? Don't believe this will work because Congree passed a law that pension and 401k benefits are taxed in state of residence. again, apparently I'm not being clear .... were you or were you not present in WV for 183 days? No THen you should have paid to NC (with the exception of the 2000 exemption) It's the taxes paid to another state that keeps you from paying tax twice ... but you have to pay tax on that SOMEWHERE... now it sounds like you WERE a NC resident ... you said in your orog question that you were in WV for 6 monts Do I have to pay NC for full year even though I was only there for 5 months. Didn't get that for before, based on WV assumption ... maybe no, you may qualify as a PART YEAR resident give me another minute please OK, now we'r're back to here: FROM NC:. Part-year residents are required to report all income received while a resident as well as from services performed in North Carolina or from tangible property located in this state. Was the pension and 401(k) from employers in another state? It looks to me that they are saying that you only report the income that was received WHILE YOU WERE THERE ... Earned pension and 401k benefits inGa. but what about the federal law that says state is to be paid in state of residence. This very confusing. Again here's that link to the NC dept of revenue site ... as I said earlier, you should claim that you were only a part year resident I don't know what you're talking about Do you have a citation? the law probably does say that BUT you were not a resident for 7 out of 12 months you UNDER NCs laws ... and that is what is at issue here are a part-year resident No got that from one of your associates Megan What she gave you is correct ... HOWEVER< you were not a resident for 7 out of 5 months the dots completely connect here So hopefully NC will accept that I was only a resident for 5 months. Just want to make sure I'm good grounds in dealing with them. Thats how I responded to them. Waiting for a reply from them. Yep, Guess we are finished. just document well things like move-in dates (may a lease signed in the first month for trailer space?... along with documentation of costs paid to other states (hookup fees, etc) Thanks very much for your help. Will pay you a hundred. Whatever you do ... keep this: Not sure how that can work here ... maybe a bonus? do whatever you can ... also be sure to come back here for the links... they'll stay active Sorry you can rate now still with me? I still don't see you coming into the chat session, so I'll move us to the "Q&A" mode. … Maybe that will help … Thanks again Lane
http://www.justanswer.com/tax/83ftx-nc-send-notice-intent-access-2009-pension-401k.html
CC-MAIN-2015-32
refinedweb
1,578
75.84
Understanding the ADF Business Components State Management Feature This article contains advanced topics and it is assumed that reader has some experience and basic understanding of ADF Business Components (ADF BC). Contents Introduction State management is a set of features in the Oracle Application Development Framework (ADF) that preserves the state of pending changes in your application over a period of time. This is a very typical task for a large group of applications called stateful web applications. Stateful web applications preserve logical application state across several HTTP requests. Web applications that do not preserve this kind of information are referred to as stateless applications. In stateless applications that involve database transactions, a transaction gets started and terminated by commit or rollback within the scope of one request. The reason for this is the stateless nature of the HTTP protocol itself. If a web application requires a transaction spanning multiple HTTP requests, it is the application’s responsibility to preserve the pending changes to be made as part of the transaction and to keep it consistent between HTTP requests. In this article, when we say “pending changes” or “pending session state” we mean the ADF entity objects that have been created, updated, or removed during the current transaction but which haven't yet been permanently stored to the database by a post or commit operation.. Overview Review of Business Components Terminology An ADF BC middle tier application consists of one or more root Application Modules (AM). Each root AM correlates to a single database transaction. Each AM may contain instances of View Objects (VOs) and/or nested AMs (which always share the parent AM’s transaction). A VO’s attributes may be based on Entity Object (EO) attributes, be populated from a SQL-calculated expression (known as “SQL-derived”), or they can be calculated in Java and not correlate to a database at all (known as “transient”). By convention, if all attributes of a VO are transient then VO itself is called a transient VO. Review of HTTP Client to ADF BC Middle Tier Interaction Oracle ADF implements a MVC (Model – View – Controller) architecture. In this architecture the model is an abstraction level that separates client from middle tier business services. The client (known as the “View” in MVC) communicates with model layer through the controller, and the model layer relays the requests from client to the middle tier business services. The controller also relays the reply from the middle tier business services back to the model layer to that the View layer can display it to the client. In this way, the client layer is not dependent on the implementation details of your business services. Figure 1 shows schematically what is explained above. It is important to understand the interaction between an HTTP client (HttpSession) and the model layer. The ADFBindingFilter in the oracle.adf.model.servlet package is a servlet filter that intercepts all incoming requests from Web-based clients. On the first request the filter initializes the ADF data binding support classes. Among other things, during this bootstrap step it creates the BindingContext object and associates it with the HttpSession. There is one BindingContext object per HttpSession. HttpSession ADFBindingFilter oracle.adf.model.servlet BindingContext The BindingContext contains one or more Data Control and Binding Container objects. As its name implies, the Binding Container contains bindings, which are helper objects that abstract the details of “wiring” UI controls to business service data. These bindings interact with data provided and methods implemented by the Data Control in order to work with the model layer data. Each Data Control contains one ADF BC SessionCookie and uses it to checkout and release the underlying ApplicationModule instance that implements the business service’s functionality. That SessionCookie is used as an AM state identifier. An HttpSession can contain references to multiple Data Controls, but any given Data Control instance is always tied to one HttpSession. That is, the relationship between HttpSession and Data Controls is one to many. So in summary, the BindingContext is related to the HttpSession, and the Data Controls in the BindingContext use a SessionCookie to acquire and release an AM instance when they need to perform work. This SessionCookie is implemented by the oracle.jbo.http.HttpSessionCookieImpl class. SessionCookie oracle.jbo.http.HttpSessionCookieImpl Now that we have the structure in place, we may describe in short how it is functioning. When the ADFBindingFilter receives an HTTP request it fires beginRequest notifications on all Data Controls that are associated with that request's HttpSession (via the BindingContext). It then passes the request to the next filter/servlet in the processing chain. Once the processing chain is finished control is passed back to the ADFBindingFilter. The ADFBindingFilter then fires endRequest notifications on all of the Data Controls that are associated with the request's HttpSession. The ADF Business Components Data Control responds to the beginRequest notification by using the SessionCookie to acquire an ApplicationModule for the request. The ApplicationModule is therefore "pinned" to the Data Control for the duration of the request. The ADF BC Data Control responds to the endRequest notification by using the SessionCookie to release the request ApplicationModule. This article will discuss in depth the technologies provided that enable that release while still managing the Data Control state. Figure 2 illustrates the steps involved. This is of course a brief very short and incomplete description of how model layer works, but detailed discussion of this issue is out of scope of this document. We just need to establish general understanding for the purposes of discussion of several issues in this document later on. Review of State Management The following steps describe briefly how ADF uses state management to preserve pending changes made in the current HttpSession across HTTP requests. The simplest case is as follows: Sometimes application module instances need to be shared among different HttpSessions, because a high number of users are accessing the application simultaneously. In this case, the application pool must recycle a currently referenced application module instance for use by another session, as follows: The process of passivation, activation, and recycling allows the state referenced by Data Control to be preserved across requests without requiring a dedicated AM instance for each Data Control. Both browser users in the above scenario are carrying on an application transaction that spans multiple HTTP requests, but the end-users are unaware whether the passivation and activation is occurring in the background. They just continue to see the pending, but as of yet uncommitted, changes. Options for persisting passivated state are described later in this document. While ADF’s architecture allows any data control to participate in the state management lifecycle, currently only the ADF Business Components Data Control offers an out-of-the-box implementation of the state management support. Release Level Once a Data Control receives the “endRequest” notification (which means that HTTP request has been serviced and now is terminated) it releases and checks back the AM instance into the AM pool (or releases it for garbage collection if AM pool is not used). After every HTTP request Data Control is responsible for releasing the AM with the correct release level, one of the following three: Unmanaged Level (formerly known as Stateless Mode) This mode implies that no state associated with this Data Control has to be preserved to survive beyond the current HTTP request. This level is the most efficient in performance because there is no overhead related to state management, but it is limited in its use to applications that require no state management, or to cases when state no longer needs to be preserved at this point (classic example is releasing AM after servicing HTTP request from logout page. Managed Level (formerly known as Stateful Mode) This is the default level. This level implies that AM’s state is relevant and has to be preserved for this Data Control to span over several HTTP requests. Managed level does not guarantee that for next request this Data Control will receive the same physical AM instance, but it guarantees that an AM with identical state will be provided so it is logically the same AM instance each time. It is important to note that the framework makes the best effort it can to provide the same instance of AM for the same Data Control if it is available at the moment. This is done for better performance since the same AM does not need to activate the previous state which it still has intact after servicing the same Data Control during previous request. However the Data Control is not guaranteed to receive the same instance for all its requests and if the AM that serviced that Data Control during previous is busy or unavailable different AM will activate this Data Control’s state. For this reason it is not valid to cache references to AM objects, View Objects, or View Rows across HTTP requests in controller-layer code. Reserved Level (formerly known as Reserved Mode) This level guarantees that each Data Control will be assigned its own AM during its first request and for all subsequent requests coming from the HttpSession associated with this Data Control. This Data Control will always receive the same physical instance of AM. This mode exists for legacy compatibility reasons and for very rare special case uses. In general it is strongly recommended never to use this mode. The reasons are that with this mode since Data Control to Application Module correlation becomes one to one, the scalability of the application reduces very sharply and so does reliability of the application. Reliability suffers because if for whatever reason the AM is lost, the Data Control will not be able to receive any other AM in its place from the pool, and so HttpSession gets lost as well, which is not the case for managed level. Setting the Release Level Release level can be set in your Struts action code related to the current request. If you are using an action that extends DataForwardAction in the oracle.adf.controller.struts.actions package, you will override the following method: DataForwardAction oracle.adf.controller.struts.actions protected void handleLifecycle(DataActionContext actionContext) throws Exception As mentioned above Managed Level is the default level and if request doesn’t take any action to override the specification of the release level, the Managed Level will be used. This is expected to be the common case. However, if the release level for AM has been changed to “Reserved” it will stay so for all consequent requests until explicitly changed. Therefore, it is possible to specify managed level explicitly as well. To do so invoke method: setReleaseLevel(int releaseLevel) of class oracle.adf.model.bc4j.DCJboDataControl or interface oracle.jbo.ApplicationModule (or override method getReleaseLevel()). Invoke the setter method with parameter ApplicationModule.RELEASE_LEVEL_MANAGED. oracle.adf.model.bc4j.DCJboDataControl oracle.jbo.ApplicationModule getReleaseLevel() ApplicationModule.RELEASE_LEVEL_MANAGED To set Unmanaged Level invoke the method resetState() of class DCDataControl (in the oracle.adf.model.binding package) at any time during request processing. This will cause AM not to passivate its state at all once it is released. (Obviously after this the AM will become unreferenced and reset, and when it will be used next time it will have its Release Level set to Stateful by default unless it is changed explicitly). To set Reserved Level use the setReleaseLevel() method in the class DCJboDataControl (in the oracle.adf.model.bc4j package) or on the oracle.jbo.ApplicationModule interface, passing the value ApplicationModule.RELEASE_LEVEL_RESERVED as an argument. resetState() DCDataControl oracle.adf.model.binding setReleaseLevel() DCJboDataControl oracle.adf.model.bc4j ApplicationModule.RELEASE_LEVEL_RESERVED Limitations Implied By the State Management Feature As explained above, the entire state management mechanism relies on passivation and activation as a vehicle to replicate the state of one AM instance to another one, so that those two instances are indistinguishable from the Data Control’s perspective. This is possible only if all pending changes are managed by the application module instance on the middle tier. This insures that each passivated “snapshot” of the pending changes accurately reflects all the changes the user has made but not yet committed. The alternative would be to save the pending changes to the database by posting the appropriate INSERT, UPDATE, and DELETE statements in the current database transaction – without committing them yet – however this approach would have two major drawbacks, one on performance and one on functionality. Before explaining the details of those drawbacks it is important to mention that by default AM is configured to use AM pooling and not to use supplementary connection pooling. What this means is that AM receives its JDBC connection at the moment it is created and holds this connection for its entire lifespan in the pool. So by default AM is always tied to the same JDBC connection. It is recommended to keep such configuration as it is the best choice for performance. This is so because by holding onto the JDBC connection that was used to create it’s JDBC PreparedStatement objects, ADF can reuse those. With this in mind we now will explain what the drawbacks on performance and functionality are if pending changes are posted to Database but not committed. Regarding performance, the AM would be forced to stay dedicated to its current Data Control to remain in the context of these pending changes. This would effectively require releasing the application module with the Reserved Level and would lower application scalability. Regarding functionality, doing early posting of changes to the database would force possibly incomplete information to be posted to the database before they were completely valid, potentially causing integrity violations. The cleanest and most scalable strategy is to keep pending changes in middle-tier objects and not tie Data Control to a particular AM instance and its JDBC connection containing pending database-level transaction state. This allows the highest leverage of the performance optimizations offered by the Application Module pool. So, based on the above the following restrictions apply when using State persistence spanning over several HTTP requests: jbo.locking.mode If you do want to create a transactional state in Database in some request by invoking postChanges() method or by calling PL/SQL stored procedure but do not want to issue commit or rollback by the end of request, the solution is that from that request on and until commit or rollback is issued all requests for this Data Control must release AM with reserved level, guaranteeing that the HttpSession will use the same AM instance. The recommendation is that it should be a short period of time between creation of transactional state in Database and commit or rollback, so reserved level doesn’t have to be used for long time. Because, as mentioned above, reserved level has adverse effects on application’s scalability and reliability. postChanges() Once an application module has been released with Reserved Level, it will be configured to be released with that level for all subsequent requests until release level is explicitly changed. So it is the developer’s responsibility to set Release Level back to Managed Level (Stateful Mode) once commit or rollback has been issued. The statement above brings us to another best practice : The use of database connection pooling (parameter jbo.doconnectionpooling set to true) fundamentally incompatible with the practice of calling postChanges() and/or invoking PL/SQL stored procedures which perform DML operations in the current transaction —without committing the transaction in the same request. As explained above, if you either: outside of the normal framework transaction commit processing cycle, then this requires releasing your application module with the Reserved Level so it stays dedicated to its current Data Control and its underlying application module instance in which this pending database transaction state was first created. However, if you are using the Disconnect Application Module Upon Release option in the application module's configuration in order to share a common pool of database connections across multiple application module pools, then upon releasing your application module to the AM pool, its JDBC connection will be disconnected from it and released back to the database connection pool and a ROLLBACK will be issued on that connection. This implies that all changes which were posted but not commited will be lost. On the next request when the AM is used it will receive a JDBC connection from the pool — which likely won't be the exact same connection object that was used previously — those changes that were posted but not commited into DB during previous request are no longer there. ROLLBACK Failover Feature The ADF Business Components of affairs” from a persisted snapshot. There is a parameter called jbo.dofailover that can be set in your AM configuration. This parameter controls when and how often passivation occurs. If the failover feature is turned off, then application module pending state will only be passivated just before the pool must hand out a currently-referenced AM instance to a different Data Control. That is, the AM state is not saved until it has to be. With failover feature turned on, the application module’s pending state is passivated every time it is checked in back into AM pool thus saving its state immediately upon return to the pool. jbo.dofailover The idea behind failover is that if for whatever reason AM instance gets lost (for example one of OC4J instances to which this application is deployed crashed) its state is always saved and may be activated by any AM instance at any time. This capability comes at expense of the additional overhead of performing passivation eagerly every time AM is checked in (with managed level) back into the pool. The failover option is a classic case of performance versus reliability trade off. There is no clear-cut recommendation on the value of this parameter and each user has to make the decision based on the resources available and the nature of the application. The default setting of the failover mode is true; out of the box ADF BC opts to err on the side of reliability, rather than performance in this area. The failover option is ignored for AM released with Reserved release level since the meaning of Reserved level is that Data Control requires the same AM and substitute by different AM is not acceptable, making the failover option meaningless in this case. But as soon as release level will be changed from Reserved back to Stateful the value of the failover parameter will become relevant. Passivation Storage Options Passivated information can be stored in several places. You can control it by configuring an option in AM configuration or programmatically. The choices are Database, file stored on local file system and memory: File This choice may be the fastest available as access to the file is faster then access to the database. This choice is good if the entire middle tier (one or multiple Oracle Application Server installation(s) and all their OC4J instances either installed on the same machine or have access to commonly shared file system, so passivated information is accessible to all. Usually, this choice may be good for small middle tier where one OracleAS is used. In other words this is very suitable choice for small middle tier such as one Oracle AS with all its components installed on one physical machine. The location and name of the persistent snapshot files are determined by jbo.tmpdir property if specified. It follows usual rules of BC4J property precedence for a configuration property. If nothing else is specified then the location is determined by user.dir if specified as a java.util.Property. This is a default property and OS specific. jbo.tmpdir user.dir java.util.Property Database This is the default choice. While performance-wise it may be a little slower then passivating to file it is by far the most reliable choice. With passivation to file the common problem might be that it is not accessible to OracleAS instances that are remotely installed, so in a cluster environment if one node goes down the other may not be able to access passivated information and then failover will not work. Another possible problem is that even if file is accessible to the remote node, the access time for local and remote node may be very different and performance will be inconsistent. With database access time should be about the same for all nodes. So database is the most reliable and robust choice even though somewhat slower then file. Passivated information is stored as XML snapshot (this is true for all storages), and in case of Database storage it is written into BLOB column into temporary table within schema specified in jbo.server.internal_connection property jbo.server.internal_connection Memory This choice is for testing purposes only and should not be used in production environment. An obvious problem is that this storage will not be accessible to different processes and nodes. To set the value of your choice in design time set the property jbo.passivationstore to database or file. Value null will indicate that default should be used, which is database. Any values other than "database" and "file" will result default behaviour. Specifically, a DBSerializer is used by default if the database type is Oracle or DB2. A FileSerializer is used by default otherwise. jbo.passivationstore database file null To set the storage programmatically use the method setStoreForPassiveState() of interface oracle.jbo.ApplicationModule. The parameter values that you can pass are: setStoreForPassiveState() PASSIVATE_TO_DATABASE PASSIVATE_TO_FILE PASSIVATE_TO_MEMORY What Gets Passivated? Here is a partial list of the information passivated during as part of the AM passivation “snapshot”. And for each active view object (both statically and dynamically created) This is not a full list of what is passivated but covers the bulk of what's written out. Here is simple example of a passivation snapshot from AM that holds VO based on Departments table from HR schema. This snapshot is holding one new row with department number value 271 and department name value “TestDept” : <AM MomVer="0"> <cd/> <TXN Def="1" New="0" Lok="1"> <EO Name="model.Departments"> <![CDATA[000100000003C20348]]> <DepartmentsRow PS="0" PK="Y"> <DepartmentId>271</DepartmentId> <DepartmentName>TestDept</DepartmentName> </DepartmentsRow> </EO> </TXN> <VO> <VO It="1" Sz="10" St="17" Ex="1" Def="model.DepartmentsView" Name="DepartmentsView1" cli="1"> <Key> <![CDATA[000100000003C20348]]> </Key> <cd> <QC> <Ke>ACED000577020000</Ke> <NR Hdl="76" Idx="26"> <Ke>000100000003C20348</Ke> </NR> </QC> </cd> </VO> <VO It="1" Sz="10" Ex="1" Def="model.EmployeesView" Name="EmployeesView3" cli="1"/> </VO> </AM> Timeouts There are several timeout parameters that can be configured. Two of them will be discussed in this article. First one is HTTP timeout. This parameter is not specified in AM configuration. It is specified in your client project for web application in file web.xml. The default value is 35 minutes. It could be edited manually in text of web.xml file and finding the following fragment: web.xml <session-config> <session-timeout>35</session-timeout> </session-config> Or better yet, by making a right click on the file and choosing Properties.... The HttpSession timeout titled “Session timeout” may be specified in General section (the first one that appears by default). However, the most interesting thing about this parameter is not how to set it but how it is interpreted by the middle tier J2EE container. The HttpSession may be treated as physical resource or as logical user session. Logical user session means a user interaction session with application. Physical resource means that HttpSession is treated as some memory-consuming object that may be removed and reinstantiated according to system needs and its termination and reinstantiation is completely transparent to the user. BC4J uses the SessionCookie stored in Data Control to store a state identifier for AM state related to Binding Context that correlated to that HttpSession (the passivation id). Recall that the HttpSession has a single BindingContext and all Data Controls in the BindingContext are indirectly related to the same HttpSession as containees of BindingContext. When the HttpSession times out the BindingContext will go out of scope, so that SessionCookie stored in the Data Control and used as state identifier will go out of scope and the AM state referenced by this Data Control may no longer be accessible. At the same time AM holding current state will become unreferenced and it will be reset (its state cleaned up) and available to service any HttpSession. If failover is disabled the HttpSession timeout will represent both the physical and the logical end of that session because both the physical HttpSession instance and the state associated with that session will be inaccessible. (So in this case user attempting to continue working will not be able to do so until (s)he starts a new HttpSession. The old HttpSession and state associated with it are discarded. If failover is enabled, the HttpSession timeout will represent the physical end of the session only; the HttpSession instance for that session will be inaccessible but the state associated with Data Control related to that session will still be accessible. (Even though BindingContext with all Data Controls it contains will be out of scope together with its HttpSession). At this point the AM also will be reset and made unreferenced but its state is passivated earlier due to enabled failover feature. The reason that the state still will be accessible is because when failover is enabled the HttpSession cookie that is stored in the HttpSession will also be stored on the browser tier as a browser cookie. This is performed by the framework to ensure that the possibility of re-establishing the link between a new HttpSession and the pending session state in the case of being routed to a different middle-tier server. For example, consider a scenario in which a user opens the browser does some work and lets say does not commit his changes and leaves for lunch. Assume that failover is enabled. The HttpSession will time out and will be removed from the memory and so will BindingContext. Corresponding AM will become unreferenced and it will be reset, but it will not signify the end of user’s session from user’s point of view. When user comes back and tries to continue working, his HttpSession is recreated using browser cookie that is stored on his local file system, ADFBindingFilter will perform bootstraping again and will recreate the BindingContext with its Data Controls with SessionCookie holding identical state identifier, and Data Control that checked out AM during first request from this HttpSession will be able to identify and activate the AM state referenced by the previous HttpSession through its old Data Control. So, the user will be able to continue working as if the HttpSession had never timed out. In other words, from user’s point of view the session never was terminated. The session is treated only as physical resource that may be removed for efficiency reasons but the logical application session lives on, so to speak. To test this, try the following: create simple ADF Business Components application and web client to it. Set the HttpSession timeout to 1 minute, and make sure that failover is enabled, run your client application, create a new row or modify some value but do not commit (or rollback). Now wait for more then one minute to let the HttpSession timeout. Note that if in your ViewController project you add a Java VM property on the “Runner” panel like -Djbo.debugoutput=console you will actually see when your HttpSession times out in the debug trace information. Now try to continue working. You will see that all your state has been preserved as if the HttpSession never timed out. You will be able to see all your changes that have not been committed yet and you still will be able to commit them as well. Now you may try the same scenario, but now with failover turned off. You will see that after timeout your pending state is lost. So you will have to start from the point where you last committed your changes. ViewController -Djbo.debugoutput=console So, if from user’s perspective HTTP timeout is transparent and unnoticeable what is it really used for? It is used for resource management. With Internet Explorer it is possible to launch the browser several times from the (Start) menu, and each gets run in a separate process and behaves as if it were a separate browser user. In contrast, other browsers — including IE itself if you only create a new browser window rather than launching another browser process — treat all windows as the same browser user. Assuming that user may open many browser windows, it's clearly the case that they can only perform active work in one window at a time. So you specify HttpSession timeout so inactive sessions will be removed and AMs referenced by them become unreferenced and will be reset to save the resources and they will be restored only when someone will continue to work on particular window. However, be careful not to set it too short so excessive removal and recreating of HttpSessions and extra passivation and activation of AMs do not occur. One more detail about HttpSession timeout is that it could be caused programmatically. To do so user needs to get access to instance of the class javax.servlet.http.HttpSession and to invoke its method called invalidate(). Note that this will have the same effect as HTTP timeout, which does not necessarily mean logical session termination as described above. javax.servlet.http.HttpSession invalidate() In many cases it important that unauthorized user may not get an access to an existing HttpSession after an authorized user has finished working on his/her session. To prevent this, logical user’s session has to be terminated, and that as we saw does not happen with HttpSession timeout if failover is enabled. One way to do so is to close the browser window (or more precisely all windows belonging to the same browser process). This will terminate the process and effectively will end user’s HttpSession. But even that could be reconfigured, as it will be explained below. Using another timeout parameter that we will discuss later, it is possible to make the logical session survive for a certain time even after browser process has been terminated. The other way to properly terminate user’s session is to create a button or link in the application called “Log off” and upon user clicking on this button AM should be released with stateless level. This will cause AM not to get passivated at all, so no state for this session will be saved. (Of course it is recommended that at this moment all pending transaction changes have been committed or rolled back. As the developer, you may want to check to make sure this is so, and if not appropriate action should be taken before log-off occurs). There is a very important exception to the rule that the HttpSession is treated as physical resource only and not the logical termination of user’s session when failover is enabled. If AM was released with reserved level the HttpSession timeout will be logical session termination and user will not be able to continue working after timeout as if nothing happened. User will have to go through authentication process, and all unsaved changes will be lost. Recall that reserved release level ignores the jbo.dofailover value. Of course, if failover is disabled then HttpSession will be treated as logical termination of user’s session regardless of release level. There’s something important to understand about the HttpSession object. ADF Business Components session state is identified by an ADF BC SessionCookie. The ADF Business Components SessionCookie registers itself with the HttpSession so that it may be managed between the requests of an HttpSession. An HttpSession is identified by an id generated by the servlet container. An application developer may use a variety of HttpSession tracking mechanisms, like browser cookies and URL rewriting, to associate the HttpSession id with a browser and to correlate a set of HTTP requests from a browser with a particular HttpSession. The SessionCookie in turn has a browser cookie stored on the local file system where the browser is located. If web application is marked as distributed and it is installed on several nodes within a cluster, at run time the HttpSession and its SessionCookie is replicated to all instances of OC4J where application is installed. (This is true only if application is configured to be in state replicating mode on OracleAS). So if one of the nodes goes down HttpSession still will be available on other OC4J instances for seamless failover. If replication fails, the ADF BC SessionCookie can still be recreated; the generic HttpSession may not be recreated. This means the logical user session and their pending work can still can be recovered and get recreated using the browser cookie. The second important timeout parameter that we will discuss is set in AM configuration and it is called jbo.maxpoolcookieage. This parameter is specified in seconds and it defines how long browser cookie will survive after the browser process has been terminated or after the last activity in the browser. The default value is –1 and for most of the cases it should always remain such. The default value means that browser cookie will exist as long as browser process is alive. If you set it to positive value it will mean that browser cookie will be kept for specified period of time after last activity in the browser, even if the browser process is terminated. The most important consequence that needs to be understood here is, that if user opens the browser and creates some AM state within his application and then closes all browser windows, if the same browser will be reopened within the timeout period (one that is specified in jbo.maxpoolcookieage parameter), user’s session will be restored and all the uncommited changes will be restored with it. That is, the user may continue working as if the browser’s process had never been terminated. jbo.maxpoolcookieage Due to known bug in JDeveloper version 9.0.5.X the parameter jbo.maxpoolcookieage is ignored if set in AM configuration and default is always used. To work around this problem this parameter could be passed as command line parameter in your client project properties. (It has to be set in client project as oppose to server one since it is client project that is executed and it is its properties that are picked up) In project properties under “Runner” you may specify additional parameter in java options. To pass the options use –D flag. For instance for this parameter you will need to add -Djbo.maxpoolcookieage=300. This will set the value of this parameter to 5 minutes. (There is another parameter that gets ignored in AM configuration and it is jbo.ampool.monitorsleepinterval. This is also a known bug. This parameter is not discussed in this document). Both of those mentioned bugs are fixed in JDeveloper 10.1.2 and from that version on there will be no need to set any parameters in this way, although it still will be possible to do so. -Djbo.maxpoolcookieage=300 jbo.ampool.monitorsleepinterval I’ll use a simple use case to demonstrate the point above. Set the value jbo.maxpoolcookieage property to 5 minutes, run your Web application and create some state by updating or inserting some record. Now close the browser. (Make sure that your browser process has been terminated by checking that in your task manager browser process is no longer found). Open the browser again within time frame not longer then timeout you specified. Notice that your changes are picked up and you continue working as if browser was never closed. So going back to HttpSession timeout interpreted as physical resource and not logical session termination for stateful release level with failover enabled: if developer wants to change this behavior and make HttpSession timeout to be interpreted as logical session termination, developer may set HttpSession timeout and jbo.maxpoolcookieage to the same value. In this case both HttpSession cookie and ADF BC SessionCookie-related browser cookie will go out of scope and will be deleted at the same time and there will be nothing left to restore session from. A drawback is that the ADF BC session state could be restored after the browser process has been killed if that browser is restarted before the jbo.maxpoolcookieage has elapsed. For example, if one user performed some work and closed the browser then a second user could restart a new browser instance on that machine and gain access to any AM/VO/Transaction state (where clauses, RowSets, etc.) that was created by the first user. Most of the users will never need to change the default value for this property. Don’t change this value if you don’t absolutely need it. Changing the default to some positive value creates a potential security vulnerability. If you change this value make sure that all consequences are anticipated. Managing Custom User Specific Info It is fairly common practice to add custom user defined information in the AM. It could be member variables added by user into AM or some custom information stored in session object. ADF BC framework provides mechanism to passivate this information as well. This is done using so-called hooks – API provides some empty methods that are invoked by framework during passivation and activation. By overriding those methods user gets the chance to add custom logic executed with each passivation and activation occurrence. The methods that user may override to take advantage of this feature could be found in oracle.jbo.server.ApplicationModuleImpl. Some of the methods are: oracle.jbo.server.ApplicationModuleImpl protected void passivateState(Document doc, Element parent) public void activateState(Element elem) There are other hooks that could be used for this purpose as well. Please see API for oracle.jbo.ApplicationModule and oracle.jbo.server.ApplicationModuleImpl for more details. VO and EO also have hook methods. Below is a simple example that shows how to override methods mentioned above to make sure that custom information stored in AM is included in passivation/activation cycle. Assume that you would like to keep some custom parameter in your AM called jbo.counter that has session related value that you are interested to preserve. Each AM has a session object associated with it that stores its state (please do not confuse with HTTPSession, See oracle.jbo.Session interface for reference) in the session there is an object designated for storing user custom information. It is called “User’s data”. This is where custom info usually stored. So in this case in your class that extends oracle.jbo.server.ApplicationModuleImpl you will need to override two methods mentioned above. It might look like this: jbo.counter oracle.jbo.Session public void passivateState(Document doc, Element parent) { int counterValue = getCounterValue(); Node node = doc.createElement(COUNTER); Node cNode = doc.createTextNode(Integer.toString(counterValue)); node.appendChild(cNode); parent.appendChild(node); } public void activateState(Element elem) { super.activateState(elem); if (elem != null) { NodeList nl = elem.getElementsByTagName(COUNTER); if (nl != null) { for (int i=0, length = nl.getLength(); i < length; i++) { Node child = nl.item(i).getFirstChild(); if (child != null) {"; This is a simple example that demonstrates use of some but not all hooks that allow developer to take care of persisting custom information. Managing Transient ViewObjects For passivation/activation purposes Transient VO attributes and VO attributes not based on EO ones but derived directly from the database through SQL-calculated expressions are treated in the same way. So for simplicity only transient versus EO based attributes are discussed here. Transient attributes are not passivated by default. This is because due to their nature they are usually intended to be “read only” and very easily recreatable. So it often doesn’t make sense to passivate their values as part of the XML snapshot. However, each transient attribute may be configured to be passivation-enabled. And every VO can be also configured to be passivation enabled. This is true for any VO and not only for transient VO. By default all VOs are marked as passivation-enabled, and all transient attributes are not. That means that VO that only contains transient attributes is marked to be passivation enabled, but only passivates its non transactional state. Recall that information saved by passivation is divided in two parts: transactional and non-transactional state. Transactional state is the set of updates made to EO data – performed either directly on entity objects or on entities through view object rows – that are intended to be saved into DB. Non-transactional state comprises VO attributes, such as current row index, “where” clause, “order by” clause etc. Please see the section “What gets passivated” for details. It is worth to mention that passivating transient attributes is more costly resource- and performance- wise, because transactional functionality is usually managed on EO level. Since transient VOs are not based on EO this means that all updates are managed in VO cache and not in EO as usual. Therefore passivating transient VOs or attributes requires special handling. Usually passivation only saves the values that have been changed, but with Transient VOs passivation has to save entire row (row will include only attributes marked for passivation). Consider the following example: regular (i.e. non-transient) VO contains 10 rows and each row has 7 attributes. The update has been made in two attributes in row number 2 and one attribute in row number 5. During the passivation three values will be passivated (the ones that have been updated). Now consider the same size transient VO with 4 out of 7 transient attributes marked for passivation. Assume that the same updates where made as in previous case for regular VO. The passivation will have to save all 10 rows with 4 attributes each (as we said that only 4 attributes out of 7 are marked for passivation). This is 40 attributes to passivate as oppose to 3 in case of regular VO. Therefore if you have any transient VOs or attributes that you want to passivate, consider making them not transient in the first place. To configure VO to be passivation-enabled or disabled, double-click on VO to open the VO Editor and go to the Tuning panel. There is a checkbox there called “Enable passivation” that is set on by default. There is additional checkbox there called “For all transient attributes”, and this box is not checked on by default. Checking this box will mark all transient attributes to be passivation-enabled. It is also possible to mark each transient attribute as passivation enabled. In the VO editor, go to the Attributes node in the left-hand tree and expand it to show each attribute. For each attribute you can set attribute related configuration options. Note that checkbox called “Passivate” appears for transient attributes only. There is no need for any custom code to passivate transient attributes. But keep in mind that it is costly operation and use it sparingly. Partial Rollback on Middle Tier Partial rollback is a potentially very powerful feature. In the database server we have the savepoint feature that allows a developer to rollback to a certain point within a transaction instead rolling back the entire transaction. Here we have the same feature but implemented in middle tier. There are three methods in oracle.jbo.ApplicationModule interface that allow you to take advantage of this feature. The methods are: public String passivateStateForUndo(String id,byte[] clientData,int flags) public byte[] activateStateForUndo(String id,int flags) public boolean isValidIdForUndo(String id) These methods allow developer to create a stack of identifiable snapshots and restore the pending transaction state from them by name. Keep in mind that those snapshots do not survive past duration of transaction i.e. events of commit or rollback. This feature could be used to develop complex capability of application to undo and redo changes. One of ambitious goals could be implement functionality for back and forward browser buttons. But more simple uses obviously could be very handy. Configuration Parameters and Interesting Use Cases Tuning ADF-BC is not the topic of this paper, but there are some very important parameters that should be mentioned here, because they have strong impact on state management. Also some simple testing scenarios that should help to demonstrate visually some complicated issues explained in this paper. The first parameter is jbo.recyclethreshhold. This parameter controls how many AM instances AM pool tries to preserve to be “sticky” to their Data Controls before it will take one to recycle instead of creating a new AM instance. The value of this parameter should be equal to the expected number of "active" concurrent HTTP sessions. Define an "active" session as one, which will be expected to send subsequent requests before timing out. If this parameter is lower then it should be it will cause excessive recycling of AMs which will have negative impact on performance. jbo.ampool.maxavailablesize - This is the maximal amount of Application modules that could be kept idle in the pool waiting for the user to come. If one available then upon request it will be given instead of creating a new one, which is a costly performance operation. Creation of new AM involves creating AM instance itself and all its VOs as well. When each VO is instantiated the VO’s query gets executed. So each AM creation involves execution of multiple queries (one pr each VO). Therefore it is best to configure AM pool to have minimal amount of creations and removals of AMs jbo.ampool.minavailablesize - This is the minimal amount of Application modules that will be kept idle in the pool waiting for the user to come. It is recommended that both of those parameters should be set to equal value and that value should be expected number of HTTP requests serviced concurrently. Otherwise, you will note high Application Module creation/removal. This will also impact performance negatively. Please note that both those parameters refer to referenced and unreferenced AMs that have been released Just to demonstrate how those parameters influence the pool consider the following situation: Assume that you have a pool which has been configured for normal workload of 50 concurrent users. Let’s say that the number of requests serviced concurrently at average is 10. So assume that jbo.ampool.minavailablesize and jbo.ampool.maxavailablesize are set to 10. So in a normal situation we will have 50 AMs in the pool that are frequently used and the pool will make sure that at any given moment there are at least 10 AMs available in the pool. Assume that there is a peak time and we got 100 concurrent users working on the application. So the pool will have to create extra 50 AMs to accommodate this situation. But once the pick time is over we get back to our regular workload. But we have 100 AMs in the pool of which 50 don’t get used, but some if not all of those inactive 50 AMs are referenced (i.e. have the state of the Data Control request from which they serviced last). This is true only if this AM has been released with stateful release level. When the time specified in jbo.ampool.maxinactiveage will elapse for AM since it last being used it will be marked for removal from AM pool (because at the moment we have more inactive AMs then specified in jbo.ampool.maxavailablesize) and so the pool will be “shrinking,” removing extra AM instances, until it leaves only 10 inactive AMs in the pool. But if failover is not enabled each such AM holds the state that has not been passivated (again if it was released with stateful level). So in this case (failover is not enabled) before AM is removed from the pool it will get passivated in order to preserve its state and keep it accessible. Further discussion of ADF-BC tuning is out of scope of this document. Please refer to How to Performance Tune an ADF Business Components Application. Testing ADF Business Components A very interesting test tool could be made by overriding just few methods in class that extends oracle.jbo.server.ApplicationModuleImpl. Add two variables to your class: static int idProducer = 0; private int amId; amId will be variable that uniquely identifies AM instance. Override the constructor as follows: public AppModuleImpl() { amId = ++idProducer; System.out.println("AM with ID " + amId + " is being created"); } You may add and expose to your clients the following method public int getAmId() { return amId; } And add these three methods as well: protected void afterConnect() { System.out.println("Application Module with id " +amId + " just got connected"); super.afterConnect(); } protected void prepareSession(oracle.jbo.Session session) { System.out.println("Application Module with id " + amId + " is about to be used by different session"); super.prepareSession(session); } protected void finalize() { System.out.println("Application Module with id " + amId + " is getting garbage collected"); super.finalize(); } Those methods will put out diagnostic printouts that will help developer to understand what happens behind the scenes and how and when different events occur. You will see that if AM pooling is on and Connection pooling is off AM gets connected right after it’s creation and holds to its connection for entire life duration. It will get disconnected only when it will be removed from AM pool. The fact that prepareSession has occurred means that AM has been recycled, i.e. its state has been reset and it assumed the state of different Data Control then the one it serviced before. Of course this method will be invoked always when AM will service request for the first time in its life. prepareSession On your client you may get reference to your AM and use method getAmId to see which AM is servicing Data Control from Binding Context related to your current HTTP session. If your AM pool is configured correctly and recycle threshold is higher then the number of HTTP sessions serviced at the moment you will see that usually your HTTP session will always be serviced by the same AM instance. To get reference to your AM instance on your client side you may create an action for your JSP page and override the method handleLifecycle as follows handleLifecycle public class DeptEmpBrowserAction extends DataForwardAction { protected void handleLifecycle(DataActionContext ctx) throws Exception { HttpServletRequest request = actionContext.getHttpServletRequest(); BindingContext bc = ctx.getBindingContext(); YourModule am = (YourModule)bc.findDataControl("YourModuleDataControl") .getDataProvider(); System.out.println("Message from client: The AM with id "+ am.getAmId() + " is in use"); super.handleLifecycle(actionContext); } } For the testing purposes you may want to disable AM pooling to see that in that case every single request is serviced by different AM instance. And if you create some state that is carried over between requests you will know for sure that it is not because your Data Control received the same AM instance but because your state has been successfully passivated by previous AM and activated by a different one. Another testcase is to enable AM pooling and set recycle threshold to 1 and open two different HTTP sessions (two different browsers such as Internet Explorer and Mozilla or two different windows of Internet Explorer that are executed in different processes.) You will see that with this parameter you will be juggling AM instances between your sessions. There are many other cases that such simple tool could be used to demonstrate on practice the complex features described in this paper.
http://www.oracle.com/technology/products/jdev/howtos/10g/bcstate/index.html
crawl-002
refinedweb
8,626
52.19
Hi, i try to sort layers in the TOC, in ascending or by name alphbetical with this code: import arcpy mxd = arcpy.mapping.MapDocument(r"D:\desktop\Project\project.mxd") df = arcpy.mapping.ListDataFrames(mxd)[0] # Assuming one data frame group_lyr = [lyr for lyr in arcpy.mapping.ListLayers(mxd) if lyr.isGroupLayer][0] # The temp group layer should be the only one lyr_names = sorted(lyr.name for lyr in arcpy.mapping.ListLayers(mxd) if lyr.isFeatureLayer) for name in lyr_names: arcpy.mapping.MoveLayer(df, group_lyr, arcpy.mapping.ListLayers(mxd, name)[0], "BEFORE") print name +' sorted' arcpy.mapping.RemoveLayer(df, group_lyr) and got: >>> land use sorted river sorted >>> but the TOC do't sorted. For clarity, i saw this question in arcgis 10.0 - Arc GIS 10.1 - How to sort Layers ascending at TOC in "List by drawing order" - Geographic Information Sys… I work with arc view 10.3. I know it possible with extension, but i have no extensions. Is it possible to do it with python? I don't see where you saved the document. You may want to use savACopy() till you get what you want. MapDocument—Help | ArcGIS for Desktop
https://community.esri.com/thread/170316
CC-MAIN-2019-18
refinedweb
194
54.69
Qt provides two APIs for creating plugins: For example, if you want to write a custom QStyle subclass and have Qt applications load it dynamically, you would use the higher-level API; whereas if you want to extend Qt Designer, you would use the lower-level API. Since the higher-level API is built on top of the lower-level API, some issues are common to both. Topics: Writing a plugin that extends Qt itself is achieved by subclassing the appropriate plugin base clase, implementing a few functions, and adding a macro. There are several plugin base classes. Derived plugins are stored by default in the standard plugin directory. But where is the plugins directory? When the application is run, Qt will first treat the application's executable directory as the pluginsbase. For example if the application is in C:\Program Files\MyApp and has a style plugin, Qt will look in C:\Program Files\MyApp\styles. (See Q(). Suppose that you have a new style class called MyStyle that you want to make available as a plugin. The required code is straightforward: class MyStylePlugin : public QStylePlugin { public: QStringList keys() const { return QStringList() << "mystyle"; } QStyle *create(const QString &key) { if (key == "mystyle") return new MyStyle; return 0; } }; Q_EXPORT_PLUGIN(MyStylePlugin) (Note that QStylePlugin is case-insensitive, and the lower-case version of the key is used; most other plugins are case sensitive.). Qt applications automatically know which plugins are available, because plugins are stored in the standard plugin subdirectories. Because of this applications don't require any code to find and load plugins, since Qt handles them automatically. The default directory for plugins is QTDIR/plugins (where QTDIR is the directory where Qt is installed), with each type of plugin in a subdirectory for that type, e.g. styles. If you want your applications to use plugins and you don't want to use the standard plugins path, have your installation process determine the path you want to use for the plugins, and save the path, e.g. using QSettings, for the application to read when it runs. The application can then call QCoreApplication::addLibraryPath() with this path and your plugins will be available to the application. Note that the final part of the path (e.g., styles) cannot be changed..0") Here's the definition of a plugin class that implements that interface: #include <QObject> #include <QStringList> #include <QImage> #include <plugandpaint/interfaces.h> class ExtraFiltersPlugin : public QObject, public FilterInterface { Q_OBJECT. When loading plugins, the Qt library does some sanity checking to determine whether or not the plugin can be loaded and used. This provides the ability to have multiple versions and configurations of the Qt library installed side by side. Rationale: A plugin linked against a newer Qt library may use new features that are not available in older versions. Trolltech has a policy of adding new features and APIs only between minor releases, which is why this test only looks at the major and minor version numbers, and not at the patch. The build key contains the following information: Rationale: In cases where different versions of the same compiler do not produce binary compatible code, the version of the compiler is also present in the build key. Rationale: Two different configurations of the same version of the Qt library are not binary compatible. The Qt library that loads the plugin uses the list of (missing) features to determine if the plugin is binary compatible. Note: There are cases where a plugin can use features that are available in two different configurations. However, the developer writing plugins would need to know which features are in use, both in their plugin and internally by the utility classes in Qt. The Qt library would require complex feature and dependency queries and verification when loading plugins. Requiring this would place an unnecessary burden on the developer, and increase the overhead of loading a plugin. To reduce both development time and application runtime costs, a simple string comparision of the build keys is used. Rationale: When distributing binaries of the Qt library with an application, this provides a way for developers to write plugins that can only be loaded by the library with which the plugins were linked. See also QPluginLoader and QLibrary.
http://doc.trolltech.com/4.0/plugins-howto.html
crawl-001
refinedweb
709
51.07
Internet of Things Programming Projects Build modern IoT solutions with the Raspberry Pi 3 and Python Colin Dow BIRMINGHAM - MUMBAI Internet of Things Programming: Prachi Bisht Content Development Editor: Deepti Thore Technical Editor: Varsha Shivhare Copy Editor: Safis Editing Project Coordinator: Kinjal Bari Proofreader: Safis Editing Indexer: Mariammal Chettiyar Graphics: Jisha Chirayil Production Coordinator: Aparna Bhagat First published: October 2018 Production reference: 1301018 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78913-480. I would like to thank my wife Constance for her encouragement, support and assistance; and my sons Maximillian and Jackson for their inspiration and optimism. I am forever grateful to them for this unique opportunity. I would also like to thank Deepti Thore and Varsha Shivhare at Packt for their guidance and expertise throughout the whole process. Without their assistance and patience this book would not have been possible. About the reviewer Arvind Ravulavaru is a platform architect at Ubiconn IoT Solutions, with over 9 years of experience of software development and 2 years experience of hardware and product development. For the last 5 years, he has been working extensively on JavaScript, both on the server side and the client side. Over the past couple of years, his focus has been on IoT, building a platform for rapidly developing IoT solutions named The IoT Suitcase. Prior to that, Arvind worked on big data, cloud computing, and orchestration.: Installing Raspbian on the Raspberry Pi 8 A brief history of the Raspberry Pi 8 A look at operating systems for the Raspberry Pi 11 Project overview 12 Getting started 12 Installing the Raspbian OS 12 Formatting a microSD card for Raspbian 13 Copying the NOOBS files to the microSD RAM 13 Running the installer 14 A quick overview of the Raspbian OS 21 The Chromium web browser 21 The home folder 22 The Terminal 23 Mathematica 25 Sonic Pi 26 Scratch and Scratch 2.0 27 LibreOffice 28 Summary 29 Questions 29 Further reading 30 Chapter 2: Writing Python Programs Using Raspberry Pi 31 Project overview 31 Technical requirements 32 Python tools for Raspberry Pi 32 The Terminal 32 Integrated Development and Learning Environment 33 Thonny 33 Using the Python command line 35 Writing a simple Python program 39 Creating the class 39 Creating the object 40 Using the object inspector 41 Testing your class 42 Making the code flexible 43 Example one 43 Example two 43 Summary 44 Table of Contents [ ii ] Questions 44 Further reading 45 Chapter 3: Using the GPIO to Connect to the Outside World 46 Project overview 46 Technical requirements 47 Python libraries for the Raspberry Pi 47 picamera 49 Pillow 50 sense-hat and sense-emu 50 Accessing Raspberry Pi's GPIO 53 Pibrella 54 RPi.GPIO 57 GPIO zero 58 Setting up the circuit 58 Fritzing 59 Building our circuit 61 Hello LED 63 Blink LED using gpiozero 63 Morse code weather data 63 Summary 67 Questions 68 Further reading 69 Chapter 4: Subscribing to Web Services 70 Prerequisites 70 Project overview 71 Getting started 71 Cloud services for IoT 71 Amazon Web Services IoT 71 IBM Watson platform 73 Google Cloud platform 74 Microsoft Azure 75 Weather Underground 75 A basic Python program to pull data from the cloud 76 Accessing the web service 76 Using the Sense HAT Emulator 79 Summary 81 Questions 82 Further reading 82 Chapter 5: Controlling a Servo with Python 83 Knowledge required to complete this chapter 83 Project overview 83 Getting started 84 Table of Contents [ iii ] Wiring up a servo motor to the Raspberry Pi 84 Stepper motors 84 DC motors 86 Servo motors 87 Connecting the servo motor to our Raspberry Pi 89 Control the servo through the command line 91 Write a Python program to control the servo 93 Summary 96 Questions 96 Further reading 96 Chapter 6: Working with the Servo Control Code to Control an Analog Device 97 Knowledge required to complete this chapter 97 Project overview 98 Getting started 99 Accessing weather data from the cloud 99 Controlling the servo using weather data 102 Correcting for servo range 102 Changing the position of the servo based on weather data 104 Enhancing our project 106 Printing out the main graphic 107 Adding the needle and LED 108 Summary 110 Questions 111 Further reading 111 Chapter 7: Setting Up a Raspberry Pi Web Server 112 Knowledge required to complete this chapter 112 Project overview 112 Getting started 113 Introducing CherryPy – a minimalist Python web framework 113 What is CherryPy? 113 Who uses CherryPy? 113 Installing CherryPy 114 Creating a simple web page using CherryPy 115 Hello Raspberry Pi! 115 Say hello to myFriend 117 What about static pages? 119 HTML weather dashboard 120 Summary 127 Questions 128 Further reading 128 Chapter 8: Reading Raspberry Pi GPIO Sensor Data Using Python 129 Table of Contents [ iv ] Project overview 129 Getting started 130 Reading the state of a button 130 Using GPIO Zero with a button 130 Using the Sense HAT emulator and GPIO Zero button together 132 Toggling an LED with a long button press 135 Reading the state from an infrared motion sensor 137 What is a PIR sensor? 138 Using the GPIO Zero buzzer class 141 Building a basic alarm system 144 Modifying Hello LED using infrared sensor 146 Configuring a distance sensor 147 Taking Hello LED to another level 149 Summary 151 Questions 152 Further reading 152 Chapter 9: Building a Home Security Dashboard 153 Knowledge required to complete this chapter 153 Project overview 153 Getting started 154 Creating our dashboard using CherryPy 154 Using the DHT11 to find temperature and humidity 154 Using the Pi camera to take a photo 159 Creating our dashboard using CherryPy 160 Displaying sensory data on our dashboard 165 Home security dashboard with a temperature sensor 166 Home security dashboard with quick response 175 Summary 183 Questions 183 Further reading 184 Chapter 10: Publishing to Web Services 185 Project overview 185 Getting started 185 Publishing sensory data to cloud-based services 186 Install the MQTT library 186 Set up an account and create a device 186 Reading sensory data and publishing to ThingsBoard 189 Creating a dashboard in ThingsBoard 192 Sharing your dashboard with a friend 195 Setting up an account for text message transmission 196 Setting up a Twilio account 197 Installing Twilio on our Raspberry Pi 201 Sending a text through Twilio 201 Table of Contents [ v ] Creating a new home security dashboard 202 Summary 213 Questions 213 Further reading 214 Chapter 11: Creating a Doorbell Button Using Bluetooth 215 Project overview 215 Getting started 216 Introducing Blue Dot 216 Installing the bluedot library on the Raspberry Pi 218 Pairing Blue Dot with your Raspberry Pi 218 Wiring up our circuit 219 What is an RGB LED? 220 Testing our RGB LED 220 Completing our doorbell circuit 223 Reading our button state using Bluetooth and Python 226 Reading button information using Python 226 Creating a Bluetooth doorbell 228 Creating a secret Bluetooth doorbell 231 Summary 232 Questions 232 Further reading 233 Chapter 12: Enhancing Our IoT Doorbell 234 Project overview 235 Getting started 236 Sending a text message when someone is at the door 236 Creating a simple doorbell application with text messaging 237 Creating a secret doorbell application with text messaging 242 Summary 248 Questions 248 Further reading 248 Chapter 13: Introducing the Raspberry Pi Robot Car 249 The parts of the robot car 250 Building the robot car 252 Step 1 – Adafruit 16-Channel PWM/Servo HAT for Raspberry Pi 252 Step 2 – Wiring up the motors 254 Step 3 – Assembling the servo camera mount 257 Step 4 – Attaching the head 262 Step 5 – Assembling the DC motor plate 266 Step 6 – Attaching the motors and wheels 274 Step 7 – Wiring up the motors 276 Step 8 – Attaching the camera mount, Raspberry Pi, and Adafruit servo board 277 Table of Contents [ vi ] Step 9 – Attaching the buzzer and voltage divider 281 Step 10 – Wiring up T.A.R.A.S 284 Learning how to control the robot car 287 Configuring our Raspberry Pi 287 Python library for Adafruit Servo HAT 288 Summary 289 Questions 290 Chapter 14: Controlling the Robot Car Using Python 291 Knowledge required to complete this chapter 291 Project overview 292 Getting started 292 Taking a look at the Python code 293 Controlling the drive wheels of the robot car 293 Moving the servos on the robot car 294 Taking a picture 295 Making a beep noise 296 Making the LEDs blink 296 Modifying the robot car Python code 299 Move the wheels 299 Move the head 300 Make sounds 302 Enhancing the code 304 Stitching our code together 304 Summary 306 Questions 306 Further reading 307 Chapter 15: Connecting Sensory Inputs from the Robot Car to the Web 308 Knowledge required to complete this chapter 308 Project overview 309 Getting started 309 Identifying the sensor on the robot car 309 Taking a closer look at the HC-SR04 310 Reading robot car sensory data with Python 313 Publishing robot car sensory data to the cloud 314 Create a ThingsBoard device 315 Summary 321 Questions 321 Further reading 321 Chapter 16: Controlling the Robot Car with Web Service Calls 322 Knowledge required to complete this chapter 322 Project overview 323 Technical requirements 323 Table of Contents [ vii ] Reading the robot car's data from the cloud 323 Changing the look of the distance gauge 323 Changing the range on the distance gauge 326 Viewing the dashboard outside of your account 328 Using a Python program to control a robot car through the cloud 329 Adding a switch to our dashboard 331 Controlling the green LED on T.A.R.A.S 333 Using the internet to make T.A.R.A.S dance 336 Summary 338 Questions 338 Further reading 339 Chapter 17: Building the JavaScript Client 340 Project overview 340 Getting started 341 Introducing JavaScript cloud libraries 341 Google Cloud 341 AWS SDK for JavaScript 342 Eclipse Paho JavaScript client 342 Connecting to cloud services using JavaScript 342 Setting up a CloudMQTT account 343 Setting up an MQTT Broker instance 345 Writing the JavaScript client code 347 Running the code 350 Understanding the JavaScript code 353 Publishing MQTT messages from our Raspberry Pi 356 Summary 357 Questions 358 Further reading 358 Chapter 18: Putting It All Together 359 Project overview 360 Getting started 361 Building a JavaScript client to connect to our Raspberry Pi 361 Writing the HTML code 362 Writing the JavaScript code to communicate with our MQTT Broker 366 Creating a JavaScript client to access our robot car's sensory data 372 Writing the code for T.A.R.A.S 373 Livestreaming videos from T.A.R.A.S 377 Enhancing our JavaScript client to control our robot car 379 Nipple.js 380 HTML5 Gamepad API 380 Johnny-Five 380 Summary 381 Questions 381 Table of Contents [ viii ] Further reading 382 Assessments 383 Other Books You May Enjoy 403 Index 406 Preface The Internet of Things (IoT) promises to unlock the real world the way that the internet unlocked millions of computers just a few decades ago. First released in 2012, the Raspberry Pi computer has taken the world by storm. Originally designed to give newer generations the same excitement to programming that personal computers from the 1980s did, the Raspberry Pi has gone on to be a staple of millions of makers everywhere. In 1991, Guido van Rossum introduced the world to the Python programming language. Python is a terse language and was designed for code readability. Python programs tend to require fewer lines of code than other programming languages. Python is a scalable language that can be used for anything from the simplest programs to massive large-scale projects. In this book, we will unleash the power of Raspberry Pi and Python to create exciting IoT projects. The first part of the book introduces the reader to the amazing Raspberry Pi. We will learn how to set it up and jump right into Python programming. We will start our foray into real- world computing by creating the "Hello World" app for physical computing, the flashing LED. Our first project takes us back to an age when analog needle meters ruled the world of data display. Think back to those old analog multimeters and endless old sci-fi movies where information was controlled and displayed with buttons and big flashing lights. In our project, we will retrieve weather data from a web service and display it on an analog needle meter. We will accomplish this using a servo motor connected to our Raspberry Pi through the GPIO. Home security systems are pretty much ubiquitous in modern life. Entire industries and careers are based on the installation and monitoring of them. Did you know that you could easily create your own home security system? In our second project, we do just that, as we build a home security system using Raspberry Pi as a web server to display it. The humble doorbell has been with us since 1831. In our third project, we will give it a 21st century twist and have our Raspberry Pi send a signal to a web service that will text us when someone is at the door. Preface [ 2 ] In our final project, we take what we've learned from our previous two projects and create an IoT robot car we call T.A.R.A.S (This Amazing Raspberry-Pi Automated Security Agent). In years to come, driverless cars will become the rule instead of the exception, and ways of controlling these cars will be needed. This final project gives the reader insight and knowledge into how someone would go about controlling cars devoid of a human driver. Who this book is for This book is geared toward those who have had some sort of exposure to programming and are interested in learning about the IoT. Knowledge of the Python programming language would be a definite asset. An understanding of, or a keen interest in, object- oriented programming will serve the reader well with the coding examples used in the book. What this book covers Chapter 1, Installing Raspbian on the Raspberry Pi, sets us off on our Raspberry Pi IoT journey by installing the Raspbian OS on our Raspberry Pi. We will then take a look at some of the programs that come pre-installed with Raspbian. Chapter 2, Writing Python Programs Using Raspberry Pi, covers how Windows, macOS, and Linux are operating systems that are familiar to developers. Many a book on developing the Raspberry Pi involves using one of these operating systems and accessing the Raspberry Pi remotely. We will take a different approach in this book. We will use our Raspberry Pi as a development machine. In this chapter, we will get our feet wet with using the Raspberry Pi as a development machine. Chapter 3, Using the GPIO to Connect to the Outside World, explains how, if the Raspberry Pi was just a $35 computer, that would be enough for many of us. However, the real power behind the Raspberry Pi is the ability of the developer to access the outside world through the use of the General Purpose Input Output (GPIO) pins. In this chapter, we will delve into the GPIO and start to connect the Raspberry Pi to the real world. We will create a Morse code generator for our project using an outside LED and then use this generator to blink out simulated weather information. Chapter 4, Subscribing to Web Services, explores a few web services offered by some of the biggest companies in the world. Our project will use the virtual version of the Raspberry Pi Sense HAT as a ticker to display current weather information from the Yahoo! Weather web service. Preface [ 3 ] Chapter 5, Controlling a Servo with Python, introduces the concept of creating an analog meter needle using a servo motor connected to the Raspberry Pi. Chapter 6, Working with the Servo Control Code to Control an Analog Device, continues the theme of working with servo motors as we build our first real IoT device, a weather dashboard. Not only will this weather dashboard feature an analog needle; it will use the needle to point to a picture of a suggested wardrobe based on the weather conditions. Chapter 7, Setting Up a Raspberry Pi Web Server, goes into how to install and configure the web framework CherryPy. We will conclude the chapter by building a local website that displays weather information. Chapter 8, Reading Raspberry Pi GPIO Sensor Data Using Python, covers how to read the state of a button before moving on to a PIR sensor and distance sensor. We will conclude the chapter by building simple alarm systems. Chapter 9, Building a Home Security Dashboard, explains how to build a home security dashboard using the Raspberry Pi as a web server serving up HTML content containing sensory data collected from the GPIO. Chapter 10, Publishing to Web Services, goes into how to measure room temperature and humidity and publish these values to the web through the use of an IoT dashboard. We will also set up and run a text messaging alert using the service Twilio. Chapter 11, Creating a Doorbell Button Using Bluetooth, turns our focus to using Bluetooth in this chapter. Bluetooth is a wireless technology that allows for transmission of data over short distances. For our project we will explore the BlueDot app from the Android Play Store. We will use this app to build a simple Bluetooth connected doorbell. Chapter 12, Enhancing Our IoT Doorbell, will take the simple doorbell we created in Chapter 11, Creating a Doorbell Button Using Bluetooth, and turn it into an IoT doorbell using the knowledge we learned in Chapter 10, Publishing to Web Services. Chapter 13, Introducing the Raspberry Pi Robot Car, starts us off on our journey into the IoT robot car by introducing This Amazing Raspberry-Pi Automated Security Agent (T.A.R.A.S). This chapter will begin by outlining the components we need to build T.A.R.A.S and then we will proceed to putting it all together. Chapter 14, Controlling the Robot Car Using Python, goes into how to write Python code for our robot car. We will utilize the GPIO Zero library to make the car wheels move forward, move the servo motors holding the camera, and light up the LEDs at the back of the robot car. Preface [ 4 ] Chapter 15, Connecting Sensory Inputs from the Robot Car to the Web, helps us understand that in order to turn our robot car into a true IoT device we have to connect it to the internet. In this chapter we will connect the distance sensor from our robot car to the internet. Chapter 16, Controlling the Robot Car with Web Service Calls, continues to turn our robot car into an Internet of Things device by taking a deeper look at the internet dashboard we created for the robot car. Chapter 17, Building the JavaScript Client, moves our attention away from Python, switching our focus to JavaScript instead. We will use JavaScript to build a web-based client that communicates over the internet using the MQTT protocol. Chapter 18, Putting It All Together, covers how we will connect our robot car, T.A.R.A.S, to a JavaScript client, and control it over the internet using the MQTT protocol. To get the most out of this book To get the most out of this book, I will assume the following: You have purchased, or will purchase, a Raspberry Pi Computer, preferably a 2015 model or newer. You have had some exposure to the Python programming language, or are eager to learn it. You have a basic familiarity with electronic components and how to use a breadboard. You have purchased, or are willing to purchase, basic electronic components. In terms of hardware requirements, you will need at least the following: A Raspberry Pi Model 3 (2015 model or newer) A USB power supply A computer monitor A USB keyboard A USB mouse A microSD RAM card A breadboard and breadboard jumpers Preface [ 5 ] Additional pieces of hardware will be introduced at the beginning of every chapter. In terms of software requirements, you will require the Raspberry Pi NOOBS image (. org/ downloads/ noobs/ ). Additional software, accounts, and Python packages will be presented along the way. Any piece of software, web service, or Python package we use in this book is free of charge./Internet- of- Things- Programming- Projects. In case there's an update to the code, it will be updated on the existing GitHub repository. We also have other code bundles from our rich catalog of books and videos available at. com/ PacktPublishing/ . Check them out! Preface [ 6 ] Download the color images We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https:/ /www. packtpub. com/ sites/ default/ files/ downloads/9781789134803_ ColorImages. pdf. Conventions used There are a number of text conventions used throughout this book. CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "In order to access Python 3, we type the python3 command in a Terminal window." A block of code is set as follows: wind_dir_str_len = 2 if currentWeather.getWindSpeed()[-2:-1] == ' ': wind_dir_str_len = 1 Any command-line input or output is written as follows: pip3 install weather-api Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "From the View menu, select Object inspector and Variables." Installing Raspbian on the Raspberry Pi The Raspberry Pi is marketed as a small and affordable computer that you can use to learn programming. At least that was its initial goal. As we will see in this book, it is much more than that. The following topics will be covered in this chapter: A brief history of the Raspberry Pi A look at operating systems for the Raspberry Pi Installing the Raspbian OS A quick overview of the Raspbian OS A brief history of the Raspberry Pi First released in 2012, the first Raspberry Pi featured a 700 MHz single core processor and 256 MB of RAM. The Raspberry Pi 2 was released in February of 2015 with a 900 MHz quad core processor and 1 GB of RAM. Released in February of 2016, the Raspberry Pi 3 increased the processor speed to 1.2 GHz. This model was also the first one to include wireless LAN and Bluetooth. Installing Raspbian on the Raspberry Pi Chapter 1 [ 9 ] Here is an image of a Raspberry Pi 3 B (2015): This version of the Raspberry Pi features the following parts: Four USB 2 ports A LAN port A 3.5 mm composite video and audio jack An HDMI port for video and audio An OTG USB port (which we will use to connect the power) A microSD slot (to hold our operating system) Installing Raspbian on the Raspberry Pi Chapter 1 [ 10 ] A DSI display port for the Raspberry Pi touchscreen A General Purpose Input Output (GPIO) pins A camera port for a special Raspberry Pi camera The Raspberry Pi Zero was released in November of 2015. Here is an image of it: Although not as powerful as the previous Raspberry Pis, the Zero featured a smaller size (65 mm X 30 mm), perfect for projects with limited physical space (namely, wearable projects). Plus, the Raspberry Pi zero was priced at $5 USD, making it very affordable. The Raspberry Pi zero W was released on February 28, 2017 at double the price ($10 USD) with built-in Wi-Fi and Bluetooth capabilities. The latest model, as of the time of writing, is the Raspberry Pi 3 B+, which was released on March 14, 2018. The processor speed has been upgraded to 1.4 GHz as well as the wireless LAN now supporting both 2.4 GHz and 5 GHz bands. Another upgrade is the addition of Bluetooth low energy, a technology built for applications that do not require large amounts of data to be exchanged but are required to have a long battery life. Installing Raspbian on the Raspberry Pi Chapter 1 [ 11 ] Creators of the Raspberry Pi initially believed that they would sell at most 1,000 units. Little did they know that their invention would explode in popularity. As of March 2018, sales of Raspberry Pi computers has passed the 19 million mark. A look at operating systems for the Raspberry Pi There are various operating systems (or system images) that may be installed on the Raspberry Pi. These range from application-specific operating systems, such as audio players, to various general purpose operating systems. The power behind Raspberry Pi is the way it can be used for various applications and projects. The following is a list of just a few of the operating systems (system images) available for the Raspberry Pi: Volumio: Do you have a desire to set up a networked audio system where you access your music list using a computer or cell phone? Volumio may be what you are looking for. Installing it on a Raspberry Pi creates a headless audio player (a system that does not require a keyboard and mouse) that connects to your audio files either over USB or a network. A special audio Hardware Added on Top (HAT) may be added to your Pi to provide a pristine audio connection to an amplifier and speakers. There is even a plugin to add Spotify so that you can set up your Raspberry Pi to access this service and play music over your sound system. PiFM radio transmitter: The PiFM radio transmitter turns your Raspberry Pi into an FM transmitter, which you can use to send audio files over the air to a standard FM radio receiver. Using a simple wire connected to one of the GPIO pins (we will learn more about GPIO later), you can create an antenna for the transmitted FM signal, which is surprisingly strong. Stratux: ADS-B is the new standard in aviation where geo-location and weather information are shared with ground controllers and pilots. The Stratux image with additional hardware turns the Raspberry Pi into an ADS-B receiver of this information. RetroPie: RetroPie turns your Raspberry Pi into a retro game console by emulating gaming consoles and computers from the past. Some of the emulations include Amiga, Apple II, Atari 2600, and the Nintendo Entertainment System of the early 1980s. Installing Raspbian on the Raspberry Pi Chapter 1 [ 12 ] OctoPi: OctoPi turns your Raspberry Pi into a server for your 3D printer. Through OctoPi, you may control your 3D printer over the network, including viewing the status of your 3D printer using a webcam. NOOBS: This is arguably the easiest way to install an operating system on the Raspberry Pi. NOOBS stands for New Out-Of-the Box Software, and we will be using NOOBS to install Raspbian. Project overview In this project, we will install the Raspbian operating system onto our Raspberry Pi. After installation, we will take a quick tour of the operating system to familiarize ourselves with it. We will start by formatting a microSD card to store our installation files. We will then run the installation from the microSD card. After Raspbian has been installed, we will take a quick look at it in order to familiarize ourselves with it. This project should take about two hours to complete, as we install the Raspbian operating system and take a quick look at it. Getting started The following is required to complete this project: A Raspberry Pi Model 3 (2015 model or newer) A USB power supply A computer monitor A USB keyboard A USB mouse A microSD RAM card A Raspberry Pi NOOBS image (https:/ /www. raspberrypi. org/ downloads/ noobs/) Installing the Raspbian OS The Raspbian OS is considered the default or go-to operating system for the Raspberry Pi. In this section, we will install Raspbian using the NOOBS image. Installing Raspbian on the Raspberry Pi Chapter 1 [ 13 ] Formatting a microSD card for Raspbian Raspberry Pi uses a microSD card to store the operating system. This allows you to easily switch between different operating systems (system images) for your Raspberry Pi. We will be installing the default Raspbian OS for our projects using the NOOBS image. Start by inserting the microSD card into a USB adapter and plug it into your computer: You may need to format the microSD card. If so, use the utilities appropriate for your computer's operating system to format the card to FAT32. It is recommended that you use a card with a capacity of 8 GB or greater. For Windows OS and cards with 64 GB of capacity or greater, a third-party tool such as FAT32 format should be used for formatting. Copying the NOOBS files to the microSD RAM Unzip the NOOBS image that you downloaded. Open up the unzipped directory and drag the files over to the microSD card. Installing Raspbian on the Raspberry Pi Chapter 1 [ 14 ] The files should look the same as in the following screenshot: Running the installer We will now install Raspbian on our Raspberry Pi. This step should be familiar to those that have previous experience installing operating systems such as Windows or macOS. The Raspbian operating system will be installed and will run off of our microSD card. Installing Raspbian on the Raspberry Pi Chapter 1 [ 15 ] To install Raspbian onto our microSD card, do the following: Start by inserting the microSD card into the appropriate slot on the Raspberry1. Pi. Be sure to install it so that the label side (opposite side of the exposed contacts) is facing up. Insert it with the metal contacts facing the board. The microSD card should have a slight ridge at the top of the label side, which is good for easy removal using a fingernail. Insert a keyboard and mouse into the USB slots on the side, a monitor into the2. HDMI port, and lastly, a USB power cable into the power port. The Raspberry Pi does not have an on/off switch and will power up as soon as the power cable is connected: Installing Raspbian on the Raspberry Pi Chapter 1 [ 16 ] After an initial black screen with rolling white text, you should see the following3. dialog: Installing Raspbian on the Raspberry Pi Chapter 1 [ 17 ] In the previous screenshot, we clicked on the Language option. For our purposes,4. we will keep the default of English (UK). We will also keep the keyboard at the standard gb. As the Raspberry Pi 3 has wireless LAN, we can set up our Wi-Fi (for older5. boards, please plug a Wi-Fi dongle into a USB port or use the wired LAN port and skip the next step): Installing Raspbian on the Raspberry Pi Chapter 1 [ 18 ] Click on the Wifi networks (w) button. Choose the Authentication method6. using the radio buttons. Some routers are equipped with a WPS button that allows you to connect directly to the router. To use the password method, choose the Password authentication radio button and enter the password for your network. After connecting to your network, you will notice that there are now more operating system options to select from: Installing Raspbian on the Raspberry Pi Chapter 1 [ 19 ] We will go with the top option, Raspbian. Check the box beside Raspbian7. [RECOMMENDED] and then click on the Install (i) button at the top-left corner of the dialog. Raspbian will start installing on your Raspberry Pi. You will see a progress bar with previous graphics, describing various features of the Raspbian operating system: Installing Raspbian on the Raspberry Pi Chapter 1 [ 20 ] After the progress bar hits 100%, the computer will reboot and you will see a8. screen with text before the default desktop loads up: Installing Raspbian on the Raspberry Pi Chapter 1 [ 21 ] A quick overview of the Raspbian OS The Raspbian desktop is similar to the desktops of other operating systems such as Windows and macOS. Clicking the top-left button drops down the application menu where you may access the various pre-installed programs. We may also shut down the Raspberry Pi from this menu: The Chromium web browser The second button from the left loads the Google Chromium web browser for the Raspberry Pi: Installing Raspbian on the Raspberry Pi Chapter 1 [ 22 ] The Chromium browser is a lightweight browser that runs remarkably well on the Raspberry Pi: The home folder The two-folders button opens up a window showing the home folder: Installing Raspbian on the Raspberry Pi Chapter 1 [ 23 ] The home folder is a great place to start when looking for files on your Raspberry Pi. In fact, when you take screenshots using either the scrot command or the Print Screen button, the file is automatically stored in this folder: The Terminal The third button from the left opens up the Terminal. The Terminal permits command-line access to Raspberry Pi's files and programs: It is from the command line where you may update the Raspberry Pi using the sudo apt- get update and sudo apt-get dist-upgrade commands. Installing Raspbian on the Raspberry Pi Chapter 1 [ 24 ] apt-get updates the packages list, and apt-get dist-upgrade updates the packages: It's a good idea to run both of these commands right after installing Raspbian using the sudo command. The default user for Raspbian on the Raspberry Pi is pi, which is part of the Super Users group in Raspbian, and thus must use the sudo command (the default password for the pi user is raspberry): Installing Raspbian on the Raspberry Pi Chapter 1 [ 25 ] Mastering the command line is a virtue that many a programmer aspires to acquire. Being able to rapidly type command after command looks so cool that even movie makers have picked up on it (when was the last time you saw the computer wiz in a movie clicking around the screen with a mouse?). To assist you in becoming this uber cool computer wiz, here are some basic Raspbian commands for you to master using the Terminal: ls: Command to see the contents of the current directory cd: Command to change directories. For example, use cd to move up a directory from where you currently are pwd: Command to display the directory you are currently in sudo: Allows the user to perform a task as the super user shutdown: Command that allows the user to shut down the computer from the Terminal command line Mathematica The third and fourth buttons are for Mathematica, and a terminal to access the Wolfram language, respectively: Mathematica spans all areas of technical computing and uses the Wolfram language as the programming language. The areas in which Mathematica is used include machine learning, image processing, neural networks and data science: Installing Raspbian on the Raspberry Pi Chapter 1 [ 26 ] Mathematica, a proprietary software first released in 1988, can be used free for individuals on the Raspberry Pi through a partnership that was announced in late 2013. Now let’s take a look at some of the programs that are accessed from the main drop-down Sonic Pi Sonic Pi is a live coding environment for creating electronic music. It is accessed from the Programming menu option. Sonic Pi is a creative way to create music as the user programs loops, arpeggios, and soundscapes in real time by cutting and pasting code from one part of the app to another. Synthesizers in Sonic Pi may be configured on a deep level, providing a customized experience for the music coder: Installing Raspbian on the Raspberry Pi Chapter 1 [ 27 ] Geared toward an EDM style of music, Sonic Pi may also be used to compose classical and jazz styles of music. Scratch and Scratch 2.0 Scratch and Scratch 2.0 are visual programming environments designed for teaching programming to children. Using Scratch, the programmer creates their own animations with looping and conditional statements. Games may be created within the program. The first version of Scratch was released in 2003 by the Lifelong Kindergarten group at the MIT media lab. Scratch 2.0 was released in 2013, and development is currently underway with Scratch 3.0: Scratch and Scratch 2.0 may be accessed under the Programming menu option. Installing Raspbian on the Raspberry Pi Chapter 1 [ 28 ] LibreOffice LibreOffice is a free and open source office suite that forked over from OpenOffice in 2010. The LibreOffice suite consists of a word processor, a spreadsheet program, a presentation program, a vector graphics editor, a program for creating and editing mathematical formulae, and a database management program. The LibreOffice suite of programs may be accessed through the LibreOffice menu option: Installing Raspbian on the Raspberry Pi Chapter 1 [ 29 ] Summary We started this chapter with a look at the history of the Raspberry Pi. What started as an initiative to promote programming to a new generation has grown into a global phenomenon. We then downloaded the NOOBS image and installed the Raspbian OS, the default operating system for the Raspberry Pi. This involved formatting and preparing a microSD card for the NOOBS files. It's easiest to think that a computer as inexpensive and small as the Raspberry Pi is not all that powerful. We demonstrated that the Raspberry Pi is indeed a very capable computer, as we took a look at some of the applications that come pre-installed with the Raspbian OS. In Chapter 2, Writing Python Programs Using Raspberry Pi, we will begin Python coding using the Raspberry Pi and some of the development tools available in Raspbian. Questions What year did the first Raspberry Pi come out?1. What upgrades did the Raspberry Pi 3 Model B+ have over the previous version?2. What does NOOBS stand for?3. What is the name of the pre-installed application that allows for creating music4. with Python code? Where is the operating system stored for the Raspberry Pi?5. What is the name of the visual programming environment designed for children6. that comes pre-installed with Raspbian? What is the name of the language used in Mathematica?7. What is the default username and password for Raspbian?8. What does GPIO stand for?9. What is RetroPie?10. True or false? Clicking on the two-folders icon on the main bar loads the home11. folder. True or false? The microSD card slot is located at the bottom of the Raspberry Pi.12. True or false? To shutdown the Raspberry Pi, select Shutdown from the13. Application menu. True or false? You may only install the Raspbian OS with NOOBS.14. True or false? Bluetooth low energy refers to people that eat too many15. blueberries and have a hard time waking up in the morning. Installing Raspbian on the Raspberry Pi Chapter 1 [ 30 ] Further reading For more information on the Raspberry Pi, please consult the main Raspberry Pi website at. 2 Writing Python Programs Using Raspberry Pi In this chapter, we will start writing python programs with Raspberry Pi. Python is the official programming language for Raspberry Pi and is represented by the Pi in the name. The following topics will be covered in this chapter: Python tools for Raspberry Pi Using the Python command line Writing a simple Python program Python comes pre-installed on Raspbian in two versions, versions 2.7.14 and 3.6.5 (as of this writing) representing Python 2 and Python 3, respectively. The differences between the two versions are beyond the scope of this book. We will use Python 3 in this book unless otherwise stated. Project overview In this project, we will become comfortable with Python development on Raspberry Pi. You may be used to development tools or Integrated Development Environments (IDEs) on other systems such as Windows, macOS, and Linux. In this chapter, we will get our feet wet in terms of using Raspberry Pi as a development machine. We will start off slowly with Python as we get our development juices flowing. Writing Python Programs Using Raspberry Pi Chapter 2 [ 32 ] Technical requirements The following is required to complete this project: Raspberry Pi Model 3 (2015 model or newer) USB power supply Computer monitor USB keyboard USB mouse Python tools for Raspberry Pi The following are pre-installed tools that we may use for Python development on Raspberry Pi using Raspbian. This list is by no means the only tools that we may use for development. The Terminal As Python comes pre-installed with Raspbian, an easy way to launch it is to use the Terminal. As we can see in the following screenshot, the Python interpreter can be accessed by simply typing python as the command prompt in a Terminal window: We may test it out by running the simplest of programs: print 'hello' Writing Python Programs Using Raspberry Pi Chapter 2 [ 33 ] Notice the Python version in the line after the command, 2.7.13. The python command in Raspbian is tied to Python 2. In order to access Python 3, we must type the python3 command in a Terminal window: Integrated Development and Learning Environment The Integrated Development and Learning Environment (IDLE) has been the default IDE for Python since version 1.5.2. It is written in Python itself using the Tkinter GUI toolkit and is intended to be a simple IDE for beginners: IDLE features a multi-window text editor with auto-completion, syntax highlighting, and smart indent. IDLE should be familiar to anyone that has used Python. There are two versions of IDLE in Raspbian, one for Python 2 and the other for Python 3. Both programs are accessed from Application Menu | Programming. Thonny Thonny is an IDE that comes packaged with Raspbian. With Thonny, we may evaluate expressions by using the debug function. Thonny is also available for macOS and Windows. Writing Python Programs Using Raspberry Pi Chapter 2 [ 34 ] To load Thonny, go to Application Menu | Programming | Thonny: Above is the default screen for Thonny. Panels to view variables in your program, as well as a panel to view the filesystem, are toggled on and off from the View menu. Thonny's compact structure makes it ideal for our projects. We will be learning a bit more about Thonny as we go through the rest of this book. Writing Python Programs Using Raspberry Pi Chapter 2 [ 35 ] Using the Python command line Let's start doing some coding. Whenever I start using a new operating system for development, I like to go through some basics just to get my mind back into it (I'm speaking particularly to those of us who are all too familiar with coding into the wee hours of the morning). The simplest way to access Python is from the Terminal. We will run a simple program to get started. Load the Terminal from the main toolbar and type python3 at the prompt. Type the following line and hit Enter: from datetime import datetime This line loads the datetime object from the datetime module into our instance of Python. Next type the following and hit Enter: print(datetime.now()) You should see the current date and time printed to the screen: Let's try another example. Type the following into the shell: import pyjokes Writing Python Programs Using Raspberry Pi Chapter 2 [ 36 ] This is a library that's used to tell programming jokes. To have a joke printed out, type the following and hit Enter: pyjokes.get_joke() You should see the following output: OK, so this may not be your cup of tea (or coffee, for the Java programmers out there). However, this example demonstrates how easy it is to import a Python module and utilize it. If you receive an ImportError, it is because pyjokes did not come pre- installed with your version of the OS. Similar to the following example, typing sudo pip3 install pyjokes will install pyjokes onto your Raspberry Pi. What these Python modules have in common is their availability for our use. We simply need to import them directly into the shell in order to use them, as they are pre-installed with our Raspbian operating system. However, what about libraries that are not installed? Let's try an example. In the Python shell, type the following and hit Enter: import weather Writing Python Programs Using Raspberry Pi Chapter 2 [ 37 ] You should see the following: Since the weather package is not installed on our Raspberry Pi we get an error when trying to import. In order to install the package, we use the Python command-line utility pip, or in our case, pip3 for Python 3: Open up a new Terminal (make sure that you're in a Terminal session and not a1. Python shell). Type the following: pip3 install weather-api Hit Enter. You will see the following:2. Writing Python Programs Using Raspberry Pi Chapter 2 [ 38 ] After the process is finished, we will have the weather-api package installed on3. our Raspberry Pi. This package will allow us to access weather information from Yahoo! Weather. Now let's try out a few examples: Type python3 and hit Enter. You should now be back in the Python shell. 1. Type the following and hit Enter:2. from weather import Weather from weather import Unit What we have done is imported Weather and Unit from weather. Type the3. following and hit Enter: weather = Weather(unit=Unit.CELSIUS) This instantiates a weather object called weather. Now, let's make use of this4. object. Type the following and hit Enter: lookup = weather.lookup(4118) We now have a variable named lookup that's been created with the code 4118,5. that corresponds to the city Toronto, Canada. Type the following and hit Enter: condition = lookup.condition We now have a variable called condition that contains the current weather6. information for the city of Toronto, Canada via the lookup variable. To view this information, type the following and hit Enter: print(condition.text) You should get a description of the weather conditions in Toronto, Canada.7. When I ran it, the following was returned: Partly Cloudy Now that we've seen that writing Python code on the Raspberry Pi is just as easy as writing it on other operating systems, let's take it a step further and write a simple program. We will use Thonny for this. Writing Python Programs Using Raspberry Pi Chapter 2 [ 39 ] A Python module is a single Python file containing code that may be imported for use. A Python package is a collection of Python modules. Writing a simple Python program We will write a simple Python program that contains a class. To facilitate this, we will use Thonny, a Python IDE that comes pre-installed with Raspbian and has excellent debug and variable introspection functionalities. You will find that its ease of use makes it ideal for the development of our projects. Creating the class We will begin our program by creating a class. A class may be seen as a template for creating objects. A class contains methods and variables. To create a class in Python with Thonny, do the following: Load Thonny through Application Menu | Programming | Thonny. Select New1. from the top left and type the following code: class CurrentWeather: weather_data={'Toronto':['13','partly sunny','8 km/h NW'], 'Montreal':['16','mostly sunny','22 km/h W'], 'Vancouver':['18','thunder showers','10 km/h NE'], 'New York':['17','mostly cloudy','5 km/h SE'], 'Los Angeles':['28','sunny','4 km/h SW'], 'London':['12','mostly cloudy','8 km/h NW'], 'Mumbai':['33','humid and foggy','2 km/h S'] } def __init__(self, city): self.city = city def getTemperature(self): return self.weather_data[self.city][0] def getWeatherConditions(self): return self.weather_data[self.city][1] def getWindSpeed(self): return self.weather_data[self.city][2] Writing Python Programs Using Raspberry Pi Chapter 2 [ 40 ] As you can see, we've created a class called CurrentWeather that will hold weather conditions for whichever city we instantiated the class for. We are using a class as it will allow us to keep our code clean and prepare us for using outside classes later on. Creating the object We will now create an object from our CurrentWeather class. We will use London as our city: Click on the Run Current Script button (a green circle with a white arrow) in the1. top menu to load our code into the Python interpreter. At the command line of the Thonny shell, type the following and hit Enter:2. londonWeather = CurrentWeather('London') We have just created an object in our code called londonWeather from our CurrentWeather class. By passing 'London' to the constructor (init), we set our new object to only send weather information for the city of London. This is done through the class attribute city (self.city). Type the following at the shell command line:3. weatherLondon.getTemperature() You should get the answer '12' on the next line. To view the weather conditions for London, type the following:4. weatherLondon.getWeatherConditions() You should see 'mostly cloudy' on the next line. To get the wind speed, type the following and hit Enter:5. weatherLondon.getWindSpeed() You should get 8 km/h NW on the next line. Writing Python Programs Using Raspberry Pi Chapter 2 [ 41 ] Our CurrentWeather class simulates data coming from a web service for weather data. The actual data in our class is stored in the weather_data variable. In future code, whenever possible, we will wrap calls to web services in classes in order to keep things organized and make the code more readable. Using the object inspector Let's do a little analysis of our code: From the View menu, select Object inspector and Variables. You should see the1. following: Highlight the londonWeather variable under the Variables tab. We can see that2. londonWeather is an object of type CurrentWeather. In the Object inspector, we can also see that the attribute city is set to 'London'. This type of variable inspection is invaluable in troubleshooting code. Writing Python Programs Using Raspberry Pi Chapter 2 [ 42 ] Testing your class It is very important to test your code as you write it so that you can catch errors early on: Add the following function to the CurrentWeather class:1. def getCity(self): return self.city Add the following to the bottom of CurrentWeather.py. The first line should2. have the same indentation as the class definition as this function is not part of the class: if __name__ == "__main__": currentWeather = CurrentWeather('Toronto') wind_dir_str_len = 2 if currentWeather.getWindSpeed()[-2:-1] == ' ': wind_dir_str_len = 1 print("The current temperature in", currentWeather.getCity(),"is", currentWeather.getTemperature(), "degrees Celsius,", "the weather conditions are", currentWeather.getWeatherConditions(), "and the wind is coming out of the", currentWeather.getWindSpeed()[-(wind_dir_str_len):], "direction with a speed of", currentWeather.getWindSpeed() [0:len(currentWeather.getWindSpeed()) -(wind_dir_str_len)] ) Run the code by clicking on the Run current script button. You should see the3. following: The current temperature in Toronto is 13 degrees Celsius, the weather conditions are partly sunny and the wind is coming out of the NW direction with a speed of 8 km/h The if __name__ == "__main__": function allows us to test the class in the file directly as the if statement will only be true if the file is run directly. In other words, imports of CurrentWeather.py will not execute the code following the if statement. We will explore this method more as we work our way through this book. Writing Python Programs Using Raspberry Pi Chapter 2 [ 43 ] Making the code flexible Code that is more generic is more flexible. The following are two examples of how we can make the code less specific. Example one The wind_dir_str_len variable is used to determine the length of the string for wind direction. For example, a direction of S would only use one character, whereas NW would use two. This is done so that an extra space is not included in our output when the direction is represented by only one character: wind_dir_str_len = 2 if currentWeather.getWindSpeed()[-2:-1] == ' ': wind_dir_str_len = 1 By looking for a space using [-2:-1], we can determine the length of this string and change it to 1 if there is a space (as we are parsing back two characters from the end of the string). Example two By adding the getCity method to our class, we are able to create classes with more generic names like currentWeather as opposed to torontoWeather. This makes it easy to reuse our code. We can demonstrate this by changing the following line: currentWeather = CurrentWeather('Toronto') We will change it to this: currentWeather = CurrentWeather('Mumbai') If we run the code again by clicking on the Run button, we get different values for all the conditions in the sentence: The current temperature in Mumbai is 33 degrees Celsius, the weather conditions are humid and foggy and the wind is coming out of the S direction with a speed of 2 km/h Writing Python Programs Using Raspberry Pi Chapter 2 [ 44 ] Summary We began this chapter by discussing the various tools that are available for Python development in Raspbian. The quickest and easiest way to run Python is from the Terminal window. Since Python comes pre-installed in Raspbian, the python command in the Terminal prompt loads Python (Python 2, in this case). There is no need to set environment variables in order to have the command find the program. Python 3 is run from the Terminal by typing python3. We also took a brief look at IDLE, the default IDE for Python development. IDLE stands for Integrated Development and Learning Environment and is an excellent tool for beginners to use when learning Python. Thonny is another Python IDE that comes pre-installed with Raspbian. Thonny has excellent debug and variable introspection functionalities. It too is designed for beginning Python developers, however, its ease of use and object inspector make it ideal for the development of our projects. We will be using Thonny more as we progress through the book. We then jumped right into programming in order to get our development juices flowing. We started out with simple expressions using the Terminal and concluded with a weather data example designed to emulate objects that are used to call web services. In Chapter 3, Using the GPIO to Connect to the Outside World, we will jump right into the most powerful feature of programming on Raspberry Pi, the GPIO. The GPIO allows us to interact with the real world through the use of devices connected to this port on Raspberry Pi. GPIO programming will take our Python skills to a whole new level. Questions Which operating systems is Thonny available for?1. How do we enter Python 2 from the Terminal command line?2. Which tool in Thonny do we use to view what is inside an object?3. Give two reasons as to why we are using an object in our weather example code.4. What is the advantage of adding a method called getCity to5. the CurrentWeather class? What language is IDLE written in?6. Writing Python Programs Using Raspberry Pi Chapter 2 [ 45 ] What are the two steps taken in order to print the current date and time?7. In our code, how did we compensate for wind speed directions that are8. represented by only one letter? What does the if __name__ =="__main__" statement do?9. What does IDLE stand for?10. Further reading Python 3 - Object Oriented Programming by Dusty Phillips, Packt Publishing. 3 Using the GPIO to Connect to the Outside World In this chapter we will start unlocking the real power behind the Raspberry Pi—the GPIO, or General Purpose Input Output. The GPIO allows you to connect your Raspberry Pi to the outside world through the use of pins that may be set to input or output, and are controlled through code. The following topics will be covered in this chapter: Python libraries for the Raspberry Pi Accessing Raspberry Pi’s GPIO Setting up the circuit Hello LED Project overview In this chapter, we start by exploring Raspberry Pi-specific libraries for Python. We will demonstrate these with a few examples by using the Raspberry Pi camera module and Pibrella HAT. We will try a few coding examples with the Sense Hat emulator before moving on to designing a physical circuit using the Fritzing program. Using a breadboard, we will set up this circuit and connect it to our Raspberry Pi. We will finish off this chapter by building a Morse code generator that transmits weather data in Morse code from the class we created in Chapter 2, Writing Python Programs Using Raspberry Pi. This chapter should take an afternoon to complete. Using the GPIO to Connect to the Outside World Chapter 3 [ 47 ] Technical requirements The following is required to complete this project: A Raspberry Pi Model 3 (2015 model or newer) A USB power supply Computer monitor A USB keyboard A USB mouse A Raspberry Pi camera module (optional)—https:/ /. org/ products/ camera- module- v2/ A Pribrella HAT (optional)— A Sense HAT (optional, as we will be using the emulator in this chapter)—https:/ /www. raspberrypi. org/ products/ sense- hat/ a A breadboard Male-to-female jumper wires An LED Python libraries for the Raspberry Pi We will turn our attention to the Python libraries or packages that come pre-installed with Raspbian. To view these packages from Thonny, click on Tools | Manage Packages. After a short delay, you should see many packages listed in the dialog: Using the GPIO to Connect to the Outside World Chapter 3 [ 48 ] Let's explore a few of these packages. Using the GPIO to Connect to the Outside World Chapter 3 [ 49 ] picamera The camera port, or CSI, on the Raspberry Pi allows you to connect the specially designed Raspberry Pi camera module to your Pi. This camera can take both photos and videos, and has functionality to do time-lapse photography and slow-motion video recording. The picamera package gives us access to the camera through Python. The following is a picture of a Raspberry Pi camera module connected to a Raspberry Pi 3 Model B through the camera port: Connect your Raspberry Pi camera module to your Pi, open up Thonny, and type in the following code: import picamera import time picam = picamera.PiCamera() picam.start_preview() time.sleep(10) picam.stop_preview() picam.close() Using the GPIO to Connect to the Outside World Chapter 3 [ 50 ] This code imports the picamera and time packages, and then creates a picamera object called picam. From there, we start the preview and then sleep for 10 seconds, before stopping the preview and then closing the camera. After running the program, you should see a 10 second preview from the camera on your screen. Pillow The Pillow package is used for image processing with Python. To test this out, download an image to the same directory as your project files. Create a new file in Thonny and type in the following: from PIL import Image img = Image.open('image.png') print(img.format, img.size) You should see the format and size of the image (in brackets) printed at the commandline that follows. sense-hat and sense-emu The Sense HAT is a sophisticated add-on board for the Raspberry Pi. The Sense HAT is the main component in the Astro Pi kit, part of a program to have young students program a Raspberry Pi for the International Space Station. The Astro Pi competition was officially opened in January of 2015 to all primary and secondary school-aged children in the United Kingdom. During a mission to the International Space Station, British astronaut Tim Peake deployed Astro Pi computers on board the station. The winning Astro Pi competition code was loaded onto an Astro Pi while in orbit. The data generated was collected and sent back to Earth. Using the GPIO to Connect to the Outside World Chapter 3 [ 51 ] The Sense HAT contains an array of LEDs that can be used as a display. The Sense HAT also has the following sensors onboard: Accelerometer Temperature sensor Magnetometer Barometric pressure sensor Humidity sensor Gyroscope We can access the sensors and LEDs on the Sense HAT through the sense-hat package. For those that do not have a Sense HAT, the Sense HAT emulator in Raspbian may be used instead. We use the sense-emu package to access the emulated sensors and LED display on the Sense HAT emulator. To demonstrate this, perform the following steps: Create a new file in Thonny and name it sense-hat-test.py, or something1. similar. Type in the following code:2. from sense_emu import SenseHat sense_emulator = SenseHat() sense_emulator.show_message('Hello World') Load the Sense HAT Emulator program from Application Menu | Programming3. | Sense HAT Emulator. Arrange your screen so that you can see the LED display of the Sense HAT4. emulator and the full window of Thonny (see the following screenshot): Using the GPIO to Connect to the Outside World Chapter 3 [ 52 ] Click on the Run current script button.5. You should see the Hello World! message scroll across the LED display of the6. Sense HAT emulator one letter at a time (see the previous screenshot). Using the GPIO to Connect to the Outside World Chapter 3 [ 53 ] Accessing Raspberry Pi's GPIO Through the GPIO, we are able to connect to the outside world. Here is a diagram of the Raspberry Pi GPIO pins: The following is an explanation of these pins: Red pins represent power coming out of the GPIO. The GPIO provides 3.3 Volts and 5 Volts. Black pins represent pins used for electrical ground. As you can see, there are 8 ground pins on the GPIO. Using the GPIO to Connect to the Outside World Chapter 3 [ 54 ] Blue pins are used for Raspberry Pi Hardware Added on Top (HATs). They allow communication between the Raspberry Pi and the HAT's Electrical Erasable Programmable Read-Only Memory (EEPROM). Green pins represent the input and output pins that we may program for. Please note that some of the green GPIO pins double up with additional functionality. We will not be covering the additional functionality for this project. The GPIO is what lies at the heart of the Raspberry Pi. We can connect LEDs, buttons, buzzers, and so on to the Raspberry Pi through the GPIO. We can also access the GPIO through HATs designed for the Raspberry Pi. One of those, called Pibrella, is what we will use next to explore connecting to the GPIO through Python code. Raspberry Pi 1 Models A and B only have the first 26 pins (as shown by the dotted line). Models since then, including Raspberry Pi 1 Models A+ and B+, Raspberry Pi 2, Raspberry Pi Zero and Zero W, and Raspberry Pi 3 Model B and B+, have 40 GPIO pins. Pibrella Pibrella is a relatively inexpensive Raspberry Pi HAT that makes connecting to the GPIO easy. The following are the components on-board of Pibrella: 1 red LED 1 yellow LED 1 green LED Small speaker Push button 4 inputs 4 outputs Micro USB power connector for delivering more power to the outputs Pibrella was designed for early Raspberry Pi models and thus only has a 26-pin input. It can, however, be connected to later models through the first 26 pins. Using the GPIO to Connect to the Outside World Chapter 3 [ 55 ] To install the Pibrella Hat, line up the pin connectors on the Pibrella with the first 26 pins on the Raspberry Pi, and push down. In the following picture, we are installing Pibrella on a Raspberry Pi 3 Model B: Pibrella should fit snugly when installed: Using the GPIO to Connect to the Outside World Chapter 3 [ 56 ] The libraries needed to connect to Pibrella do not come pre-installed with Raspbian (as of the time of writing), so we have to install them ourselves. To do that, we will use the pip3 command from the Terminal: Load the Terminal by clicking on it on the top tool bar (fourth icon from the left).1. At the Command Prompt, type the following: sudo pip3 install pibrella You should see the package load from the Terminal:2. With the Pibrella library, there is no need to know the GPIO pin numbers in3. order to access the GPIO. The functionality is wrapped up in the Pibrella object we import into our code. We will do a short demonstration. Create a new file in Thonny called pibrella-test.py, or name it something4. similar. Type in the following code: import pibrella import time pibrella.light.red.on() time.sleep(5) Using the GPIO to Connect to the Outside World Chapter 3 [ 57 ] pibrella.light.red.off() pibrella.buzzer.success() Run the code by clicking on the Run current script button. If you typed5. everything in correctly, you should see the red light on the Pibrella board turn on for 5 seconds before a short melody is played over the speaker. Congratulations, you have now crossed the threshold into the world of physical computing. RPi.GPIO The standard Python package for accessing the GPIO is called RPi.GPIO. The best way to describe how it works is with some code (this is for demonstration purposes only; we will be running code to access the GPIO in the upcoming section): import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) time.sleep(5) GPIO.output(18, GPIO.LOW) As you can see, this code seems a little bit confusing. We will step through it: First, we import the RPi.GPIO and time libraries:1. import RPi.GPIO as GPIO import time Then, we set the mode to BCM:2. GPIO.setmode(GPIO.BCM) In BCM mode, we access the pin through GPIO numbers (the ones shown in our3. Raspberry Pi GPIO graphic). The alternative is to access the pins through their physical location (GPIO.BOARD). To set GPIO pin 18 to an output, we use the following line:4. GPIO.setup(18, GPIO.OUT) Using the GPIO to Connect to the Outside World Chapter 3 [ 58 ] We then set GPIO 18 to HIGH for 5 seconds before setting it to LOW:5. GPIO.output(18, GPIO.HIGH) time.sleep(5) GPIO.output(18, GPIO.LOW) If we had set up the circuit and run the code, we would see our LED light for 5 seconds before turning off, similar to the Pibrella example. GPIO zero An alternative to RPi.GPIO is the GPIO Zero package. As with RPi.GPIO, this package comes pre-installed with Raspbian. The zero in the name refers to zero boilerplate or setup code (code that we are forced to enter every time). To accomplish the same task of turning an LED on and off for 5 seconds, we use the following code: from gipozero import LED import time led = LED(18) led.on() time.sleep(5) led.off() As with our RPi.GPIO example, this code is for demonstration purposes only as we haven't set up a circuit yet. It's obvious that the GPIO Zero code is far simpler than the RPi.GPIO example. This code is pretty self-explanatory. In the following sections, we will start building a physical circuit on a breadboard with an LED, and use our code to turn it on and off. Setting up the circuit The Pibrella HAT gave us a simple way of programming the GPIO, however, the ultimate goal of Raspberry Pi projects is to create a customized working circuit. We will now take the steps to design our circuit, and then create the circuit using a breadboard. The first step is to design our circuit on the computer. Using the GPIO to Connect to the Outside World Chapter 3 [ 59 ] Fritzing Fritzing is a free circuit design software available for Windows, macOS, and Linux. There is a version in the Raspberry Pi store that we will install on our Raspberry Pi: From the Application Menu, choose Preferences | Add / Remove Software. In1. the Search box, type in Fritzing: Select all three boxes and click on Apply, and then OK. After installation, you2. should be able to load Fritzing from Application Menu | Programming | Fritzing. Click on the Breadboard tab to access the breadboard design screen. A full size3. breadboard dominates the middle of the screen. We will make it smaller as our circuit is small and simple. Using the GPIO to Connect to the Outside World Chapter 3 [ 60 ] Click on the breadboard. In the Inspector box, you will see a heading called4. Properties. Click on the Size dropdown and select Mini.5. To add a Raspberry Pi to our circuit, type in Raspberry Pi in the search box.6. Drag a Raspberry Pi 3 under our breadboard. From here, we may drag and drop components onto our breadboard.7. Add an LED and 330 Ohm resistor to our breadboard, shown in the following8. diagram. We use the resistor to protect both the LED and Raspberry Pi from excessive currents that may cause damage: Using the GPIO to Connect to the Outside World Chapter 3 [ 61 ] You will notice that as we hover our mouse over each pin on our Raspberry Pi9. component, a yellow tip will pop up with the pin's BCM name. Click on GPIO 18 and drag a line over to the positive leg of our LED (the longer one). Do the same to drag a GND connection to the left-hand side of the resistor.10. This is the circuit we will build for our Raspberry Pi. Building our circuit To build our physical circuit, start by inserting components into our breadboard. Referring to our diagram from before, we can see that some of the holes are green. This indicates continuity in the circuit. For example, we connect the negative leg of the LED to the 330 Ohm resistor through the same vertical column. Thus, the two component legs are connected together through the breadboard. We take this into account as we start to place our components on the breadboard: Insert the LED into our breadboard, as shown in the preceding picture. We are1. following our Fritzing diagram and have the positive leg in the lower hole. Follow our Fritzing diagram and wire up the 330 Ohm resistor. Using female-to-2. male jumper wires, connect the Raspberry Pi to our breadboard. Refer to our Raspberry Pi GPIO diagram to find GPIO 18 and GND on the3. Raspberry Pi board. Using the GPIO to Connect to the Outside World Chapter 3 [ 62 ] It is a good practice to have the Raspberry Pi powered off when connecting jumpers to the GPIO. As you can see in the following image, the complete circuit resembles our Fritzing diagram (only our breadboard and Raspberry Pi are turned sideways): Connect the Raspberry Pi back up to the monitor, power supply, keyboard, and4. mouse. We are now ready to program our first real GPIO circuit. Using the GPIO to Connect to the Outside World Chapter 3 [ 63 ] Hello LED We will jump right into the code: Create a new file in Thonny, and call it Hello LED.py or something similar.1. Type in the following code and run it:2. from gpiozero import LED led = LED(18) led.blink(1,1,10) Blink LED using gpiozero If we wired up our circuit and typed in our code correctly, we should see our LED blink for 10 seconds in 1 second intervals. The blink function in the gpiozero LED object allows us to set on_time (the length of time in seconds that the LED stays on), off_time (the length of time in seconds that the LED is turned off for), n or the number of times the LED blinks, and background (set to True to allow other code to run while the LED is flashing). The blink function call with its default parameters looks like this: blink(on_time=1, off_time=1, n=none, background=True) Without parameters passed into the function, the LED will blink non-stop at 1 second intervals. Notice how we do not need to import the time library like we did when we used the RPi.GPIO package for accessing the GPIO. We simply pass a number into the blink function to represent the time in seconds we want the LED on or off. Morse code weather data In Chapter 2, Writing Python Programs Using Raspberry Pi, we wrote code that simulates calls to a web service that supplies weather information. Taking what we learned in this chapter, let's revisit that code and give it a physical computing upgrade. We will use our LED to flash a Morse code representation of our weather data. Using the GPIO to Connect to the Outside World Chapter 3 [ 64 ] Many of us believe that the world only started to become connected in the 1990s with the World Wide Web. Little do we realize that we already had such a world beginning in the 19th century with the introduction of the telegraph and trans-world telegraph cables. The language of this so-called Victorian Internet was Morse code, with the Morse code operator as its gate keeper. The following are the steps for flashing Morse code representation of our weather data: We will first start by creating a MorseCodeGenerator class:1. from gpiozero import LED from time import sleep class MorseCodeGenerator: led = LED(18) dot_duration = 0.3 dash_duration = dot_duration * 3 word_spacing_duration = dot_duration * 7 MORSE_CODE = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', ' ': ' ' } def transmit_message(self, message): for letter in message: morse_code_letter = self.MORSE_CODE[letter.upper()] for dash_dot in morse_code_letter: if dash_dot == '.': self.dot() elif dash_dot == '-': self.dash() elif dash_dot == ' ': self.word_spacing() self.letter_spacing() def dot(self): self.led.blink(self.dot_duration,self.dot_duration,1,False) Using the GPIO to Connect to the Outside World Chapter 3 [ 65 ] def dash(self): self.led.blink(self.dash_duration,self.dot_duration,1,False) def letter_spacing(self): sleep(self.dot_duration) def word_spacing(self): sleep(self.word_spacing_duration-self.dot_duration) if __name__ == "__main__": morse_code_generator = MorseCodeGenerator() morse_code_generator.transmit_message('SOS') After importing the gpiozero and time libraries into our2. MorseCodeGenerator class, we define GPIO 18 as our LED with the line led=LED(18) We set the duration of how long a dot lasts with the line dot_duration = 0.33. We then define the duration of the dash and spacing between words based on4. the dot_duration To speed up or slow down our Morse code transmutation, we may adjust5. dot_duration accordingly We use a Python dictionary with the name MORSE_CODE. We use this dictionary6. to translate letters to Morse code Our transmit_message function steps through each letter of the message, and7. then each character in the Morse code, which is equivalent to using the dash_dot variable The magic of our class happens in the dot and dash methods by using the blink8. function from the gpiozero library: def dot(self): self.led.blink(self.dot_duration, self.dot_duration,1,False) In the dot method, we can see that we turn the LED on for the duration set in dot_duration, and then we turn it off for the same amount of time. We only blink it once as set it by the number 1 in the blink method call. We also set the background parameter to False. Using the GPIO to Connect to the Outside World Chapter 3 [ 66 ] This last parameter is very important, as if we leave it to the default of True, the code will continue to run before the LED has a chance to blink on and off. Basically, the code won't work unless the background parameter is set to False. We forgo the usual Hello World for our test message and instead use the standard SOS, which is familiar to the most casual of Morse code enthusiasts. We may test our class by clicking on the Run button and, if all is set up correctly, we will see the LED blink SOS in Morse code. Now, let's revisit our CurrentWeather class from Chapter 2, Writing Python Programs Using Raspberry Pi. We will make a few minor modifications: from MorseCodeGenerator import MorseCodeGenerator class CurrentWeather: weather_data={ 'Toronto':['13','partly sunny','8 NW'], 'Montreal':['16','mostly sunny','22 W'], 'Vancouver':['18','thunder showers','10 NE'], 'New York':['17','mostly cloudy','5 SE'], 'Los Angeles':['28','sunny','4 SW'], 'London':['12','mostly cloudy','8 NW'], 'Mumbai':['33','humid and foggy','2 S'] } def __init__(self, city): self.city = city def getTemperature(self): return self.weather_data[self.city][0] def getWeatherConditions(self): return self.weather_data[self.city][1] def getWindSpeed(self): return self.weather_data[self.city][2] def getCity(self): return self.city if __name__ == "__main__": current_weather = CurrentWeather('Toronto') morse_code_generator = MorseCodeGenerator() morse_code_generator.transmit_message(current_weather. getWeatherConditions()) Using the GPIO to Connect to the Outside World Chapter 3 [ 67 ] We start by importing our MorseCodeGenerator class (make sure that both files are in the same directory). As we do not have a Morse code equivalent of /, we take out the km/h in the weather_data data set. The rest of the class remains the same as it did in Chapter 2, Writing Python Programs Using Raspberry Pi. In our test section, we instantiate both a CurrentWeather class and a MorseCodeGenerator class. Using the CurrentWeather class, we pass the weather conditions for Toronto into the MorseCodeGenerator class. If there aren't any mistakes made in entering the code, we should see our LED blink partly sunny in Morse code. Summary A lot was covered in this chapter. By the end of it, you should be feeling pretty good about developing applications on the Raspberry Pi. The picamera, Pillow, and sense-hat libraries make it easy to communicate with the outside world with your Raspberry Pi. Using the Raspberry Pi camera module and picamera, we open up a whole new world of possibilities with our Pi. We only touched on a small part of what picamera can do. Additionally, we only scratched the surface of image processing with the Pillow library. The Sense HAT emulator allowed us to save spending money on buying the actual HAT and test out our code. With sense-hat and the Raspberry Pi Sense HAT, we truly expand our reach into the physical world. The inexpensive Pibrella HAT provided an easy way to jump into the physical computing world. By installing the pibrella library, we are giving our Python code access to an assortment of LEDs, a speaker, and a button, all neatly packaged into a Raspberry Pi HAT. However, the true ultimate goal with physical computing is to build electronic circuits that bridge the gap between our Raspberry Pi and the outside world. We started our journey of building electronic circuits with the Fritzing circuit builder, available from the Raspberry Pi store. From there, we built our first circuit on a breadboard with an LED and resistor. Using the GPIO to Connect to the Outside World Chapter 3 [ 68 ] We concluded this chapter by creating a Morse code generator with our Raspberry Pi and LED circuit. In a twist of old meets new, we were able to transmit weather data in Morse code via a blinking LED. In Chapter 4, Subscribing to Web Services, we will incorporate web services into our code, thereby connecting the internet world with the real world in a concept called the Internet of Things. Questions What is the name of the Python package that allows you access to the Raspberry1. Pi camera module? True or false? A Raspberry Pi with code written by students was deployed on the2. international space station. What are the sensors included with Sense HAT?3. True or false? We do not need to buy a Raspberry Pi Sense HAT for4. development, as an emulator of this HAT exists in Raspbian. How many ground pins are there on the GPIO?5. True or false? Raspberry Pi's GPIO has pins that supply both 5V and 3.3V.6. What is a Pibrella?7. True or false? You may only use a Pibrella on early Raspberry Pi computers.8. What does BCM mode mean?9. True or false? BOARD is the alternative to BCM.10. What does the Zero in gpiozero refer to?11. True or false? Using Fritzing, we are able to design a GPIO circuit for our12. Raspberry Pi. What is the default background parameter in the gpiozero LED blink function13. set to? True or false? It is far easier to use the gpiozero library to access the GPIO than14. it is to use the RPi.GPIO library. What is the Victorian Internet?15. Using the GPIO to Connect to the Outside World Chapter 3 [ 69 ] Further reading A lot of concepts were covered in this chapter, with the assumption that the skills needed were not beyond the average developer and tinkerer. To further solidify understanding of these concepts, please Google the following: How to install the Raspberry Pi camera module How to use a breadboard An introduction to the Fritzing circuit design software Python dictionaries For those of you that are as fascinated about technology of the past as I am, the following is a great book to read on the age of the Victorian Internet: The Victorian Internet, by Tom Standage. 4 Subscribing to Web Services Many of us take the technologies that the internet is built on top of for granted. When we visit our favorite websites, we care little that the web pages we are viewing are crafted for our eyes. However, lying underneath is the internet protocol suite of communication protocols. Machines can also take advantage of these protocols and communicate machine to machine through web services. In this chapter, we will continue our journey toward connecting devices through the Internet of Things (IoT). We will explore web services and the various technologies behind them. We will conclude our chapter with some Python code where we call a live weather service and extract information in real time. The following topics will be covered in this chapter: Cloud services for IoT Writing a Python program to extract live weather data Prerequisites The reader should have a working knowledge of the Python programming language to complete this chapter as well as an understanding of basic object-oriented programming. This will serve the reader well, as we will be separating our code into objects. Subscribing to Web Services Chapter 4 [ 71 ] Project overview In this project, we will explore the various web services that are available and touch on their core strengths. We will then write code that calls the Yahoo! Weather web service. We will conclude by having a "ticker" display of real-time weather data using the Raspberry Pi Sense HAT emulator. This chapter should take a morning or afternoon to complete. Getting started To complete this project, the following will be required: A Raspberry Pi Model 3 (2015 model or newer) A USB power supply A computer monitor (with HDMI support) A USB keyboard A USB mouse Internet access Cloud services for IoT There are many cloud services that we may use for IoT development. Some of the biggest companies in technology have thrown their weight behind IoT and in particular IoT with artificial intelligence. The following are the details of some of these services. Amazon Web Services IoT The Amazon Web Services IoT is a cloud platform that allows connected devices to securely interact with other devices or cloud applications. These are offered as pay-as-you-go services without the need for a server, thereby simplifying deployment and scalability. Subscribing to Web Services Chapter 4 [ 72 ] Amazon Web Services (AWS) services that may be used by the AWS IoT Core are as follows: AWS Lambda Amazon Kinesis Amazon S3 Amazon Machine Learning Amazon DynamoDB Amazon CloudWatch AWS CloudTrail Amazon Elasticsearch Service AWS IoT Core applications allow for the gathering, processing, and analysis of data generated by connected devices without the need to manage infrastructure. Pricing is per messages sent and received. The following is a diagram of how AWS IoT may be used. In this scenario, road conditions data from a car is sent to the cloud and stored within an S3 Cloud Storage service. The AWS service broadcasts this data to other cars, warning them of potential hazardous road conditions: Subscribing to Web Services Chapter 4 [ 73 ] IBM Watson platform IBM Watson is a system capable of answering questions posted in natural language. Originally designed to compete on the TV game show Jeopardy!, Watson was named after IBM's first CEO, Thomas J. Watson. In 2011, Watson took on Jeopardy! champions Brad Rutter and Ken Jennings and won. Applications using the IBM Watson Developer Cloud may be created with API calls. The potential for processing IoT information with Watson is immense. To put it bluntly, Watson is a supercomputer from IBM that may be accessed over the web through API calls. One such use of Watson with IoT is the IBM Watson Assistant for Automotive, an integrated solution provided to manufacturers for use in cars. Through this technology, the driver and passengers may interact with the outside world for such things as booking reservations at restaurants and checking on appointments in their calendars. Sensors in the car may be integrated, providing IBM Watson Assistant with information on the state of the car such as tire pressure. The following is a diagram illustrating a scenario where Watson warns the driver of low tire pressure, suggests having it fixed, and then books an appointment at the garage: IBM Watson Assistant for Automotive is sold as a white-label service so that manufacturers may label it to suit their needs. The success of IBM Watson Assistant for Automotive will depend on how well it competes with other AI assistant services such as Amazon's Alexa and Google's AI assistant. Integration with popular services such as Spotify for music and Amazon for shopping will also play a role in future success. Subscribing to Web Services Chapter 4 [ 74 ] Google Cloud platform Although not as extensive and well-documented as AWS IoT, Google is taking on IoT with a lot of interest. A developer may take advantage of Google's processing, analytics, and machine intelligence technologies through the use of Google Cloud Services. The following is a list of some of the services offered through Google Cloud Services: App engine: Application hosting service BigQuery: Large-scale database analytics service Bigtable: Scalable database service Cloud AutoML: Machine learning services that allow developers access to Google's Neural Architecture Search technology Cloud machine learning engine: Machine learning service for TensorFlow models Google video intelligence: Service to analyze videos and create metadata Cloud Vision API: Service to return data on images through the use of machine learning The following is a diagram of how the Google Cloud Vision API may be used. An image of a dog standing next to an upside-down flowerpot is passed to the service through the API. The image is scanned and, using machine learning, objects are identified in the photo. The returning JSON file contains the results in percentages: Google's focus on keeping things easy and fast gives developers access to Google's own private global network. Pricing for the Google Cloud Platform is lower than AWS IoT. Subscribing to Web Services Chapter 4 [ 75 ] Microsoft Azure Microsoft Azure (known formerly as Windows Azure) is a cloud-based service from Microsoft that allows developers to build, test, deploy, and manage applications using Microsoft's vast array of data centers. It supports many different programming languages, which are both Microsoft-specific and from outside third parties. Azure Sphere, part of the Microsoft Azure framework, was launched in April of 2018 and is Azure's IoT solution. The following is a scenario where Azure Sphere (or Azure IoT, as shown in the diagram) may be used. In this scenario, a robot arm located in a remote factory is monitored and controlled by a cellphone app somewhere else: You may have noticed that the previous examples could be set up with any of the competing cloud services, and that really is the point. By competing with each other, the services become better and cheaper, and as a result, more accessible. With these large companies such as IBM, Amazon, Google, and Microsoft taking on the processing of IoT data, the future of IoT is boundless. Weather Underground Although not heavyweight like the Googles and IBMs of the world, Weather Underground offers a web service of weather information that developers may tie their applications into. Through the use of a developer account, IoT applications utilizing current weather conditions may be built. Subscribing to Web Services Chapter 4 [ 76 ] At the time of writing this chapter, the Weather Underground network offered APIs for developers to use to access weather information. An end- of-service notice has been posted to the Weather Underground API site since. To keep up to date on the state of this service, visit https:/ /www. wunderground. com/ weather/ api/ . A basic Python program to pull data from the cloud In Chapter 2, Writing Python Programs Using Raspberry Pi, we introduced a package called weather-api that allows us to access the Yahoo! Weather web service. In this section, we will wrap up the Weather object from the weather-api package in our own class. We will reuse the name CurrentWeather for our class. After testing out our CurrentWeather class, we will utilize the Sense Hat Emulator in Raspbian and build a weather information ticker. Accessing the web service We will start out by modifying our CurrentWeather class to make web service calls to Yahoo! Weather through the weather-api package: Open up Thonny from Application Menu | Programming | Thonny
https://ar.b-ok.org/book/3695529/6b4930
CC-MAIN-2020-10
refinedweb
15,095
59.43
According to the contributor terms, there is the possibility to switch to an "other free and open licence". So if today I import data covered by OdBL, these data may no longer be used after a switch to a licence other than OdBL. Does this mean that I can not import data covered by OdBL? asked 03 Mar '13, 14:15 rkluge50 16●1●1●1 accept rate: 0% The contributor terms require that "You have the right to authorize OSMF to use and distribute those Contents." This means that what you import must be able to be distributed under the ODbL. This would include public domain, but also include ODbL licensed data. The license status should be made clear when consulting with the imports@ list on the import. answered 04 Nov '14, 23:59 pnorman 2.4k●5●21●40 accept rate: 18% Yes, the contributor terms mean that you can only import data that is (effectively) public domain data or data for which you have explicit permission to import it into OSM. public domain in this context includes CC0, WTFPL, Unlicense, etc. Also note the other pitfalls for imports mentioned many times in other responses here and on the wiki. answered 03 Mar '13, 16:16 cartinus 7.0k●9●65●105 accept rate: 27% edited 03 Mar '13, 16:19 Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: import ×187 license ×153 odbl ×31 question asked: 03 Mar '13, 14:15 question was seen: 3,001 times last updated: 04 Nov '14, 23:59 Can I import CC-BY-SA data into OpenStreetMap? Allowed tiles licences License question: odbl use case When will OpenStreetMap license officially change to ODBL? Creating a UK Speed Limit Map but can I sell it? Collective / Produced / Derivative Work!
https://help.openstreetmap.org/questions/20462/contributor-terms-and-import-of-odbl-licensed-data?sort=newest
CC-MAIN-2021-43
refinedweb
322
70.33
Is there any way to disable the fullscreen mode or disable the double click event for a Media Player built with Microsoft Expression Encoder? Yes. Edit BasePlayer.js: Change: _onFullScreen:function(){var a=this.get_element().content;a.fullScreen=!a.fullScreen} To: _onFullScreen:function(){var a=this.get_element().content;a.fullScreen=false} I tried various methods to overide this method in the inherited Extended Player Class, but without success. Perhaps there are private member variables that the inherited class cannot access, or perhaps I was doing something wrong. In any case, this method works. If you know of a better one, let me know. Inside. If. After; This is an alternate version to the one originally posted here. It occurred to me that if someone was actually at the console and the program quit without warning, while allegedly waiting for a key press, that would be a bit surprising and/or annoying. This new version displays a warning with an on screen count down leading up to the automatic exit: 1 using System; 2 using System.Threading; 3 4 namespace ConsoleApplication1 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 //... code here for whatever your console app does 11 Console.WriteLine("[Result of the Program]" + Environment.NewLine); 12 13 Console.WriteLine("...press any key to exit." + Environment.NewLine); 14 15 delay = new ExitDelay(); 16 delay.Start(); 17 MyTimer = new Timer(TimesUp, null, 1000, 1000); 18 } 19 20 static ExitDelay delay; 21 static Timer MyTimer; 22 static int CountDown = 10; 23 24 // Timer callback: they didn't press any key, but we don't want this window open forever! 25 private static void TimesUp(object state) 26 { 27 if(CountDown > 0) 28 { 29 Console.CursorLeft = 0; 30 Console.Write("Program will exit automatically in " + CountDown + " "); 31 CountDown--; 32 } 33 else 34 { 35 Console.CursorLeft = 0; 36 Console.WriteLine("Exiting - Bye! "); 37 Thread.Sleep(1000); 38 delay.Stop(); 39 MyTimer.Dispose(); 40 Environment.Exit(0); 41 } 42 } 43 44 } 45 46 public class ExitDelay 47 { 48 private readonly Thread workerThread; 49 50 public ExitDelay() 51 { 52 this.workerThread = new Thread(this.work); 53 this.workerThread.Priority = ThreadPriority.Lowest; 54 this.workerThread.Name = "ExitTimer"; 55 } 56 57 public void Start() 58 { 59 this.workerThread.Start(); 60 } 61 62 public void Stop() 63 { 64 this.workerThread.Abort(); 65 } 66 67 private void work() 68 { 69 Console.ReadKey(); 70 this.Stop(); 71 } 72 } 73 74 } Add this class to your console application, to assure the users that long running tasks are still working. 1 Imports System.Threading 2 3 Public Class ConsoleSpinner 4 ' Methods 5 Public Sub New(ByVal ProcessingMsg As String, ByVal FinishedMessage As String) 6 Me.processingMessage = ProcessingMsg 7 Me.finishedMessage = FinishedMessage 8 Me.workerThread = New Thread(New ThreadStart(AddressOf Me.Spin)) 9 Me.workerThread.Priority = ThreadPriority.Lowest 10 Me.workerThread.Name = "ConsoleSpinner" 11 End Sub 13 Private Sub Spin() 14 Dim index As Integer = 0 15 Do While (1 <> 0) 16 Console.Write(ChrW(13) & "{0} {1}", Me.processingMessage, ConsoleSpinner.anim(index)) 17 index += 1 18 If (index >= ConsoleSpinner.anim.Length) Then 19 index = 0 20 End If 21 Thread.Sleep(100) 22 Loop 23 End Sub 24 25 Public Sub Start() 26 Me.workerThread.Start() 27 End Sub 28 29 Public Sub [Stop]() 30 Me.workerThread.Abort() 31 Console.WriteLine("") 32 Console.WriteLine(Me.finishedMessage) 33 End Sub 34 35 36 ' Fields 37 Private Shared anim As String() = New String() {"|", "/", "-", "\", "|", "/", "-", "\"} 38 Private finishedMessage As String 39 Public processingMessage As String = String.Empty 40 Private workerThread As Thread 41 End Class Call it from any point in your main program using: Dim cs As New ConsoleSpinner("Working...", "Done.") cs.Start() ' Do Something that may take a while... cs.Stop() Suppose you need to write a console application that will run as a scheduled task on a busy production server, but you want to delay the exit so that they can read the results on the screen, but not force someone to push a key, as there may not always be someone at the console to do so. Ending with Console.ReadKey() is no good as it will wait until you push a key before it exits. Here is my solution: 11 12 Console.WriteLine("Press any key to exit..."); 13 14 delay = new ExitDelay(); 15 delay.Start(); 16 MyTimer = new Timer(TimesUp, null, 10000, Timeout.Infinite); 17 } 18 19 static ExitDelay delay; 20 static Timer MyTimer; 21 22 // Timer callback: they didn't press any key, but we don't want this window open forever! 23 private static void TimesUp(object state) 24 { 25 delay.Stop(); 26 MyTimer.Dispose(); 27 Environment.Exit(0); 28 } 29 30 } 31 32 public class ExitDelay 33 { 34 private readonly Thread workerThread; 36 public ExitDelay() 37 { 38 this.workerThread = new Thread(this.work); 39 this.workerThread.Priority = ThreadPriority.Lowest; 40 this.workerThread.Name = "ExitTimer"; 41 } 42 43 public void Start() 44 { 45 this.workerThread.Start(); 46 } 47 48 public void Stop() 49 { 50 this.workerThread.Abort(); 51 } 52 53 private void work() 54 { 55 Console.ReadKey(); 56 this.Stop(); 57 } 58 } 59 60 } This gives someone 10 seconds to read the result and press a key before exiting the application automatically. Edit: A newer Version of this technique us available . The new Version provides an on screen countdown, notifying the user that the program is about to exit - otherwise if there is someone at the console and it suddenly quits while instructing them to hit any key to quit, that might be a bit worrying! I leave this example here because it is a good example of how start and stop a new Thread as well as how to use the System.Threading.Timer Class in a slightly different way to the new version which uses polling.. I
http://www.williablog.net/williablog/author/Williarob.aspx?page=5
CC-MAIN-2020-45
refinedweb
964
60.11
This useless robot will panic if you get very close. By shaking its arms it will try to push you away but truth is this monkey needs love! Material Needed: Servo Motor 1 (HS-422) Servo Motor 2 (HS-805) Ultrasonic Range Detector Breadboard Mainboard Wires 0.5mm Plexiglass 0.5mm plastic strong glue double side tape EPS Polystyrene Foam board Step 1: Designing the Monkey The first step for building our robot is to decide on its shape. We used Rhino to define the geometry of the parts and the inner gear system and later created a laser file. Reference to inspiration: Step 2: Cutting the Parts Our lovely monkey is made out of different pieces which have been laser cut out of a 0.5mm polystyrene sheet. Each of the parts is layered out of two pieces of 0.5mm polystyrene to provide estability to its core gear system. This means that the parts have to be cut twice. Step 3: Assembling the Body The monkey parts fit perfectly together. The articulations are glued to the outer layers and the three layers (front and back outer layers and inner gear system) are later put together with some subtle double sided tape. We decided to cut one of the outer layers of the monkey out of transparent plexiglas to allow to see through into the working of the inner gear system. Step 4: Understanding the Circuit The movement of the monkey robot will be triggered by the proximity of humans. An ultrasonic sensor will give an input whenever somebody gets too close to the robot and will activate two servo motors. One of them will provide the movement to the arms and the other will spin around the whole body of the monkey. Step 5: Creating the "engine" In order to give the monkey the power to move and express his feelings we installed two servo motors on it. One will help him move his arms and the second servo will help him spin around his whole body. Step 6: The Code The following code was used to cotrol the robot. Two different levels of panic are defined depending in the distance from a human to the monkey: the closer the human, the stronger the panic. #include <br>#define trigPin 7 #define echoPin 6 Servo firstServo; Servo secondServo; int sound = 250; // void setup() { firstServo.attach(8); secondServo.attach(3); Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(2); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; // if(distance < 20){ firstServo.write(90); secondServo.write(10); delay(350); firstServo.write(150); secondServo.write(90); delay(350); Serial.println("the distance is less than 20"); } if(distance > 21){ firstServo.write(0); secondServo.write(0); delay(2700); firstServo.write(180); secondServo.write(180); delay(2700); Serial.println("the distance is larger 40"); } } Discussions 8 months ago Fun project.
https://www.instructables.com/id/Dont-Mess-With-Da-Monkey/
CC-MAIN-2019-04
refinedweb
495
56.35
On Sat, 26 Jul 2003 15:20:24 GMT, Paul Paterson <paulpaterson at users.sourceforge.net> wrote: >Stefan Schwarzer wrote: > >> Hi Paul >> >> Paul Paterson wrote: >> >>> This is a very interesting (and Pythonic) approach, thanks for >>> suggesting it! This is certainly what I would try to do if I were >>> writing the code from scratch. It may be possible to construct a >>> "namespace" type object which gets passed to the function. >> >> >> I think the most common way to make a namespace in Python is > ><snip nice example of namespace class> > >Thanks, the bare namespace class is essentially what I am going to try. > >> >> Of course, if you have a better name for your container, that's even >> better. Think of Ian's Point example. :-) > >I think you may have missed my original post; I am writing a generic VB >to Python converter so generating good names based on code intent would >be pretty tough! Perhaps in v2.0 ;) > >My current thinking is (for the orignal example of changing one >variable, 'y' but not another, 'x'), > >class Namespace: pas > ># ByVal arguments passed directly, ByRef via a namespace >def change(x, byrefs): > x = x + 1 > byrefs.y = byrefs.y + 1 > >ns = Namespace() # The local namespace >ns.x = 0 >ns.y = 0 >change(ns.x, ns) ># Now ns.x = 0, ns.y = 1 > This looks readable, to me ;-) But it is not pointer semantics, since you have to know the name for y inside change. It will be nice and fast if you can use the above, but if not, in some cases, class NSP below will let you use it just like Namespace above, though with pointer features if you need them. I just wanted to throw in here that the namespace approach will also let you use properties (there's a handy builtin to create them from accessor methods, or you can instantiate them from your own descriptor classes) as your byrefs "variables" if you like. You just have to mane the NameSpace class inherit from object, to make it a new-style class. Then you can add properties either right in the class definition or later by setting class attributes , e.g., >>> class Namespace(object): pass ... >>> ns = Namespace() >>> ns.x = 123 >>> Namespace.p = property(lambda self:'Read is only access function specified here') Note that the above was *not* setting an instance attribute with ns.p = property(...) >>> ns.x 123 >>> ns.p 'Read is only access function specified here' >>> ns.x = 456 >>> ns.p = 789 Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: can't set attribute >>> del ns.p Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: can't delete attribute So you can define a kind of constant, or have any side effect you want for setting, getting, and deleting. Note that normal class attributes are shadowed by instance attributes, e.g., >>> ns.x # from last assignment 456 >>> Namespace.>> ns.x 456 >>> del ns.x # deletes ordinary instance attribute >>> ns.x # and if instance attribute is absent, it will be looked for in class '456000' Actually it is a little more complicated than that, since it has to be determined that there is not a data descriptor/property in the class overriding the instance variable access. That's why I said "normal" ;-) A namespace for variables also gives you the potential to define methods for the name space itself. Here is an example with a name space that has an internal pointer class and lets you create "pointers" to the "variables" in the namespace, using ns[vname] syntax, which goes to the __getitem__ method of the class to make a "pointer" (__slots__ hopefully just makes pointer instances better optimized): >>> class NSP(object): ... """NSP defines name space with "pointer" creation via p = ns[vname]""" ... class Ptr(object): ... """Ptr instance holds ns ref and vname for access to ns.vname""" ...>> You can also save a "pointer" and use it later, or pass it around: >>> px = ns['x'] >>> px[:] 123 ( [:] is just sugar, since the arg is ignored. [0] will run faster, since no slice object is needed) >>> px[0] 123 >>> px[0] = 'new x value' >>> ns.x 'new x value' >>> Establish some new values: >>> ns.x = 123; ns.y = 456 >>> ns.x, ns.y (123, 456) An important distinction from using explicit byref attribute names (e.g. byref.y) in change(): >>> change('byvalue', px) # note we are passing px in the py parameter position >>> ns.x, ns.y ('new via py[:]', 456) I.e., change was passed a "pointer" it thought of as pointing to y (i.e., was named "py" by the programmer to suggest the meaning), but it pointed to x, and so x changed when py[:] was assigned to. Changes to 'byvalue' were just local to change, as expected. We can also delete an attribute via the pointer: >>> del px[0] >>> ns.x Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'NSP' object has no attribute 'x' which doesn't affect the "pointer" itself: >>> px[0]='an x again' >>> ns.x 'an x again' but of course deleting the pointer itself as opposed to px[0] will: >>> del px >>> ns.x 'an x again' >>> px Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'px' is not defined i.e., the pointer got deleted, not the thing pointed to. I'm not necessarily recommending any of the above, but I thought it might give you some ideas. There is definitely a performance hit in px[:] (or better, px[0]) vs byref.x to consider. Anyway, I thought properties and descriptors might also come in handy somewhere in your quest ;-) Raymond Hettinger has written a nice "How-To Guide for Descriptors": and for properties (follow Table Of Contents link in below page) and much more there is HTH Regards, Bengt Richter
https://mail.python.org/pipermail/python-list/2003-July/177511.html
CC-MAIN-2016-44
refinedweb
974
73.68
TabGroup individual size On 17/12/2016 at 16:58, xxxxxxxx wrote: All groups in a tabGroup are sized to the max size of each tab. For exemple if tab A got 3 elements and the tab B got 1 elements, you will have extra space in the tab B for matching the size of tab A. Is there a way to remove this extra size? Thanks in advance ! On 19/12/2016 at 09:17, xxxxxxxx wrote: Hi, Do you some code showing this? The size of tab pages groups is adapted to the size of its main TabGroup and not to their content. The TabGroup doesn't resize when the active tab page changes. On 19/12/2016 at 09:29, xxxxxxxx wrote: Originally posted by xxxxxxxx The size of tab pages groups is adapted to the size of its main TabGroup and not to their content. Yep that is the problem, is there a workaround to fix it? Here a code sample as you said there are extra space in the second tab I didn't want. Since in my script (not this one) I deal with 1 tab that can have 400/800 height px and another tab with only 10/20 px is really not visual pleasante to have a lot of extra space dat you can't avoid. import c4d class MyDialog(c4d.gui.GeDialog) : dialog = None def CreateLayout(self) : if self.TabGroupBegin(id=1001, flags=c4d.BFH_LEFT, tabtype=c4d.TAB_TABS) : if self.GroupBegin(id=1011, flags=c4d.BFH_FIT, cols=2, title="1st tab") : self.element = self.AddStaticText(id=1005, flags=c4d.BFH_LEFT, initw=275, name="a", borderstyle=c4d.BORDER_NONE) self.element = self.AddStaticText(id=1006, flags=c4d.BFH_LEFT, initw=275, name="b", borderstyle=c4d.BORDER_NONE) self.element = self.AddStaticText(id=1007, flags=c4d.BFH_LEFT, initw=275, name="c", borderstyle=c4d.BORDER_NONE) self.element = self.AddStaticText(id=1008, flags=c4d.BFH_LEFT, initw=275, name="d", borderstyle=c4d.BORDER_NONE) self.element = self.AddStaticText(id=1009, flags=c4d.BFH_LEFT, initw=275, name="e", borderstyle=c4d.BORDER_NONE) self.GroupEnd() if self.GroupBegin(id=1021, flags=c4d.BFH_SCALE, cols=2, rows=4, title="2nd tab") : self.element = self.AddStaticText(id=1010, flags=c4d.BFH_LEFT, initw=275, name="a", borderstyle=c4d.BORDER_NONE) self.element = self.AddStaticText(id=1011, flags=c4d.BFH_LEFT, initw=275, name="b", borderstyle=c4d.BORDER_NONE) self.GroupEnd() self.GroupEnd() return True def main() : a = MyDialog() a.Open(c4d.DLG_TYPE_MODAL) if __name__=='__main__': main() On 20/12/2016 at 04:02, xxxxxxxx wrote: There's no workaround for this. This is how the TabGroup gadget work and this kind of control doesn't usually resize its pages. You should maybe rethink your UI.
https://plugincafe.maxon.net/topic/9861/13277_tabgroup-individual-size
CC-MAIN-2020-50
refinedweb
446
68.16
Crossfire 1.4.0 Announcement Crossfire 1.4.0 has been released. The main change is the use of automake. The addition of abstracting body locations for equipment is included - this allwos for finer granularity in controlling what different races can put on. The experience for different levels is now moved to a configuration file, making it easier to tune the differeing values. There are also lots of bugfixes. NOTE: With the automake changes, the location of the configuration files has changed. See the NEWS file in the server directory. I packed up gnuzip (.gz) versions of the files. Looking at the download stats on sourceforge, these are more popular, and for the most part, are not that much larger than the .bz2. Only doing one such method also makes it easier on me to distribute the files. Files released for this version: sums (bsd) filename 61293 1464 crossfire-1.4.0-arch.tar.gz 63480 4523 crossfire-1.4.0-maps.tar.gz 21772 3477 crossfire-1.4.0.tar.gz 13017 394 crossfire-client-1.4.0.tar.gz 11454 1304 crossfire-client-images-1.4.0.tar.gz 06374 253 crossfire-client-sounds-1.4.0.tar.gz Sums (md5) 5df9f8981afdd4e6c174b49e8e3c0db2 crossfire-1.4.0-README dd54ea16b98d0bb95a6ed176e0046013 crossfire-1.4.0-arch.tar.gz 788381affd5b29d6601dd4371314bb80 crossfire-1.4.0-maps.tar.gz 999b7a1a678e8ffa075fed45545a6ef6 crossfire-1.4.0.tar.gz 6ab310b8d2ea80e7fae246775dc819e2 crossfire-client-1.4.0.tar.gz 7b8ea870de491cf5070f05ae876bcbf2 crossfire-client-images-1.4.0.tar.gz 1b33401d9d2af0d391fee7ad04282cfd crossfire-client-sounds-1.4.0.tar.gz crossfire-client-1.4.0 is the client (X11) distribution - standard X11 and gtk interfaces are provided. A major bug related to image caching is fixed. Better handling of configuration options was done. Stat bars can now be drawn in graduated colors. crossfire-client-images.1-client-sounds-1.4.0.tar.gz contains sound files for the client. The change was to increase the volume of the sound files so that they are more in line with other sounds played on the system. crossfire-1.4.0.tar.gz contains the server code with prebuilt archetype and image files. crossfire-1.4.0.arch.tar.gz contains the unpacked archetype changes. This is not needed if you only want to compile the server and play the game. Several monsters were tuned, and new ones added. crossfire-1.4.0-maps.tar.gz contains the maps. This is needed with the server distribution. FOR FIRST TIME USERS: You will only need the appropriate server, map: server/disease.c: Change move_disease() somehwat - before, if you were not susceptible to a disease, it would never run its course. Yet you would still get stuck with the symptoms. there was a case on metalforge where a character had a symptom with no disease, and had immunity, yet was still getting stuck with the symptoms. Not sure if this change will help prevent that in the future or not. include/player.h: Change item_power in player structure to be 16 bits - 8 bit values were getting overflowed. MSW 2002-09-14 INSTALL: Update directions with new automake method. common/Makefile.am, common/Makefile.in: Fix code for building the libproto.h file - it was including loader.l and not loader.c common/exp.c: Add init_experience() and dump_experience() functions - init_experience() loads the experience table from a file. Add default experience table into this file common/init.c: Add call to init_experience() common/living.c: Remove experience tables - players can select the one they want by changing the exp_table file. Remove reference to new_levels[] - only levels[] is used now for the formentioned reason. include/config.h: Update notes about SIMPLE_EXP system. include/libproto.h: rebuilt. lib/Makefile.am, lib/Makefile.in: Add exp_table to list of files. lib/exp_table: New file that contains experience information. server/c_object.c: Modify command_take() to look for objects above the player to pick up, then objects below. This fixes the bug with not being able to use the take command on items from a chest the player opens without moving off the space. server/init.c: Add -mexp dump switch to dump the experience table. Allow the simple experience system to be set in the settings file. server/skill_util.c: Fix oddness in calc_skill_exp() which could result in add amounts of exp given. MSW 2002-09-10 include/sproto.h: rebuilt lib/help/killpets: New file lib/Makefile.in: Add help/killpets file. server/c_misc.c: Add command_kill_pets(). server/commands.c: add killpets command which kills your pets. server/monster.c: Add some code in check_enemy so that the enemy has to be a monster/generator/player to be considered valid - I was seeing things like arrows ending up as target enemies. MSW 2002-09-07 More bugfixes: common/loader.l, loader.c: Fix up the handling with speed with respect to style maps - the objects were still getting put on the active list. common/map.c: Fix up blocked_link() to behave more like the blocked_two() function - inventory checkers and door handling. Comment out blocked_two since it isn't used anymore. Modify load_objects to remove objects on style maps from the active list. Remove some of the debug messages about map loading. common/object.c: Add remove_from_active_list() function for use in map.c to remove objects from active list. common/porting.c: Comment out debug message if open_and_uncompress() can open a file - caller of the function should print out messages, and it really isn't much of an error in any case. include/libproto.h: rebuilt. random_maps/special.c: Modify place_special_exit() - this should fix bug of very large treasure maps - problem was if the generated map size was too small, when generate_random_map was called, it would generate a newly sized map that was much larger. Code was also re-arranged some to make it a little more readable. server/attack.c: Fix crash when creature may not have an owner and it kills something else. server/move.c: comment added - no code change. socket/request.c: Fix off by one error in esrv_send_animation() - rare condition as it only showed up when trying to send the last animation (zombie) - only an issue if the player is put on top of a zombie for some reason (no other space for them) - observed when leaving the random dungeon in the undead church in scorn without clearing out all the zombies first. MSW 2002-09-06 CHANGES: Update build instructions for the plugin. random_maps/square_spiral.c: Fix bug that could cause the search function to go off the edge of the map looking for a clear space. Doesn't happen often, but one crash did happen here. server/monster.c: Fix some bugs with monsters and wakeup - remove check for friendly that could never be true, and also fix logic so that monsters will now find the players. MSW 2002-09-05 common/button.c: Fix do_mood_floor() to look at all objects on space for something to effect, not just things above the moodfloor. server/attack.c: Add missing check to make sure the plugin exists before we try to access the plugin function. common/readlable.c: Fix crash caused by passing null value to mon_desc - check for non null was at end of { } do loop - check should be at the start. server/monster.c: Make it so that monsters with see invisible are not immune to blind - monster can be given appropriate resistance to make it so it is not effected by blind. MSW 2002-09-04 server/main.c: Move #endif in crypt_string to more proper place. server/monster.c: Fix bad if statement that may have been waking up monsters when they shouldn't have been. MSW 2002-09-03 This change mostly deals with improving behaviour of pet monstes. Most of the code is from K. Reinert - however, I did some code cleanup/ fixes related to pet monsters, so it is difficult to note where each piece of code came from. One thing this does fix is handling of multipart pets - these now work properly. common/map.c: Update comment for get_rangevector() - no code change. common/object.c: Add get_search_arr() which is used in pet monster code. This returns a semi random scrambling of the freearr array. doc/Developers/protocol: Update documentation about map1a protocol command. include/libproto.h, include/sproto.h: rebuilt. server/attack.c: Have drain attacks return 1 damage so that it is clear that you are actually hitting your opponent. Otherwise, you would get messages that 'you missed xyz', even though you are draining it. This extra point of damage shouldn't change balance in any significant way. server/monster.c: Update hnadling of enemies for pet monsters. It should more intelligently choose the monsters and not switch/clear the enemy field for no reason anymore. Change find_nearest_living_creature to use the get_search_arr() to more randomly choose direction of target - before, there was a proclivity to always look in the north direction. Modify can_hit() to look for closes part of enemy - otherwise, monsters may not attack opponents even if they were right next to them because they couldn't get to the enemies head. Remove move_object from this function - merged with move_ob in move.c server/move.c: Fix move_ob to use 'cleaner' code of move_object, but also have specific features that move_ob had (player handling). Before move_ob didn't handle multipart objects correctly, and the two functions were largely the same. Now move_object() just calls move_ob - the only difference in the functions is that move_ob() takes 3 parameters instead of 2 of move_object() (added parameter is originator). I think this should now mean multipart player objects may now work. server/pets.c: get_pet_enemy enhanced to be much smarter about selecting/finding things for the pet to attack. server/player.c: Remove commented out line of init_beforeplay MSW 2002-08-31 server server/time.c: Possible fix for bug seen on metalforge - in move_player_mover, make sure we are working with the head of the monster. MSW 2002-08-13 common/item.c: Have describe monster show resistances of monsters - useful for spoiler output, as well probe spell. server/disease.c: Fix typo. MSW 2002-08-02 Various bug fixes, add glyph spell: TODO: Updated common/map.c: Fix change_map_light() - if darkness was reduced to zero, it wouldn't properly notify the players or update the maps they are on. Also, make it more robust to handle changes by more than one. include/define.h: Increase NROFREALSPELLS include/spellist.h: Add glyph spell. include/spells.h: Add SP_GLYPH entry. server/attack.c: Fix up kill_object() - it has had some many various additions that it was difficult to follow the logic. It should also now do better check on skill objects when awarding experience. server/player.c: Add some checks/addition to properly deal with freeing the name_pl in the player object. Fix it so that if you are braced, you still won't attack friendly creatures. server/rune.c: Add cast_generic_rune() to handle the glyph and rune spell. server/spell_effect.c: Fix up some pointers in cast_cause_disease() - needed so that it works properly when embedded in a glyph. Have it return 1 even if no one caught anything - you still cast the spell, so you should lose the grace for it. server/spell_util.c: Fix some formatting. Break out the code dealing with rune into cast_generic_rune() socket/loop.c: Add flag to player command mapping, and update structure - if flag is set, command can only be issued when player is in play, and not when waiting at the quit or login prompt - fixes crashes where players could wait for the map to get swapped out (after quitting), and then looking at a space. socket/request.c: Fix map2cmd so that invisible players are drawn. MSW 2002-07-24 Add dm command 'freeze' which freezes a player from doing anything for some amount of time. include/sproto.h: rebuilt. lib/Makefile.in: Add freeze to wizhelp files. lib/wizhelp/freeze: New file. server/c_wiz.c: Add command_freeze(). Also, break out get_other_player_from_name() - several functions need the same logic of getting a player named X that is not us - making it a function reduces the duplicate code. Fix some formatting for some functions. server/commands.c: Add command_freeze to the dispatch table. MSW 2002-07-17 lib/Makefile.in: add a 'archonly' directive that only collects archetypes and doesn't collect images. lib/archetypes: rebuilt for fixes made to arches. lib/collect.pl.in: modified to take second parameter -ARCHONLY, that causes it not to save out animation, bmaps and faces file. server/apply.c: Change order of print when applying/unapplying - print out the 'you apply/unapply' before we print out the changes that applying the item does. It seems odd for it to be 'you feel stronger. you apply xyz'. Fix can_apply_object() so that if a player needs to unapply several items, the right return code is returned and we don't say the player has a choice. server/player.c: Fix missing clearing of player->next. MSW 2002-07-15 -- Start body commit notes -- Major commit. This adds body locations which is used for equipping items. Equipment has information which body part it gets equipped to, and monsters have information on how which body locations they can have. As part of this work, I also did a lot of code cleanup. To use this, you must use up to date archetypes - the ones included in this commit are fine - just make sure you install them. If you don't, players will not be able to equip items. common/arch.c: Initialize body_used to be same as body_info for archetypes - this way when monsters are created, they can start equipping items right away. common/exp.c: update new_exp() - some flags it checked for before no longer exist or have new names. common/info.c: describe_item() now takes second parameter - update dump_abilities to use new calling convention. common/item.c: Add table that describes the body_info locations and their names. Add functions that calculate item power for objects that don't have it set. Update display functions to show item_power in items. Update describe_monster() - use_horn/wand/rod merged into just use_range. Modify describe_item() to take second paramater - who the item is being described for. Show item_power in describe_item. common/living.c: Pull out MAXLEVEL from being defined in this file - define in in define.h, since other files use it. Add NUM_STATS define - replace hard coded values of having just 7 stats with it. Update change_abil to not display that the player has a new attacktype when equipping a bow that has it - fix_player() ignores the attacktype of the bow, so it was incorrect information. fix_player(): Initialize player ranges structure to null - will get filled in by code in function, updated to deal with updating the body_used data from body_info in the objects. Replace instances of last_heal with gen_sp_armour. Rearrange some code to make function more readable. common/loader.c, common/loader.l: Remove the variable_const information - no longer needed and confusing for new people when adding in new object elements. Add set_body_info() - parses the string from the load file and sets the appropriate array element. Add check_loaded_object() - does sanity checking for an object after finished loading - replaces need for long processing directive in the actual rules by having seperate function. Remove unused flags from load directives (apply_once, no_pretext, can_apply), add some new ones (item_power, gen_sp_armour), update others to can_use_range. Replace flag_links with simple array that contains the name for each corresponding flag. Update get_ob_diff to not use the V_ values and just include the actual string name - all recent changes have done this, just updated for old stuff. Update get_ob_diff to save new values that have been added. common/object.c: clear_object: Modify to use memset to clear the structure to zero - this is less error prone than listing all the specific values, and probably faster. Also, makes it easier to add new elements - no need to update object.c in most cases. common/player.c: Remove get_player_ob routine - this is now merged in with get_player_ob in server/player.c. Remove generate_ext_title - not used. common/readable.c: Update to pass second argument to describe_item. common/treasure.c: Update to calculate item_power of generated items. Clean up a lot of code formatting. Update add_abilities to use gen_sp_armour values, not last heal (note, it appears the last_heal values weren't being used before). Update calls to describe item to take second parameter. doc/Developers/objects: Update will_apply notes, add note about item_power, body location. include/define.h: Comment out unused flags (flag_apply_once, flag_paralyzed, flag_no_pretext, flag_ready_rod, flag_read_horn). Add flag_use_shield. rename flag_use_wand to flag_use_range. rename flag_ready_wand to flag_ready_range. Add flag_ready_scroll. Update ARMOUR_SPELLS access macro. Add AP_PRINT flag to apply flags. Add CAN_APPLY_.. return types for can_apply_object function. include/includes.h: add strftime, mktime checks to this file. include/libproto.h: rebuilt. include/living.h: Add NUM_STATS define, update extern declarations to use it for sizing. include/loader.h: remove the V_.. info and xbm_.. externs that were not used. include/newserver.h: Remove ext_tile information. include/object.h: Add Body_Locations structure, NUM_BODY_LOCATIONS define. Add definitions for WILL_APPLY values. Clean up object structure - formatting is now consistent, ordering of values groups values together more logically. Update all types to use the int8/int16/int32 types. Several unused fields removed. include/player.h: Update rangetype enum. Add unapplymode enum. Clean up player structure - type updates, unused fields removed, formatting fixed up. include/spells.h: remove range_name extern. Update SpellTypeFrom field to combine wand/rod/horn into spellMisc - none of the spell casting code was differentiating these. include/sproto.h: rebuilt. lib/Makefile.in: Add new help files (applymode, bind, brace) lib/archetypes: rebuilt for body_info, gen_sp_armour, item_power, can_use_shield information. lib/artifacts: updated for item_poer and gen_sp_armour changes. lib/treasures: remove unused _force for player treasure. plugin/plugin_python.c: Change FLAG_USE_WAND to FLAG_USE_RANGE. server/apply.c: Move stftime, mktime to include/includes.h. Remove draw_find() - one line function can just as easly be in the code itself. Update calls to long_desc to pass second parameter. move gravestone_text() to player.c file. Add direction parameter to apply_scroll() - in this way monsters can use it properly. Remove dead code. Update apply_special function. Add unapply_special(), get_item_from_body_location(), unapply_for_ob(), and can_apply_object() functions. server/attack.c: Remove SET_FLAG(op, FLAG_PARALYZED) line - no code was ever checking status of FLAG_PARALYZED. server/c_misc.c: add command_body() which dumps body information for player. Update who as idle element in player structure removed - was not being used by anything. Add command_applymode() to set players prefered unapply method. Remove calls to unlock_player() in various functions - unlock_player() has not done anything meaningful for a while. server/c_object.c: Modify long_desc to take a second parameter which is who is examing the object. this is needed so that we can pass it down to some of the lower level functions. Update calls to describe_item to pass this second parameter. remove FLAG_NO_PRETEXT code - no archetyps were using it. When examining objects, also tell player where to put them on. server/c_range.c: Update legal_range() - we now store the object that is responsible for a range in the player object, so code is much simpler. Update change_spell() to not destroy golem just by readying another spell - we now let players regain control of golems after switching to another range. Update change_spell to use item name of object for range description. server/c_wiz.c: remove reference to count_left from player object - field removed from structure. server/commands.c: add new commands (applymode, body) to command dispatch table. server/login.c: Remove unlock_player() and lock_player() and calls to it - current checking of names at login should be sufficient to prevent duplicates. Remove dead code from check_name. Update load/save code for unapply mode value. Add set_flag(op, FLAG_USE_SHIELD) if player is allowed to use armor - needed since flag_use_shield is really a class feature and so is not automatically updated for old player files. server/main.c: Remove references to count_left. memset marker object to NULL - seems to increase stability on metalforge server. server/monster.c: Many updates related to the body info - monsters follow some rules as players. Add monster_should_cast_spell function - monsters will use this for all spellcasting related actions (abilities, scrolls, wands, etc). Update for merged rod/horn/wand ranges. Update bow use by monsters - they don't actually need to equip it to fire - this way we don't need to constantly swap the monsters weapons between the bow and melee item. Use fire_bow from player.c for most of the work. Modify scroll usage - monster will use it when player is near, not when it first picks it up. Add FLAG_READY_SCROLL to denote the monster has a scroll to use. Also, monster now casts it in appropriate direciton. Merge the monster_use_wand/rod/horn into monster_use_range. Modify check_good_weapon and check_good_armour to just look at the stats of the two items without needing the monster to apply it first. server/player.c: Print motd in green so it is more noticable. Update get_player function to do work it did before as well as that of get_player_ob. Have get_player take a parameter which is the object of the player if he has one. Modify to use memset to clear the player structure - more sure fire than explicitly listing values to initialize. Remove calls to unlock_player. Modify fire_bow so that monsters can also use the function. Add fire_misc_object() to fire_wand/rod/horn - removes code from fire(). Add gravesetone_text() to this file. server/shop.c: Update to pass second parameter to describe_item(). server/skill_util.c: Update check_skill_to_fire since there are fewer rangetypes now. change range_scroll name to range_golem, as that is a bit more accurate for what it actually does. Modify show_skills() to show player his item power and total of items he has equipped. server/skills.c: Add second paramater to long_desc, remove references to count_left. server/spell_effect.c: Add second paramater to long_desc, remove references to count_left. Update range_scroll to range_golem server/spell_util.c: remove references to count_left. Update messages if player trying to cast where he can't with new range names. socket/info.c: Update range information and how we display what it is - we will use the object name of the range if available. Remove reference last_known_spell, last_shoot, last_spell, last_value player structure fields. socket/init.c: Remove ext_title information. socket/request.c: Add element for life_stealing in the resistance array. Remove references to idle, count_left in player structure. remove ext2 title information. MSW 2002-07-14 -- End body commit notes -- common/anim.c, common/button.c, common/friend.c, common/glue.c, common/init.c,common/logger.c, common/los.c, common/porting.c, common/time.c, common/utils.c, crossedit/png.c, crossedit/xutil.c, include/attack.h, include/config.h, include/map.h, include/material.h, include/newclient.h, include/skills.h, include/treasure.h, random_maps/decor.c, random_maps/door.c, random_maps/floor.c, random_maps/monster.c, random_maps/special.c, random_maps/standalone.c, random_maps/style.c, random_maps/wall.c, server/alchemy.c, server/c_chat.c, server/c_party.c, server/gods.c, server/hiscore.c, server/init.c, server/pets.c, server/resurrection.c, server/rune.c, server/time.c, socket/metaserver.c: Update banner copyright with proper contact information. MSW 2002-07-14 server/disease.c: Fix propogation of diseases with negative damage (these do a percent of the creatures damage). The new disease was getting a damage rating of 1 in all cases because we were passing a negative value to random_roll for the top end of the range. MSW 2002-07-08 common/arch.c: Add 'unlocked' match for item_matched_string. lib/help/drop, lib/help/dropall: Help files for these commands. lib/Makefile.in: Update to include help commands above. server/spell_effect.c: Fix formatting of summon_pet() function. Modified so that it no longers sucks player spellpoints when casting it via scroll - scrolls should not cast the player spellpoints. No idea why that code was there - in fact, casting off a scroll used more sp than casting from memory. Modify cast_cause_disease() function so that if the passed direction is 0, we refer to the facing and cast in that direction - this means spells of cause disease now work. Also perform some minor formatting changes in the function. TODO: Add not about inscription. MSW 2002-07-05 common/arch.c: Fix bug in item_matched_string which was matching all values (inverse in fact) when passed with count > 1 in matching string - missing ! operator. README: Update - remove note about windows client, since it is currently unsupported and could stop working in some future release. MSW 2002-07-05 client: common/image.c: Fix bug of not fulling clearing the cache entry data after allocation. This resulted in various random crashes when using cached image mode. x11/x11.c: Add note about -facset. CHANGES, Makefile.in, configure, configure.in: Update for 1.4 release MSW 2002-09-14 common/item.c: Update comment about possible sorting improvements. gtk/gx11.c: Add missing foodbeep functionality to GTK client. MSW 2002-08-13 Makefile.in: if no makedepend, don't run make depend directive. README: Add not about ALSA revisions and possible problems compiling. MSW 2002-07-10 This commit adds graduated colored statbars to the gtk client. What this means is that the color of the statbar goes smoothly from red to yellow to green depending on what percentage of your hp/sp/grace/food is compared to your maximum. To use this, you need to go to the config pane and hit
http://crossfire.real-time.com/download/140release.html
CC-MAIN-2019-18
refinedweb
4,261
59.4
Having the images and/or text used through an application packed into a single resource component which is included into your main assembly is very attractive for an application as it makes the deployment set compact. Moreover, loading these images from code is much less prone to errors since otherwise there will be a bunch of images spread out in some folder. Furthermore when working on full applications, sometimes it is a necessary to mix C# and VB due to either end-user requests or the need to interface with APIs and/or legacy library calls and some of the arguments for those are specific for either language and finding the equivalent is cumbersome or the conversion just does not work. This article covers both topics as I ran into this and had to dig a bit deep to get an actual working solution. The basics are straightforward but the details are what needed some research and some extra tools/steps as the Microsoft documentation is a bit vague, nothing new there. First we create a resource component: Right click on the solution and select Add Component on the pop up menu. This will display different templates, select a resource file: An extra Resource item will be listed on your solution, now click on the newly added resource item. You will get the option to add resources, do add your images, in our case we picked a couple of pre-cooked images. Upon completion you'll see there will also be a resources folder created under your solution, and your images will be listed there. For the method shown here, make sure that each of the images is set as an embedded resource. OK, now the code for calling is listed below. The highlighted section shows the syntax to extract the specific image from the resource. The namespaces needed here are System.Reflection for Assembly interface and System.IO for Streaming. System.Reflection System.IO private void btnLoad_Click(object sender, EventArgs e) { //load the images from the resource string start_name = "resource_sample"; // the target EXE (or DLL if mixed code mode) //set the basic drawing displayBuffy = new Bitmap(200,200); //set ip the screen canvas Graphics displayCanvas = Graphics.FromImage(displayBuffy); Bitmap bmp; // Now grab the image from the resource as a stream Assembly assembly = Assembly.GetExecutingAssembly(); string strRes = start_name + ".Resources.bandera_checker.gif"; Stream stream = assembly.GetManifestResourceStream(strRes); bmp = null; try { bmp = new Bitmap(stream); } catch { } stream.Close(); //displayCanvas.DrawImage(bmp, 10, 10); displayCanvas.DrawImage(bmp, new Rectangle(5, 5, bmp.Width / 3, bmp.Height / 3), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel); //show on the form Invalidate(); } // --- end of btnLoad_Click -- private void Form1_Paint(object sender, PaintEventArgs e) { if (displayBuffy != null) { Graphics g = e.Graphics; g.DrawImage(displayBuffy, 0, 0); } } // --- end of Form1_Paint --- Up to here nothing exciting. Of course if you only have one or two images, it will all work beautifully, but when building large applications, quite a few images are needed and they usually are modified as the development goes on. But while doing this, the code will eventually not load a specific image no matter how deep your debug goes. To solve this, first we need to double check the name and path of the image in the EXE, due to the many changes made sometimes it either gets moved or is not included. The Visual Studio tool called ILDASM.exe comes pretty handy here, loading your EXE (or DLL for mixed language solutions) will allow you to see the actual path to the included resources, just click on the MANIFEST as shown in the picture below and you will see the actual details for the specific image or if it is actually included in the resource component. The ILDASM.exe is part of the framework SDK. If you don't have it, it can be downloaded from here. With this, it is straightforward to double check if the specific images were actually included in the resource. As we well know, when the code grows in size and there are a large number of images being modified, it does not take long to get them out of place or hit a glitch in the VS where it ends up skipping them. As stated at the beginning, for many reasons it may be necessary to have mixed code, sometimes the end-user has some older code which usually is in VB and wants to still use it and maintain it or some other similar reasons. For this, we can easily add a VB section as a DLL and it is all good. It can go either way, e.g. having the main code in VB and adding the companion as C# or the other way. In the sample here C# will be the main code and the companion code will be in VB. In essence, all we need to do is add another project to the current solution in the other language (VB in the sample below), add a reference to the companion code and use the proper syntax. The first step is to add another project to our current solution. If you have the VS installed by default, you will not see the option to add another project. To enable it, go to Tools->Options->Projects & Solutions and make sure you check always show solution as in the figure below: So now you will get the solution view, highlight the solution and click Add New Project in the pop up, select the VB smart_device type as shown in the figure below: On the next screen, we select the type as class library and we are ready to go. This will make the VB section a DLL where the needed VB routines will live. Our project will now list a class vb file under the newly added VB project. Inside this file we can put our library of VB routines. In a real world scenario where we have many routines, it makes sense if we group routines with some common behaviour and/or handling into a respective namespace. Such code is listed below: ' All we need is to define our little home-brewed namespace and ' we are good to go with the mix Namespace resource_sample_VB Public Class VB_Class_1 Public Sub My_add_date(ByRef this_date As Date, ByVal days_2_add As Integer) Dim tmp_date As Date tmp_date = this_date Try tmp_date = tmp_date.AddDays(days_2_add) Catch tmp_date = this_date End Try this_date = tmp_date End Sub End Class End Namespace Finally we need to call this VB code from the main Project (C#). Since we made the VB code as a class library, the code will be compiled into a DLL. We need this DLL to be available to the main Project. To do so, a reference to the VB DLL needs to be added as in the figure below: One small issue here is that while browsing to make a reference of the VB DLL at the very beginning there will be no such DLL as the VB project has not been built yet. A quick workaround is to highlight the vb project and build it from the Build Menu, afterwards you can go to the references and browse for the DLL. Finally from C#, this is the syntax to call it . . . using System.Reflection; // Needed for Assembly using System.IO; // Needed for Stream using resource_sample_VB_pieces.resource_sample_VB; // from our VB section . . . private void btn_Add2Date_Click(object sender, EventArgs e) { // instantiate the VB class VB_Class_1 vb_tools = new VB_Class_1(); DateTime thisDate = DateTime.Parse (textDate.Text); //call the VB method vb_tools.My_add_date(ref thisDate, Int32.Parse( textDays.Text )); //print out the result carried out by VB LblResult.Text = thisDate.ToString("d"); } // --- end of btn_Add2Date_Click --- In our sample code, the btnLoad_Click loads the image from the Resource component and the btn_Add2Date_Click button passes the values on the textboxes to the VB and the simple date calculation is printed out. btnLoad_Click btn_Add2Date_Click textbox Statistically, old VB code is used from legacy code and/or the end-user wants to maintain it. The mixing code shown above allows to cover such a case where the preferred C# runs along with the VB code. Also the resource component or another set of resources could be also placed on the DLL to make it more memory efficient. Of course, this is not the only way to accomplish this, but it is tested and it works. This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)
http://www.codeproject.com/Articles/36897/How-To-Use-a-Single-Resource-Component-for-your-Im
crawl-003
refinedweb
1,413
60.04
These are chat archives for ramda/ramda Ramda's lens is a bit involved. What's the extra complexity for, compared to something like: const lens = (get, set) => ({get, set}) const view = (lens, data) => lens.get(data) const set = (lens, v, data) => lens.set(v, data) const over = (lens, fn, data) => lens.set(fn(lens.get(data)), data) aand you have a lens that points to a property byou can compose them compose(lensA, lensB) setin terms of over, but viewcould be a lot less indirect { value: theValue }in that process type Iso s a = forall p. (Profunctor p) => p a a -> p s s type Iso' s a = (a -> a) -> (s -> s) henswas a tickling starting place. fromPromisemethod was the way to go... Hey @m59peacemaker I'll give it a closer look soon, but ftr you can take advantage of block scoping see: mapand chain, its also made by the same person who wrote most.js, so it's probably pretty fast too. isLens) out of interest? fromPromiseto do. But then can't seem to just get out the resolved value (which I want to shove into an Either for handling whether or not the fields I need exist on the json...) Future, so something like Future.bimap( Left, Right )will give you a Future Either a .bimap(e => e, s => s.users_url)but accessing the users_url may fail as it may not exist (hence wanting to shove it into an Either) R.minByon an array of objects but considering two properties on the object? That is "choose the object from the array that has the smaller X, and the smaller Y" (in that order) var sortByKeys = pipe( map( pipe(prop, ascend) ) ,sortWith ) sortByKeys(['x','y'])(xs) pipe( map( pipe(prop, ascend) ) ,(fs) => (a,b) => sortWith(fs, [a,b]) ) (() => {and I didn't feel like it const should have just done 1 thing, made a variable immutable, but they throw in block scoping, which var doesn't do, so there's now this inconsistency, where previously it was just "no block scoping use functions". It also didn't really get immutability right, so... And "no block scoping: use functions" isn't a bad thing at all, its just unusual. But JS is unusual, and if we just accept it for what it is we could avoid these additions that have complex exceptional behaviour. this, again exceptional behaviour that is of 0 use in FP Everything they add, its like they get the thing its meant to do wrong, and they add some special addendum. Reading the spec is like "its like ... kind of sort of, except when.... oh and watch out for" They design the language for sub optimal use cases which only validates those sub optimal paths as optimal paths. So I wish they just stopped adding stuff. And if they are going to add stuff, be consistent, respect the existing language behaviour and extend it instead of pretending its a different language. I mean web assembly is here, there's really no reason to pretend JS isn't JS anymore. const x = {}; x.newProp = 'huehuehue' also pet peeve with block scoping: try { const a = ... const b = ... const c = ... throw ... } catch (e) { // I want to access a,b,c (e.g. for logging) here but I can't } The above seems easy to fix, but the solution is to just localize try catches as much as possible, adding more and more layers of nesting. This problem doesn't really affect me because I don't use try catch, but it still annoys me in principal. But I imagine it would come up a lot when people write imperative code with async await. const mapNth = (n, fn, data) => over(lensIndex(n), fn, data) over. mapLensdoesn't make sense :) @ramda/reduce @ramda/mapetc overtopic, I think having mapin the name makes it more understandable. You both might have different experience to me, but so far I've found trying to write utils that hide the lens from the caller ends up being less powerful/useful. I mean, there's exceptions, but instead of mapNth, I'd just make writing lensIndex less verbose, like L.at over filterByStatepoint free?, optionally by using lenses: const list = { tasks: [ { id: 2, state: 'done' }, { id: 3, state: 'todo' }, { id: 4, state: 'done' }, ], }; const filterByState = state => R.pipe( R.prop('tasks'), R.defaultTo([]), R.filter(R.propEq('state', state)), ); const todos = filterByState('todo'); const result = todos(list); const mapNth = (n, fn, data) => over(lensIndex(n), fn, data) vs over( L.at(0), fn, data ) Not so bad inline const mapNth = n => over(L.at(n)) map(over(lensIndex(1), inc), { foo: 1 }) // { foo: 2 } map(overNth(1), inc overis elegant there. pipe(map(inc), filter(isEven))// actually using transducers but looks the same as usual forloop wrt let for used to be sugar for (var i = 0; i < 4; i++) {...}; // same as var i = 0; while (i < 4) {...; i++;} but w/ let i is weirdly scoped to the block over, thinking that it is like normal mapwhere that's ok because you're creating a new thing. [ k, v ]all the time overLastjust for that purpose. overFirstto map the keys for (let i = 0; i < 4; i++) {...}; // same as { let i = 0; while (i < 4) {...; i++;} } I was working on a ui abstraction over lenses, and it quickly became apparent hiding lenses from the user, would make things more complex than that getting them comfortable with lenses. So instead of hiding them, I changed the api around, basically binding lenses to a particular state stream, which you'd think would defeat the point of lenses, but on reflection, reading/writing from arbitrary state is less useful than composing lenses (for me at least) convergeor useWithhave been the ticket to making it point free. first, headand tail. useWith( filter, [propEq('state'), propOr([], 'tasks')] ) ([ k , v ]) => [ k, inc(v) ] overNth(1, inc) // how does first, last, head, or tail help? @smeijer the first argument will go to the first function of the list, so 'todo' would go into propEq('state', 'todo') propEq('state', 'todo') And the list, argument will go to the second funciton propOr([], 'tasks', list) Then when they're expanded, they both get applied to filter. So we end up with something like filter( propEq('state', 'todo'), propOr([], 'tasks', list) useWithis helpful when you have separate transform paths for separate args, convergeis useful when you have multiple transform paths for the same arg propor plucketc function, you know they will put thisin it. thisis this? thisand first-class functions you don't need a module system implementation. I know it's heresy. But you do need a specification importbased module system over the anarchy of the past babel-preset-envfor the super winniest win everest node_modules/appto accomplish something like that postinstallhook :( require('~/path/like/this')would work require('project-relative-require').setRoot(__dirname) const things = require('~/things/relatively') cwd()as a default if no path given? path.resolve( require.resolve('yourpackage'), '..', '..' ) mainis, but that's in your control require.resolve('yourpackage/package.json') var p; while( p = require.parent ){ } root = p.id process.env.ROOT_DIR? Run script with ROOT_DIR=/my/root node ./main.js var p = process.env.ROOT_DIR || path.resolve( require.resolve('yourpackage'), '..', '..' ) require.main.id const fs = require('fs') var p = __dirname var root; while( !root ){ fs.readdirSync('.') .find( s => s.includes('package.json') p = path.resolve( p, '..' ) } const fs = require('fs') var p = __dirname var root = process.env.ROOT_DIR; while( !root ){ fs.readdirSync('.') .find( s => s.includes('package.json') p = path.resolve( p, '..' ) } ROOT_DIR=/usr/local/myproject node ./testfile.js doin loop form? async function* OMG() { yield await response() } forEachfor async iterators? aand b. I want to test whether a[ k ] === b[ k ]. I'm drawing a blank. pipe(pluck,apply(equals)) @Ramblurr I think its a great idea, but my experience to date (typescript) is essentially useless for point free style. It makes composition painful. (I really, really wanted it to work, and I tried so many times :( ) But you could have a type system that worked really well for FP JS, I just don't think the likes of Facebook or Microsoft would jump on that project. While trying to make it work I realised how much I value composition above static type guarantees. And that the bugs typescript catches aren't bugs you'd encounter if you wrote FP style code anyway. I'd really like to be proven wrong here though! /* globals localStorage */ //eslint-disable-next-line no-undef const checkTypes = !!process.env.CHECK_TYPES const $ = require('sanctuary-def') const Type = require('sum-type')($, { checkTypes, env: $.env }) const Stream = require('flyd') const remember = Stream.stream(true) import $AuthPermission from '../../../types/auth_permissions' const $Auth = Type.Named('Auth', { LoggedOut: {} ,LoggedIn: { auth_token: String , user_id: String , auth_permissions: $.Array($AuthPermission) } }) const initial = JSON.parse(localStorage.getItem('auth') || 'null') const auth = Stream.stream( initial ? $Auth.LoggedInOf(initial) : $Auth.LoggedOutOf({}) ) // notifications if an invalid auth object is created auth.map( $Auth.case({ LoggedOut: () => localStorage.setItem('auth', 'null') ,LoggedIn: () => remember() && localStorage.setItem('auth', JSON.stringify(auth()) ) }) ) export default { stream: auth , type: $Auth , remember } @kurtmilam Anything you have to share (thoughts, intuitions, etc) would be appreciated. I’ve done some experimenting with State and streams in isolation…not really lenses though sum-typethe other day. Really cool. Any reason you're not using sanctuary-defas an internal dependency? over, setand getbut they take streams rather than objects, and operate on the objects contained in the streams. flyd.stream partial.lenses const s = flyd.stream( {} ) // later on s() // to get the value in the stream s( {a:1} ) // to set the value in the stream sliceor lensedstreams that focus on a specific part of the state object in the state stream container. const over = stream => optic => fn => R.compose( R.tap( stream ) , Object.freeze , L.modify( optic, fn ) )( stream() ) @kurtmilam yeah…I mean the Monad A Day - State example is the most “complete” example that I’ve found. Second I guess would be the ramda-fantasy state example. But they are really just handling one process…and maybe that is enough to start with. mainor IO) before the values go to the view (which can ONLY be managed via side effects) evolve, where the transformations could become rather complex adjust(add(10), 1, data) over(lensIndex(1), add(10), data) evolveand assocPath, now I can't see a use for lenses :/ Is there a way to delay evaluation of the default expression in pathOr. For example, in my redux thunk action creator: const setEvent: ThunkActionCreator = (eventId: EventId): Thunk => async (dispatch: Dispatch, getState: GetState): AsyncVoid => { const event = R.pathOr(await getEvent(eventId), ['events', 'map', eventId], getState()); console.log(event); }; I want to see if the event exists in state.events.map, and if not, I'll call my api method to fetch it. It works, but getEvent is called even if the event exists in the map. I want it to be lazily evaluated. Can I make that happen? await getEvent(eventId)in a thunk and check to see if eventis a function. If so, call it const setEvent: ThunkActionCreator = (eventId: EventId): Thunk => async (dispatch: Dispatch, getState: GetState): AsyncVoid => { const event = R.pathOr(async () => await getEvent(eventId), ['events', 'map', eventId], getState()); console.log(typeof event === 'function' ? event() : event); }; asyncfunctions and didn't even know they had asyncarrow functions yet. @gabejohnson Thanks, that works. I would just have to change event() to await event(), but I think I'm just going to stick with: const event = R.path(['events', 'map', eventId], getState()) || await getEvent(eventId); It's a little cleaner. @JAForbes isn't pipeK + yield/value (a way to fold) essentially a for expression? it's not at all. nevermind @gabejohnson thanks, yeah it used to be a direct dependency, but sanctuary-def changes versions so rapidly that I couldn't keep up. I decided I'd set the version as a peer dep that I know works, but if I'm a few versions behind someone can live dangerously and inject their own. Once the api's for both libraries settle I'll go back to a direct dependency most likely. There's going to be a lot of breaking changes coming up in sum-type, eventually, one thing I'd really like to fix is the initialization experience for users that have no idea what sanctuary-def is, and don't want to pass in env etc. But I think that will depend on upstream discussions, which would probably make it a sum-type 2.0 change. The breaking changes I'm driving towards right now, are really just removing stuff, moving in a more static direction, removing prototype support, making case's behaviour more powerful but also predictable, uncurried constructors (the most common footgun I run into), support object literal style only, easier serialization for sending types over the wire, a lot of small changes that should make for a simpler library. @Ramblurr I don't sorry :( I've seen lots of back end code in that style, for a library, but large systems code, and especially front end code is exceedingly rare in open source in that style. @miwillhite I've ranted a lot in the past about why I think Rx's whole "subject's are bad" is harmful. Clearly subjects aren't bad per se, because they use them internally for things like fromEvent etc. I think the reason they say pushing values into streams is bad, is because they are worried people will do it all the time instead of writing reactive code. And for their demographic (OO programmers) that is perfectly understandable. But if you have a source of data (e.g. a virtual dom node) and you want to have a source stream for that event. Then naturally there's nothing wrong with { onclick: clicks }. Particularly when event listeners are already destroyed in element removal, which in the context of virtual dom isn't something you need to think about. And old streams will be gc'd automatically. In fact { onclick: clicks } is a lot simpler and declarative than obtaining the DOM node via a hook to pass to Rx so it can set up event listeners on its own separate to the framework. That's pretty ridiculous in my opinion. Particularly in frameworks like mithril, where event binding and redraw logic is handled by the framework automatically. I do think we should as much as possible define streams in terms of mapping over a source stream, and we shouldn't push values into dependent streams (except when we know what we're doing in some rare, but powerful cases) The reason its not simply misguided but harmful in my opinion to advocate for "subjects are bad": If you aren't allowed to compose subjects directly you end up requiring a massive list of predefined operators (e.g. Rx's standard lib) to do anything useful. And even worse, you need to name them, and store those names in your head! And even worse a lot of the names are proprietary and specific to Rx, or they reuse names from FP but incorrectly. Flyd can do everything Rx can do. A lot of operators in Rx can be reproduced effortlessly in flyd simply because subjects are ok. Really with flyd all you ever need is map. The ability to push values into a stream, and retrieve the most recent value, is invaluable for client side development. If you can't do that you end up jumping through all these hoops on the quest of avoiding subjects that you have to invent entirely new UI programming paradigms. But flyd is also fantasy land compatible, so it works with ramda/sanctuary out of the box. Most is a great library, but I think streams shouldn't be monadic, they should just be applicative functors. We shouldn't be using observables for everything, its like using div's for everything. There's no reason to have a nested stream in my experience. And there's no reason for a stream to have any notion of errors, we've got Either, Maybe, Future etc for that already. There's so much wrong with the way we talk about streams/observables in my opinion. E.g. the constant comparison to promises, when they are useful for completely different things. Or thinking of streams as "observable" is a very imperative framing. Instead of thinking about "values that change over time" we should be thinking about "permanent relationships that never change". And focusing on time at all defeats the point of abstracting over it. I wish we called them Fact's instead of Streams, or Observables. But I think Streams is arguably closer to the truth than observables. Think of a line plot. Rx thinks of streams as a series of dots on the graph. We should think of streams as a line or curve on that plot where the individual dots are not of any interest, but the relationship, or the equation is. So y = x ^ 2not [{ x:0, y:0}, { x:2, y: 4}, { x: 3, y: 9 }, ...] The fact there are discrete points on a line isn't important at all. Anyway that's my rant on Rx/observables :D adjust(add(10), 1, data) // instead of over(lensIndex(1), add(10), data) [{name: "Brian", address: {street: {no: 32, name: "George", suffix: "St"}}}] adjuststuff as well? return (acc, value) => { const key = getKey(value) const group = getGroup(key, acc) const newGroup = putIntoGroup(value, group) return nextStep(acc, [ key, newGroup ]) } array of objects-to-object-with-key, array-pairs-groupbyout of that? R.groupBy const getKey = v => v.name const getGroup = (key, coll) => coll[key] || [] const putIntoGroup = (value, group) => { group.push(value) // not really supposed to mutate, but it's ok here return group } const groupBy = getKey => nextStep => { return (acc, value) => { const key = getKey(value) const group = getGroup(key, acc) const newGroup = putIntoGroup(value, group) return nextStep(acc, [ key, newGroup ]) } } getGroup, putIntoGroupand derive a groupByfor something other than array to object. pipe(groupBy(prop('name')), filter(v => v[1].length > 2))
https://gitter.im/ramda/ramda/archives/2017/04/04?at=58e3a7da408f90be66894a24
CC-MAIN-2020-10
refinedweb
3,013
63.8
Posted on March 1st, 2001. The support for datagrams in Java has the same feel as its support for TCP sockets, but there are significant differences. With datagrams, you put a DatagramSocket on both the client and server, but there is no analogy to the ServerSocket that waits around for a connection. That’s because there is no “connection,” but instead a datagram just shows up. Another fundamental difference is that with TCP sockets, once you’ve made the connection you don’t need to worry about who’s talking to whom anymore; you just send the data back and forth through conventional streams. However, with datagrams, the datagram packet must know where it came from and where it’s supposed to go. That means you must know these things for each datagram packet that you load up and ship off. A DatagramSocket sends and receives the packets, and the DatagramPacket contains the information. When you’re receiving a datagram, you need only provide a buffer in which the data will be placed; the information about the Internet address and port number where the information came from will be automatically initialized when the packet arrives through the DatagramSocket. So the constructor for a DatagramPacket to receive datagrams is: DatagramPacket(buf, buf.length) in which buf is an array of byte. Since buf is an array, you might wonder why the constructor couldn’t figure out the length of the array on its own. I wondered this, and can only guess that it’s a throwback to C-style programming, in which of course arrays can’t tell you how big they are. You can reuse a receiving datagram; you don’t have to make a new one each time. Every time you reuse it, the data in the buffer is overwritten. The maximum size of the buffer is restricted only by the allowable datagram packet size, which limits it to slightly less than 64Kbytes. However, in many applications you’ll want it to be much smaller, certainly when you’re sending data. Your chosen packet size depends on what you need for your particular application. When you send a datagram, the DatagramPacket must contain not only the data, but also the Internet address and port where it will be sent. So the constructor for an outgoing DatagramPacket is: DatagramPacket(buf, length, inetAddress, port) This time, buf (which is a byte array) already contains the data that you want to send out. The length might be the length of buf, but it can also be shorter, indicating that you want to send only that many bytes. The other two arguments are the Internet address where the packet is going and the destination port within that machine. [64] You might think that the two constructors create two different objects: one for receiving datagrams and one for sending them. Good OO design would suggest that these should be two different classes, rather than one class with different behavior depending on how you construct the object. This is probably true, but fortunately the use of DatagramPackets is simple enough that you’re not tripped up by the problem, as you can see in the following example. This example is similar to the MultiJabberServer and MultiJabberClient example for TCP sockets. Multiple clients will send datagrams to a server, which will echo them back to the same client that sent the message. To simplify the creation of a DatagramPacket from a String and vice-versa, the example begins with a utility class, Dgram, to do the work for you: //: Dgram.java // A utility class to convert back and forth // Between Strings and DataGramPackets. import java.net.*; public class Dgram { public static DatagramPacket toDatagram( String s, InetAddress destIA, int destPort) { // Deprecated in Java 1.1, but it works: byte[] buf = new byte[s.length() + 1]; s.getBytes(0, s.length(), buf, 0); // The correct Java 1.1 approach, but it's // Broken (it truncates the String): // byte[] buf = s.getBytes(); return new DatagramPacket(buf, buf.length, destIA, destPort); } public static String toString(DatagramPacket p){ // The Java 1.0 approach: // return new String(p.getData(), // 0, 0, p.getLength()); // The Java 1.1 approach: return new String(p.getData(), 0, p.getLength()); } } ///:~ The first method of Dgram takes a String, an InetAddress, and a port number and builds a DatagramPacket by copying the contents of the String into a byte buffer and passing the buffer into the DatagramPacket constructor. Notice the “+1” in the buffer allocation – this was necessary to prevent truncation. The getBytes( ) method of String is a special operation that copies the chars of a String into a byte buffer. This method is now deprecated; Java 1.1 has a “better” way to do this but it’s commented out here because it truncates the String. So you’ll get a deprecation message when you compile it under Java 1.1, but the behavior will be correct. (This bug might be fixed by the time you read this.) The Dgram.toString( ) method shows both the Java 1.0 approach and the Java 1.1 approach (which is different because there’s a new kind of String constructor). Here is the server for the datagram demonstration: //: ChatterServer.java // A server that echoes datagrams import java.net.*; import java.io.*; import java.util.*; public class ChatterServer { static final int INPORT = 1711; private byte[] buf = new byte[1000]; private DatagramPacket dp = new DatagramPacket(buf, buf.length); // Can listen & send on the same socket: private DatagramSocket socket; public ChatterServer() { try { socket = new DatagramSocket(INPORT); System.out.println("Server started"); while(true) { // Block until a datagram appears: socket.receive(dp); String rcvd = Dgram.toString(dp) + ", from address: " + dp.getAddress() + ", port: " + dp.getPort(); System.out.println(rcvd); String echoString = "Echoed: " + rcvd; // Extract the address and port from the // received datagram to find out where to // send it back: DatagramPacket echo = Dgram.toDatagram(echoString, dp.getAddress(), dp.getPort()); socket.send(echo); } } catch(SocketException e) { System.err.println("Can't open socket"); System.exit(1); } catch(IOException e) { System.err.println("Communication error"); e.printStackTrace(); } } public static void main(String[] args) { new ChatterServer(); } } ///:~ The ChatterServer contains a single DatagramSocket for receiving messages, instead of creating one each time you’re ready to receive a new message. The single DatagramSocket can be used repeatedly. This DatagramSocket has a port number because this is the server and the client must have an exact address where it wants to send the datagram. It is given a port number but not an Internet address because it resides on “this” machine so it knows what its Internet address is (in this case, the default localhost). In the infinite while loop, the socket is told to receive( ), whereupon it blocks until a datagram shows up, and then sticks it into our designated receiver, the DatagramPacket dp . The packet is converted to a String along with information about the Internet address and socket where the packet came from. This information is displayed, and then an extra string is added to indicate that it is being echoed back from the server. Now there’s a bit of a quandary. As you will see, there are potentially many different Internet addresses and port numbers that the messages might come from – that is, the clients can reside on any machine. (In this demonstration they all reside on the localhost, but the port number for each client is different.) To send a message back to the client that originated it, you need to know that client’s Internet address and port number. Fortunately, this information is conveniently packaged inside the DatagramPacket that sent the message, so all you have to do is pull it out using getAddress( ) and getPort( ), which are used to build the DatagramPacket echo that is sent back through the same socket that’s doing the receiving. In addition, when the socket sends the datagram, it automatically adds the Internet address and port information of this machine, so that when the client receives the message, it can use getAddress( ) and getPort( ) to find out where the datagram came from. In fact, the only time that getAddress( ) and getPort( ) don’t tell you where the datagram came from is if you create a datagram to send and you call getAddress( ) and getPort( ) before you send the datagram (in which case it tells the address and port of this machine, the one the datagram is being sent from). This is an essential part of datagrams: you don’t need to keep track of where a message came from because it’s always stored inside the datagram. In fact, the most reliable way to program is if you don’t try to keep track, but instead always extract the address and port from the datagram in question (as is done here). To test this server, here’s a program that makes a number of clients, all of which fire datagram packets to the server and wait for the server to echo them back. //: ChatterClient.java // Tests the ChatterServer by starting multiple // clients, each of which sends datagrams. import java.lang.Thread; import java.net.*; import java.io.*; public class ChatterClient extends Thread { // Can listen & send on the same socket: private DatagramSocket s; private InetAddress hostAddress; private byte[] buf = new byte[1000]; private DatagramPacket dp = new DatagramPacket(buf, buf.length); private int id; public ChatterClient(int identifier) { id = identifier; try { // Auto-assign port number: s = new DatagramSocket(); hostAddress = InetAddress.getByName("localhost"); } catch(UnknownHostException e) { System.err.println("Cannot find host"); System.exit(1); } catch(SocketException e) { System.err.println("Can't open socket"); e.printStackTrace(); System.exit(1); } System.out.println("ChatterClient starting"); } public void run() { try { for(int i = 0; i < 25; i++) { String outMessage = "Client #" + id + ", message #" + i; // Make and send a datagram: s.send(Dgram.toDatagram(outMessage, hostAddress, ChatterServer.INPORT)); // Block until it echoes back: s.receive(dp); // Print out the echoed contents: String rcvd = "Client #" + id + ", rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": " + Dgram.toString(dp); System.out.println(rcvd); } } catch(IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { for(int i = 0; i < 10; i++) new ChatterClient(i).start(); } } ///:~ ChatterClient is created as a Thread so that multiple clients can be made to bother the server. Here you can see that the receiving DatagramPacket looks just like the one used for ChatterServer. In the constructor, the DatagramSocket is created with no arguments since it doesn’t need to advertise itself as being at a particular port number. The Internet address used for this socket will be “this machine” (for the example, localhost) and the port number will be automatically assigned, as you will see from the output. This DatagramSocket, like the one for the server, will be used both for sending and receiving. The hostAddress is the Internet address of the host machine you want to talk to. The one part of the program in which you must know an exact Internet address and port number is the part in which you make the outgoing DatagramPacket. As is always the case, the host must be at a known address and port number so that clients can originate conversations with the host. Each thread is given a unique identification number (although the port number automatically assigned to the thread would also provide a unique identifier). In run( ), a message String is created that contains the thread’s identification number and the message number this thread is currently sending. This String is used to create a datagram that is sent to the host at its address; the port number is taken directly from a constant in ChatterServer. Once the message is sent, receive( ) blocks until the server replies with an echoing message. All of the information that’s shipped around with the message allows you to see that what comes back to this particular thread is derived from the message that originated from it. In this example, even though UDP is an “unreliable” protocol, you’ll see that all of the datagrams get where they’re supposed to. (This will be true for localhost and LAN situations, but you might begin to see some failures for non-local connections.) When you run this program, you’ll see that each of the threads finishes, which means that each of the datagram packets sent to the server is turned around and echoed to the correct recipient; otherwise one or more threads would hang, blocking until their input shows up. You might think that the only right way to, for example, transfer a file from one machine to another is through TCP sockets, since they’re “reliable.” However, because of the speed of datagrams they can actually be a better solution. You simply break the file up into packets and number each packet. The receiving machine takes the packets and reassembles them; a “header packet” tells the machine how many to expect and any other important information. If a packet is lost, the receiving machine sends a datagram back telling the sender to retransmit. [64] TCP and UDP ports are considered unique. That is, you can simultaneously run a TCP and UDP server on port 8080 without interference. There are no comments yet. Be the first to comment!
https://www.codeguru.com/java/tij/tij0166.shtml
CC-MAIN-2018-51
refinedweb
2,206
62.78
Combinatorics has many applications within computer science for solving complex problems. However, it is under-represented in libraries since there is little application of Combinatorics in business applications. Fortunately, the science behind it has been studied by mathematicians for centuries, and is well understood and well documented. However, mathematicians are focused on how many elements will exist within a Combinatorics problem, and have little interest in actually going through the work of creating those lists. Enter computer science to actually construct these massive collections. The C++ Standard Template Library (STL) brought us the very useful algorithm next_permutation, which generates permutations of lists using iterators. However, most languages, including C#, do not have built in libraries for the generation of these lists. To fill this gap, a lot of work has been done in different languages focused on permutations, including a host of articles at the CodeProject. Even though so much quality work has already been done, I still found myself wanting for additional capabilities. In particular, a single solution that fulfils all of the following self-imposed requirements: next_permutation foreach If you're new to Combinatorics, then many of these requirements may not make sense. The Background section below includes a complete overview of the combinatorial concepts, including samples and how to calculate the size of the output sets. The Using the Code section follows up with the classes provided for each collection, and describes the features provided with these classes; this section contains everything you need to know to use the enclosed classes. Next, the Algorithm and Performance section discusses some of the options for implementation that were considered, and explains some of the major design decisions. Finally, the Sample section explains the small sample application included to demonstrate the use and need for Variations. There are two common combinatorial concepts that are taught in every probability course. These are permutations and combinations. There is a lesser known collection known as a variation, which adapts features from both permutations and combinations. In addition, there are variants of each of these three which involve introducing repetition to the input or the output. These collections with repetition are also typically glossed over in introductory courses. So, the complete list of combinatorial collections is: Permutations deal with the ordering of a set of items, for example, how many ways a deck of 52 cards can be shuffled. Combinations deal subsets of a set of items, for example, how many 5 card poker hands can be dealt from a deck of 52 cards. In both cases, each card in the deck or in the hand is unique, so repetition is not a factor. However, problems do arise where repetition does occur in the input and/or output. For these cases, the repetition versions allow us more options in constructing our output sets. Variations are used when not only the subset provided by combinations is relevant but also the ordering within that subset. Each of these is covered below. Permutations are all possible orderings of a given input set. Each ordering of the input is called a permutation. When each item in the input set is different, there is only one way to generate the permutations. However, when two or more items in the set are the same, two different permutation sets are possible. These are called Permutations and Permutations with Repetition. Standard permutations simply provide every single ordering of the input set: Permutations of {A B C}: {A B C}, {A C B}, {B A C}, {B C A}, {C A B}, {C B A} The number of Permutations can be easily shown [2] to be P(n) = n!, where n is the number of items. In the above example, the input set contains 3 items, and the size is 3! = 6. This means that the number of permutations grows exponentially with n. Even a small n can create massive numbers of Permutations; for example, the number of ways to randomly shuffle a deck of cards is 52! or approximately 8.1E67. Permutations with Repetition sets give allowance for repetitive items in the input set that reduce the number of permutations: Permutations with Repetition of the set {A A B}: {A A B}, {A B A}, {B A A} The number of Permutations with Repetition is not as large, being reduced by the number and count of repetitive items in the input set. For each set of m identical items, the overall count is reduced by m!. In the above example, the input set contains 3 items with one subset of 2 identical items, the count is 3! / 2! = 6 / 2 = 3. The idea behind the count is easier than the formula since the formula requires the product of each repetitive set of size ri. The total size is Pr(n) = n! / Π(ri!) (where Π is the product operator). All of the collating and calculating is handled for us using the Permutation.Count property. Permutation.Count The code library accompanying this article will determine, based on the input set, which type of permutation to use. Alternately, a type may be supplied to determine which permutation type to use. Combinations are subsets of a given size taken from a given input set. The size of the set is known as the Upper Index (n) and the size of the subset is known as the Lower Index (k). When counting the number of combinations, the terminology is generally "n choose k", and is known as the Binomial Coefficient [3]. Unlike permutations, combinations do not have any order in the output set. Like permutations, they do have two generation methods based on the repeating of output items. These are called Combinations and Combinations with Repetition. Combinations can be thought of as throwing a set of n dominos into a hat and then retrieving k of them. Each domino can only be chosen once, and the order that they were fished out of the hat is irrelevant. In a similar fashion, (n = 100) Scrabble tiles can be thrown into a bag, and the first player will select (k = 7) tiles. However, there are 9 A's in the bag, and selecting {A A A A A A A} would be a valid, although unlikely, draw. Since there are only 6 Ns in the bag, it is not possible to draw 7 Ns. As such, the values of the tiles are ignored for the Combinations, this differs from Permutations. Combinations of {A B C D} choose 2: {A B}, {A C}, {A D}, {B C}, {B D}, {C D} The number of outputs in this particular example is the Binomial Coefficient. It is calculated as n! / ( k! * (n - k)! ) [4]. The Scrabble example above would give us 100! / (7! * 93!) = 16,007,560,800. Note that the answer to 100! is much larger than the answer as most of its magnitude was cancelled out by 93!. Combinations with Repetition are determined by looking at a set of items, and selecting a subset while allowing repetition. For example, choose a tile from the scrabble bag above, write down the letter, and return the letter to the bag. Perform this 7 times to generate a sample. In this case, you could "draw" 7 Ns, just with a lower probability than drawing 7 As. As such, Combinations with Repetition are a superset of Combinations, as seen in the following example: Combinations with Repetition of {A B C D} choose 2: {A A}, {A B}, {A C}, {A D}, {B B}, {B C}, {B D}, {C C}, {C D}, {D D} Combinations are used in a large number of game type problems. For example, a deck of (n = 52) cards of which a (k = 5) card hand is drawn. Using the set of all combinations would allow for a brute force mechanism of solving statistical questions about poker hands. Variations combine features of combinations and permutations, they are the set of all ordered combinations of items to make up a subset. Like combinations, the size of the set is known as the Upper Index (n) and the size of the subset is known as the Lower Index (k). And, the generation of variations can be based on the repeating of output items. These are called Variations and Variations with Repetition. Variations are permutations of combinations. That is, a variation of a set of n items choose k, is the ordered subsets of size k. For example: Variations of {A B C} choose 2: {A B}, {A C}, {B A}, {B C}, {C A}, {C B} The number of outputs in this particular example is similar to the number of combinations of n choose k divided by the permutations of k. It can be calculated as V(n, k) = C(n, k) * P(k) = (n! / ( k! * (n - k)! )) * k! = n! / (n - k)!. The sample project included uses variations to select digits to be substituted for letters in a simple cryptographic word problem. Variations with Repetition expands on the set of variations, and allows items to be reused. Since each item can be re-used, this allows for variations to include all items in the output to be a single item from the input. For example: Variations with Repetition of {A B C} choose 2: {A A}, {A B}, {A C}, {B A}, {B B}, {B C}, {C A}, {C B}, {C C} The size of the output set for variations is easier to compute since factorials are not involved. Each of the p positions can be filled from any of the n positions in the input set. The first item is one of n items, the second is also one of n, and the pth is also one of n. This gives us Vr(n, k) = nk total variations of n items choose k. There are three class entry points in the code library, Permutations, Combinations, and Variations. Each of these is a generic class based on the type T of the items in the set. Each of these also generates a collection of collections based on the input set, making each a meta-collection. For ease of use, the classes implement IEnumerable<T>, which returns an IList<T>. However, this generic code is designed to make the consumption of each class easy. For example, using Permutations: Permutations Combinations Variations T IEnumerable<T> IList<T> char[] inputSet = {'A', 'B', 'C'}; Permutations<char> permutations = new Permutations<char>(inputSet); foreach(IList<char> p in permutations) { Console.WriteLine(String.Format("{{{0} {1} {2}}}", p[0], p[1], p[2])); } will generate: {A B C} {A C B} {B A C} {B C A} {C A B} {C B A} Using Combinations and Variations is similar, but the Lower Index must also be specified. (The Upper Index is derived from the size of the input set.) For example: char[] inputSet = { 'A', 'B', 'C', 'D' }; Combinations<char> combinations = new Combinations<char>(inputSet, 3); string cformat = "Combinations of {{A B C D}} choose 3: size = {0}"; Console.WriteLine(String.Format(cformat, combinations.Count)); foreach(IList<char> c in combinations) { Console.WriteLine(String.Format("{{{0} {1} {2}}}", c[0], c[1], c[2])); } Variations<char> variations= new Variations<char>(inputSet, 2); string vformat = "Variations of {{A B C D}} choose 2: size = {0}"; Console.WriteLine(String.Format(vformat, variations.Count)); foreach(IList<char> v in variations) { Console.WriteLine(String.Format("{{{0} {1}}}", v[0], v[1])); } Combinations of {A B C D} choose 3: size = 4 {A B C} {A B D} {A C D} {B C D} Variations of {A B C D} choose 2: size = 12 {A B} {A C} {A D} {B A} {C A} {D A} {B C} {B D} {C B} {D B} {C D} {D C} By default, Permutations, Combinations, and Variations will generate the standard or no-repetition sets. Each class has an overloaded constructor that takes a GenerateOption, which can either be GenerateOption.WithoutRepetition (the default) or GenerateOption.WithRepetition. For example, to generate a permutation set with and without repetition: GenerateOption GenerateOption.WithoutRepetition GenerateOption.WithRepetition char[] inputSet = { 'A', 'A', 'C' }; Permutations<char> P1 = new Permutations<char>(inputSet, GenerateOption.WithoutRepetition); string format1 = "Permutations of {{A A C}} without repetition; size = {0}"; Console.WriteLine(String.Format(format1, P1.Count)); foreach(IList<char> p in P1) { Console.WriteLine(String.Format("{{{0} {1} {2}}}", p[0], p[1], p[2])); } Permutations<char> P2 = new Permutations<char>(inputSet, GenerateOption.WithRepetition); string format2 = "Permutations of {{A A C}} with Repetition; size = {0}"; Console.WriteLine(String.Format(format2, P2.Count)); foreach(IList<char> p in P2) { Console.WriteLine(String.Format("{{{0} {1} {2}}}", p[0], p[1], p[2])); } Permutations of {A A C} without Repetition; size = 3 {A A C} {A C A} {C A A} Permutations of {A A C} with Repetition; size = 6 {A A C} {A C A} {A A C} {A C A} {C A A} {C A A} Note that the input set for Permutations must have repetition in it in order to see a difference in the output. Combinations and Variations will generate additional sets regardless of the similarity of incoming values. While the intent of these classes is not to calculate Binomial Coefficients, each class does have a Count property. This property will calculate the actual count of collections returned, without iterating through them. This is done by applying the formulas in the general discussion above and returning the value as a long. Finally, the counting is done without internal overflow, which is important since 21! will overflow a long. Count long The constructor parameters are also available; the upper index and lower index are available using UpperIndex and LowerIndex, respectively. The generator option is available through the Type property. For example: UpperIndex LowerIndex Type char[] alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray(); Combinations<char> C = new Combinations<char>(alphanumeric, 10); Console.WriteLine(String.Format("{0} choose {1} = {2}", C.UpperIndex, C.LowerIndex, C.Count)); 36 choose 10 = 254186856 Finally, these common features are formalized through the IMetaCollection interface that each of these classes implement. IMetaCollection At this point, we've covered everything that is required to understand and use these classes. The remainder of this discussion describes a bit of the background and decision making processes used in its implementation. The numbers of permutations, combinations, and variations all grow exponentially. As such, a meta-collection enumerator on any but a trivial set of items will quickly exceed any available computation time. For example, a system that can enumerate a permutation of 10 items in 1 second will take over 1000 years to enumerate a permutation of 20 items. Since the performance for even the best algorithm will degrade, pretty much any algorithm will do. However, no developer could hold their head high without evaluating options and choosing the best algorithm for the job, even if it only knocks 50 years off a 1000 year run. The ability to calculate a permutation is core to all of the combinatorial classes. Several algorithms have been developed for calculating permutations, three of which were evaluated for this implementation, namely Recursive, Lexicographic, and Heap's algorithms [1]. The Lexicographic algorithm [3] is perfectly suited for the IEnumerable interface, since it uses the same GetNext() style and requires very little adaptation. Both Recursive and Heap's algorithms are more efficient at generating permutations of integers, but need to be adapted for an IEnumerable interface by either converting to an iterative algorithm or using C# continuation. IEnumerable GetNext() The first attempt was to take the more efficient heap based algorithms and un-roll them into iterative algorithms, and then to make them conform to the one result per call behavior of the IEnumerable interface. Both heap algorithms stored quite a bit of state information and did not un-roll easily. Once done, they each went from about twice as fast as lexicographic to about twice as slow. The second attempt was to use the continuation feature added to C# in .NET 2.0. This feature provides the yield return syntax for quickly creating enumerators. It is also capable, with a bit of extra work, to handle recursive enumerators. The good news is that this mechanism works, but the performance was even worse than un-rolling the recursive algorithm by a factor of 4. yield return The lexicographic algorithm was therefore chosen as the best algorithm for this implementation. The next issue revolved around performance of comparisons. All algorithms tested had to be changed to accommodate non-integer data. The lexicographic algorithm needs to compare objects to determine their sort order to be able to create a unique lexicographic order. The standard way of resolving this involves the IComparable or IComparer interfaces to determine the order. As this is a generic collection, it is relatively straightforward to adapt the integer comparison to an IComparer provided comparison. Unfortunately, this comparison is called a lot and any inefficiency is magnified. Since this is a generic type comparison, the CLR does not optimize this nearly as efficiently as a value type. IComparable IComparer The other problem with the use of a direct comparison on objects to permute is that the permutations will always be Repetitive instead of Non-Repetitive. That is, you cannot create a Non-Repetitive permutation of {A A B}. Together with the above performance issues, another solution was required. {A A B} The final solution was to have a parallel array of integers on which the comparisons are performed. Both arrays will have items swapped in parallel, creating the correct output. The performance improves to within a few percent of the integer only solution that the algorithm started with. And the repetitive and non-repetitive set solutions are done by having different integer assignments in the parallel array. For repetitive, the assignment for {A A B} is {1 2 3}, and for non-repetitive, the assignment is {1 1 2}. The IComparer is used to sort the list, and then once more to check for neighboring duplicates if and only if the repetitive mode is chosen, but is not used during the GetNext() call. {1 2 3} {1 1 2} Most of the research around algorithms appear to have been focused on permutations, with less work being done on combinations and variations. As such, the combination and variation implementations use internal permutations to calculate their sets. For example, the Combinations class uses a Permutations<bool> class to indicate the positions to be included. The permutations of this underlying class indicate the subset to be selected by the combinations. Variations also use a similar mechanism, except for variations with repetition. Permutations<bool> Therefore, the work on making permutations work efficiently is inherited by combinations and variations. Additional performance improvements in the combinations and variations implementations were not sought. First, these classes are not designed to efficiently calculate tables of Binomial Coefficients. However, they do need to provide the Count of the collection that they are currently enumerating. As discussed above, these values can get really big, and can easily overflow 64 bit integers. But, the divisors in the count formulas bring the values back down to a manageable level. So, to properly count these collections, some type of large-integer calculations need to be performed. The outputs of these counts are obviously always integers, so the prime factors of the denominators of the formulas will always be found in the prime factors of the numerators. Rather than performing large integer computations, a list of numerator prime factors and a list of denominator prime factors are calculated. Then, the list of denominators is removed from the list of numerators, and the product of the remaining numerators is returned. No attempt was made to compare the efficiency of this process, see paragraph above. If you troll the code, you will find a SmallPrimeUtility class that is used for the above algorithm. I make no warranty of the suitability of this class for anything else, it is a down and dirty class with no elegance to it at all. It is the Hyundai Excel of classes, it gets you where you're going, but not much else. SmallPrimeUtility The classes created here are designed to exhaustively enumerate massive numbers of collections. For all but the most trivial sets, the amount of time required to enumerate exceeds all available computing capacity. So, there are times when it is necessary to brute force your way through a problem, but the fact that you can't for large N is what makes Computer Science fun. For small problems, this set of classes is suitable; for larger problems, this set can assist in quickly validating other more interesting algorithms. For large problems, you need a keen mind and not a dumb computer. For more complex problems related to permutations or combinations, the total solution space, S, grows far too quickly for it to be feasible to evaluate every option. These classes are designed to enumerate every permutation in S; however, many problems present a smaller feasible search space, F. [5]. For example, in the following numeric substitution problem: S F F O U R + F I V E --------- N I N E There are 8 variables {F O U R I V E N} to be chosen from 10 digits {0 1 2 3 4 5 6 7 8 9}. This implies that there are variations of 10 choose 8 possibilities in the solution space S, which is 10! / 2! = 1,814,800 variations for the solution space S. However, several observations can be made; for example, the fourth column provides us with R + E = E, which implies R = 0. This has simplified the problem to 7 unknown variables to be chosen from 9 digits, or 9! / 2! = 181,480 variations. Further, the first column implies that F <= 4, as we can't allow an overflow on this column. This removes 5/9th of the remaining variations that need to be tested, leaving 80,640 variations to test. Additional simplifications exist, and will reduce the space even further. {F O U R I V E N} {0 1 2 3 4 5 6 7 8 9} The point being that the more we know about the specifics of a problem, the more we are likely to be able to reduce the size of the feasible search space, the more likely we can solve the problem in a reasonable amount of time. The FOUR + FIVE problem above is just one of a nearly inexhaustible supply of numeric substitution letter problems. This can be used to show that THREE + SEVEN = EIGHT, and even that WRONG + WRONG = RIGHT. Using the attached sample, you can enter the operands and the sum, and have the program search for any and all solutions. The program uses the Variations class to exhaustively search every possible variation, and checks if the variation satisfies the equation. To compute a problem, simply enter the operands, e.g., "FOUR" and "FIVE", into the operands fields, and the sum, e.g. "NINE", into the sum field. The Problem frame will automatically update to present the summation problem. Please ensure that there are no more than 10 distinct characters entered, as no validation is done on this input. Entering more than 10 will ensure that no solution will be found. There are many more ways to ensure that no solution exists such as A + BC = DEFGH. The interface will happily accept these inputs and then return that no solutions were found. Once the problem is entered, clicking Solve will enumerate all possible variations of the digits 1 through 10 for each character in the input. The status bar will display the total number of Variations that will be checked; this will vary based on the number of unique characters in the inputs. This will vary from a low of 90 variations to solve A + A = B, to a high of 3,628,800 when 10 characters are used such as in ABCDE + ABCDE = FGHIJ. The progress bar will indicate the overall progress, which should only take a few seconds for any of these problems. The Solution(s) frame will show the total number found and the most recently found solution, as the program progresses. After all solutions have been found, select the drop down list in the Solution(s) frame to move through all of the solutions that were found. The Facet.Combinatorics namespace is contained in the sample's Combinatorics sub-directory. It contains all of the code required to support Permutations, Combinations, and Variations. It has no dependencies aside from the standard .NET 2.0 System references. This directory can be lifted into other solutions to utilize these classes, no separate library is created. Facet.Combinatorics System The form code is plain vanilla, not production ready UI stuff which can be safely ignored. It has all of the UI elements, and defers the problem solving to the TextSumProblem class which encapsulates this particular problem. TextSumProblem The meat of the sample is in the TextSumProblem which creates every possible variation for the problem. The core of the solution is to generate all variations of integers that are possible candidates for the letters of the problem. In the sample, the Solve() method has logic similar to: Solve() int[] ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; Variations<int> variations = new Variations<int>(ints, 8); foreach(IList<int> variation in variations) { if(Satisfies(variation) == true) { // Huzzah, found a solution... } } Finally, the TextSumProblem has a pair of events that signal when a candidate solution has been tried and also when a solution has been found. The form subscribes to these events to provide real time feedback of the problem's progress. Any number of funny examples can be created to "prove" all sorts of contradictions. Most of them will have multiple solutions (ID + EGO = SELF has 1200 solutions, although it's a bit of a cheat), drop me a note if you find a good one that has a single unique solution, I've never been able to find.
http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G?fid=1313343&df=90&mpp=10&sort=Position&spc=None&select=4049142&tid=3994991
CC-MAIN-2016-18
refinedweb
4,329
52.49
In a script that is tied to a prefab for an object I have the following: function OnCollisionEnter(collision : Collision) { print(collision.gameObject.name); } And this works fine, when my game is running on collision the colliding gameObject name is showing up in the status line. I have a variety of gameObjects (instantiated prefabs) in my game and each prefab its own script. Within each script I define 'var Alliance : int;'. What I am having trouble with is in the OnCollisionEnter routine I want to access the Alliance variable that is in the script of the collision gameobject. Since the script name that attaches to the gameObject varies (I name the script something different) what would be the syntax for me to access the Alliance variable? essentially I want to do: collisionObjectId = collision.gameObject."script name".Alliance; but since the script name varies, what do I do here? thanks for any help! Answer by Maltus · Nov 01, 2010 at 05:14 AM //yourscript.js var Alliance : int; function OnCollisionEnter(collision : Collision) { print(collision.gameObject.name); var hitAllianceint : int = collision.gameObject.GetComponent(yourScript).Alliance; print(hitAllianceint.ToString()); } this should work Thanks but this doesn't appear to answer my question. In you example I must replace 'yourScript' with the name of the script. Yes. $$anonymous$$y issue is that the colliding gameObject can have different script names. For example, I call the script that is attached to a enemy ship 'Enemy_AI.js'. I call the script that is attached to an enemy bullet 'Enemy_bullet.js'. Both of these will have a variable Alliance. The object whose OnCollisionEnter() is being called is the player ship which could be colliding with an enemy ship or an enemy bullet. What am I missing here? You need to specify the function you want to call on those objects in an interface. So you have the function "int GetAlliance();" in an interface. Then your different scripts (bullet, ship) need to implement that interface. This looks like: "public class Enemy : iAttackingObject", where iAttackingObject is the name of the interface. When you have that, you can do this: int allianceInt = collision.gameObject.GetComponent(iAttackingObject).GetAlliance(); Is. Editing a variable from another script on collision 3 Answers Is it possible to change a variable, into a script not assigned to any game object? 3 Answers What is the problem in my script? 2 Answers Accessing a variable effected by a GUI slider from another scipt 1 Answer How to access variables from another script on collision ? 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/32352/collision-object-and-access-to-a-script-variable.html
CC-MAIN-2022-21
refinedweb
422
57.67
Welcome to part 23 of the intermediate Python programming tutorial series. In this tutorial, we're going to cover how to handle for errors that occur in a headless/automated program that you're not constantly monitoring. In our previous tutorial, we covered logging with Python, which is very useful, but, if you do hit errors and just return the str(e) of that error, you are likely to find it's not enough useful information, especially if your program is large. If it's a small program, you can probably find the variable it's talking about, like when you get a NameError: a is not defined, maybe you only define and reference this a once, so it's easy to immediately know where things went wrong. What if you get an error and have many references to a? It might not be a NameError either, it could be anything. With logging as we have it right now, we'd have no clue where to begin. What if your program is 100,000 lines long?! Yikes! So let's dig into how we can start to solve this. Let's start with something simple, like: try: a+b except Exception as e: print(str(e)) Here, we get name 'a' is not defined. Luckily for us, we can actually use the sys module to access more of the exception's information with sys.exc_info, like so: import sys try: a+b except: print(sys.exc_info()[0]) print(sys.exc_info()[1]) print(sys.exc_info()[2].tb_lineno) print('Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)) In this case, you will see: <class 'NameError'> name 'a' is not defined 4 Error: <class 'NameError'>. name 'a' is not defined, line: 4 Notice that we've simply sliced the values of sys.exc_info(), and we didn't unpack them to variables. As per a StackOverflow comment I read, it would be unwise to unpack them, just in case you get an exception within the exception itself, and you would wind up with a circular reference that never gets garbage collected. Above my head, but apparently that's a thing. Now, we can combine this with logging, and do something like: import sys import logging def error_handling(): return 'Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno) try: a+b except: logging.error(error_handling()) Output: ERROR:root:Error: <class 'NameError'>. name 'a' is not defined, line: 9 Obviously, you can also configure logging to instead log this to a file. See the logging tutorial in this series for more information there.
https://pythonprogramming.net/headless-error-handling-intermediate-python-tutorial/?completed=/logging-intermediate-python-tutorial/
CC-MAIN-2019-26
refinedweb
436
62.27
. bl 0 p gs o t.c Financial Managemente o bo 0 s2 ebooks2000.blogspot.com .bl 0 The Accountancy College Ltd, January 2011 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of The Accountancy College Ltd.ebooks2000.blogspot.com ContentsPAGEINTRODUCTION TO THE PAPER FORMULAE SHEET CHAPTER 1: CHAPTER 2: CHAPTER 3: CHAPTER 4: CHAPTER 5: CHAPTER 6: CHAPTER 7: CHAPTER 8: CHAPTER 9: FINANCIAL MANAGEMENT: AN INTRODUCTION INVESTMENT APPRAISAL TECHNIQUES ADVANCED DISCOUNTED CASH FLOW TECHNIQUES LONG TERM SOURCES OF FINANCE COST OF CAPITAL CAPITAL STRUCTURE AND RISK ADJUSTED WACC RATIO ANALYSIS RAISING EQUITY FINANCE 5 7 11 21 39 61 69 87 97 113 121 147 151 165 CHAPTER 10: EFFICIENT MARKET HYPOTHESIS CHAPTER 11: VALUATION CHAPTER 12: RISK IN T R O D U C T I O N T O T H E P A P E R o sp examination. The syllabus is assessed by a three hour paper-based log .b The examination consists of 4 questions of 25 marks each. All 00 0 compulsory. s2 k oo FAQs ebWhat level of mathematical ability is required in F9? questions are You will be required to apply formulae either given or memorised. This may require limited manipulation of formulae. The level of computational complexity is normally inversely related to the conceptual difficulty of the topic. Formulae FORMULAE FORMULAEEconomic Order Quantity = 2C0D CH P0 = kD0(1+ g)(Ke g) D0 (1+ g) (re g) V V e d WACC = ke + kd (1T) V +V V +V e d e d Periods (n) 1% 2% 3% 4% 5% 6% 7% 8% 9% 10% ________________________________________________________________________________ 1 2 3 4 5 6 7 8 9 10 0.990 0.980 0.971 0.961 0.951 0.942 0.933 0.923 0.914 0.905 0.980 0.961 0.942 0.924 0.906 0.888 0.871 0.853 0.837 0.820 0.971 0.943 0.915 0.888 0.863 0.837 0.813 0.789 0.766 0.744 0.962 0.925 0.889 0.855 0.822 0.790 0.760 0.731 0.703 0.676 0.952 0.907 0.864 0.823 0.784 0.746 0.711 0.677 0.645 0.614 0.943 0.890 0.840 0.792 0.747 0.705 0.665 0.627 0.592 0.558 0.935 0.873 0.816 0.763 0.713 0.666 0.623 0.582 0.544 0.508 0.926 0.857 0.794 0.735 0.681 0.630 0.583 0.540 0.500 0.463 0.917 0.842 0.772 0.708 0.650 0.596 0.547 0.502 0.460 0.422 0.909 0.826 0.751 0.683 0.621 1 2 3 4 5 11 0.896 0.804 0.722 0.650 0.585 0.527 0.475 0.429 0.388 0.350 11 12 0.887 0.788 0.701 0.625 0.557 0.497 0.444 0.397 0.356 0.319 12 13 0.879 0.773 0.681 0.601 0.530 0.469 0.415 0.368 0.326 0.290 13 14 0.870 0.758 0.661 0.577 0.505 0.442 0.388 0.340 0.299 0.263 14 15 0.861 0.743 0.642 0.555 0.481 0.417 0.362 0.315 0.275 0.239 15 ________________________________________________________________________________ 0 20 (n) 11% 12% 13% 14%s 15% 16% 17% 18% 19% 20% ________________________________________________________________________________ ok o 1 0.901 0.893 0.885 eb 0.877 0.870 0.862 0.855 0.847 0.840 0.833 1 2 0.812 0.797 0.783 0.769 0.756 0.743 0.731 0.718 0.706 0.694 23 4 5 6 7 8 9 10 11 12 13 14 15 0.731 0.659 0.593 0.535 0.482 0.434 0.391 0.352 0.317 0.286 0.258 0.232 0.209 0.712 0.636 0.567 0.507 0.452 0.404 0.361 0.322 0.287 0.257 0.229 0.205 0.183 0.693 0.613 0.543 0.480 0.425 0.376 0.333 0.295 0.261 0.231 0.204 0.181 0.160 0.675 0.592 0.519 0.456 0.400 0.351 0.308 0.270 0.237 0.208 0.182 0.160 0.140 0.658 0.572 0.497 0.432 0.376 0.327 0.284 0.247 0.215 0.187 0.163 0.141 0.123 0.641 0.552 0.476 0.410 0.354 0.305 0.263 0.227 0.195 0.168 0.145 0.125 0.108 0.624 0.534 0.456 0.390 0.333 0.285 0.243 0.208 0.178 0.152 0.130 0.111 0.095 0.609 0.516 0.437 0.370 0.314 0.266 0.225 0.191 0.162 0.137 0.116 0.099 0.084 0.593 0.499 0.419 0.352 0.296 0.249 0.209 0.176 0.148 0.124 0.104 0.088 0.074 0.579 0.482 0.402 3 4 5 0.335 6 0.279 7 0.233 8 0.194 9 0.162 10 0.135 0.112 0.093 0.078 0.065 11 12 13 14 15 1 - (1 + r)-n r Where Periods (n) 1% 2% 3% 4% 5% 6% 7% 8% 9% 10% ________________________________________________________________________________ 1 2 3 4 5 6 7 8 9 10 0.990 1.970 2.941 3.902 4.853 5.795 6.728 7.652 8.566 9.471 0.980 1.942 2.884 3.808 4.713 5.601 6.472 7.325 8.162 8.983 0.971 1.913 2.829 3.717 4.580 5.417 6.230 7.020 7.786 8.530 0.962 1.886 2.775 3.630 4.452 5.242 6.002 6.733 7.435 8.111 0.952 1.859 2.723 3.546 4.329 5.076 5.786 6.463 7.108 7.722 0.943 1.833 2.673 3.465 4.212 4.917 5.582 6.210 6.802 7.360 0.935 1.808 2.624 3.387 4.100 4.767 5.389 5.971 6.515 7.024 0.926 1.783 2.577 3.312 3.993 4.623 5.206 5.747 6.247 6.710 0.917 1.759 2.531 3.240 3.890 4.486 5.033 5.535 5.995 6.418 0.909 1.736 2.487 3.170 3.791 1 2 3 4 5 11 10.37 9.787 9.253 8.760 8.306 7.887 7.499 7.139 6.805 6.495 11 12 11.26 10.58 9.954 9.385 8.863 8.384 7.943 7.536 7.161 6.814 12 13 12.13 11.35 10.63 9.986 9.394 8.853 8.358 7.904 7.487 7.103 13 14 13.00 12.11 11.30 10.56 9.899 9.295 8.745 8.244 7.786 7.367 14 15 13.87 12.85 11.94 11.12 10.38 9.712 9.108 8.559 8.061 7.606 15 ________________________________________________________________________________ (n) 11% 12% 13% 14% 15% 16% 17% 18% 19% 20% ________________________________________________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0.901 1.713 2.444 3.102 3.696 4.231 4.712 5.146 5.537 5.889 6.207 6.492 6.750 6.982 7.191 0.893 1.690 2.402 3.037 3.605 4.111 4.564 4.968 5.328 5.650 5.938 6.194 6.424 6.628 6.811 0.885 1.668 2.361 2.974 3.517 3.998 4.423 4.799 5.132 5.426 5.687 5.918 6.122 6.302 6.462 0.877 1.647 2.322 2.914 3.433 3.889 4.288 4.639 4.946 5.216 5.453 5.660 5.842 6.002 6.142 0.870 1.626 2.283 2.855 3.352 3.784 4.160 4.487 4.772 5.019 5.234 5.421 5.583 5.724 5.847 0.862 1.605 2.246 2.798 3.274 3.685 4.039 4.344 4.607 4.833 5.029 5.197 5.342 5.468 5.575 0.855 1.585 2.210 2.743 3.199 3.589 3.922 4.207 4.451 4.659 4.836 4.988 5.118 5.229 5.324 0.847 1.566 2.174 2.690 3.127 3.498 3.812 4.078 4.303 4.494 4.656 4.793 4.910 5.008 5.092 0.840 1.547 2.140 2.639 3.058 3.410 3.706 3.954 4.163 4.339 4.486 4.611 4.715 4.802 4.876 0.833 1.528 2.106 2.589 2.991 1 2 3 4 5 3.326 6 3.605 7 3.837 8 4.031 9 4.192 10 4.327 4.439 4.533 4.611 4.675 11 12 13 14 15 10 Chapter 1 11 C H A P T E R 1 F IN A N C I A L M A N A G E M E N T : A N IN T R O D U C T I O N CHAPTER CONTENTSWHAT IS FINANCIAL MANAGEMENT? --------------------------------- 13THE THREE KEY DECISIONS CORPORATE STRATEGY AND FINANCIAL MANAGEMENT FINANCIAL OBJECTIVES VALUE FOR MONEY STAKEHOLDERS 13 15 15 16 17 12 The management of all matters associated with the cash flow of the organisation both short and long-term. Working Capital Application of funds Financial management is often described in terms of the three basic decisions to be made: Sourcing of funds Each of these decisions have to be looked at in far greater detail later on in the course but as an outline these are the basic considerations: 1.1. 2. 3. 13 Capital assetsA critical decision because of the strategic implications of many investments, the decision would include the following financial considerations: 1. 2. 3. 4. Return Risk Cash flow Profit. Working capitalThe cash resource available to the business on a day-to-day basis and used to fund the current assets such as inventory and receivables. The key to identifying the level of investment is to balance the risk of insolvency against the cost of funding. Financial assetsNot a core area of the course, we tend to focus on financing from the perspective of a company rather than the investor. This being the case the only financial investment to consider is short-term saving. In this circumstance then the key considerations are, in order: 1. 2. 3. Risk Liquidity Return. 2.1. 2. 3. 4. When looking at the financing of a business there are 4 basic questions to consider: 14 Debt vs equityThe gearing decision which forms the basis of two later chapters. A critical issue in terms of risk and cost of funding. 3. The amount of return to be paid in cash to shareholders. This is a critical measure of the companies ability to pay a cash return to its shareholders. The level of dividend paid will be determined by the following: 1. 2. 3. 4. 5. Profitability Cash flow Growth Legal restrictions Shareholder expectations. eb Financial objectivesFinancial objectives of commercial companies may include: 1. 2. 3. Maximising shareholders wealth Maximising profits Satisficing. 1. A fundamental aim within financial management is to create and sustain shareholders wealth. Wealth being the ongoing value of shares of the organisation. The importance of this concept is that there is no time period to the wealth and that it is determined by the relative risk/ return balance of the business. All aspects of financial management are based on this basic premise. 15 2. Maximising profits Within organisations it is normal to reward management on some measure of profit such as ROI or RI. In simple terms we would expect a close relationship between profit and shareholders wealth. There are, however, ways in which they may conflict such as: 1. 2. 3. Short-termism. Cash vs accruals. Risk. Short-termismA profit target is normally calculated over one year, it is relatively easy to manipulate profit over that period to enhance rewards at the expense of future years. Cash vs accrualsAs we will see later, wealth is calculated on a cash basis and ignores accruals. Risk A manager may be inclined to accept very risky projects in order to achieve profit targets which in turn would adversely affect the value of the business. Satisficing Many organisations do not profit maximise but instead aim to satisfice. This means that they attempt to generate an acceptable level of profit with a minimum of risk. It reflects the fact that many organisations are more concerned with surviving than growth. 4. These organisations are established to pursue non-financial aims but are to provide services to the community. Such organisations like profit-seeking companies need funds to finance their operations. Their major constraint is the amount of funds that they would be able to raise. As a result not-for-profit organisations should seek to use the limited funds so as to obtain value for money. 16 ECONOMY EFFECTIVENESS EFFICIENCY Economy measures the cost of obtaining the required quality inputs needed to produce the service. The aim is to acquire the necessary input at the lowest possible cost. Effectiveness means doing the right thing. service meets its declared objectives. It measures the extent to which the Efficiency means doing the right thing well. It relates to the level of output generated by a given input. Reducing the input: output ratio is an indication of increased efficiency. Example ---- in refuse collection service, The service will be economic if it is able to minimise the cost of weekly collection and not suffer from wasted use of resources. The service will be effective if it meet it target of weekly collection. The service will be efficient if it is able to raise the number of collection per vehicle per week. StakeholdersWe tend to focus on the shareholder as the owner and key stakeholder in a business. A more comprehensive view would be to consider a wider range of interested parties or stakeholders. Stakeholders are any party that has both an interest in and relationship with the company. The basic argument is that the responsibility of an organisation is to balance the requirements of all stakeholder groups in relation to the relative economic power of each group. Group taskRequired Identify as many stakeholder groups as you can for a commercial organisation. 17 Group taskRequired Using the stakeholder groups already identified suggest 5 possible conflicts of interest that need to be considered. Agency theory Principal Agency relationships occur when one or more people employ one or more persons as agent. The persons who employ others are the principals and those who work for them are called the agent In an agency situation, the principal delegate some decision-making powers to the agent whose decisions affect both parties. This type of relationship is common in business life. For example shareholders of a company delegate stewardship function to the directors of that company. The reasons why an agents are employed will vary but the generally an agent may be employed because of the special skills offered, or information the agent possess or to release the principal from the time committed to the business. Agent 0.b lo Goal CongruenceGoal congruence is defined as the state which leads individuals or groups to take actions which are in their self interest and also in the best interest of the entity. For an organisation to function properly, it is essential to achieve goal congruence at all level. All the components of the organisation should have the same overall objectives, and act cohesively in pursuit of those objectives. In order to achieve goal congruence, there should be introduction of a careful designed remuneration packages for managers and the workforce which would motivate them to take decisions which will be consistent with the objectives of the shareholders. 18 QuestionIdentify 5 key areas of conflict between directors and shareholders and suggest what can be done to encourage goal congruence between the two parties. 19 20 Chapter 2 SYLLABUS CONTENT Payback ARR 21 C H A P T E R 2 I N V E S T M E N T A P P R A IS A L T E C H N IQ U E S Basic techniques bo s ok 0 00 log .b o sp t. m DCF techniques coNet present (NPV) value of 22 CHAPTER CONTENTSINVESTMENT APPRAISAL AND CAPITAL BUDGETING --------------- 24PAYBACK RETURN ON CAPITAL EMPLOYED (ROCE) 25 27 23 There are 4 basic methods to be mastered 1. 2. 3. 4. Payback Return on Capital Employed (ROCE) Net present value (NPV) Internal rate of return (IRR). We shall use the following example to illustrate how each method is calculated. Example 1 Reina Ltd Reina Ltd has the opportunity to invest in an investment with the following initial costs and returns: e1 2 3 4 5 A ($000s) (100) 50 40 30 25 20 5 Residual value Yr 5 24 PaybackThe length of time it takes for cash inflows from trading to pay back the initial investment. Example 1 contdA Initial investment Periodic Net cash flows ($) Yr 1 Yr 2 Yr 3 Yr 4 Required: Cumulative Finnan Ltd$60,000 25 Advantages1. 2. 3. It is simple to use (calculate) and easy to understand It is a particularly useful approach for ranking projects where a company faces liquidity constraints and requires a fast repayment of investment. It is appropriate in situations where risky investments are made in uncertain market that are subject to fast design and product changes or where future cash flows are particularly difficult to predict. The method is often used in conjunction with the NPV or IRR method and act as the first screening device to identify projects which are worthy of further investigation. Unlike the other traditional methods payback uses cash flows, rather than accounting profits, and so is less likely to produce an unduly optimistic figure distorted by assorted accounting conventions. 5. Disadvantages1. It does not give a measure of return, as such it can only be used in addition to other investment appraisal methods. 2. It does not normally consider the impact of discounted cash flow although a discounted payback may be calculated (see later). 3. 4. po sany cash flows beyond that point It only considers cash flow up to the payback, log are ignored. .b 00 is an acceptable payback period, any There is no objective measure of what 0 target payback is necessarily s2 subjective. k oo ebChromex (exam standard question amended) Example 2 Chromex plc manufactures bicycles for the UK and European markets, and has made a bid to take over Bexell plc, their main UK competitor. Chromex anticipates labour savings of $700,000 per year, created by more efficient production and distribution facilities, if the takeover is completed. In addition, the company intends to sell off surplus land and buildings with a balance sheet value of $15 million, acquired in the course of the takeover. For the year ended 31 December 20X7, Bexell reported an operating profit of $10 million. In calculating profits, Bexell included a depreciation charge of $0.5 million. The total amount to be invested in Bexell is $140m prior to any disposal of assets. Required: Assuming that the bid is accepted by Bexell, calculate the payback period (pre-tax) for the investment, if the land and buildings are immediately sold for $5 million less than the balance sheet valuation, and Bexells sales figures remain static. (3 marks) 26 Investment appraisal Time period When? Use Over the life of the project Future Decision making ROCE contd Average annual profit Total profit Less depreciation Total net cash flow number of years = average profit Average investment Initial investment Plus residual value 2 Equals ave. investment ARR 27 Decision criteriaA profit measure that must be compared to a target profit. This profit is likely to be related to the target performance measure already discussed Advantages1. 2. 3. 4. It is easy to understand and easy to calculate. The impact of the project on a companys financial statement can also be specified ROCE is still the commonest way in which business unit performance is measured and evaluated, and is certainly the most visible to shareholders Managers may be happy in expressing project attractiveness in the same terms in which their performance will be reported to shareholders, and according to which they will be evaluated and rewarded. The continuing use of the ARR method can be explained largely by its utilisation of balance sheet and P&L account magnitudes familiar to managers, namely profit and capital employed. Disadvantages1. 2. 3. 4. 5. It fails to take account of the project life or the timing of cash flows and time value of money within that life It uses accounting profit, hence subject to various accounting conventions. There is no definite investment signal. The decision to invest or not remains subjective in view of the lack of objectively set target ARR. Like all rate of return measures, it is not a measurement of absolute gain in wealth for the business owners. The ARR can be expressed in a variety of ways and is therefore susceptible to manipulation. 28 Example 3 Armcliff Limited is a division of Sherin plc which requires each of its divisions to achieve a rate of return on capital employed of at least 10 per cent per annum. For this purpose, capital employed is defined as fixed capital and investment in stocks. This rate of return is also applied as a hurdle rate for new investment projects. Divisions have limited borrowing powers and all capital projects are centrally funded. The following is an extract from Armcliffs divisional accounts. Profit and loss account for the year ended 31 December 20X4 $m Turnover 120 Cost of sales (100) ____ Operating profit 20 ==== Assets employed as at 31 December 20X4 $m Fixed assets (net) Current assets (including stocks $25m) Current liabilities 45 (32) ___ Armcliffs production engineers wish to invest in a new computer-controlled press. The equipment cost is $14 million. The residual value is expected to be $2 million after four years operation, when the equipment will be shipped to a customer in South America. The new machine is capable of improving the quality of the existing product and also of producing a higher volume. The firms marketing team is confident of selling the increased volume by extending the credit period. The expected additional sales are as follows. Year Year Year Year 1 2 3 4 2,000,000 1,800,000 1,600,000 1,600,000 units units units units 00 $m m co75 t. 13 ___ 88 === Sales volume is expected to fall over time because of emerging competitive pressures. Competition will also necessitate a reduction in price by $0.5 each year from the $5 per unit proposed in the first year. Operating costs are expected to be steady at $1 per unit, and allocation of overheads (none of which are affected by the new project) by the central finance department is set at $0.75 per unit. Higher production levels will require additional investment in stocks of $0.5 million, which would be held at this level until the final stages of operation of the project. Customers at present settle accounts after 90 days on average. 29 Required: (a) Determine whether the proposed capital investment is attractive to Armcliff, using the average rate of return on capital method, defined as average profit to average capital employed, ignoring debtors and creditors. (7 marks) Note. Ignore taxes. (b) (i) (ii) (c) Suggest three problems which arise with the use of the average return method for appraising new investment. (3 marks) In view of the problems associated with the ARR method, why do companies continue to use it in project appraisal? (3 marks) Briefly discuss the dangers of offering more generous credit, and suggest ways of assessing customers creditworthiness. (7 marks) (20 marks) 30 Year 0 Year 1 Reasons 1 2 3 o .bl 0 Reminder - compound interest 00 2 ks o Example 4 bo e If we invest $100 now (Yr. 0) what will the value of that investment be in 1, 2, 3, 4years at a compound rate of 10%? Present Value Calculation Future Value 1 2 3 4 $100 31 Therefore we are able to express Present Values in terms of Future Values using the following formula: FV =Where FV r n PV Present value. Future value. PV (1 + r)n DiscountingThe opposite of compounding, where we have the future value (eg an expected cash inflow in a future year) and we wish to consider its value in present value terms. IllustrationCOMPOUNDING Year 0DISCOUNTING 1 (1 + r)n = FV (1 + r)-n PV = FV Use tables to calculate the present values of example 4 on the previous page. Year Present Value $ 32 Decision criteriaIf the investment has a positive NPV then the project should be accepted (negative rejected). A positive NPV means that the project will increase the wealth of the company by the amount of the NPV at the current cost of capital. NPV Advantages1. 2. 3. 4. 5. A project with a positive NPV increases the wealth of the companys, thus maximise the shareholders wealth. Takes into account the time value of money and therefore the opportunity cost of capital. Discount rate can be adjusted to take account of different level of risk inherent in different projects. Unlike the payback period, the NPV takes into account events throughout the life of the project. Superior to the internal rate of return because it does not suffer the problem of multiple rates of return. 33 6. 7. 8. Better than accounting rate of return because it focuses on cash flows rather than profit. NPV technique can be combined with sensitivity analysis to quantify the risk of the projects result. It can be used to determine the optimum policy for asset replacement. Disadvantages1. 2. 3. 4. 5. 6. NPV assumes that firms pursue an objective of maximising the wealth of their shareholders. Determination of the correct discount rate can be difficult. Non-financial managers may have difficulty understanding the concept. The speed of repayment of the original investment is not highlighted. The cash flow figures are estimates and may turn out to be incorrect. NPV assumes cash flows occur at the beginning or end of the year, and is not a technique that is easily used when complicated, mid-period cash flows are present. Decision criteria If the IRR is greater than the cost of capital accept the project. Example 5 k oo Ltd Carragher eb A project costing $1000 will return $1,160 in the following year. Required: What will be the NPV at 10% and 20% discount rates? 34 Illustration NPV rate of return Linear interpolation We must attempt to guess the IRR by linear interpolation. This uses the following formula. Interpolated IRRWhere: L H NL NH = = = = k oo 0 s2= NL L+ N - N (H - L) H L Lower discount rate Higher discount rate NPV at lower discount rate NPV at higher discount rate Advantages1. 2. 3. 4. Like the NPV method, IRR recognises the time value of money. It is based on cash flows, not accounting profits. More easily understood than NPV by non-accountant being a percentage return on investment. For accept/ reject decisions on individual projects, the IRR method will reach the same decision as the NPV method. 35 Disadvantages1. 2. 3. 4. 5. Does not indicate the size of the investment, thus the risk involve in the investment. Assumes that earnings throughout the period of the investment are reinvested at the same rate of return. It can give conflicting signals with mutually exclusive project. If a project has irregular cash flows there is more than one IRR for that project (multiple IRRs). Is confused with accounting rate of return. Two projects are mutually exclusive if only one of the projects can be undertaken. In this circumstance the NPV and IRR may give conflicting recommendation. The reasons for the differences in ranking are: 1. 2. NPV is an absolute measure but the IRR is a relative measure of a projects viability. k oo The two methods are sometimes said to be based Reinvestment assumption. eb about the rate at which funds generated by the on different assumptionsproject are reinvested. NPV assumes reinvestment at the companys cost of capital, IRR assumes reinvestment at the IRR. AnnuitiesAn annuity is a series of equal cash flows. Example 6 Agger Ltd A project costing $2,000 has returns expected to be $1,000 each year for 3 years at a discount rate of 10%. Required: (a) (b) (c) NPV using existing analysis. NPV using annuity tables Solely considering the annuity, what if the cash flows commenced in: 1. 2. 3. Year 4, Year 6, Year 0? 36 PerpetuitiesA form of annuity that arises forever (in perpetuity). In this situation the calculation of the present value of the future cash flows is very straightforward. The is of particular importance when considering cost of capital later. Present value of the perpetuity =Cash flow per annum Interest rate Example 7 Riise Ltd A company expects to receive $1,000 each year in perpetuity. The current discount rate is 9%. Required: 1. 2. What is the present value of the perpetuity? What is the value if the perpetuity starts in 5 years? 37 38 Chapter 3 SYLLABUS CONTENT Relevant cost analysis Inflation Tax 39 C H A P T E R 3 A D V A N C E D D IS C O U N T E D C A S H F L O W T E C H N IQ U E S Lease vs buy Inflation Applications Asset replacement Taxation Capital rationing 40 CHAPTER CONTENTSDECISION MAKING THEORY -------------------------------------------- 42RELEVANT COST 42 RISK----------------------------------------------------------------------- 56SENSITIVITY ANALYSIS EXPECTED VALUES 0.b s log t. po om 52 52 52 54 56 57 59 59 60 41 Relevant costA relevant cost has 3 criteria that must be fulfilled: 1. 2. 3. It must arise in the future It must be a cash flow It must arise as a direct consequence of the decision. Non-relevant costs1. 2. 3. 4. Sunk costs Committed costs 42 andUse a money rate of return andUse a real rate of return Exam tip Must use where there is more than one inflation rate in the question Exam tip Can use where a single inflation rate is given for an easier computation The relationship between real and money interest is given below (also see tables) (1 + m) =or (1 + r) (1 + i) e(1 + r) = (1 + m) (1 + i)Where r m i = = = real discount rate money discount rate inflation rate Example 1r = 8% i = 5% 43 Example 2m = 10.6% i = 5% Example 3A company has invested $50,000 in a project. The project generates net cash inflows of $14,000 each year for 5 years in year 0 terms. The rate of return is 12% and inflation is expected to be 3.6% Required: Calculate the NPV using both the money and real analyses. Example 4(a) (b) m co required on an Explain how inflation affects the rate oft.return o investment project, and the distinction between a real and a nominal sp (or money terms) approach to the evaluation of an investment log project under inflation. (4 marks) .b 00 Howden plc is contemplating investment in an additional production line to 0 s2 produce its range of compact discs. A market research study, undertaken by k a well-known firm of oo consultants, has revealed scope to sell an additional output of 400,000 b e units per annum. The study cost $100,000 but theHowden (exam standard question)account has not yet been settled. The price and cost structure of a typical disc (net of royalties) is as follows. $ Price per unit Costs per unit of output Material cost per unit Direct labour cost per unit Variable overhead cost per unit Fixed overhead cost per unit $ 12.00 Profit 44 The fixed overhead represents an apportionment of central administrative and marketing costs. These are expected to rise in total by $500,000 per annum as a result of undertaking this project. The production line is expected to operate for five years and to require a total cash outlay of $11 million, including $0.5 million of materials stocks. The equipment will have a residual value of $2 million. The working capital balance will remain constant after allowing for inflation of materials. The production line will be accommodated in a presently empty building for which an offer of $2 million has recently been received from another company. If the building is retained, it is expected that property price inflation will increase its value to $3 million after five years. While the precise rates of price and cost inflation are uncertain, economists in Howdens corporate planning department make the following forecasts for the average annual rates of inflation relevant to the project (per annum). Retail Price Index Disc prices Material prices Direct labour wage rates Variable overhead costs Other overhead costs 6 5 3 7 7 5 per per per per per per cent cent cent cent cent cent Note. You may ignore taxes and capital allowances in this question. Required: Given that Howdens shareholders require a real return of 8.5 per cent for projects of this degree of risk, assess the financial viability of this proposal. (10 marks) (c) Briefly discuss how inflation may complicate the analysis of business financial decisions. (6 marks) (20 marks) 45 Good Any investment in a capital asset will give rise to a capital allowance. Thecapital allowance will lead to a reduction in the amount of tax subsequently paid CASH INFLOW Ugly Sometimes the examiner may delay all cash flow associated with taxationby one year, this is done to reflect the delays between tax arising and being paid. Take care and read the question carefully. 4. Investment e5. Residual value 46 Example 5An asset is bought on the first day of the year for $20,000 and will be used for four years after which it will be disposed of (on the final day of year 4) for $5,000. Tax is payable at 30% one year in arrears. Required: Calculate the writing down allowance and hence the tax savings for each year. Cash flow m4 Tax 47 Year 1 Investment W.D.A. 2 W.D.V. W.D.A. 3 W.D.V. W.D.A. 4 W.D.V Proceeds BA/BC Allowance Tax saving Timing Continuing from the previous example. We are further told that net cash from trading is $8,000 per annum from trading. The cost of capital is 10%. 48 Blackwater plc, a manufacturer of speciality chemicals, has been reported to the anti-pollution authorities on several occasions in recent years, and fined substantial amounts for making excessive toxic discharges into local rivers. Both the environmental lobby and Blackwaters shareholders demand that it clean up its operations. It is estimated that the total fines it may incur over the next four years can be summarised by the following probability distribution (all figures are expressed in present values). Filta & Strayne Limited (FSL), a firm of environmental consultants, has advised that new equipment costing $1 million can be installed to virtually eliminate illegal discharges. Unlike fines, expenditure on pollution control equipment is taxallowable via a 25 per cent writing-down allowance (reducing balance). The rate of corporate tax is 33 per cent, paid with a one-year delay. The equipment will have no resale value after its expected four-year working life, but can be in full working order immediately after Blackwaters next financial year. A European Union Common Pollution Policy grant of 25 per cent of gross expenditure is available, but with payment delayed by a year. Immediately on receipt of the grant from the EU, Blackwater will pay 20 per cent of the grant to FSL as commission. These transactions have no tax implications for Blackwater. 0 20 is that it will raise production costs by $30 s A disadvantage of the new equipment ok Current production is 10,000 tonnes per annum, per tonne over its operating life. o eb but is expected to grow by 5 per cent per annum compound. It can be assumedthat other production costs and product price are constant over the next four years. No change in working capital is envisaged. Blackwater applies a discount rate of 12 per cent after all taxes to investment projects of this nature. All cash inflows and outflows occur at year ends. Required: (a) Calculate the expected net present value of the investment assuming a four-year operating period. Briefly comment on your results. (12 marks) 49 ASSET REPLACEMENTThe decision how to replace an asset. The asset will be replaced but we aim to adopt the most cost effective replacement strategy. The key in all questions of this type is the lifecycle of the asset in years. Key ideas/assumptions: 1. Cash inflows from trading (revenues) are not normally considered in this type of question. The assumption being that they will be similar regardless of the replacement decision. The operating efficiency of machines will be similar with differing machines or with machines of differing ages. The assets will be replaced in perpetuity or at least into the foreseeable future. 2. 3. Example 8A company is considering the replacement of an asset with the following two machines: MachineP $000s 60 3 years 10 p.a. 0 20 o .bl Required: Determine which machine should be bought using a NPV analysis at a cost of capital of 10%. Discount factorP $000s 1.000 0.909 0.826 0.751 H $000s 0 1 2 3 50 P ($000s)Net present value Annuity factor H ($000s) EAC 51 CAPITAL RATIONINGA limit on the level of funding available to a business, there are two types: Wish to concentrate on relatively few projects Unwillingness to take on external funds Only a willingness to concentrate on strongly profitable projects. Example 9The funds available for investment are $200,000. All investments must be started now (Yr 0): Project Initial investment (Yr 0) NPV $000s $000s A 100 25 B 200 35 C 80 21 D 75 10 Required: Which project(s) should we invest in to maximise the return to the business? 52 Scenario 1: divisibilityie each project can be taken in part and the returns (NPV) will be proportionate to the amount of investment. P.I. = NPV/Investment Project A B C D Working P.I. Ranking Funds available Projects undertaken NPV earned KeyWe identify all possible mixes and establish which mix generates the maximum NPV. Example 9Required: Which project(s) should we invest in to maximise the return to the business given the projects are now non-divisible? 53 KeyThere are three possible types of profit maximising mix each of which must be considered in isolation and then compared with each other. They are that the investment must include either: 1. 2. 3. Project A Project C, or neither Project. Example 9But projects A and C are mutually exclusive. o sp of funds in more than one A more complex environment where there is og l a shortage period. This makes the analysis more .b complicated because we have multiple 0 constraints and multiple outputs. Linear programming would have to be employed. 00 2 ks o bo e 54 Example 10 Horge Co Horge Co is reviewing investment proposals that have been submitted by divisional managers. The investment funds of the company are limited to $800,000 in the current year. Details of three possible investments, none of which can be delayed, are given below. Project 1An investment of $300,000 in work station assessments. Each assessment would be on an individual employee basis and would lead to savings in labour costs from increased efficiency and from reduced absenteeism due to work-related illness. Savings in labour costs from these assessments in money terms are expected to be as follows: 1 85 2 90 3 95 4 100 5 95 An investment of $450,000 in individual workstations for staff that is expected to reduce administration costs by $140,800 per annum in money terms for the next five years. Project 3 An investment of $400,000 in new ticket machines. Net cash savings of $120,000 per annum are expected in current price terms and these are expected to increase by 3.6% per annum due to inflation during the five-year life of the machines. 0 20of 12% and taxation should be ignored. s Horge Co has a money cost of capital ok o Required: eb(a) (i) (ii) Determine the best way for Horge Co to invest the available funds and calculate the resultant NPV: on the assumption that each of the three projects is divisible; on the assumption that none of the projects are divisible.(10 marks) Explain how the NPV investment appraisal method is applied in situations where capital is rationed. (3 marks) Discuss the reasons why capital rationing may arise.(7 marks) Discuss the meaning of the term 'relevant cash flows' in the context of investment appraisal, giving examples to illustrate your discussion. (5 marks) (25 marks) 55 RISKAssessment of risk is particularly important when performing investment appraisal due to: 1. 2. 3. 4. Long timescale Outflow today, inflow in the future Large size in relation to the size of the company Strategic nature of the decision. Techniques available: 1. 2. 3. 4. Sensitivity analysis Expected values Adjusted discount rates Payback. Sensitivity Analysis A technique that considers a single variable at a time and identifies by how much that variable has to change for the decision to change (from accept to reject). Example 11 An investment of $50,000 in year 0 is expected to give rise to inflows of $22,000 for each of years 1 to 3. The discount rate is 10%. The net cash inflow p.a. is made up of fixed cost per annum of $8,000. Selling price of $10/unit and variable cost of $7/unit. Volume is estimated at 10,000 units. Required: (a) (b) Should we accept or reject the investment based on NPV analysis? By how much would the values have to change for the decision to alter for: (i) (ii) initial investment; cash inflows (in detail); Key workingNet Present Value Present Value of the cash flow under consideration Sensitivity Margin = 56 Expected valuesWhere there are a range of possible outcomes which can be identified and a probability distribution can be attached to those values. In this situation then we may use a variety of techniques to establish some sort of average return. The measure of average return is then assumed to be the value that we should use. The expected value is the arithmetic mean of the outcomes as expressed below: EV = pxWhere P = the probability of an outcome x = the value of an outcome Example 12A new project is being launched. There are four possible outcomes identified with the investment financial impact (NPV) is given in $m. The management team attached the best estimate of probability to the outcomes: Outcome Profit/Loss (x)$25m $10m $3m Probability (p) ($20m) t.c o0.10 p0.25 Working (px) 0.35 0.30 Required: (a) (b) What is the expected value of the project? Suggest flaws with the analysis 57 Example 13 Monica plc, a manufacturer of building products, mainly supplies the wholesale trade. It has recently suffered falling demand due to economic recession, and thus has spare capacity. It now perceives an opportunity to produce designer ceramic tiles for the home improvement market. It has already paid $0.5 million for development expenditure, market research and a feasibility study. The initial analysis reveals scope for selling 150,000 boxes per annum over a fiveyear period at a price of $20 per box. Estimated operating costs, largely based on experience, are as follows. Cost per box of tiles (at todays prices): Materials cost Direct labour Variable overhead Fixed overhead (allocated) Distribution, etc $ 8.00 2.00 1.50 1.50 2.00 Production can take place in existing facilities although initial re-design and set-up costs would be $2 million after allowing for all relevant tax reliefs. Returns from the project would be taxed at 33 per cent. Monicas shareholders require a nominal return of 14 per cent per annum after tax, which includes allowance for generally expected inflation of 5.5 per cent per annum. It can be assumed that all operating cash flows occur at year ends. Required: (a) Assess the financial desirability of this venture in real terms, finding both the net present value and the internal rate of return (to the nearest 1 per cent) offered by the project. (7 marks) Note. Assume no tax delay. (b) Briefly explain the purpose of sensitivity analysis in relation to project appraisal, indicating the drawbacks with this procedure. (6 marks) Determine the values of: (i) (ii) price volume (c) at which the projects NPV becomes zero. Discuss your results, suggesting appropriate management action. (7 marks) (20 marks) 58 PaybackAs discussed earlier in the notes payback gives a simple measure of risk. shorter the payback period, the lower the risk. The 59 Key information1. Discount rate = post tax cost of borrowing The rate is given by the rate on the bank loan in the question, if it is pre-tax then the rate must be adjusted for tax. If the loan rate was 10% pre-tax and corporation tax is 30% then the post -tax rate would be 7%. (10% x (1 0.3) 2. Cash flows Bank loan1/ Cost of the investment 2/ WDA tax relief on investment 3/ Residual value Finance Lease1/ Lease rental - in advance - annuity 2/ Tax relief on rental Example 14 Smicer plc is considering how to finance a new project that has been accepted by its investment appraisal process. 00 2the company can either arrange a bank loan at For the four year life of the project s an interest rate of 15% before corporation tax relief. The loan is for $100,000 and ok bo would be taken out immediately prior to the year end. The residual value of the ethe end of the fourth year. equipment is $10,000 atAn alternative would be to lease the asset over four years at a rental of $30,000 per annum payable in advance. Tax is payable at 33% one year in arrears. Capital allowances are available at 25% on the written down value of the asset. Other considerations1. Who receives the residual value in the lease agreement? It is possible that the residual value may be received wholly by the lessor or almost completely by the lessee. There may be restrictions associated with the taking on of leased equipment. The agreements tend to be much more restrictive than bank loans. Are there any additional benefits associated with lease agreement? Many lease agreements will include within the payments some measure of maintenance or other support services. 60 Chapter 4 ebooks2000.blogspot.com 61 Equity (shares) Ordinary shares Preference shares s ok Other sourcesSale and leaseback Warrants Convertibles Islamic finance 62 CHAPTER CONTENTSEQUITY ------------------------------------------------------------------- 64ORDINARY SHARES PREFERENCE SHARES 64 64 DEBT ---------------------------------------------------------------------- 65SECURITY TYPES OF DEBT TYPES OF ISSUED DEBT 65 65 66 63 EQUITYEquity relates to the ownership rights in a business. Ordinary shares1. 2. 3. 4. 5. Owning a share confers part ownership. High risk investments offering higher returns. Permanent financing. Post-tax appropriation of profit, not tax efficient. Marketable if listed. Advantages1. 2. 3. 4. No fixed charges (e.g. interest payments). No repayment required. Carries a higher return than loan finance. Issuing equity finance can be expensive in the case of a public issue 9see later). 0 20 if new shares issued. s Problem of dilution of ownership ok Dividends are not tax-deductible. bo eof equity can increase the overall cost of capital for the A high proportionShares in unlisted companies are difficult to value and sell. company. Preference shares1. 2. 3. Fixed dividend Paid in preference to (before) ordinary shares. Not very popular, it is the worst of both worlds, ie not tax efficient no opportunity for capital gain (fixed return). 64 DEBTThe loan of funds to a business without any ownership rights. 1. 2. Paid out as an expense of the business (pre-tax). Risk of default if interest and principal payments are not met. SecurityChargesThe debtholder will normally require some form of security against which the funds are advanced. This means that in the event of default the lender will be able to take assets in exchange of the amounts owing. CovenantsA further means of limiting the risk to the lender is to restrict the actions of the directors through the means of covenants. These are specific requirements or limitations laid down as a condition of taking on debt financing. They may include: 1. 2. 3. 4. Types of debtDebt may be raised from two general sources, banks or investors. Bank financeFor companies that are unlisted and for many listed companies the first port of call for borrowing money would be the banks. These could be the high street banks or more likely for larger companies the large number of merchant banks concentrating on securitised lending. This is a confidential agreement that is by negotiation between both parties. Traded investmentsDebt instruments sold by the company, through a broker, to investors. features may include: 1. 2. 3. Typical The debt is denominated in units of $100, this is called the nominal or par value and is the value at which the debt is subsequently redeemed. Interest is paid at a fixed rate on the nominal or par value. The debt has a lower risk than ordinary shares. It is protected by the charges and covenants. 65 DebenturesDebt secured with a charge against assets (either fixed or floating), low risk debt offering the lowest return of commercially issued debt. Unsecured loansNo security meaning the debt is more risky requiring a higher return. Mezzanine financeHigh risk finance raised by companies with limited or no track record and for which no other source of debt finance is available. A typical use is to fund a management buy-out. 66 OTHER SOURCESSale and Leaseback1. 2. 3. Selling good quality fixed assets such as high street buildings and leasing them back over many (25+) years. Funds are released without any loss of use of assets. Any potential capital gain on assets is forgone. Grants1. 2. 3. 4. Often related to regional assistance, job creation or for high tech companies. Important to small and medium sized businesses (ie unlisted). They do not need to be paid back. Remember the EU is a major provider of loans. Retained earningsThe single most important source of finance, for most businesses the use of retained earnings is the core basis of their funding. Warrants1. 2. 3. 4. An option to buy shares at a specified point in the future for a specified (exercise) price. The warrant offers a potential capital gain where the share price may rise above the exercise price. The holder has the option to buy the share. determined date. The warrant has many uses including: additional consideration when issuing debt. incentives to staff. 67 Prohibited activitiesIn Shariah Law there are some activities that are not allowed and as such must not be provided by an Islamic financial institution, these include: 1. 2. 3. Interest in normal financing relates to the monetary unit and is based on the principle of time value of money. Sharia Law does not allow for the earning of interest on money. It considers the charging of interest to be usury or the compensation without due consideration. This is called Riba and underpins all aspects of Islamic financing. Instead of interest a return may be charged against the underlying asset or investment to which the finance is related. This is in the form of a premium being paid for a deferred payment when compared to the existing value. There is a specific link between the charging of interest and the risk and earnings of the underlying assets. Another way of describing it is as the sharing of profits arising from an asset between lender and user of the asset. Murabaha trade credit Ijara lease finance Mudaraba equity finance Sukuk debt finance Musharaka venture capital 68 Chapter 5 Cost of capital 69 WACC 70 CHAPTER CONTENTSBASICS OF COST OF CAPITAL ------------------------------------------ 72RISK-FREE RETURN COST OF EQUITY 72 73 KD THE COST OF DEBT ------------------------------------------------- 80 WACC WEIGHTED AVERAGE COST OF CAPITAL -------------------- 84 71 Overall returnA combination of two elements determine the return required by an investor for a given financial instrument. 1. 2. Risk-free return The level of return expected of an investment with zero risk to the investor. Risk premium the amount of return required above and beyond the riskfree rate for an investor to be willing to invest in the company Risk-free return o .bl the return offered by short-dated 0 The risk-free rate is normally equated to 00 government bonds or treasury bills. The government is not expected (we would 2 hope!) to default on either interest payments or capital repayments. ks o The risk-free rate is determined by the market reflecting prevailing interest and bo e inflation rates and market conditions.Degree of riskHigh risk investments 72 Cost of equityThe rate of return required by a shareholder. This may be calculated in one of two ways: 1. 2. Dividend Valuation Model (DVM). Capital Asset Pricing Model (CAPM). Perpetuity formulaPV of a perpetuity = Cash inflow p.a. Rate of return Introducing terminologyShare price = Dividend p.a. Cost of Equity P0where Ke d P0 d = Ke= = = cost of equity We can rearrange the formula to get the one below: The dividend valuation model with constant dividends Ke = d P0 Example 1The ordinary shares of Kewell Ltd are quoted at $5 per share ex div. A dividend of 40p per share has just been paid and there is expected to be no growth in dividends. 73 Example 2The ordinary shares of Gerrard Ltd are quoted at $2 per share. A dividend of 15p is about to be paid. There is expected to be no growth in dividends. Introducing growthThe dividend valuation model with constant growth Ke =where g d1 d0 d1 +g P0= = = or d0 (1 + g) +g P0 LEARN THIS a constant rate of growth in dividends dividend to be paid in one years time current dividend Example 3Alonso Ltd has a share price of $4.00 ex-div and has recently paid out a dividend 20p. Dividends are expected to growth at an annual rate of 5% g = where Example 4Sissoko Ltd paid a dividend of 20p per share 4 years ago, and the current dividend is 33p. The current share price is $6 ex div. Required: (a) (b) Estimate the rate of growth in dividends. Calculate the cost of equity. Example 5Mascherano Ltd paid a dividend of 6p per share 8 years ago, and the current dividend is 11p. The current share price is $2.58 ex div. 74 Example 6The ordinary shares of Torres Ltd are quoted at $5.00 cum div. A dividend of 40p is just about to be paid. The company has an annual accounting rate of return of 12% and each year pays out 30% of its profits after tax as dividends. 75 Portfolio theoryRisk and ReturnThe basis of portfolio theory is that an investor may reduce risk with no impact on return as a result of holding a mix of investments. Risk of portfolio () Unsystematic Risk Systematic Risk If we start constructing a portfolio with one share and gradually add other shares to it we will tend to find that the total risk of the portfolio reduces as follows: Initially substantial reductions in total risk are possible; however, as the portfolio becomes increasingly diversified, risk reduction slows down and eventually stops. The risk that can be eliminated by diversification is referred to as unsystematic risk. This risk is related to factors that affect the returns of individual investments in unique ways, this may be described as company specific risk. The risk that cannot be eliminated by diversification is referred to as systematic risk. To some extent the fortunes of all companies move together with the economy. This may be described as economy wide risk. The relevant risk of an individual security is its systematic risk and it is on this basis that we should judge investments. Non systematic risk can be eliminated and is of no consequence to the well-diversified investor. Implications1. 2. If an investor wants to avoid risk altogether, he must invest in a portfolio consisting entirely of risk-free securities such as government debt. If the investor holds only an undiversified portfolio of shares he will suffer unsystematic risk as well as systematic risk. 76 If an investor holds a balanced portfolio of all the stocks and shares on the stock market, he will suffer systematic risk which is the same as the average systematic risk in the market. Individual shares will have systematic risk characteristics which are different to this market average. Their risk will be determined by the industry sector and gearing (see later). Some shares will be more risky and some less. (beta) factorThe method adopted by CAPM to measure systematic risk is an index . factor is the measure of a shares volatility in terms of market risk The The factor of the market as a whole is 1. Market risk makes market returns volatile and the factor is simply a yardstick against which the risk of other investments can be measured. The factor is critical to applying the CAPM, it illustrates the relationship of an individual security to the market as a whole or conversely the market return given the return on an individual security. For example, suppose that it has been assessed statistically that the returns on shares in XYZ plc tend to vary twice as much as returns from the market as a whole, so that if market returns went up by 6%, XYZs returns would go up by 12% and if market returns fell by 4% then XYZs returns would fall by 8%, XYZ would be said to have a factor of 2. The security market line gives the relationship between systematic risk and return. We know 2 relationships. This carries no risk and therefore no systematic risk and therefore has a eta of zero. This represents the ultimate in diversification and therefore contains only systematic risk. It has a eta of 1. 77 Return (%age) Rm Rf 1.0 Risk () From the graph it can be seen that the higher the systematic risk, the higher the required rate of return. The SML and the relationship between required return and risk can be shown using the following formula: Ke where = Ke Rf + (Rm - Rf) = = = = Rf Rm o .bl 0 required return from individual security 00 Beta factors2individual security of ok of interest risk-free rate o eb on market portfolio return 4. 5. 6. 7. 78 Kuyt Ltd The market return is 15%. Kuyt Ltd has a beta of 1.2 and the risk free return is 8%. Example 8 Crouch plc The risk-free rate of return is 8% The market risk premium is 6% The beta factor for Crouch plc is 0.8 79 Terminology1. 2. 3. Loan notes, bonds and debentures are all types of debt issued by a company. Gilts and treasury bills are debt issues by a government. Traded debt is always quoted in $100 nominal units or blocks Interest paid on the debt is stated as a percentage of nominal value ($100 as stated). This is known as the coupon rate. It is not the same as the cost of debt. Debt can be: (i) (ii) (iii) 5. Irredeemable never paid back redeemable at par (nominal value) Interest can be either fixed or floating (variable). All questions are likely to give fixed rate debt. 0 20 reason for learning the valuation is that it Irredeemable debt is very rare. s (The k gives a quick way to calculate the cost of debt if the current market value and the oo the same (see example 14).) redemption value of theeb are debtKd for irredeemable debtKd =where i T P0 i(1 - T) P0= = = interest paid marginal rate of tax ex interest (similar to ex div) market price of the loan stock. Example 9 Rafa The 10% irredeemable loan notes of Rafa plc are quoted at $120 ex int. Corporation tax is payable at 30%. 80 Year 0 1 to n n Cash flow Market value of the loan note Annual interest payments Redemption value of loan P0 i(1 - T) RV Warnock Ltd Warnock Ltd has 10% loan notes quoted at $102 ex int redeemable in 5 years time at par. Corporation tax is paid at 30%. Technique1. 2. 3. 4. 3. 4. 5. 7 columns Identify the cash flows discount at 5% and 10% slot values in the IRR formula discount at 10% if npv is positive discount at 15%, if negative, discount at 5% slot values in the IRR formula. The 10% loan notes of Rafa plc are quoted at $120 ex int. Corporation tax is payable at 30%. They will be redeemed at a premium of $20 over par in 4 years time Required:What is the net of tax cost of debt (a) (b) 81 Convertible debtA loan note with an option to convert the debt into shares at a future date with a predetermined price. In this situation the holder of the debt has the option therefore the redemption value is the greater of either: 1. 2. The share value on conversion or The cash redemption value if not converted. Example 12 Dudek Dudek has convertible loan notes in issue that may be redeemed at a 10% premium to par value in 4 years. The coupon is 10% and the current market value is $95. Alternatively the loan notes may be converted at that date into 25 ordinary shares. The current value of the shares is $4 and they are expected to appreciate in value by 6% per annum o spis not traded. Bank loans and A substantial proportion of the debt of companies og lequal to the coupon rate adjusted for other non-traded loans have a cost of debt .b tax. 00 0 K = Interest (Coupon) rate x (1 T) s2 k oo eb Example 13 TraoreNon-tradeable debtd Traore has a loan from the bank at 12% per annum. Corporation tax is charged at 30% 82 Preference sharesA fixed rate charge to the company in the form of a dividend rather than in terms of interest. Preference shares are normally treated as debt rather than equity but they are not tax deductible. They can be treated using the dividend valuation model with no growth Kp = Hamann 83 Example 15 Baros plc Baros plc has 20m ordinary 25p shares quoted at $3, and $8m of loan notes quoted at $85. The cost of equity has already been calculated at 15% and the cost of debt (net of tax) is 7.6% 84 Example 16 Olachika plc Statement of Financial Position (Balance sheet) for the last year Non-current assets Current assets Total assets Equity and liabilities Ordinary shares, par value $1 Retained earnings Total equity 10% loan notes 9% preference shares, par value $1 Total non-current liabilities Current liabilities Total equity and liabilities The current ex div ordinary share price is $5.50 per share. An ordinary dividend of 40 cents per share has just been paid and dividends are expected to increase by 4.5% per year for the foreseeable future. .b m co ot. The current ex div preference share price is 78.9 cents. The loan notes are secured on the existing non-current assets of Olachika Co and are redeemable at par in six years time. They have a current ex interest market price of $102.5 per $100 loan note. Olachika Co pays tax on profits at an annual rate of 30%. Required: (a) Calculate the current weighted average cost of capital of Olachika plc. (9 marks) 85 86 Chapter 6 87 CHAPTER CONTENTSCAPITAL STRUCTURE AND THE COST OF CAPITAL ------------------- 89 GEARING THEORIES ----------------------------------------------------- 90THE TRADITIONAL VIEW OF CAPITAL STRUCTURE MODIGLIANI AND MILLER (M&M) NO TAXES MODIGLIANI AND MILLER WITH TAX PROBLEMS WITH HIGH GEARING PECKING ORDER THEORY 90 91 92 92 92 88 Key relationship Increase in WACC 89 Cost of debtThere is no impact on the cost of debt until the level of gearing is prohibitively high. When this level is reached the cost of debt rises. Ke Kd Gearing (D/E) Key pointThere is an optimal level of gearing at which the WACC is minimized and the value of the company is maximised 90 Cost of debtThere is no impact on the cost of debt until the level of gearing is prohibitively high. The assumptionsM&M in 1958 was based on the premise of a perfect capital market in which: 1. 2. 3. 4. 5. 6. 7. Perfect capital market exist where individuals and companies can borrow unlimited amounts at the same rate of interest. There are no taxes or transaction costs. Personal borrowing is a perfect substitute for corporate borrowing. Firms exist with the same business or systematic risk but different level of gearing. All projects and cash flows relating thereto are perpetual and any debt borrowing is also perpetual. All earnings are paid out as dividend. Debt is risk free. Big idea The increase in Ke directly compensates for the substitution of expensive equity with cheaper debt. Therefore the WACC is constant regardless of the level of gearing. Ke Cost of capital WACC Gearing (D/E) If the weighted average cost of capital is to remain constant at all levels of gearing it follows that any benefit from the use of cheaper debt finance must be exactly offset by the increase in the cost of equity. 91 ImplicationAs the level of gearing rises the overall WACC falls. having the highest level of debt possible. The company benefits from p Kd(1-t) gs blo 92 Key pointThe project is assessed on its ability to earn a return in relation to its own level of risk. Possible to assess all projects providing the level of risk (beta) can be determined. By considering only systematic risk we have a better theoretical basis for setting a discount rate. 0 20 3. It reflects the position of large companies which are likely to be well. s ok o eb Example 1 Toshack plcRequired: (a) (b) What is the required return of the project? Toshack plc is an all equity company and has a cost of capital of 17% p.a. A new project has arisen with an estimated beta of 1.3. rf = 10% and m = 20%. r What relationship does this have to the cost of capital to the company? Johnson plc Johnson plc is an all equity company with a beta of 0.6. It is considering a single year project which requires an outlay now of $2,000 and will generate cash in one year with an expected value of $2,500. The project has a beta of 1.3. rf = 10%, m = 18%. r Required: (a) (b) (c) What is the Johnsons cost of equity capital? What is the required return of the project? Is the project worthwhile? 93 Asset Beta( asset) Financial Gearing Re-gear De-gear Equity beta Asset betaA measure solely of systematic risk. companies in the same industry. The asset beta will be the same for all Key formula asset(ungeared) = equity (geared) E E + D (1 - t) 94 Question approach1. Equity beta Identify a suitable equity beta we need a value from a company in the similar industry. This beta will probably include gearing risk (if the company has any debt finance). De-gear Use the formula given to strip out the gearing risk to calculate the asset beta for the project. The asset beta will be the same for all companies/ projects in a similar industry. To calculate a meaningful asset beta it is useful to use a simple average of a number of proxy asset betas. This way a better assessment of the level of systematic risk suffered by the industry is calculated. m co t. Re-work the same formula to add back the unique gearing relating to the project. po s 5. Use CAPM log .b Calculate the cost of equity using the CAPM formula. 00 0 s2 k Example 3 Voronin plc oo eb Voronin plc is a matruska doll manufacturer with a equity:debt ratio of 5:3. The4. Re-gearcorporate debt, which is assumed to be risk free, has a gross redemption yield of 10%. The beta value of the companys equity is 1.2. The average return on the stock market is 16%. The corporation tax rate is 30%. The company is considering a rag doll manufacturing project. The following three companies are currently operating in the ragdoll industry. CompanyEquity beta Debt (%) Equity (%) T1.05 30 70 L1.10 35 65 C1.18 40 60 Voronin plc maintains its existing capital structure after the implementation of the new project. 95 Example 4 Toshack Toshack, an all equity agro-chemical firm, is about to invest in a diversification in the consumer pharmaceutical industry. Its current equity beta is 0.8, whilst the average equity of pharmaceutical firms is 1.3. Gearing in the pharmaceutical industry averages 40% debt, 60% equity. Corporate debt is considered to be risk free. Rm = 14%, Rf = 4%, corporation tax rate = 30%. Required: What would be a suitable discount rate for the new investment if Toshack were to finance the new project in each of the following ways: (a) (b) by 30% debt; 70% equity? 96 Chapter 7 Ratio analysis 97 C H A P T E R 7 R A T IO A N A L Y S I S Ratio Analysis Profitability Return on capital employed Return on equity Asset turnover Operating profit margin InvestorEPS PE ratio Dividend cover Dividend yield Gearing m Operating gearing Financial gearing Capital gearing measure Interest cover 98 CHAPTER CONTENTSPROFITABILITY RATIOS ----------------------------------------------- 100RETURN ON CAPITAL EMPLOYED ROCE RETURN ON EQUITY ROE 100 100 105 105 99 PROFITABILITY RATIOSThe underlying aim of a company. There are two basic measures: 1. 2. Operating ProfitX 100 Capital employed Operating profit 0 20 it includes Equity and Long-term Debt. The total funds invested in the business, s ok bo Return on equity e ROECapital employedA measure of return to the shareholders. It is calculated after taxation and before dividends have been paid out. It will be affected by gearing. ROE Equity Key working$ PBIT less Interest PBT Less Tax PAT Less Dividends Retained Earnings ( ) Case A company is considering a number of funding options for a new project. The new project may be funded by $20m of equity or debt. Below are the financial statements given the project has been funded in either manner. Balance sheet extract Equity Finance$m Creditors Debentures (10%) 0.0 Debt Finance$m 20.0 Capital Share Capital (50p) Share Premium Reserves Profit and Loss Account extract $m Turnover Gross Profit less expenses (excluding interest) Operating Profit .bl 00 010.0 2 Calculate profitability ratios and compare the financial performance of the company under both equity and debt funding. 101 GEARINGShould we finance the business using debt or equity? There are two basic considerations: 1. 2. Cost. Risk. CostAny finance will incur servicing costs, debt will require interest payments and equity will require payment of dividends or at least capital growth. On the basis of cost of servicing we would always pick debt over equity. Debt should be less expensive for two reasons: Debt is tax deductible because the debt holders are not owners of the business. Equity however will receive a return after tax because they receive an appropriation of profits. Debt is therefore tax efficient saving 30(ish)%. o sp shareholder. If there is lower The debt holder is in a less risky position than the log a lower return. The lower risk risk then the debt holder should be willing b expect . to 00 is due to two factors: 0 s2 1. Fixed coupon A legal obligation to pay interest. k oo 2. Security Charges or covenants against assets. eb2. Risk Business riskBusiness risk is inherent to the business and relates to the environment in which the business operates. 1. 2. 3. 4. Competition Market Legislation Economic conditions. 102 Financial riskRisk associated with debt financing. If the company is financed using equity, it carries no financial risk. This is because it has no need to pay shareholders a return (dividend) in the event of a poor trading year. If the company finances itself using debt as well as equity then it must generate sufficient cash flow to pay interest payments as they fall due. The greater the level of debt, the greater the interest payments falling due and hence the higher the risk of default. This is financial risk. 103 GEARING TYPESGearing is a measure of risk. There are two measures of gearing: 1. Operating gearingRisk associated with the level of fixed costs within a business. The higher the fixed cost, the more volatile the profit. The level of fixed cost is normally determined by the type of industry and cannot be changed. This is unlikely to arise in the F9 syllabus since it will be incorporated as part of the systematic risk of the company/ industry. 2. Financial gearingRisk associated with debt financing. The company can decide the level of financial risk it wishes to take on. Impact A company can/must accept some level of risk, and is willing to trade additional risk for additional gain. The effect of risk is cumulative: if a company already has high operating gearing it will have to be more conservative with its financial gearing. 104 Capital gearingThe mix of debt to equity. Debt + Equity Debt1. 2. 3. mX All permanent capital charging a fixed interest may be considered debt. Debentures and loans, bank overdraft (if significant), preference share capital. Equity1. 2. 3. Ordinary share capital share premium reserves. 105 Redknapp Ltd$m $m20.0 12.0 Fixed assets (total) Current assets (total) Current liabilities Trade creditors Bank overdraft Long-term liabilities Debenture 10% Capital Ordinary share capital Ordinary share premium Preference share capital Reserves 106 INTEREST COVERAn income statement measure that considers the ability of the business to cover the interest payments as they fall due. Interest cover PBIT Interest Example 4Stan the man Collymore Income statement extract Operating Profit Interest Profit Before Tax Tax @ 30% Profit After Tax $m 20.0 (4.5) 15.5 (4.65) 10.85 Required: (a) (b) Calculate the interest cover. Is this level of cover safe? 107 Newsam plc is a quoted company which produces a range of branded products all of which are well-established in their respective markets, although overall sales have grown by an average of only 2 per cent per annum over the past decade. The board of directors is currently concerned about the companys level of financial gearing, which although not high by industry standards, is near to breaching the covenants attaching to its 15 per cent debenture issue, made twelve years ago at a time of high market interest rates. Issued in order to finance the acquisition of the premises on which it is secured, the debenture is repayable at par value of $100 per unit of stock at any time during the period 20X420X7. There are two covenants attaching to the debenture, which state: At no time shall the ratio of debt capital to shareholders funds exceed 50 per cent. The company shall also maintain a prudent level of liquidity, defined as a current ratio at no time outside the range of the industry average (as published by the corporate credit analysts, Creditex), plus or minus 20 per cent. Newsams most recent set of accounts is shown in summarised form below. The buildings have been depreciated since acquisition at 4 per cent per annum, and most of the machinery is only two or three years old, having been purchased mainly via a bank overdraft. The interest rate payable on the bank overdraft is currently 9 per cent. The finance director argues that Newsam should take advantage of historically low interest rates on the European money markets by issuing a medium-term Eurodollar bond at 5 per cent. The dollar is currently selling at a premium of about 1 per cent on the three-month forward market. Newsams ordinary shares currently sell at a P/E ratio of 14, and look unattractive compared to comparable companies in the sector which exhibit an average P/E ratio of 18. According to the latest published credit assessment by Creditex, the average current ratio for the industry is 1.35. The debentures currently sell in the market at $15 above par. The summarised financial accounts for Newsam plc for the year ending 30 June 20X4 are as follows. Profit and loss account extract for the year ended 30 June 20X4 Sales Operating profit Interest payable Profit before tax Taxation Profit after tax Dividend Retained profit $m 28.00 ______ 3.00 (1.00) ______ 2.00 (0.66) ______ 1.34 (0.70) ______ 0.64 108 Balance sheet as at 30 June 20X4 $m $m 5.0 4.0 11.0 ____ 20.0 2.5 4.0 0.5 ____ 7.0 ____ 3.0 4.0 ____ (7.0) ____ Net current assets Total assets less current liabilities Long-term creditors 15% debentures 20X4 20X7 0.0 ____ 20.0 (5.0) ____ 15.0 ==== 5.0 10.0 ____ 15.0 ==== Required: (a) Calculate appropriate gearing ratios for Newsam plc using: (i) (ii) (b) (c) (d) book values; and market values.(3 marks) Assess how close Newsam plc is to breaching the debenture covenants. (3 marks) Discuss whether Newsam plcs gearing is in any sense dangerous. (4 marks) Discuss what financial policies Newsam plc might adopt: (i) (ii) in order to lower its capital gearing; and to improve its interest cover.(10 marks) 109 Arwin plans to raise $5m in order to expand its existing chain of retail outlets. It can raise the finance by issuing 10% loan notes redeemable in 2X15, or by a rights issue at $4.00 per share. The current financial statements of Arwin are as follows. Income statement for the last year Sales Cost of sales Gross profit Administration costs Profit before interest and tax Interest Profit before tax Taxation at 30% Profit after tax Dividends Retained earnings Statement of Financial Position (Balance sheet) extract Net non-current assets Net current assets 12% loan notes 2X10Ordinary shares, par value 25c Retained profit $'000 50,000 30,000 20,000 14,000 6,000 300 5,700 1,710 3,990 2,394 1,596 The expansion of business is expected to increase sales revenue by 12% in the first year. Variable cost of sales makes up 85% of cost of sales. Administration costs will increase by 5% due to new staff appointments. Arwin has a policy of paying out 60% of profit after tax as dividends and has no overdraft. o eb 2 ks Required: (a) (b) For each financing proposal, prepare the forecast income statement after one additional year of operation. (5 marks) Evaluate and comment on the effects of each financing proposal on the following: (i) (ii) Financial gearing; Operational gearing; Discuss the dangers to a company of a high level of gearing, including in your answer an explanation of the following terms: (i) (ii) Business risk; Financial risk.(8 marks) (25 marks)ebooks2000.blogspot.com 110 EPS Example 7The Sammy Hyypia Company earned profits after tax of $14m and has a preference dividend of $2m. There are 6 million ordinary shares in circulation. The P/E ratio is a measure of future earnings growth, it compares the market value to the current earnings. PE Ratio ebExample 8Share Price EPS Dividend per share Number of shares 0 s2 EPS k oo Danny200 pence 10 pence 2 pence 2 million Stephan80 pence 8 pence 8 pence 4 million 111 Dividend CoverThe relationship between the dividend paid and the funds available to pay the dividend ie the attributable profit 1. 2. 3. 4. 5. The industry type Shareholder expectations The investment opportunities Tax Dividend policy. Dividend cover Example 8 contdRequired: What is the dividend cover for each company? Dividend Yield The cash return from holding a share. considers part of the return available to the shareholder (the other part being the capital gain or increase in share price). eDividend yield = Example 8 contdRequired: Calculate the dividend yield. 112 Chapter 8 113 C H A P T E R 8 R A IS IN G E Q U I T Y F IN A N C E CHAPTER CONTENTSRAISING EQUITY FINANCE -------------------------------------------- 115UNLISTED COMPANIES STOCK MARKETS CONSIDERATIONS METHODS OF OBTAINING A LISTING 115 115 115 114 115 PlacingShares are placed with / sold to institutional investors, keeping the cost of the issue to a minimum. 116 Rights issuesA rights issue is the right of existing shareholders to subscribe to new share issues in proportion to their existing holdings. This is to protect the ownership rights of each investor. Advantages1. 2. 3. Low cost Protect ownership rights Rarely fail. Marcus Marcus plc, which has an issued capital of 4,000,000 shares, having a current market value of $2.80 each, makes a rights issue of one new share for every three existing shares at a price of $2.0. Value of a rightThe new shares are issued at a discount to the existing market value, this gives the rights some value. 117 Shareholders optionsThe shareholders options with a rights issue are to: 1. 2. 3. 4. Take up (buy) the rights Sell the rights A bit of both Do nothing. Example 2A shareholder had 10,000 shares in Marcus plc before the rights offer. Required: Calculate the effect on his net wealth of each of the following options: (a) (b) (c) Take up the shares, Sell the rights, Do nothing. Tirwen Tirwen is a medium-sized manufacturing company which is considering a 1 for 5 rights issue at a 15% discount to the current market price of $4.00 per share. Issue costs are expected to be $220,000 and these costs will be paid out of the funds raised. It is proposed that the rights issue funds raised will be used to redeem some of the existing loan stock at par. Financial information relating to Tirwen is as follows: Ordinary shares (par value 50c) Reserves 12% loan notes 2X12 Current liabilities Trade payables Overdraft 118 Other information: Price/earnings ratio of Tirwen: Overdraft interest rate: Tax rate: Sector averages: debt/equity ratio (book value): interest cover: Required: (a) Ignoring issue costs and any use that may be made of the funds raised by the rights issue, calculate: (i) (ii) the theoretical ex rights price per share; the value of rights per existing share. (3 marks) What alternative actions are open to the owner of 1,000 shares in Tirwen as regards the rights issue? Determine the effect of each of these actions on the wealth of the investor. (6 marks) Calculate the current earnings per share and the revised earnings per share if the rights issue funds are used to redeem some of the existing loan notes. (6 marks) Evaluate whether the proposal to redeem some of the loan notes would increase the wealth of the shareholders of Tirwen. Assume that the price/earnings ratio of Tirwen remains constant. (3 marks) Discuss the reasons why a rights issue could be an attractive source of finance for Tirwen. Your discussion should include an evaluation of the effect of the rights issue on the debt/equity ratio and interest cover. (7 marks) (d) (e) (25 marks) 119 120 Chapter 9 121 CHAPTER CONTENTSTHE TREASURY FUNCTION--------------------------------------------- 123ROLE CENTRALISATION VS. DECENTRALISATION PROFIT CENTRE VS. COST CENTRE SHORT-TERM SOURCES OF FINANCE ASSET SPECIFIC SOURCES OF FINANCE 123 123 124 125 126 129 132 122 RoleTreasury management is the corporate handling of all financial matters, the generation of external and internal funds for business. The management of currencies and cash flows, and complex strategies, policies and procedures of corporate finance. The role being summarised under 5 headings: 1. 2. 3. 4. 5. Corporate objectives Liquidity management Investment management o bo Currency management. eFunding management Advantages of centralisation1. Avoid duplication of skills of treasury across each division. A centralised team will enable the use of specialist employees in each of the roles of the department. Borrowing can be made in bulk taking advantage of better terms in the form of keener interest rates and less onerous conditions. Pooled investments will similarly take advantage of higher rates of return than smaller amounts. Pooling of cash resources will allow cash-rich parts of the company to fund other parts of the business in need of cash. Closer management of the foreign currency risk of the business.ebooks2000.blogspot.com 2. 3. 4. 5. 123 Advantages of decentralisation1. 2. Greater autonomy of action by individual treasury departments to reflect local requirements and problems. Closer attention to the importance of cash by each division. Cost centre A function to which costs are accumulated. Profit centre A function to which both costs and revenues are accounted for. Advantages of using a profit centre1. 2. 3. 4. 5. The use of the treasury department is given a value which limits the use of the service by the divisions. The prices charged by the treasury department measure the relative efficiency of that internal service and may be compared to external provision. The treasury department may undertake part of the hedging risk of a trade thereby saving the company as a whole money. The department may gain other business if there is surplus capacity within the department. Speculative positions may be taken that net substantial returns to the business. 124 The factor is often more successful at enforcing credit terms leading a lower level of debts outstanding. Factoring is therefore not only a source of short-term finance but also an external means of controlling or reducing the level of debtors. Invoice discountingA service also provided by a factoring company. Selected invoices are used as security against which the company may borrow funds. This is a temporary source of finance repayable when the debt is cleared. The key advantage of invoice discounting is that it is a confidential service, the customer need not know about it. Trade credit 0 20 The delay of payment to suppliers is effectively a source of finance. ks ocompany is able to fund its stock of the material at By paying on credit terms the o eb the expense of its suppliers.OverdraftsA source of short-term funding which is used to fund fluctuating working capital requirements. Its great advantage is that you only pay for that part of the finance that you need. The overdraft facility (total limit) is negotiated with the bank on a regular basis (maybe annually). For a company with a healthy trading record it is normal for the overdraft facility to be rolled over from one year to the next although theoretically it is repayable on demand. Bank loansBank loans or term loans are loans over between one and three years which have become increasingly popular over the past ten to fifteen years as a bridge between overdraft financing and more permanent funding. Bills of exchangeA means of payment whereby by a promissory note is exchanged for goods. The bill of exchange is simply an agreement to pay a certain amount at a certain date in the future. No interest is payable on the note but is implicit in the terms of the bill.ebooks2000.blogspot.com 125 Hire purchaseThe purchase of an asset by means of a structured financial agreement. Instead of having to pay the full amount immediately, the company is able to spread the payment over a period of typically between two and five years. Finance leaseA type of asset financing that appears initially very similar to hire purchase. Again the asset is paid for over between two and five years (typically) and again there is a deposit (initial rental) and regular monthly payments or rentals. The key difference is that at the end of the lease agreement the title to the asset does not pass to the company (lessee) but is retained by the leasing company (lessor). This has important potential tax advantages covered later in the course. Operating lease In this situation the company does not buy the asset (in part or in full) but instead rents the asset. lo .basset is only required for a short period The operating lease is often used where 0 00 the has no interest in acquiring the asset of time such as Plant Hire or the 2 company ks simply wishing to use it such as a company vehicle or photocopier. o bo e 126 CURRENT ASSETSInventory Receivables Cash and Bank MINUS CURRENT LIABILITIESPayables Bank overdraft 127 Assets mShort-term funds Non-current assets Long-term funds Time 128 Efficiency measureMeasuring the speed of circulation of cash within the company The operating cycle Measures Liquidity ratiosCurrent assets may be financed by current liabilities or by long-term funds. The ideal current ratio is 2:1. This would mean that half of the current assets are financed by current liabilities and therefore half by long-term funds. Similarly the ideal quick ratio is 1:1. Current ratio A simple measure of how much of the total current assets are financed by current liabilities. A safe measure is considered to be 2:1 or greater meaning that only a limited amount of the assets are funded by the current liabilities. Current Ratio Quick ratioA measure of how well current liabilities are covered by liquid assets. A safe measure is considered to be 1:1 meaning that we are able to meet our existing liabilities if they all fall due at once. Current Assets minus Stock Quick Ratio = (or acid test) Current Liabilities Operating cycleAlso known as the cash cycle or trading cycle. The operating cycle is the length of time between the companys outlay on raw materials, wages and other expenditures and the inflow of cash from the sale of goods. Purchases Inventory Sales Receivables Receipt Operating cycle $ 250,000 90,000 Gross profit 50,000 130 OVERTRADINGOvertrading is the term applied to a company which rapidly increase its turnover without having sufficient capital backing, hence the alternative term undercapitalisation. Output increase are often obtained by more intensive utilisation of existing fixed assets, and growth tends to be financed by more intensive use of working capital. Overtrading companies are often unable or unwilling to raise long-term capital and thus tend to rely more heavily on short-term sources such as overdraft and trade creditors. Debtors usually increase sharply as the company follows a more generous trade credit policy in order to win sales, while stock tend to increase as the company attempts to produce at a faster rate ahead of increase demand. Overtrading is thus characterised by rising borrowings and a declining liquidity position in terms of the quick ratio, if not always according to the current ratio. Symptoms of overtrading1. 2. 3. 4. 5. 6. Rapid increase in turnover Fall in liquidity ratio or current liabilities exceed current assets Sharp increase in the sales-to-fixed assets ratio Increase in the trade payables period Increase in short term borrowing and a decline in cash balance Fall in profit margins. 0 20 Overtrading is risky because short-term finance may be withdrawn relatively s quickly if creditors lose confidence in the business, or if there is general tightening ok o of credit in the economy b eresulting to liquidity problems and even bankruptcy, even though the firm is profitable.The fundamental solution to overtrading is to replace short-term finance with longterm finance such as term loan or equity funds. 131 MANAGING RECEIVABLES Offering credit introduces risk of default, defers inflow of cash and needs managing Credit managementThere are three aspects to credit management 1. 2. 3. Assessing credit status Terms Day to day management. The creditworthiness of all new customers must be assessed before credit is offered, it is a privilege and not a right. Existing customers must also be reassessed on a regular basis. The following may be used to assess credit status of a company 1. 2. 3. 4. 5. Bank References Trade References Published accounts Credit rating agencies Companys own Sales Record. TermsGiven that we are willing to offer credit to a company, we must know consider the limits to the agreement. This may include: 1. 2. 3. 4. Credit limit value Number of days credit Discount on early payment Interest on overdue account. Action Send statement of account Reminder letter 2nd reminder Legal action threat Take action to recover funds 133 Shankly Limited has sales of $40m for the previous year, receivables at the year end were $8m. The cost of financing debtors is covered by an overdraft at the interest rate of 14%. Required: (a) (b) What are the receivables days for Shankly? Calculate the cost of financing receivables. Example 3Shankly as above but a discount of 2% is offered for payment within 10 days. Required: Should the company introduce the discount given that 50% of the customers take up the discount? Advantages/Disadvantages Advantages1. 2. Early payment reducing the debtor balance and hence the interest charge. May reduce the bad debts arising. 134 Disadvantages1. 2. 3. 4. Difficulty in setting the terms. Greater uncertainty as to when cash receipts will be received. May not reduce bad debt in practice. Customers may pay over normal terms but still take the cash discount. FactoringThere are three main types of factoring service available: 1. 2. 3. Debt Collection And Administration Credit Insurance Financing. Example 4Shankly again but a factor has offered a debt collection service which should shorten the debtor collection period on average to 50 days. It charges 1.6% of turnover but should reduce administration costs to the company by $175,000. Required: p gs Should the company use the factoring facility? o .bl 00 Advantages/Disadvantages0 2 ks o Advantages bo e1. 2. 3. Saving in internal administration costs. Reduction in the need for day to day management control. Particularly useful for small and fast growing businesses where the credit control department may not be able to keep pace with volume growth. Disadvantages1. 2. 3. 4. 5. Should be more costly than an efficiently run internal credit control department. Factoring has a bad reputation associated with failing companies, using a factor may suggest your company has money worries. Customers may not wish to deal with a factor. Once you start factoring it is difficult to revert easily to an internal credit control. The company may give up the opportunity to decide to whom credit may be given. 135 Ewden plc is a medium-sized company producing a range of engineering products which it sells to wholesale distributors. Recently, its sales have begun to rise rapidly following a general recovery in the economy as a whole. However, it is concerned about its liquidity position and is contemplating ways of improving its cashflow. Ewdens accounts for the past two years are summarised below. Profit and loss account for the year ended 31 December 20X2 $000 Sales Cost of sales Operating profit Interest Profit before tax Taxation (after capital allowances) Profit after tax Dividends Retained profit 12,000 7,000 ______ 5,000 200 ______ 20X3 $000 16,000 9,150 ______ 6,850 250 ______ 6,600 1,600 ______ 5,000 2,000 ______ 3,000 ====== m 1,000 co ______ t.3,800 1,500 ______ 2,300 ====== 4,800 20X2 $000 $000 9,000 20X3 $000 $000 12,000 2,200 2,600 100 ______ 4,900 200 2,000 200 ______ (2,000) (2,400) (2,000) ______ 12,500 ====== (2,000) ______ 9,500 ====== Net assets 136 Capital and reserves Ordinary shares (50p) Profit and loss account 3,000 6,500 ______ 9,500 ====== 3,000 9,500 ______ 12,500 ====== In order to speed up collection from debtors, Ewden is considering two alternative policies. One option is to offer a 2 per cent discount to customers who settle within 10 days of dispatch of invoices rather than the normal 30 days offered. It is estimated that 50 per cent of customers would take advantage of this offer. Alternatively Ewden can utilise the services of a factor. The factor will operate on a service-only basis, administering and collecting payment from Ewdens customers. This is expected to generate administrative savings of $100,000 per annum and, it is hoped, will also shorten the debtor days to an average of 45. The factor will make a service charge of 1.5 per cent of Ewdens turnover. Ewden can borrow from its bankers at an interest rate of 18 per cent per annum. Required: (a) Identify the reasons for the sharp decline in Ewdens liquidity and assess the extent to which the company can be said to be exhibiting the problem of overtrading. o sp performance and liquidity Illustrate your answer by referenceog key to ratios computed from Ewdens accounts. (13 marks) .bl 00 benefits of the two methods of 0 Determine the relative costs and s2 reducing debtors, and recommend an appropriate policy. (7 marks) ok o (20 marks) eb Example 6We offer a cash discount of 2% for payment over 10 days rather than the normal 60 days. Required: (a) (b) What is the annualized cost of the cash discount? If the overdraft rate is 10% should we take offer the discount? 137 MANAGING INVENTORYHolding stock is necessary for operations, in terms of finished goods it offers greater choice to customers Holding stock incurs costs, in particular there is the opportunity cost of money tied up in stock Material costsMaterial costs are a major part of a companys costs and need to be carefully controlled. There are 4 types of cost associated with stock: 1. 2. 3. 4. ordering costs, holding costs, stockout costs, purchase cost. Ordering costs The clerical, administrative and accounting costs of placing an order. usually assumed to be independent of the size of the order. They are Holding costsHolding costs include items such as: 1. 2. 3. 4. Opportunity cost of the investment in stock Storage costs Insurance costs Deterioration. Stockout costs1. 2. 3. 4. Lost contribution through loss of sale; Lost future contribution through loss of customer; The cost of emergency orders of materials; The cost of production stoppages. 138 Cost Cost Total cost Holding Costs EOQ eExample 7 Ordering Costs Reorder Quantity A company requires 10,000 units of material X per month. The cost per order is $30 regardless of the size of the order. The holding costs are $20 per unit per annum. It is only possible to buy the stock in quantities of 400, 500, 600 or 700 units at one time. Required: What is the cheapest option? Using the formula Q =Co D Ch = = = 2Co.D Ch Cost per order Annual demand Cost of holding one unit for one year. 139 Example 7 contdRequired: Calculate the economic order quantity using the formula given. Example 8Annual demand is 120,000 units. Ordering costs are $30 per order and holding costs are $20/unit/annum. The material can normally be purchased for $10/unit, but if 1,000 units are bought at one time they can be bought for $9,800. If 5,000 units are bought at one time, they can be bought for $47,500. Required: What reorder quantity would minimize the total cost? 140 CASH MANAGEMENT Holding cash is necessary to be able to pay the bills and maintain liquidity Cash is an idle asset that costs money to fund but generates little or no return There are three areas associated with managing cash: 1. 2. 3. The Miller-Orr Model The Baumol Model The Cash Budget. A model that considers the level of cash that should be held by a company in an environment of uncertainty. The decision rules are simplified to two control levels in order that the management of the cash balance can be delegated to a junior manager. Maximum level Cash balance spread Return point TimeThe model allows us to calculate the spread. Given that we have the spread all key control levels can be calculated. 141 Minimum level given in the question Maximum level = minimum level + spread Return point = minimum level + spread Example 9The minimum level of cash is $25,000. The variance of the cash flows is $250,000. The transaction cost for both investing and en-cashing funds is $50. The interest rate per day is 0.05%. Required: Calculate the: (a) (b) (c) spread maximum level return point. Tansaction cost of investing/ en-cashing a security Excess cash available to invest in short-term securities Opportunity cost of holding cash Example 10A company generates $5,000 per month excess cash. The interest rate it can expect to earn on its investment is 6% per annum. The transaction costs associated with each separate investment of funds is constant at $50. Required: (a) (b) (c) What is the optimum amount of cash to be invested in each transaction? How many transactions will arise each year? What is the cost of making those transactions per annum? 142 Cash budgetA budget prepared on a monthly basis (at least) to ensure that the company has an understanding of its cash position going forward. There are 3 considerations: Inflow and outflows of cash Ignore non cash flows Pro forma led 143 Example 11In the near future a company will purchase a manufacturing business for $315,000, this price to include goodwill ($150,000), equipment and fittings ($120,000), and stock of raw materials and finished goods ($45,000). A delivery van will be purchased for $15,000 as soon as the business purchase is completed. The delivery van will be paid for in the second month of operations. The following forecasts have been made for the business following purchase: (i) Sales (before discounts) of the business's single product, at a mark-up of 60% on production cost will be: Month ($000) 1 96 2 96 3 92 4 96 5 100 6 104 25% of sales will be for cash; the remainder will be on credit, for settlement in the month following that of sale. A discount of 10% will be given to selected credit customers, who represent 25% of gross sales. (ii) Production cost will be $5.00 per unit. The production cost will be made up of: Raw materials Direct labour Fixed overhead (iii) Production will be arranged so that closing stock at the end of any month is sufficient to meet sales requirements in the following month. A value of $30,000 is placed on the stock of finished goods which was acquired on purchase of the business. This valuation is based on the forecast of production cost per unit given in (ii) above. The single raw material will be purchased so that stock at the end of a month is sufficient to meet half of the following month's production requirements. Raw material stock acquired on purchase of the business ($15,000) is valued at the cost per unit which is forecast as given in (ii) above. Raw materials will be purchased on one month's credit. Costs of direct labour will be met as they are incurred in production. The fixed production overhead rate of $1.00 per unit is based upon a forecast of the first year's production of 150,000 units. This rate includes depreciation of equipment and fittings on a straight-line basis over the next five years. (iv) m $2.50 co t. $1.50 $1.00 (v) (vi) (vii) Selling and administration overheads are all fixed, and will be $208,000 in the first year. These overheads include depreciation of the delivery van at 30% per annum on a reducing balance basis. All fixed overheads will be incurred on a regular basis, with the exception of rent and rates. $25,000 is payable for the year ahead in month one for rent and rates. Required: Prepare a monthly cash budget. You should include the business purchase and the first four months of operations following purchase. 144 Example 12Kool Co has annual sales revenue of $7 million and all sales are on 30 days credit, although customers on average take fifteen days more than this to pay. Contribution represents 55% of sales and the company currently has no bad debts. Accounts receivable are financed by an overdraft at an annual interest rate of 8%. Kool Co plans to offer an early settlement discount of 1.4% for payment within 20 days and to extend the maximum credit offered to 65 days. The company expects that these changes will increase annual credit sales by 8%, while also leading to additional variable costs equal to 0.5% of turnover. The discount is expected to be taken by 35% of customers, with the remaining customers taking an average of 65 days to pay. Required: (a) (b) Evaluate whether the proposed changes in credit policy will increase the profitability of Kool Co. (6 marks) Tiger Co, a subsidiary of Kool Co, has set a minimum cash account balance of $2,000. The average cost to the company of making deposits or selling investments is $50 per transaction and the standard deviation of its cash flows was $1,000 per day during the last year. The average interest rate on investments is 9.125%. (c) (d) o sp the return point for the Determine the spread, the upper limit and og cash account of Tiger Co using .bl Miller-Orr model and explain the the relevance of these values for 00 cash management of the company. the (6 marks) 20 ksthe key areas of accounts receivable o Identify and explain bo management. e (6 marks)Discuss the key factors to be considered when formulating a working capital funding policy. (7 marks) (25 marks) 145 146 Chapter 10 147 C H A P T E R 1 0 E F F I C I E N T M A R K E T H Y P O T H E S IS CHAPTER CONTENTSEFFICIENT MARKET HYPOTHESIS (EMH) ---------------------------- 149DEGREE OR FORMS OF EFFICIENCY IMPLICATIONS OF EMH FOR FINANCIAL MANAGERS 149 150 148 Weak form Weak form hypothesis states that current share prices reflect all relevant information about the past price movements and their implications. If this is true, then it should be impossible to predict future share price movements from historic information or pattern. Share prices only changes when new information about a company and its profits have become available. Since new information arrives unexpectedly, changes in share prices should occur in a random fashion, hence weak form can be referred to as random walk hypothesis. 2.(i) (ii) Semi-strong form hypothesis state that current share prices reflects both Any new publicly accessible information whether comments in the financial press, annual reports or brokers investment advisory services, should be accurately and immediately reflected in current share prices, so investment strategies based on such public information should not enable the investor to earn abnormal profit because these will have already been discounted by the market. Strong form The strong form hypothesis states that current share prices reflect all relevant information available from past price changes public knowledge; and insider knowledge available to specialists or experts such as investment managers. 149 The more efficient the market is, the less the opportunity to make a speculative profit because it become impossible to consistently out-perform the market. Evidence so far collected suggests that stock markets show efficiency that is at least weak form, but tending more towards a semi-strong form. In other words, current share prices reflect all or most publicly available information about companies and their securities. 150 Chapter 11 Valuation 151 CHAPTER 11 VALUATION CHAPTER CONTENTSBUSINESS VALUATION ------------------------------------------------- 153APPROACHES 153 164 152 153 Po = do(1 + g) ke g FORMULA GIVEN Can either be used to calculate the total MV of a company or the value of a share. Advantages1. 2. Considers the time value of money and has an acceptable theoretical basis. Particularly useful when valuing a minority stake of a business. Disadvantages1. 2. 3. Difficulty estimating an appropriate growth rate. The model is sensitive to key variables. Note Parry A company has the following information: Share capital in issue is 2m ordinary shares (25) Current dividend per share (ex div) - 4 Dividend five years ago 2.5 Current equity beta 0.6 Market information: Current market return 17% Risk-free rate 6% Required: What is the market value of the company? 154 Moran Ltd A company has the following information: Ordinary share capital (1m par value 50c) Current dividend (ex div) - 16 Current EPS - 20 Current return earned on assets - 20% Current equity beta 0.9 Current market return 11% Risk-free rate 6% Required: Find the market capitalisation of the company. Investors do not normally buy a company for the book value of its assets, but for the earnings / cash flows that the sum of its assets can produce in the future. It ignores intangible assets. It is very possible that intangible assets are more valuable than the balance sheet assets. to identify a minimum price in a takeover if the assets are predominantly tangible assets. Replacement costMay be used to be find the maximum value for an asset. Used for a company as a going concern. 155 Fagan Ltd$ Represented by 50c ordinary shares Reserves 6% debentures Z1 300,000 285,000 200,000 _______ 785,000 _______ Notes: o sp loan notes are redeemable at a premium of 5% log b The premises have a market value 0. is $50,000 higher than the book value 0 that 0 all other assets are estimated to be realisable at their book value. s2 k oo Required: ebValue a 60% holding of ordinary shares on an assets basis. 156 PE methodPE ratios are quoted for all listed companies and calculated as: PE =Pr ice per share EPS This can then be used to value shares in unquoted companies as: Value of company Value per share = = Total earnings P/E ratio EPS P/E ratio using an adjusted P/E multiple from a similar quoted company (or industry average). Example 4 Houllier Ltd Houllier Ltd, an unlisted company: Ordinary share capital is 200,000 50 shares. Extract from income statement for the year ended 31 Dec 20X7: $ Profit before taxation Less: Corporation tax 430,000 110,000 ______ Profit after taxation Less: Preference dividend Ordinary dividend $ 0 20 s 30,000 320,000 40,000 ______ (250,000) _______ 70,000 _______ 157 Earnings yieldThe earnings yield is the inverse of the PE ratio: Earnings yield = It can therefore be used to value the shares or market capitalisation of a company in exactly the same way as the PE ratio: Value of company = Total earnings 1 Dividend yield EPS SounessA similar listed company has a dividend Kenny Dalglish 158 Paisley Ltd The following information has been taken from the income statement and balance sheet of Paisley Ltd: Revenue Production expenses Administrative expenses Tax allowable depreciation Capital investment Corporate debt Corporation tax is 30%. The WACC is 16.6%. Inflation is 6%. These cash flows are expected to continue every year for the foreseeable future. $400m $150m $36m $28m $60m $14m trading at 110% of par value Advantages May value a part of the company. Disadvantages It relies on estimates of both cash flows and discount rates may be unavailable. Difficulty in choosing a time horizon. Difficulty in valuing a companys worth beyond this period. Assumes that the discount rate and tax rates are constant through the period. 159 Predator plc The board of directors of Predator plc is considering making an offer to purchase Target Ltd, a private limited company in the same industry. If Target Ltd is purchased it is proposed to continue operating the company as a going concern in the same line of business. Summarised details from the most recent set of financial statements for Predator and Target are shown below: Freehold property Plant & equipment Inventory Receivables Cash less current liabilities Target Ltd Balance sheet as at 31 March $000 $000 460 1,310 330 290 20 (518) 122 1,892 log .b78 38 116 35 43 po m160 964 1,124 768 1,892 YearT5 T4 T3 T2 T1 T5 is five years ago and T1 is the most recent year. Targets shares are owned by a small number of private individuals. Its managing director who receives an annual salary of $120,000 dominates the company. This is $40,000 more than the average salary received by managing directors of similar companies. The managing director would be replaced, if Predator purchases Target. The freehold property has not been revalued for several years and is believed to have a market value of $800,000. The balance sheet value of plant and equipment is thought to reflect its 160 The balance sheet value of plant and equipment is thought to reflect its replacement cost fairly, but its value if sold is not likely to exceed $800,000. Approximately $55,000 of inventory is obsolete and could only be sold as scrap for $5,000. The ordinary shares of Predator are currently trading at 430 cents ex-div. A suitable cost of equity for Target has been estimated at 15%. Both companies are subject to corporation tax at 33%. Required: Estimate the value of Target Ltd using the different methods of valuation and advise the board of Predator as to how much it should offer for Targets shares.Note: There has been no increase in the share capital of Target over the last five years. 161 VALUATION OF DEBTWhen valuing debt we assume that Market price Note The debt is normally valued gross of debt because we do not know the tax position of each investor. = The discounted cash flows of the debt Irredeemable debtThe company does not intend to repay the principal but to pay interest forever, the interest is paid in perpetuity. The formula for valuing a debenture is therefore: MV =where: I = I r o sp0) MV = market price of the debenture nowog (year .bl r = debt holders required return, expressed as a decimal. 0 00 cost of debt the formula becomes: 2 If instead of r you are given the companys ks o I(1 T ) MV = bo Kd eannual interest starting in one years time where: Kd = companys cost of debt, expressed as a decimal. Abbie LouThe A company has issued irredeemable loan notes with a coupon rate of 9%. required return of investors in this category of debt is 6%. 162 Redeemable debtThe market value is the present value of the future cash flows, these normally include: 1. 2. Interest payments for the years in issue Redemption value. Freddie A company has 10% debt redeemable in 5 years. Redemption will be at par value. The investors require a return of 8%. Required: The market value of the debt? A company has in issue 9% redeemable debt with 10 years to redemption. Redemption will be at par. The investors require a return of 16%. What is the market value of the debt? Convertible debt The value of a convertible is the higher of its value as debt and its converted value. This is known as the formula value. Elliot Elliot plc has convertible loan notes with a coupon rate of 10%. Each $100 loan note may be converted into 25 ordinary shares at any time until the date of expiry and any remaining loan note will be redeemed at $100. The debenture has four years to redemption. Investors require a rate of return of 6% per annum. Required: Should we convert if the current share price is: (a) (b) (c) $4.00 $5.00 $6.00? 163 Preference sharesSimilar to irredeemable debt, the income stream is the fixed percentage dividend received in perpetuity. The formula is therefore: where: D P0 Kp = = = the constant annual preference dividend ex-div market value of the share cost of the preference share. D Kp Tosca A firm has in issue $1 11% preference shares. The required return of preference shareholders is 12%. Chapter 12 165 CHAPTER 12 RISK CHAPTER CONTENTSFOREIGN CURRENCY RISK --------------------------------------------- 168 THE EXCHANGE RATE--------------------------------------------------- 169SPOT RATE SPOT RATE WITH SPREAD 169 169 171 om c ot. WHAT MAKES EXCHANGE RATES FLUCTUATE? ---------------------- 172 p gs BALANCE OF PAYMENTS 172 o .bl CAPITAL MOVEMENTS BETWEEN COUNTRIES 172 00 0 PURCHASING POWER PARITY THEORY (PPPT) 172 s2 k(IRPT) INTEREST RATE PARITY THEORY 173 o bo EFFECT THE INTERNATIONAL e FISHER 174 HEDGING EXCHANGE RATE RISK ------------------------------------- 176 INTERNAL HEDGING TECHNIQUES ----------------------------------- 177INVOICE IN OWN CURRENCY LEADING PAYMENT MATCHING OR NETTING DO NOTHING 177 177 177 177 166 167 168 Conversion rule ( and ) 1st currency to calculate the 2nd 2nd currency to calculate the 1st Flow rule (when looking at the 1st currency use Bart Simpson) eExample 1 Bart Simpson Spot rate $: 1.9500 0.0350 : 1.2500 0.0275 (a) (b) (c) (d) A 300,000 receipt is transferred to our bank account. A 400,000 receipt is to be transferred into our $ bank account. A $250,000 payment is to be paid from our bank account. A 100,000 payment is to be paid from our bank account. 169 Where the market is allowed to determine the exchange rate but with government intervention to reduce the adverse impacts of a freely floated rate. The basic aim is to damp the volatility by intervening or being prepared to intervene to maintain the value within a trading range. A government may further attempt to influence the ongoing value of the currency. If this is materially at odds with the markets perception of the value however it is rarely successful in the long run. Examples of this failing include the pound falling out of the ERM or the collapse in the value of the Argentinian Peso. The government may intervene by: Using reserves to buy or sell currency the government can artificially stimulate demand or supply and keep the currency within a trading range reducing volatility. Using interest rates, by increasing the interest rate within the economy the government makes the currency more attractive to investors in government debt and will attract speculative funds. 170 Transaction riskThe risk associated with short-term cash flow transactions. This may include: Commercial trade this is normally reflected by the sale of goods in a foreign currency but with a delay in payment. The receipt will have an uncertain value in the home currency. Borrowing or lending in another currency subsequent cash flows relating to interest payments would be uncertain in the home currency. These transactions may be hedged relatively easily either using internal or external hedging tools. Economic risk o .bl asset investment in a foreign country Long-term cash flow effects associated with 0 00 or alternatively loans taken out or made in a foreign currency and the subsequent 2 capital repayments. ks o Economic risk is more difficult to hedge given the longer term nature of the risk bo e (possibly over 10 or more years). A simple technique would be to adopt a portfolioapproach to investments by currency to spread the risk. Translation riskRisk associated with the reporting of foreign currency assets and liabilities within financial statements. There is no cash flow impact of this type of risk. However, the impact on the financial statements can be severe. Translation risk may be hedged by matching the assets and liabilities within each country. Any increase or decrease in value would cancel out on consolidation. 171 Based on the law of one price in economic theory. This would suggest that the price of the same product is the same in all currencies. 0 00 suggest that a relative change in prices To extend the principle further this would 2 ks (inflation) would have a direct effect on the exchange rate. o bo predictor of future exchange rates. PPPT is an unbiased bute poorIllustration A product is currently being sold in the UK for 2,000 and in the US for $4,000. This would infer that the current exchange rate is $: 2.0000. What would we expect the exchange rate to be in 1 year if the inflation rates are 4% and 7% respectively? Year 0 Inflation 1 UK 2,000 1.04 2,080 US $4,000 1.07 $4,280 The predicted exchange rate would be $4,280/2,080 = $: 2.0577. To calculate the impact of PPPT use the following formula: 172 Example 2The current exchange rate is : 0.8333. Inflation rates for the two currency zones are as follows: Eurozone 5% UK 3% The theory that there is a no sum gain relating to investing in government bonds in differing countries. Any benefit in additional interest is eliminated by an adverse movement in exchange rates. IRPT is an unbiased but poor predictor of future exchange rates. It is possible to invest 1m in short-dated govt bonds in the UK at 6.08% or alternatively in US treasury bills at 9.14%. The current exchange rate is $:2.0000 Year 0 Interest 1 UK 1m 1.0608 1.0608m 2 = Does it work?In practice the relationship between interest and exchange rates is not perfect and certainly not simultaneous. It is possible that the exchange rate does not move in line with interest rates for long periods (research the carry trade) only to correct over a short period of time. Current spot rate x 1 + i1st = 1 + i2nd 173 Example 3The current exchange rate is : 0.7865. Interest rates for the two currency zones are as follows: Eurozone 4% UK 5.5% (1 + m) = (1 + r)(1 + i) (using values from previous illustrations for PPPT and IRPT) YR 0 PPPT 2.0000 1.07/1.04 1 2.0577 US = 1.0914/1.07 1 The reason for both PPP and IRP having the same prediction is because the international Fisher effect holds true = 2% 174 Aurelio The following interest and inflation rates are known for the pound and the euro Inflation rates UK Eurozone 5.5% 4% Interest rates 7% 5% Required: What are the predicted exchange rates in one year using: (a) (b) PPPT? IRPT? 175 176 Leading paymentBy paying early or encouraging a customer to pay early the risk relating to an individual transaction is reduced or eliminated. The earlier the cash flow, the lower the exposure to exchange rate movements. Matching or nettingIf a company makes a number of transactions in both directions it will be able to net off those transactions relating to the same dates. By doing so a company can materially reduce the overall exposure, but is unlikely to eliminate it. In order to perform netting the company must have a foreign currency bank account in the appropriate country. Do nothing A compelling idea, the exchange rates will fluctuate up and own. It could be argued that since you win some and lose some then ignoring the risk would be the best option. As a result you save on hedging costs, the downside being that the exposure to exchange rates is present in the short-term. 177 m co is expecting to receive The current spot rate is $:2.1132 0.0046. The company ot. pat a discount of 0.32 0.36 in $400,000 in three months. The forward is quoted s cents in three months. log .b 00 0 Forward rule s2 k The forward rate may be given as an adjustment to the prevailing spot rate, if so: oo eb Add a discount, subtract a premiumIllustrationSpot rate Add discount Forward rate $ 2.1086 0.0032 2.1118 $ 2.1178 0.0036 2.1214 Skrtel A US corporation is looking to hedge its foreign exchange. The current spot rate is $: 1.6578 0.0032. The company is expecting to pay 350,000 in one month. The forward is quoted at a premium of 0.13 0.11 in cents in one months. 178 Advantages flexibility with regard to the amount to be covered, should lead to a perfect hedge in terms of amount and date relatively straightforward both to comprehend and to organise. Disadvantages contractual commitment that must be completed on the due date, if the underlying transaction is in anyway doubtful this may be problem the rate is fixed with no opportunity to benefit from favourable movements in exchange rates Steps1. 2. 3. Borrow borrow funds in the currency in which you need the money. Translate exchange the funds today avoiding exposure to fluctuations in the rate. Deposit deposit the funds in the currency in which you eventually want the funds until such time as you will need them. 179 Arbeloa Arbeloa is a UK company trading extensively in the US. The current exchange rate is $: 1.97500.003. Arbeloa is a UK company trading extensively in the US. The current exchange rate is $: 1.97500.003. We wish to do the following transactions: $ Receipt of $500,000 in 1 month. $ Payment of $300,000 in 3 months. The money markets provide the following interest rates for next year (pa) UK Loan rate Deposit rate Forward rates 1 month 3 month discount discount 0.0012 0.0017 0.0034 0.0038 6.0% 4.0% US 7.5% 5.0% Calculate the receipt and payments using both money markets and forward markets. Advantages There is some flexibility regarding the date at which the transaction takes place. May be available in currencies for which a forward rate is not available. Disadvantages Complex. May be difficult to borrow/ deposit in some currencies at a risk-free rate. 180 A futures contract betting on the exchange rate rising or falling, and An underlying transaction that may fall or rise in terms of the home currency. The linking of the two cancels out the movement of the exchange rate and leads to the hedge. Currency optionsThey may be exchange traded or OTC. Options have the benefit of being a onesided bet. You can protect the downside risk of the currency moving against you but still take advantage of the upside potential. The option writer therefore only has a downside risk (as we take the upside). The option writer needs compensating for this risk and is paid a premium over and above transaction costs. Inshal CoOne month: One month: Three months: Exam standardExpected receipt of $40,000 Expected payment of $140,000 Expected receipts of $300,000 The finance manager has collected the following information: Spot rate ($ per ): One month forward rate ($ per ): Three months forward rate ($ per ): Money market rates for Inshal Co: One year sterling interest rate: One year dollar interest rate: Assume that it is now 1 April. Required: (a) (b) (c) (d) Discuss the differences between transaction risk, translation risk and (6 marks) economic risk. Explain how inflation rates can be used to forecast exchange rates. (6 marks) Calculate the expected sterling receipts in one month and in three months using the forward market. (3 marks) Calculate the expected sterling receipts in three months using a money-market hedge and recommend whether a forward market hedge or a money market hedge should be used. (5 marks) Discuss how sterling currency futures contracts could be used to hedge the three-month dollar receipt. (5 marks) (25 marks) 181 182 Liquidity preference Investors prefer to be liquid over being illiquid. To encourage investment over the longer term the long-term debt must offer a higher return over short-term debt. Market expectations If interest rates are expected to fall over time long-term rates will be lower than short-term rates. This would lead to an inverted yield curve. Market segmentation Differing parts of the market (short-term vs long-term debt markets) may react to differing economic information meaning that the yield curve is not smooth but suffers discontinuities. 183 Short-term measuresForward rate agreements (FRA)The fixing of the interest rate today in relation to a future short-term loan. It is an obligation that must be taken once entered into. It is OTC and tailored to a specific loan in terms of: 1. 2. 3. Date Amount, and Term 0 20is wholly separate to the underlying loan. and offers a perfect hedge. Thes FRA okthe interest paid but there is a downside risk that It will give certainty as regards o eb interest rates may fall and we have already fixed at a higher rate.Interest rate guarantee (IRG)Similar to a FRA but an option rather than on obligation. In the event that interest rates move against the company (eg rise in the event of a loan) the option would be exercised. If the rates move in our favour then the option is allowed to lapse. There is a premium to pay to compensate the IRG writer for accepting the downside risk. 184 Advantages of swaps Allows a change in interest rate exposure at relatively low cost and risk. May allow access to a debt type that is otherwise unavailable to the company. May reduce the overall cost of financing in certain circumstances. 185.
https://id.scribd.com/document/66947324/50576627-ACCA-F9-Class-Notes-June-2011-Version
CC-MAIN-2020-10
refinedweb
21,829
61.67
Common JavaScript Interview Question That You Need to Know In this lesson, we are quickly going to know some common javascript interview questions that every javascript developer should know. let’s start, What Is JavaScript? JavaScript is the most popular web scripting language, used for both client-side and server-side development. Supporting object-oriented programming abilities, the JavaScript code can be inserted into HTML pages that can be understood and executed by web browsers. What are Truthy and Falsy Values in JavaScript? A truthy value is one that evaluates the boolean value true. which can also be expressions, statements, and values. Some truthy values to keep in mind: - -1,10 (or other negative and non-zero numbers) - {} (empty objects) - [] (empty arrays) - function () {}, () => {} (functions, including empty functions) - non-empty strings (like “false”, ‘ ‘ — including strings with just whitespace) Other values are considered falsy values. a value that evaluates to the boolean value false expressions, statements, and values can evaluate to the false boolean value and will therefore be considered a falsy value. Some falsy values to remember: - null - undefined - NaN - false - 0 (or other forms of the number 0, -0, 0.0 ) - empty strings ( '', "", etc) What is the difference between null & undefined? Undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. It implies no object or null string, no valid boolean value, no number, and no array object. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object. What do you understand by NaN? NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN. What is the difference between the operators ‘==‘ & ‘===‘? The main difference between “==” and “===” operator is that formerly compares variable by making type correction. if you compare a number with a string with numeric literal, == allows that, but === doesn’t allow that, because it not only checks the value but also the type of two variable if two variables are not of the same type “===” return false, while “==” return true. Explain Scope in javascript? In general terms, the scope will let us know at a given part of code, what are the variables and functions that we can or cannot access. There are three types of scopes in JavaScript: - Global Scope - Local or Function Scope - Block Scope Global Scope Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code var global = "Hello Global Scope";function globalMessage(){ return global; // can access global Variable since it's written in global space } function globalMessage2(){ return globalMessage(); // Can access globalMessage function since it's written in global space } globalMessage2(); // Returns Hello Global Scope Function Scope Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it. function functionScope(){ var a = 2; var multiplyBy2 = function(){ console.log(a*2); // Can access variable "a" since a and multiplyBy2 both are written inside the same function } } console.log(a); // Throws reference error since a is written in local scope and cannot be accessed outside multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scope Block Scope Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope. Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it. { let a = 12; } console.log(a); // Gives reference error since a cannot be accessed outside of the block for(let i=0; i<5; i++){ // do something } console.log(i); // Gives reference error since i cannot be accessed outside of the for loop block Scope Chain JavaScript engine also uses Scope to find variables. Let’s understand that using an example: var a = 32; function functionScope(){ var b= 16; var scopeChain = function(){ console.log(b); // Does not find b inside scopeChain Function, so looks for variable inside favFunction, outputs 16 } var scopeChain2 = function(){ console.log(a); // Does not find a inside scopeChain2 Function, so looks for variable inside favFunction and does not find it, so looks for variable in global scope, finds it and outputs 32 } scopeChain(); scopeChain2(); } functionScope(); What are closures in JavaScript? the closure concept, function closure(str){ const message = function(str2){ console.log(str + ' ' + str2); } return message; } const closureFunction = closure('I am Closure'); closureFunction('hello '); //Output: hello I am Closure closureFunction('hi.'); //output: hi I am Closure Explain bind(), call() and apply() in JavaScript? We use to call, bind, and apply methods to set the ‘this’ keyword independent of how the function is called. Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context. bind() This method returns a new function, where the value of ‘this’ keyword will be bound to the owner object, which is provided as a parameter. Example with arguments: const normalPerson = { firstName: 'Rahim', lastName: 'uddin ', salary: 15000, chargeBill: function(amount){ this.salary = this.salary - amount; return this.salary; }}const heroPerson = { Name: 'Hero', lastName: 'Balam', salary: 25000} const heroBillCharge = normalPerson.chargeBill.bind(heroPerson);heroBillCharge(2000)console.log(heroPerson.salary); // 23000 ( 25000 - 2000 ). const normalPerson = { firstName: 'Rahim', lastName: 'uddin ', salary: 15000, chargeBill: function(amount, tax){ this.salary = this.salary - amount - tax; return this.salary; }}const heroPerson = { Name: 'Hero', lastName: 'Balam', salary: 25000}// .call()normalPerson.chargeBill.call(heroPerson, 1000, 50);console.log(heroPerson.salary); // 2350 // .bind()normalPerson.chargeBill.apply(heroPerson,[30000,1000])console.log(heroPerson.salary); // 21000 What is the purpose of the ‘This’ Keyword in JavaScript? The JavaScript ‘this’ keyword refers to the object it belongs to. This has different values depending on where it is used. In a method, this refers to the owner object and in a function, this refers to the global object. const check= { prop: 18, func: function() { return this.prop; }, };console.log(check.func()); // expected output: 18 Explain event loop in JavaScript? The event loop is the secret behind JavaScript’s asynchronous programming. JS executes all operations on a single thread, but using a few smart data structures, gives us the illusion of multi-threading. Let’s take a look at what happens on the back-end. The call stack is responsible for keeping track of all the operations in line to be executed. Whenever a function is finished, it is popped from the stack. The event queue is responsible for sending new functions to the track for processing. It follows the queue data structure to maintain the correct sequence in which all operations should be sent for execution. Whenever an async function is called, it is sent to a browser API. These are APIs built into the browser. Based on the command received from the call stack, the API starts its own single-threaded operation.
https://touhidatik81.medium.com/common-javascript-interview-question-that-you-need-to-know-dbdad689d54c?readmore=1&source=user_profile---------0----------------------------
CC-MAIN-2021-43
refinedweb
1,238
54.22
Titanic survivors, a guide for your first Data Science project Introduction In this article, we are going to go through the popular Titanic dataset and try to predict whether a person survived the shipwreck. You can get this dataset from Kaggle, linked here. This article will be focused on how to think about these projects, rather than the implementation. A lot of the beginners are confused as to how to start when to end and everything in between, I hope this article acts as a beginner’s handbook for you. I suggest you practice the project in Kaggle itself. The Goal: Predict whether a passenger survived or not. 0 for not surviving, 1 for surviving. Describing the data In this article, we will do some basic data analysis, then some feature engineering, and in the end-use some of the popular models for prediction. Let’s get started. Data Analysis Step 1: Importing basic libraries import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline Step 2: Reading the data training = pd.read_csv('/kaggle/input/titanic/train.csv') test = pd.read_csv('/kaggle/input/titanic/test.csv') training['train_test'] = 1 test['train_test'] = 0 test['Survived'] = np.NaN all_data = pd.concat([training,test]) all_data.columns Step 3: Data Exploration In this section we will try to draw insights from the Data, and get familiar with it, so we can create more efficient models. training.info() training.describe() # seperate the data into numeric and categorical df_num = training[['Age','SibSp','Parch','Fare']] df_cat = training[['Survived','Pclass','Sex','Ticket','Cabin','Embarked']] Now let’s make plots of the numeric data: for i in df_num.columns: plt.hist(df_num[i]) plt.title(i) plt.show() So as you can see, most of the distributions are scattered, except Age, it’s pretty normalized. We might consider normalizing them later on. Next, we plot a correlation heatmap between the numeric columns: sns.heatmap(df_num.corr()) Here we can see that Parch and SibSp has a higher correlation, which generally makes sense since Parents are more likely to travel with their multiple kids and spouses tend to travel together. Next, let us compare survival rates across the numeric variables. This might reveal some interesting insights: pd.pivot_table(training, index = 'Survived', values = ['Age','SibSp','Parch','Fare']) The inference we can draw from this table is: - The average age of survivors is 28, so young people tend to survive more. - People who paid higher fare rates were more likely to survive, more than double. This might be the people traveling in first-class. Thus the rich survived, which is kind of a sad story in this scenario. - In the 3rd column, If you have parents, you had a higher chance of surviving. So the parents might’ve saved the kids before themselves, thus explaining the rates - And if you are a child, and have siblings, you have less of a chance of surviving Now we do a similar thing with our categorical variables: for i in df_cat.columns: sns.barplot(df_cat[i].value_counts().index,df_cat[i].value_counts()).set_title(i) plt.show() The Ticket and Cabin graphs look very messy, we might have to feature engineer them! Other than that, the rest of the graphs tells us: - Survived: Most of the people died in the shipwreck, only around 300 people survived. - Pclass: The majority of the people traveling, had tickets to the 3rd class. - Sex: There were more males than females aboard the ship, roughly double the amount. - Embarked: Most of the passengers boarded the ship from Southampton. Now we will do something similar to the pivot table above, but with our categorical variables, and compare them against our dependent variable, which is if people survived: print(pd.pivot_table(training, index = 'Survived', columns = 'Pclass', values = 'Ticket' ,aggfunc ='count')) print() print(pd.pivot_table(training, index = 'Survived', columns = 'Sex', values = 'Ticket' ,aggfunc ='count')) print() print(pd.pivot_table(training, index = 'Survived', columns = 'Embarked', values = 'Ticket' ,aggfunc ='count')) - Pclass: Here we can see a lot more people survived from the First class than the Second or the Third class, even though the total number of passengers in the First class was much much less than the Third class. Thus our previous assumption that the rich survived is confirmed here, which might be relevant to model building. - Sex: Most of the women survived, and the majority of the male died in the shipwreck. So it looks like the saying “Woman and children first” actually applied in this scenario. - Embarked: This doesn’t seem much relevant, maybe if someone was from “Cherbourg” had a higher chance of surviving. Step 4: Feature Engineering We saw that our ticket and cabin data don’t really make sense to us, and this might hinder the performance of our model, so we have to simplify some of this data with feature engineering. If we look at the actual cabin data, we see that there’s basically a letter and then a number. The letters might signify what type of cabin it is, where on the ship it is, which floor, which Class it is for, etc. And the numbers might signify the Cabin number. Let us first split them into individual cabins and see whether someone owned more than a single cabin. df_cat.Cabin training['cabin_multiple'] = training.Cabin.apply(lambda x: 0 if pd.isna(x) else len(x.split(' '))) training['cabin_multiple'].value_counts() It looks like the vast majority did not have individual cabins, and only a few people owned more than one cabins. Now let’s see whether the survival rates depend on this: pd.pivot_table(training, index = 'Survived', columns = 'cabin_multiple', values = 'Ticket' ,aggfunc ='count') Next, let us look at the actual letter of the cabin they were in. So you could expect that the cabins with the same letter are roughly in the same locations, or on the same floors, and logically if a cabin was near the lifeboats, they had a better chance of survival. Let us look into that: # n stands for null # in this case we will treat null values like it's own category training['cabin_adv'] = training.Cabin.apply(lambda x: str(x)[0]) #comparing survival rates by cabin print(training.cabin_adv.value_counts()) pd.pivot_table(training,index='Survived',columns='cabin_adv', values = 'Name', aggfunc='count') I did some future engineering on the ticket column and it did not yield many significant insights, which we don’t already know, so I’ll be skipping that part to keep the article concise. We will just divide the tickets into numeric and non-numeric for efficient usage: training['numeric_ticket'] = training.Ticket.apply(lambda x: 1 if x.isnumeric() else 0) training['ticket_letters'] = training.Ticket.apply(lambda x: ''.join(x.split(' ')[:-1]) .replace('.','').replace('/','') .lower() if len(x.split(' ')[:-1]) >0 else 0) Another interesting thing we can look at is the title of individual passengers. And whether it played any role in them getting a seat in the lifeboats. training.Name.head(50) training['name_title'] = training.Name.apply(lambda x: x.split(',')[1] .split('.')[0].strip()) training['name_title'].value_counts() As you can see, the ship was boarded by people of many different classes, this might be useful for us in our model. Step 5: Data preprocessing for model In this segment, we make our data, model-ready. The objectives we have to fulfill are listed below: - Drop the null values from the Embarked column - Include only relevant data - Categorically transform all of the data, using something called a transformer. - Impute data with the central tendencies for age and fare. - Normalize the fare column to have a more normal distribution. - using standard scaler scale data 0-1 Step 6: Model Deployment Here we will simply deploy the various models with default parameters and see which one yields the best result. The models can further be tuned for better performance but are not in the scope of this one article. The models we will run are: - Logistic regression - K Nearest Neighbour - Support Vector classifier First, we import the necessary models from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC 1) Logistic Regression lr = LogisticRegression(max_iter = 2000) cv = cross_val_score(lr,X_train_scaled,y_train,cv=5) print(cv) print(cv.mean()) 2) K Nearest Neighbour knn = KNeighborsClassifier() cv = cross_val_score(knn,X_train_scaled,y_train,cv=5) print(cv) print(cv.mean()) 3) Support Vector Classifier svc = SVC(probability = True) cv = cross_val_score(svc,X_train_scaled,y_train,cv=5) print(cv) print(cv.mean()) Therefore the accuracy of the models are: - Logistic regression: 82.2% - K Nearest Neighbour: 81.4% - SVC: 83.3% As you can see we get decent accuracy with all our models, but the best one is SVC. And voila, just like that you’ve completed your first data science project! Though there is so much more one can do to get better results, this is more than enough to help you get started and see how you think like a data scientist. I hope this walkthrough helped you, I had a great time doing the project myself and hope you enjoy it too. Cheers!! Leave a Reply Your email address will not be published. Required fields are marked *
https://www.analyticsvidhya.com/blog/2021/05/titanic-survivors-a-guide-for-your-first-data-science-project/
CC-MAIN-2022-21
refinedweb
1,532
55.64
NAME Read data from a fifo. SYNOPSIS #include <zircon/syscalls.h> zx_status_t zx_fifo_read(zx_handle_t handle, size_t elem_size, void* data, size_t data_size, size_t* actual_count); DESCRIPTION zx_fifo_read() attempts to read up to count elements from the fifo handle into data. Fewer elements may be read than requested if there are insufficient elements in the fifo to fulfill the entire request. The number of elements actually read is returned via actual_count. The element size specified by elem_size must match the element size that was passed into zx_fifo_create(). data must have a size of at least count * elem_size bytes. actual_count is allowed to be NULL. This is useful when reading a single element: if count is 1 and zx_fifo_read() returns ZX_OK, actual_count is guaranteed to be 1 and thus can be safely ignored. It is not legal to read zero elements. RIGHTS handle must be of type ZX_OBJ_TYPE_FIFO and have ZX_RIGHT_READ. RETURN VALUE zx_fifo_read() returns ZX_OK on success, and returns the number of elements read (at least one) via actual_count. ERRORS ZX_ERR_BAD_HANDLE handle is not a valid handle. ZX_ERR_WRONG_TYPE handle is not a fifo handle. ZX_ERR_INVALID_ARGS data is an invalid pointer or actual_count is an invalid pointer. ZX_ERR_OUT_OF_RANGE count is zero or elem_size is not equal to the element size of the fifo. ZX_ERR_ACCESS_DENIED handle does not have ZX_RIGHT_READ. ZX_ERR_PEER_CLOSED The other side of the fifo is closed. ZX_ERR_SHOULD_WAIT The fifo is empty.
https://fuchsia.dev/fuchsia-src/reference/syscalls/fifo_read
CC-MAIN-2021-04
refinedweb
229
50.94
-- .Basic where import Control.Arrow import Control.Monad hiding (filterM, mapM) -- | Swap tuple. swap :: (a,b) -> (b,a) swap (a,b) = (b,a) -- | Try to swap tuple. ifSwap :: Bool -> (a, a) -> (a, a) ifSwap b x = if b then swap x else x -- | Duplicate current value with tuple. dup :: a -> (a, a) dup a = (a,a) -- | Transform Int to Double i2d :: Integral a => a -> Double i2d v = fromIntegral v :: Double -- | Integer to Int. integerToInt :: Integer -> Int integerToInt t = fromInteger t :: Int -- | Flip >> (<<) :: Monad m => m b -> m a -> m b (<<) = flip (>>) -- | Like LiftM2, but make function at middle of two arguments. liftM2' :: Monad m => m a -> (a -> b -> c) -> m b -> m c liftM2' xs f = liftM2 f xs liftM2_ :: Monad m => (a -> b -> c) -> m a -> m b -> m () liftM2_ f x y = liftM2 f x y >> return () -- | If monad. ifM :: Monad m => m Bool -> m a -> m a -> m a ifM f g h = f >>= \b -> if b then g else h -- | If monad. ifF :: Monad m => a -> (a -> m Bool) -> (a -> m b) -> (a -> m b) -> m b ifF a f g h = f a >>= \b -> if b then g a else h a -- | When monad. whenM :: Monad m => m Bool -> m () -> m () whenM f g = f >>= \x -> when x g -- | Unless monad. unlessM :: Monad m => m Bool -> m () -> m () unlessM f g = f >>= \x -> unless x g -- | Zip' zip' :: a -> b -> (a, b) zip' a b = (a, b) -- | ZipM' zipM' :: Monad m => m a -> m b -> m (a, b) zipM' = liftM2 zip' -- | FirstMap. firstMap :: (b -> c) -> [(b, d)] -> [(c, d)] firstMap = map . first -- | Zip with map. zipMap :: (a -> b, a -> c) -> a -> (b, c) zipMap (g, h) s = (g s, h s) -- | Unzip with map. unzipMap :: (a -> (b,c)) -> (a -> b, a -> c) unzipMap h = (fst . h, snd . h) -- | Trace. trace :: ((a, c) -> (b, c)) -> a -> b trace f b = c where (c, d) = f (b, d) -- | Floor to multiple. floorToMultiple :: Integral a => a -> a -> a floorToMultiple x y = x - x `mod` y -- | Like a switch statement, and less cluttered than if else if -- -- > cond [ (t1,a1), (t2,a2), ... ] cond :: Monad m => [(Bool, m ())] -> m () cond [] = return () cond ((True,action) : _) = action cond ((False,_) : rest) = cond rest -- | Like a switch statement, and less cluttered than if else if -- -- > condM [ (t1,a1), (t2,a2), ... ] condM :: Monad m => [(m Bool, m ())] -> m () condM [] = return () condM ((test,action) : rest) = test >>= \t -> if t then action else condM rest
http://hackage.haskell.org/package/manatee-core-0.0.2/docs/src/Manatee-Toolkit-General-Basic.html
CC-MAIN-2016-50
refinedweb
410
85.22
Introduction Vite has a No bundle policy and provides a fast HMR during development. However, the default template with CLI itself is fairly simple, so when you start a Vite project, you'll have to build your own environment to use the other modules. In this article, I will use Vite to build an environment for Tailwind CSS as CSS framework. Please refer to here for more details. In the following, I will assume that there is a Vite project. Environment building First, install Tailwind CSS module and generate a configuration file. As you want to use scss and sass, install modules for them as well. yarn add -D tailwindcss sassyarn tailwindcss init Next, prepare a style file to inject the tailwind directive. @tailwind base;@tailwind components;@tailwind utilities; Also need a PostCSS configuration file in the project root. module.exports = {plugins: [require('tailwindcss'), require('autoprefixer')],} Finally, import the style file at the entry point. import { createApp } from 'vue'import App from '/@/App.vue'import '/@/assets/styles/main.scss'import '/@/assets/styles/tailwind.scss'createApp(App).mount('#app') Now you can use Utility Classes during development. Improving DX VSCode allows you to make tailwind's intellisense work. here to install it. Also, VSCode has unknownAtRules by default as it validates css. To fix it, set the settings.json as follows. {"scss.validate": false,"css.validate": false} If you are using Stylelint, the syntax of @tailwind and @apply, which are specific to tailwind may cause problems with Stylelint rules. Let's get rid of this. {"rules": {"at-rule-no-unknown": [true,{"ignoreAtRules": ["tailwind","apply","variants","responsive","screen",],},],}} PurgeCSS to optimize your build If you build tailwind as is, it will also bundle a huge number of Utility Classes that you don't use with it. Tailwind CSS supports PurgeCSS as standard, so you should configure it to optimize your build. // eslint-disable-next-line @typescript-eslint/no-var-requiresconst { join } = require('path')const BASE_DIR = join(__dirname, 'src')const VUE_FILE = join('**', '*.vue')const config = {future: {removeDeprecatedGapUtilities: true,purgeLayersByDefault: true,},purge: {// Learn more on: process.env.NODE_ENV === 'production',content: [join(BASE_DIR, VUE_FILE), join(__dirname, '*.html')],},theme: {extend: {},},variants: {},plugins:[],}module.exports = config The reason why CommonJS format is used instead of ES Module format, is because the Tailwind CSS plugin cannot recognize the ES Module format. The reason why it is .js format is also the same. Now the environment of Tailwind CSS has been created. Edit this page on GitHub
https://miyauchi.dev/posts/vite-vue3-tailwindcss/
CC-MAIN-2021-43
refinedweb
408
51.14
I'm having a little bit of trouble using the ifstream 'get' command. When I say trouble I mean it is not returning the values expected and I need a little guidance, if you will :). Basically what I'm doing is reading a file in through C++ and then going to a specific location and pulling out a few pieces of the file and printing them to the screen. The expected values maybe be numeric integers or alpha-characters. All data is human-readable at the end of the day. For those curious (or maybe with experience/sample code), this a NIDS file from the NWS. Here is my code: #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <sys/stat.h> using namespace std; int main() { char file[] = "wx_data/2008/8/25/p19r0/kict.dat"; struct stat results; char ch; if (stat(file, &results) == 0) { cout << "File Size: " << results.st_size << endl; } else { cout << "Error while stat'ing the file." << endl; } ifstream myFile (file, ifstream::in | ios::binary); myFile.seekg(50); for (int x = 0; x < 4; x++) { myFile.get(ch); cout << hex << (int)ch << ' '; } myFile.close(); return 0; } I'm using 'c++' to compile this on a 32-bit system running Fedora. I'm assuming that c++ is actually using gcc on the backend. My compiler line is c++ -o parser parser.cpp. When I put the file pointer to '12' and change it to pull 2 positions, which is the day of the file, I should expect '26' which prints out '32 36' which is 2 and 6 in hex. This works great. However when I change the file position to '50' which is the latitude of the radar I receive some crazy numbers. This covers four positions in the file and should be in the format of xxyy without decimal. When I execute this I receive '0 0 ffffff93 16'. When looking at the same locations with a hex viewer I see '00 00 93 16'. My question is why in the world am I see those 'ffffff' values in there tacked onto the 93? I see this happen multiple places throughout the file. Any help would be appreciated! I have attached a copy of the file. (rename to .dat) Thanks Kelly
https://www.daniweb.com/programming/software-development/threads/143167/strange-value-with-ifstream-get
CC-MAIN-2018-43
refinedweb
377
76.22
In Perl, to lowercase a textfile, I could do the following lowercase.perl #!/usr/bin/env perl use warnings; use strict; binmode(STDIN, ":utf8"); binmode(STDOUT, ":utf8"); while(<STDIN>) { print lc($_); } perl lowercase.perl < infile.txt > lowered.txt Python lowercase.py #!/usr/bin/env python import io import sys with io.open(sys.argv[1], 'r', 'utf8') as fin: with io.open(sys.argv[2], 'r', 'utf8') as fout: fout.write(fin.read().lower()) python lowercase.py infile.txt lowered.txt lowercase.perl lowercase.py lowercase.py python lowercase.py < infile.txt > lowered.txt There seem to be two interleaved issues here and I address that first. To make both Perl and Python use either invokation with a very similar behavior see the second part of the post. Short: They differ in how they do I/O but both work line-by-line, and Python code is easily changed to allow the same command-line invokation as Perl code. Also, both can be written so to allow input either from file or from standard input stream. (1) Both of your solutions are "streaming," in the sense that they both process input line-by-line. Perl code reads from STDIN while Python code gets data from a file, but they both get a line at a time. In that sense they are comparable in efficiency for large files. A standard way to both read and write files line-by-line in Python is with open('infile', 'r') as fin, open('outfile', 'w') as fout: fout.write(fin.read().lower()) See, for example, these SO posts on processing a very large file and read-and-write files. The way your read the file seems idiomatic for line-by-line processing, see for example SO posts on reading large-file line-by-line, on idiomatic line-by-line reading and another one on line-by-line reading. Change the first open here to your io.open to directly take the first argument from the command line as the file name, and add modes as needed. (2) The command line with both input and output redirection that you show is a shell feature ./program < input > output The program is fed lines through the standard input stream (file descriptor 0). They are provided from the file input by the shell via its < redirection. From gnu bash manual (see 3.6.1), where "word" stands for our "input" Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified. Any program can be written to do that, ie. act as a filter. For Python you can use import sys for line in sys.stdin: print line.lower() See for example a post on writing filters. Now you can invoke it as script.py < input in a shell. The code >. Then you get the same invokation as for the Perl script. I take it that the standard output redirection > is clear in both cases. Finally, you can bring both to a nearly identical behavior, and allowing either invokation, in this way. In Perl, there is the following idiom while (my $line = <>) { # process $line } The diamond operator <> either takes line by line from all files submitted on the command line (found in @ARGV), or it gets its lines from STDIN (if data is somehow piped into the script). From I/O Operators in perlop. In Python you get practically the same behavior by import fileinput for line in fileinput.input(): # process line This also goes through lines of files named in sys.argv, defaulting to sys.stdin if list is empty. From fileinput documentation. In both cases, if there are command-line arguments other than file names more need be done. With this you can use both Perl and Python scripts in either way lowercase < input > output lowercase input > output Or, for that matter, as cat input | lowercase > output. All methods here read input and write output line-by-line. This is further optimized (buffered) by the interpreter, the system, and shell's redirections. It is possible to change that so to read and/or write in smaller chunks but that would be extremely inefficient and noticeably slow down programs.
https://codedump.io/share/0TXzG4LLtg3e/1/lowercasing-script-in-python-vs-perl
CC-MAIN-2017-04
refinedweb
717
74.49
menu_hook(3X) menu_hook(3X) menu_hook - set hooks for automatic invocation by applications #include <menu.h> int set_item_init(MENU *menu, Menu_Hook func); Menu_Hook item_init(const MENU *menu); int set_item_term(MENU *menu, Menu_Hook func); Menu_Hook item_term(const MENU *menu); int set_menu_init(MENU *menu, Menu_Hook func); Menu_Hook menu_init(const MENU *menu); int set_menu_term(MENU *menu, Menu_Hook func); Menu_Hook menu_term(const MENU *menu); These functions make it possible to set hook functions to be called at various points in the automatic processing of input event codes by menu_driver. The function set_item_init sets a hook to be called at menu-post time and each time the selected item changes (after the change). item_init returns the current item init hook, if any (NULL if there is no such hook). The function set_item_term sets a hook to be called at menu-unpost time and each time the selected item changes (before the change). item_term returns the current item term hook, if any (NULL if there is no such hook). The function set_menu_init sets a hook to be called at menu-post time and just after the top row on the menu changes once it is posted. menu_init returns the current menu init hook, if any (NULL if there is no such hook). The function set_menu_term sets a hook to be called at menu-unpost time and just before the top row on the menu changes once it is posted. menu_term returns the current menu term hook, if any (NULL if there is no such hook). Routines that return pointers return NULL on error. Other routines return one of the following: menu_hook(3X)
http://man7.org/linux/man-pages/man3/menu_hook.3x.html
CC-MAIN-2017-22
refinedweb
265
75.74
This. Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: These classes are not available. This section identifies and describes the document conventions for a WMI class reference page. A typical reference page contains a syntax block, methods table, and a properties list. A simplified version of MOF code that includes the class name, parent class (if any), and class properties, in alphabetical order, with data types. If a class has methods, the methods are listed in the table immediately following the syntax block. Each implemented method is linked to a reference page. Each class property is listed with a data type, access type (read-only or read/write), qualifiers, and a description of the property. class Win32_xyz : CIM_xyz { uint16 abc ; string def ; }; Data type: uint16 Access type: Shows whether you have read/write or read-only access to this property. Qualifiers: If present, shows the qualifiers for the property. For example, KeyOverride. Describes the property and provides inheritance information for the property. For example, this property is inherited from CIM_xyz. There is a link to the parent class if Microsoft provides an implementation of that class. However, the CIM classes are not available. Data type: string Access type: Read-only Description of the property. Gives more information about the class, if applicable. Also provides derivation information, if applicable. Send comments about this topic to Microsoft Build date: 6/15/2009 You can access and manipulate WMI objects using PowerShell. PowerShell's GET-WMIObject provides access to WMI classes on local or remote computer. PowerShell's Get-WMIObject cmdlet enables you to specify the namespace and class name of the managed object you with to utilise as well as the machine to operate against. Once you have obtained the object, you can access its properties and methods - just like any other .NET object. To access WMI objects on a remote system, you need to specify credentials (you can use get-credential cmdlet to create a PSCredential object you can provide to Get-WMIObject). Some of the WMI Classes are decorated with simple PoweShell samples. See for a list of classes decorted.
http://msdn.microsoft.com/en-us/library/aa394554(VS.85).aspx
crawl-002
refinedweb
354
57.67
Tag Lib - Struts . JSP Syntax Examples in Struts : Description The taglib... use the custom tag in a JSP page. You can use more than one taglib directive...Struts Tag Lib Hi i am a beginner to struts. i dont have Struts Struts... web applications quickly and easily. Struts combines Java Servlets, Java Server... developers, and everyone between. Thanks. Hi friends, Struts is a-html</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> <...;gt;/tags/struts-bean</taglib-uri> <taglib struts struts how to make one jsp page with two actions..ie i need to provide two buttons in one jsp page with two different actions without redirecting to any other page Hi.. - Struts cookies, headers, and parameters are also provided. struts-html.tld: This taglib...Hi.. Hi, I am new in struts please help me what data write in this file ans necessary also... struts-tiles.tld,struts-beans.tld,struts Struts - Struts Struts Hello I like to make a registration form in struts inwhich... course then page is redirected to that course's subjects. Also all subject should be displayed on single dynamic page according to selected by student. pls send Struts Articles Struts and Hibernate is necessary. NetUI Page Flows: An Evolution... straightforward by building a simple Page Flow model on top of Struts. Using... the topics on the screen. Struts comes with a bean taglib, that provides - Struts used in a struts aplication. these are the conditions 1. when u entered into this page the NEXT BUTTON must disabled 2. if u enter any text struts validation ;%@ include file="../common/header.jsp"%> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> < Struts iteraor Struts iteraor Hi, I am making a program in Struts 1.3.8 in which i... in tabular form. These are my action class and jsp page with iterator...;%@taglib uri="" prefix="bean"%> < struts - Struts button it has to go to another page.. for that one i taken two form tags.. i Developing Simple Struts Tiles Application how to setup the Struts Tiles and create example page with it. What is Struts.... <taglib> <taglib-uri>/tags/struts-tiles</taglib-uri> <taglib-location>/WEB-INF/struts-tiles.tld< show, hide, disable components on a page with struts - Struts show, hide, disable components on a page with struts disabling a textbox in struts.. in HTML its like disable="true/false" how can we do it in struts Struts tag - Struts Struts tag I am new to struts, I have created a demo struts application in netbean, Can any body please tell me what are the steps to add new tags to any jsp page Redirection in struts - Struts sendredirect can we forward a page in struts Hi There are more ways to forward one page to another page in struts. For Details you can click here: Thanks struts internationalisation - Struts struts internationalisation hi friends i am doing struts iinternationalistaion in the site... the welcome page it always defaultly take the french plz give solution for my Struts Layout Examples - Struts Struts Layout Examples Hi, Iam trying to create tabbed pages using the struts layout tag. I see the tab names on the page but they cannot...:// Thanks. Amarde Page Refresh - Struts Page Refresh Hi How Can we control the page does not go to refersh after its forward again from action class.in my form i have one dropdownlist... in same page and fwd the action to same page struts- login problem - Struts struts- login problem Hi all, I am a java developer, I am facing problems with the login application. The application's login page contains fields like username, password and a login button. With this functionality only . requiredFieldValidatorError.jsp<%@ taglib prefix="s" uri="/struts...What is Struts 2 RequiredFieldValidator? Need an Example or Code What is Struts 2 RequiredFieldValidator? Need an Example or Code on Field Videos Struts Videos Watch the latest videos on YouTube.com   java struts error - Struts java struts error my jsp page is post the problem... loginaction page is package com.ssss.struts; import org.apache.struts.action.... on struts visit to : Thanks struts struts in industry, struts 1 and struts 2. which is the best? which is useful as a professuional Have a look at the following link: Struts Tutorials framework Struts framework How to populate the value in textbox of one JSP page from listbox of another JSP page using Struts-html tag and java script Struts Struts When Submit a Form and while submit is working ,press the Refresh , what will happen in Struts JSF Global Navigation Example <%@ taglib uri="" prefix="h" %> <%@ taglib uri="" prefix...;Navigation Page</title></head> <body> <h1> validations - Struts validations log in page with validations user name must be special character and one number and remining is alphabetes in struts struts struts i have no any idea about struts.please tell me briefly about struts?** Hi Friend, You can learn struts from the given link: Struts Tutorials Thanks logic iterate Struts logic iterate This is my jsp page in which i used 3 logic iterate <%@taglib uri="" prefix="bean"%> <%@taglib uri="" prefix="logic"%> file download in struts - Struts used validator in struts but it didn't worked... i used validate() in form bean... entered into the page n the list content are invisible... HOw can i validate DynaActionForm ;%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html...; In this tutorial you will learn how to create Struts program code for login page in struts by using eclipse program code for login page in struts by using eclipse I want program code for login page in struts by using eclipse Struts 2.2.1 Struts 2.2.1 released The latest version of Struts framework is released. The new version is Struts 2.2.1 and it includes many new features how to start struts? Hello Friend, Please visit the following links:... can easily learn the struts. Thanks STRUTS INTERNATIONALIZATION ;%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix=" with hibernate setter method for attribute: locale <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html locale Unable to understand Struts - Struts but I did'nt get successfull msg. it doesnat forwads on the success page... = "success"; /** * This is the action called from the Struts... = response.getWriter(); try{ out.println("Home Forward Action Example to a different jsp page : <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%> <%@ taglib uri="/WEB...; <html:linkStruts Forward Action</html struts technologies like servlets, jsp,and struts. i am doing one struts application where i... the following links: http java - Struts java how can i get dynavalidation in my applications using struts... : *)The form beans of DynaValidatorForm are created by Struts and you configure in the Struts config : *)The Form Bean can be used Alternative their state, handling events and input validation, defining page navigation... Struts Alternative Struts is very robust and widely used framework, but there exists the alternative to the struts framework Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/60564
CC-MAIN-2016-07
refinedweb
1,231
67.15
Apr 26, 2007 04:54 PM|lejdborg|LINK Hi! I've installed the MySQL .NET Connector and am reading the article found here. When I try to use the source code I get loads of errors, and when I checked more into it I've got a warning telling me that the class Mysql.Data.MysqlClient can't be found or that it doesn't contain any public members. Why do I get this error? Thanks in advance! Apr 27, 2007 02:02 PM|lejdborg|LINK May 01, 2007 01:51 PM|lejdborg|LINK Member 23 Points May 03, 2008 09:21 PM|Webmonkeymon|LINK how do you add this reference? ImportsMySql.Data.MySqlClient does not work? Member 23 Points Jun 19, 2008 01:53 PM|Webmonkeymon|LINK just right click on the project and browse to the web bin folder where you just copied the mysql.data.dll file. Not the mysql.web.dll file. the file is here if you have not copied it to the bin folder. C:\Program Files\MySQL\MySQL Connector Net 5.1.6\Binaries\.NET 2.0 None 0 Points Jan 15, 2009 06:38 PM|celticdeveloper|LINK In vb.net, after adding reference to the dll, the correction is -- <%@ Import Namespace="MySql.Data.MySqlClient" %> I was having this warning Warning 1 Namespace or type specified in the Imports 'mysql.data.SqlClient' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. because the the namespace is case-sensitve. Jim 7 replies Last post Jan 15, 2009 06:38 PM by celticdeveloper
http://forums.asp.net/t/1103800.aspx
CC-MAIN-2015-18
refinedweb
286
76.93
Extended file attributes are name-value pairs that can be associated with each node in a file system. Despite the fact that POSIX.1e draft which proposed them has been withdrawn, the extended file attributes are supported by many file systems. GNU tar can store extended file attributes along with the files. This feature is controlled by the following command line arguments: Enable extended attributes support. When used a globbing pattern. For example, the following command: will include in the archive `a.tar' all attributes, except those from the `user' namespace. Any number of these options can be given, thereby creating lists of include and exclude patterns. When both options are used, first `--xattrs-include' is applied to select the set of attribute names to keep, and then `--xattrs-exclude' is applied to the resulting set. In other words, only those attributes will be stored, whose names match one of the regexps in `--xattrs-include'.: File access control lists (ACL) are another actively used feature proposed by the POSIX.1e standard. Each ACL consists of a set of ACL entries, each of which describes the access permissions on the file for an individual user or a group of users as a combination of read, write and search/execute permissions. Whether or not to use ACLs is controlled by the following two options: Enable POSIX ACLs support. When used: Security-Enhanced Linux (SELinux for short) is a Linux kernel security module that provides a mechanism for supporting access control security policies, including so-called mandatory access controls (MAC). Support for SELinux attributes is controlled by the following command line options: Enable the SELinux context support. Disable SELinux context support. This document was generated by Sergey Poznyakoff on December, 17 2017 using texi2html 1.76.
https://www.gnu.org/software/tar/manual/html_node/Extended-File-Attributes.html
CC-MAIN-2018-22
refinedweb
293
55.54
Programming, Love at First Sight If you have more than a dozen web servers in a cluster with identical setting, and you need to update the virtual directory, it is much more convenient to write a simple program to update it. This example shows how to do it. In this case, this snippet will change the physical path of a virtual directory. This snippet works on IIS 6 and IIS 7. PowerShell may not be installed in Server 2003, to make this snippet more generic, this snippet is written in C#, otherwise, PowerShell script may be a better option. private const string MetabasePath = "IIS://Localhost/W3SVC/1/Root"; //Get the virtual directory of IIS. private static DirectoryEntry GetVirtualDirectory(DirectoryEntry IISDirectory, string vDirName) { string ClassName = IISDirectory.SchemaClassName.ToString(); if (!((ClassName.EndsWith("Server")) || (ClassName.EndsWith("VirtualDir")))) { throw new Exception(String.Format("Virtual Directory can be updated under site or virual directory node. Metabase:{0}, SchemaClassName={1}", MetabasePath, ClassName)); } //Iterate through the children, as Find() method is having an issue with IIS 6, if more than one thread is accessing IIS, an AccessViolationException is thrown. //The fix is applying the a hot fix. Either use Find(), or use this method below. //Since IIS may not have the hot fix installed, this sample iterates the children. foreach (DirectoryEntry VirtualDir in IISDirectory.Children) if (String.Compare(VirtualDir.Name, vDirName, StringComparison.OrdinalIgnoreCase) == 0) return VirtualDir; return null; } //Update the physical path of the site. private static void UpdatePhysicalPath(string virtualDirectoryName, string newPath) { using (DirectoryEntry Site = new DirectoryEntry(MetabasePath)) { DirectoryEntry StatsNet = GetVirtualDirectory(Site, virtualDirectoryName); if (StatsNet == null) throw new Exception(String.Format("Site not found. Metabase={0}, virtualDirectory={1}", MetabasePath, virtualDirectoryName)); StatsNet.Properties["Path"][0] = newPath; StatsNet.CommitChanges(); } } static void Main(string[] args) { UpdatePhysicalPath("MySite", @"d:\http\MyNewSite"); } This is a quite common problem, there is a list of strings, and you need to concatenate them with a delimiter, let says a comma. There are several different approaches to this problem. Before .Net era, I use for loop, and check if the loop counter is not pointing to the last element in the list. If it is not pointing to the last element, add the delimiter. This approach has one problem, if the number of elements are not known. The other way is by concatenating the list and the delimiter, and then truncate the last delimiter after assembling the whole list. After .Net becoming more popular, the framework utilizes iterator pattern. Using foreach is much more convenient way to iterate and also to concatenate a list. The solution I had before is much more problematic, as I do not know if I am reading at the last element. Currently, I have two favorite methods to concatenate a list of elements into a single string with delimiter in between. The first one is using LINQ. public string Concatenate(IEnumerable<string> list, string delimiter) { return list.Aggregate((First, Second) => First + delimiter + Second); } That method above, probably does not have the greatest performance, as it will create too many strings, especially if the list has a lot of elements. The second one is using extension method, this code has better performance. public static class ConcatExtension { public static string Concatenate<T>(this IEnumerable<T> list, string delimiter) { StringBuilder Builder = new StringBuilder(); using (IEnumerator<T> Reader = list.GetEnumerator()) { if (Reader.MoveNext()) Builder.Append(Reader.Current.ToString()); while (Reader.MoveNext()) Builder.Append(delimiter).Append(Reader.Current.ToString()); } return Builder.ToString(); } } Now let see, the second approach uses StringBuilder, thus reducing the memory pressure. The idea is not to add delimiter after processing the element, but to add the delimiter before every element, except the first one. If I have these array of values: List<string> ListOfValues = new List<string>() { "Orange", "Apple", "Watermelon", "Grape", "Peach", "Banana" }; Then these two calls will give you identical return. string s1 = Concatenate(ListOfValues, ", "); string s2 = ListOfValues.Concatenate(", "); The results will be: Orange, Apple, Watermelon, Grape, Peach, Banana. So far, these are the simplest solution to concatenate the elements inside a collection into a delimited string.. This is the scenario, system A is taking an xml from system B. System A will deserialize the xml into an object. Unfortunately, a dev in system B decides that System.Xml namespace is evil and construct the xml using StringBuilder. In one of the element, the dev call ToString() method of a boolean variable. The result? the xml contains ‘True’ or ‘False’. System A takes the input and it throws exceptions with error message “The string 'False' is not a valid Boolean value”, or “The string 'True' is not a valid Boolean value'”. W3C defines boolean data type as ‘true’, ‘false’, ‘0’, and ‘1’. So this behavior is expected. There is a way to workaround this, only under this scenario, you want to keep the type safety of your object, and you have the code. The steps are: [XmlRoot(ElementName = "data", Namespace = "")] [XmlInclude(typeof(MyClassXmlAdapter))] public class MyClass { [XmlIgnore] public bool BooleanField { get; set; } } [XmlRoot(ElementName = "data", Namespace = "")] public sealed class MyClassXmlAdapter : MyClass { [XmlElement(ElementName = "Test")] public string BooleanAsString { get { return XmlConvert.ToString(BooleanField); } set { bool ParsedValue; if (!Boolean.TryParse(value, out ParsedValue)) ParsedValue = XmlConvert.ToBoolean(value); BooleanField = ParsedValue; } } } In your serialization code, create the XmlSerializer using MyClassXmlAdapter as type, and the serializer will serialize and deserialize to MyClass with no problem. All of your code that works with MyClass won’t have to be changed. If you don’t have access to the code, or the class is sealed, it is much more difficult. The only way to do it is by using a helper class. In this sample below, MyClass is sealed and you have only the assembly. Then the solution is to create another class that have almost identical fields with MyClass, with the exception the boolean field. [XmlRoot(ElementName = "data", Namespace = "")] public sealed class MyClass { [XmlElement] public bool BooleanField { get; set; } } [XmlRoot(ElementName = "data", Namespace = "")] public sealed class MyClassXmlAdapter { private bool _BooleanField; [XmlElement(ElementName = "Test")] public string BooleanAsString { get { return XmlConvert.ToString(_BooleanField); } set { bool ParsedValue; if (!Boolean.TryParse(value, out ParsedValue)) ParsedValue = XmlConvert.ToBoolean(value); _BooleanField = ParsedValue; } } public void CopyTo(MyClass target) { target.BooleanField = this.BooleanField; } } After deserializing the xml with ‘True’ or ‘False’, call CopyTo(). These solutions are not ideal, but at least, these are better options rather than cleaning up the Xml. C# introduces a number of syntactic sugar, including Automatic Property link. A question was asked, why is this useful, what is the advantage of this approach compared to exposing the field as public field? The advantage of the automatic property is that while you have a much cleaner code, you still have encapsulation, you can restrict the setter, so only internal classes, or descendant classes can update the property. public class AutomaticPropertyClass { public string PublicProperty { get; set; } public int ReadOnlyProperty { get; private set; } public double InternalProperty { get; internal set; } public char ProtectedProperty { get; protected set; } } That code is much simpler than having to declare private field and then the property, and the developer still can define the accessibility. Yes, this is quite old, but since I was asked that question, might as well blog about it. :) One of the requirements in building setups was to allow the Operations team to execute the .msi file from the command line. GUI is not for expert! :) If you are familiar with Visual Studio setup, each of the UI element has a property, and you pass this property to your custom action, or use it as condition in your setup (whether to install the documentation, help, or whether to install to the gac or not, etc.). msiexec.exe allows you to pass some parameters to override those properties. Unfortunately the .msi file that Visual Studio generates always set the default values, default value being the values that the developers set during design time. After inspecting the .msi, there are some custom actions that will set the property value to the default. This custom actions are always executed, whether the users sets the property via command line parameter or not. That means, if the user pass some parameters to override the property, the setup will execute the custom action, reassign the property value to the original default value. So what needs to be done is to prevent the custom action from executing when the property is overridden by the user. This can be done quite easily with text box dialogs, checkbox dialogs are a little bit more difficult, I will cover it in other post. The property has blank value/null in the beginning, if the user overrides the property via command line parameter, this value will not be null. By giving custom actions a condition, to execute only if the property is blank, the value that the user gave via command line will not be overridden. You need to set the conditions in two different tables in your .msi file, InstallExecuteSequence and InstallUISequence. One to support GUI mode (interactive) and the other to support quiet/passive mode. This is the example on how to do it, repeat the steps for every property that you want to be able to override: After executing those steps, the UI will show HELLOWORLDSERVER in the text box. To set this condition automatically as part of your build process, we need to use a script to modify the setup. This can be done by setting the post build event for your project. Standard disclaimer applies, no warranty, use it at your own risk, always test the changes. Wow, this post is longer than what I thought it would be.... I spent some time planning on improvements that I wanted to do on one of our project. I reviewed the code that I notice a place where I think I could improve the performance by avoiding locking. So I wrote the code, and tested it, works great, the new non-locking algorithm works fine. Then when I replaced the old code with my new code and ran my test, to my surprise, it did not behave the way I want it to be. Still works, but the performance and the throughput was not any better. In some cases, it actually yield worse performance compared with the old code. Curious, I captured the performance counters by running my test app side by side, the one with old code, and the other one with new code. Look and behold, under extreme cases, the old code has zero Total # of Contentions. The new code, of course has zero Total # of Contentions, and at the same time, consumes more memory due to the lock free algorithm implementation that I chose. Basically, the lock free code tries to solve a problem that did not exist in the old code. Yes, it uses lock, but the old code runs really fast, and it is very tight, so there was no contention. Moral of the story, reviewing the code may reveal some issue, put it to test, and verify that the issue is really an issue, before planning any work on it. One good thing, I did not spend too much time on it. :) I downloaded and installed IE 8 RC 1 on my machine. It works really well, the performance improvement is significant. I would encourage you to give it a try,. Disclaimer, this is an Release Candidate, not RTM. There could be some issues, but overall, this is really good. Just a simple thought, when creating a multi-threaded applications, make the number of threads configurable. ThreadPool has this behavior that it will immediately set the minimum worker threads equal to the number of logical processors in your machine, and set the maximum to 250 per logical processor, well documented in msdn (.Net Framework 2.0 SP1). ThreadPool will create a new thread every half second, also documented in msdn. This behavior could lead to thread explosions, where there are too much threads fighting for limited resources (memory, lock, disk IO, processor, etc.). Your app may run slower if the thread creation is not managed wisely. It is also a good idea to be able to throttle the application to use fewer threads. It is a good idea to be able to limit the number of threads in the system through configuration. Set the max number of threads by calling SetMaxThreads, and if the config value is less than the number of logical processors, do not forget to call SetMinThreads. Be aware that this can also lead to other issue, like thread starvation. This is just an idea, if you have been writing multi-threaded applications using ThreadPool, probably you have thought about this already. Keep in mind, your application needs as few thread as possible, but not fewer. One. When you created a Windows Service, you usually add a Service Installer to allow this service to be installed using InstallUtil or installing it programmatically like this post shows you. The service installer will create the Event Log for the service, and by default it is "Application", and the source is the name of your service. The Event Source is most likely to be fine, but the event log may need to be set to something else. Unfortunately, the option is not visible from the installer. The Installer object for your windows service, actually hosted several other Installer objects, one of the child Installer is responsible to create the Event Log. You need to find this object and then changed the Log property and it will create the appropriate event log. It is easy to find this object as this object is an instance of EventLogInstaller. The code: public partial class MyServiceInstaller : Installer { private const stringLogName = "My Service Log"; public MyServiceInstaller() { InitializeComponent(); EventLogInstaller EventLogInstall = null; foreach (Installer I in this.serviceInstaller.Installers) { EventLogInstall = I as EventLogInstaller; if(EventLogInstall != null) { EventLogInstall.Log = LogName; EventLogInstall.UninstallAction = UninstallAction.NoAction; break; } } } } That code above shows how to create a custom Event Log for your service, the code also shows that the custom event log will never be uninstalled, depending on the requirements it can be easily changed. If the event source needs to be changed as well, simply change the Source property and you are set. One thing to pay attention, if you create a custom event log, you install the service programmatically, and your service is running with a restricted account, then you have to modify the code to install the service by adding a code to write one entry to the event log that you just created. After the service installer is executed, the log is 'registered', but not created yet. To create it, one event must be written. If the service runs using a restricted user account, that account may not have enough security permission to write the first log, as the log need to be created. When installing the service, the user must run the installer as Administrator, so the installer has all security privilege that it needs. So remember to write one event entry after programmatically installing the service. + "/w3svc").Children) if (String.Compare(Site.SchemaClassName, "IIsWebServer", StringComparison.OrdinalIgnoreCase) == 0) Console.WriteLine(Site.Properties["ServerComment"].Value.ToString() + " == " + Site.Properties["LogFileDirectory"].Value.ToString()); To get more information about what fields and method you can access, please refer to this MSDN doc:. Just remember, in Vista/Windows Server 2008, you will need to run that code with elevated privilege. PDC is almost over, did you know that you can access the recorded sessions online? Go to, and click on Agenda on the top. then click on Sessions tab. Pick the session that you want to watch, scroll down, you should see a Video tab. Much shorter shortcut, got to this link. Today is Friday, 10/30, most likely today video is not available at this moment, but should be available soon. Sometimes you may want to install a Windows Service programmatically, but the target machine does not have InstallUtil.exe. To install a Windows Service programmatically, you can build an application to install that Windows Service. public static void InstallService(string ExeFilename) { System.Configuration.Install.AssemblyInstaller Installer = new System.Configuration.Install.AssemblyInstaller(ExeFilename); Installer.UseNewContext = true; Installer.Install(null); Installer.Commit(null); } To uninstall: public static void UninstallService(string ExeFilename) { System.Configuration.Install.AssemblyInstaller Installer = new System.Configuration.Install.AssemblyInstaller(ExeFilename); Installer.UseNewContext = true; Installer.Uninstall(null); }
http://blogs.msdn.com/helloworld/
crawl-002
refinedweb
2,708
55.64
![if !(IE 9)]> <![endif]> Welcome to all fans of trashing someone else's code. :) Today in our laboratory, we have a new material for a research - the source code of the AWS SDK for .NET project. At the time, we wrote an article about checking AWS SDK for C++. Then there was not anything particularly interesting. Let's see what .NET of the AWS SDK version is worth. Once again, it is a great opportunity to demonstrate the abilities of the PVS-Studio analyzer and make the world a bit better. Amazon Web Services (AWS) SDK for .NET is a set of developer's tools, meant for creating applications based on .NET in the AWS infrastructure. This set enables to significantly simplify the process of code writing. SDK includes sets API .NET for various AWS services, such as Amazon S3, Amazon EC2, DynamoDB and others. SDK source code is available on GitHub. As I mentioned, at the time we have already written the article about checking AWS SDK for C++. The article turned out to be small - only a couple of errors found per 512 thousands of lines of code. This time we are dealing with a much larger size of the code, which includes about 34 thousand of cs-files, and the total number of lines of code (excluding blank ones) is impressive 5 million. A small part of code (200 thousand lines in 664-cs files) accrues to tests, I haven't considered them. If the quality of the .NET code of the SDK version is approximately the same as the one of C++ (two errors per 512 KLOC), then we should get about 10 times greater number of errors. Of course, this is a very inaccurate calculation methodology, which doesn't take into account the linguistic peculiarities and many other factors, but I don't think the reader now wants to go into boring reasoning. Instead, I suggest moving on to the results. The check was performed using PVS-Studio 6.27. It is just incredible, but still the fact is that in the AWS SDK for .NET the analyzer managed to detect 40 errors, which would be worth to talk about. It demonstrates not only a high quality of the SDK code (about 4 errors per 512 KLOC), but also comparable quality of the C# PVS-Studio analyzer in comparison with C++. A great result! Authors of AWS SDK for .NET, you're real champs! With each project, you demonstrate tremendous quality of the code. It can be a great example for other teams. However, of course, I would not be a developer of a static analyzer, if I didn't give my 2 cents. :) We are already working with a Lumberyard team from Amazon on the use of PVS-Studio. Since it is a very large company with a bunch of units around the world, it is very likely that the AWS SDK team for .NET has never heard of PVS-Studio. Anyway, I have not found any signs of using our analyzer in the SDK code, although it doesn't say anything. However, at least, the team uses the analyzer built into Visual Studio. It is great, but code reviews can always be enhanced :). As a result, I did manage to find a few bugs in the SDK code and, finally, it's time to share them. Error in logic PVS-Studio warning: V3008 [CWE-563] The 'this.linker.s3.region' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 116, 114. AWSSDK.DynamoDBv2.Net45 S3Link.cs 116 public string Region { get { .... } set { if (String.IsNullOrEmpty(value)) { this.linker.s3.region = "us-east-1"; } this.linker.s3.region = value; } } The analyzer warns about repeated value assignment to the same variable. From the code it becomes clear that this is due to the error that violates the logic of the program work: the value of the variable this.linker.s3.region will always be equal to the value of the variable value, regardless of the condition if (String.IsNullOrEmpty(value)). return statement was missed in the body of if block. The code needs to be fixed as follows: public string Region { get { .... } set { if (String.IsNullOrEmpty(value)) { this.linker.s3.region = "us-east-1"; return; } this.linker.s3.region = value; } } Infinite recursion PVS-Studio warning: V3110 [CWE-674] Possible infinite recursion inside 'OnFailure' property. AWSSDK.ElasticMapReduce.Net45 ResizeJobFlowStep.cs 171 OnFailure? onFailure = null; public OnFailure? OnFailure { get { return this.OnFailure; } // <= set { this.onFailure = value; } } A classic example of a typo, which leads to an infinite recursion in the get accessor of the OnFailure property. Instead of returning the value of a private field onFailure, the access to property OnFailure takes place. Correct variant: public OnFailure? OnFailure { get { return this.onFailure; } set { this.onFailure = value; } } You may ask: "How did it work?" So far - no how. The property is not used anywhere else, but this is temporary. At one point, someone will start using it and will certainly receive an unexpected result. To prevent such typos it is recommended not to use identifiers that differ only in case of the first letter. Another comment to this construction is using of the identifier, which completely matches the name of the OnFailure type. From the point of view of the compiler, it is quite acceptable, but this complicates the perception of code for a person. Another similar error: PVS-Studio warning: V3110 [CWE-674] Possible infinite recursion inside 'SSES3' property. AWSSDK.S3.Net45 InventoryEncryption.cs 37 private SSES3 sSES3; public SSES3 SSES3 { get { return this.SSES3; } set { this.SSES3 = value; } } The situation is identical to the described above. However, here infinite recursion will occur when accessing the property SSES3 both for reading and assigning. Correct variant: public SSES3 SSES3 { get { return this.sSES3; } set { this.sSES3 = value; } } Test on consideration Now I'd like to cite a task from a developer, taken with using Copy-Paste method. Take a look at the way code looks like in the Visual Studio editor, and try to find an error (click on image to enlarge). PVS-Studio warning: V3029 The conditional expressions of the 'if' statements situated alongside each other are identical. Check lines: 91, 95. AWSSDK.AppSync.Net45 CreateApiKeyResponseUnmarshaller.cs 91 I reduced the body of the method UnmarshallException, having removed everything that is not needed. Now you can see that identical checks follow each other: public override AmazonServiceException UnmarshallException(....) { .... if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException")) { return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException")) { return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } .... } It might seem that the bug is not rough - just an extra checking. Nevertheless, often such a pattern may indicate more serious problems in the code, when a needed check will not be performed. In the code, there are several similar errors. PVS-Studio warnings: What are you? PVS-Studio warning: V3062 An object 'attributeName' is used as an argument to its own method. Consider checking the first actual argument of the 'Contains' method. AWSSDK.MobileAnalytics.Net45 CustomEvent.cs 261 /// <summary> /// Dictionary that stores attribute for this event only. /// </summary> private Dictionary<string,string> _attributes = new Dictionary<string,string>(); /// <summary> /// Gets the attribute. /// </summary> /// <param name="attributeName">Attribute name.</param> /// <returns>The attribute. Return null of attribute doesn't /// exist.</returns> public string GetAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } string ret = null; lock(_lock) { if(attributeName.Contains(attributeName)) // <= ret = _attributes[attributeName]; } return ret; } The analyzer has detected an error in the GetAttribute method: a string is checked whether it contains itself. From the description of the method it follows that if the attribute name (attributeName key) is found (in the dictionary _attributes), the attribute value should be returned, otherwise - null. In fact, as the condition attributeName.Contains(attributeName) is always true, an attempt is made to return the value by a key which might not be found in a dictionary. Then, instead of returning null, an exception KeyNotFoundException will be thrown. Let's try to fix this code. To understand better how to do this, you should look at another method: /// <summary> /// Determines whether this instance has attribute the specified /// attributeName. /// </summary> /// <param name="attributeName">Attribute name.</param> /// <returns>Return true if the event has the attribute, else /// false.</returns> public bool HasAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } bool ret = false; lock(_lock) { ret = _attributes.ContainsKey(attributeName); } return ret; } This method checks whether the attribute name (attributeName key) exists in the dictionary _attributes. Let's get back to the GetAttribute method again and fix the error: public string GetAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } string ret = null; lock(_lock) { if(_attributes.ContainsKey(attributeName)) ret = _attributes[attributeName]; } return ret; } Now the method does exactly what is stated in the description. One more small comment to this fragment of code. I noticed that the authors use lock when working with the _attributes dictionary. It is clear that this is necessary when having a multithreaded access, but the lock construction is rather slow and cumbersome. Instead of a Dictionary, in this case, perhaps, it would be more convenient to use thread-safe version of the dictionary - ConcurrentDictionary. This way, there will be no need in lock. Although, maybe I don't know about the specifics of the project. Suspicious behavior PVS-Studio warning: V3063 [CWE-571] A part of conditional expression is always true if it is evaluated: string.IsNullOrEmpty(inferredIndexName). AWSSDK.DynamoDBv2.PCL ContextInternal.cs 802 private static string GetQueryIndexName(....) { .... string inferredIndexName = null; if (string.IsNullOrEmpty(specifiedIndexName) && indexNames.Count == 1) { inferredIndexName = indexNames[0]; } else if (indexNames.Contains(specifiedIndexName, StringComparer.Ordinal)) { inferredIndexName = specifiedIndexName; } else if (string.IsNullOrEmpty(inferredIndexName) && // <= indexNames.Count > 0) throw new InvalidOperationException("Local Secondary Index range key conditions are used but no index could be inferred from model. Specified index name = " + specifiedIndexName); .... } The analyzer was concerned about the check string.IsNullOrEmpty(inferredIndexName). Indeed, the string inferredIndexName is assigned null, then the value of this variable isn't changed anywhere, then for some reason it is checked for null or an empty string. Looks suspicious. Let's take a close look at the above code fragment. I deliberately did not reduce it to understand better the situation. So, in the first if statement (and also in the next one) the variable specifiedIndexName is somehow checked. Depending on the results of the checks, the variable inferredIndexName is getting a new value. Now let's look at the third if statement. The body of this statement (throwing of the exception) will be performed in case if indexNames.Count > 0, as the first part of the whole condition, which is string.IsNullOrEmpty(inferredIndexName) is always true. Perhaps, variables specifiedIndexName and inferredIndexName are mixed up or the third check has to be without else, representing a standalone if statement: if (string.IsNullOrEmpty(specifiedIndexName) && indexNames.Count == 1) { inferredIndexName = indexNames[0]; } else if (indexNames.Contains(specifiedIndexName, StringComparer.Ordinal)) { inferredIndexName = specifiedIndexName; } if (string.IsNullOrEmpty(inferredIndexName) && indexNames.Count > 0) throw new InvalidOperationException(....); In this case, it is difficult to give a definite answer on options to fix this code. Anyway, the author needs to check it out. NullReferenceException PVS-Studio warning: V3095 [CWE-476] The 'conditionValues' object was used before it was verified against null. Check lines: 228, 238. AWSSDK.Core.Net45 JsonPolicyWriter.cs 228 private static void writeConditions(....) { .... foreach (....) { IList<string> conditionValues = keyEntry.Value; if (conditionValues.Count == 0) // <= continue; .... if (conditionValues != null && conditionValues.Count != 0) { .... } .... } } It's a classic. The variable conditionValues is used without a preliminary check for null. While later in the code this check is performed. The code needs to be corrected as follows: private static void writeConditions(....) { .... foreach (....) { IList<string> conditionValues = keyEntry.Value; if (conditionValues != null && conditionValues.Count == 0) continue; .... if (conditionValues != null && conditionValues.Count != 0) { .... } .... } } I found several similar errors in code. PVS-Studio warnings: The following warning is very similar in meaning, but the case is opposite to the one discussed above. PVS-Studio warning: V3125 [CWE-476] The 'state' object was used after it was verified against null. Check lines: 139, 127. AWSSDK.Core.Net45 RefreshingAWSCredentials.cs 139 private void UpdateToGeneratedCredentials( CredentialsRefreshState state) { string errorMessage; if (ShouldUpdate) { .... if (state == null) errorMessage = "Unable to generate temporary credentials"; else .... throw new AmazonClientException(errorMessage); } state.Expiration -= PreemptExpiryTime; // <= .... } One of the code fragments includes checking the value of the state variable for null. In the code below, the variable is used to unsubscribe from the PreemptExpiryTime event, however, a check for null is no longer performed and throwing of the exception NullReferenceException becomes possible. A more secure version of the code: private void UpdateToGeneratedCredentials( CredentialsRefreshState state) { string errorMessage; if (ShouldUpdate) { .... if (state == null) errorMessage = "Unable to generate temporary credentials"; else .... throw new AmazonClientException(errorMessage); } if (state != null) state.Expiration -= PreemptExpiryTime; .... } In the code, there are other similar errors: PVS-Studio warnings: Non-alternate reality PVS-Studio warning: V3009 [CWE-393] It's odd that this method always returns one and the same value of 'true'. AWSSDK.Core.Net45 Lexer.cs 651 private static bool State19 (....) { while (....) { switch (....) { case '"': .... return true; case '\\': .... return true; default: .... continue; } } return true; } The method always returns true. Let's see how critical it is for the calling code. I checked out the cases of using the State19 method. It is involved in filling the array of handlers fsm_handler_table equally with other similar methods (there are 28 of them with the names, respectively, starting from State1 to State28). Here it is important to note that, in addition to State19, for some other handlers the warnings V3009 [CWE-393] were issued as well. These are handlers: State23, State26, State27, State28. The warnings, issued by the analyzer for them: Here is the way the declaration and the array initialization of handlers look like: private static StateHandler[] fsm_handler_table; .... private static void PopulateFsmTables () { fsm_handler_table = new StateHandler[28] { State1, State2, .... State19, .... State23, .... State26, State27, State28 }; To complete the picture, let's see code of one of the handlers to which the analyzer haven't had any claims, for example, State2: private static bool State2 (....) { .... if (....) { return true; } switch (....) { .... default: return false; } } Here's the way how the call of handlers occurs: public bool NextToken () { .... while (true) { handler = fsm_handler_table[state - 1]; if (! handler (fsm_context)) // <= throw new JsonException (input_char); .... } .... } As we can see, an exception will be thrown in case of returning false. In our case, for the handlers State19, State23, State26 State27 and State28 this will never happen. Looks suspicious. On the other hand, five handlers have similar behavior (will always return true), so maybe it was so contrived and is not the result of a typo. Why am I going so deep in all this? This situation is very significant in the sense that the static analyzer often can only indicate a suspicious construction. And even a person (not a machine), who does not have sufficient knowledge about the project, is still not able to give a full answer on the presence of the error, even having spent time learning code. A developer should review this code. Meaningless checks PVS-Studio warning: V3022 [CWE-571] Expression 'doLog' is always true. AWSSDK.Core.Net45 StoredProfileAWSCredentials.cs 235 private static bool ValidCredentialsExistInSharedFile(....) { .... var doLog = false; try { if (....) { return true; } else { doLog = true; } } catch (InvalidDataException) { doLog = true; } if (doLog) // <= { .... } .... } Pay attention to the doLog variable. After initialization with the false value, this variable will get the true value in all cases further along the code. Therefore, the check if (doLog) is always true. Perhaps, earlier in the method there was a branch, in which the doLog variable wasn't assigned any value. At the moment of checking it could contain the false value, received when initializing. But now there is no such a branch. Another similar error: PVS-Studio warning: V3022 Expression '!result' is always false. AWSSDK.CognitoSync.PCL SQLiteLocalStorage.cs 353 public void PutValue(....) { .... bool result = PutValueHelper(....); if (!result) <= { _logger.DebugFormat("{0}", @"Cognito Sync - SQLiteStorage - Put Value Failed"); } else { UpdateLastModifiedTimestamp(....); } .... } The analyzer claims that the value of the result variable is always true. It is possible only in case if the method PutValueHelper will always return true. Take a look at this method: private bool PutValueHelper(....) { .... if (....)) { return true; } if (record == null) { .... return true; } else { .... return true; } } Indeed, the method will return true under all conditions. Moreover, the analyzer has issued a warning for this method. PVS-Studio warning: V3009 [CWE-393] It's odd that this method always returns one and the same value of 'true'. SQLiteLocalStorage.cs 1016 I deliberately did not cite this warning earlier when I was inquiring into other bugs V3009 and saved it up for this case. Thus, the tool was right to point out the error V3022 in the calling code. Copy-Paste. Again PVS-Studio warning: V3001 There are identical sub-expressions 'this.token == JsonToken.String' to the left and to the right of the '||' operator. AWSSDK.Core.Net45 JsonReader.cs 343 public bool Read() { .... if ( (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd || this.token == JsonToken.String || // <= this.token == JsonToken.Boolean || this.token == JsonToken.Double || this.token == JsonToken.Int || this.token == JsonToken.UInt || this.token == JsonToken.Long || this.token == JsonToken.ULong || this.token == JsonToken.Null || this.token == JsonToken.String // <= )) { .... } .... } The field this.token is compared twice with the value JsonToken.String of the enumeration JsonToken. Probably, one of the comparisons should contain another enumeration value. If so, a serious mistake has been made here. Refactoring + inattention? PVS-Studio warning: V3025 [CWE-685] Incorrect format. A different number of format items is expected while calling 'Format' function. Arguments not used: AWSConfigs.AWSRegionKey. AWSSDK.Core.Net45 AWSRegion.cs 116 public InstanceProfileAWSRegion() { .... if (region == null) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "EC2 instance metadata was not available or did not contain region information.", AWSConfigs.AWSRegionKey)); } .... } Perhaps, the format string for the string.Format method previously contained the format item {0}, for which the argument AWSConfigs.AWSRegionKey was set. Then the string was changed, the format item was gone, but a developer forgot to remove the argument. The given code example works without errors (the exception was thrown in the opposite case - the format item without the argument), but it looks not nice. The code should be corrected as follows: if (region == null) { throw new InvalidOperationException( "EC2 instance metadata was not available or did not contain region information."); } Unsafe PVS-Studio warning: V3083 [CWE-367] Unsafe invocation of event 'mOnSyncSuccess', NullReferenceException is possible. Consider assigning event to a local variable before invoking it. AWSSDK.CognitoSync.PCL Dataset.cs 827 protected void FireSyncSuccessEvent(List<Record> records) { if (mOnSyncSuccess != null) { mOnSyncSuccess(this, new SyncSuccessEventArgs(records)); } } A common situation of an unsafe call of the event handler. A user is able to unsubscribe between the checking of the variable mOnSyncSuccess for null and calling of a handler, so its value will become null. The likelihood of such a scenario is small, but it is still better to make code more secure: protected void FireSyncSuccessEvent(List<Record> records) { mOnSyncSuccess?.Invoke(this, new SyncSuccessEventArgs(records)); } In the code, there are other similar errors: PVS-Studio warnings: Crude class PVS-Studio warning: V3126 Type 'JsonData' implementing IEquatable<T> interface does not override 'GetHashCode' method. AWSSDK.Core.Net45 JsonData.cs 26 public class JsonData : IJsonWrapper, IEquatable<JsonData> { .... } The JsonData class contains quite a lot of code, so I didn't give it in whole, citing just its declaration. This class really does not contain the overridden method GetHashCode, which is unsafe, as it can lead to erroneous behavior when using the JsonData type for working, for example, with collections. Probably, there is no problem at the moment, but in future this type of strategy might change. This error is described in the documentation in more detail. Conclusion These are all interesting bugs that I was able to detect in the code of AWS SDK for .NET using the PVS-Studio static analyzer. I'd like to highlight once again the quality of the project. I found a very small number of errors for 5 million lines of code. Although probably more thorough analysis of issued warnings would let me add a few more errors to this list. Nevertheless, it is also quite likely that I added on some of the warnings to errors for nothing. Unambiguous conclusions in this case are always made only by a developer who is in the context of the checked code.: ...
https://www.viva64.com/en/b/0605/
CC-MAIN-2020-05
refinedweb
3,407
50.84
Hi all, We have a client who required a website with a related document function. This means that each document in a collection contains keywords, and when the document is displayed, it also shows a list of other documents that contain one or more of the same keywords. There are a lot of documents in this collection, and although they are stored in an XML database, I didn't really feel like querying them in real-time. I really wanted something lean and mean. So in XP fashion, I picked the simplest datatype to express relations, java.util.Map, and went from there. The keys in the map are the keywords from the document collection, the values it returns are URLs pointing to the documents that contain this keyword. So I ended up with two components: - MapManager - initializes one or more maps from a ( cocoon ) xml-source, which is constructed according to a specific DTD. The datatype stored in the map can currently be one of String, Set or SortedSet ( in case results are sorted by relevance ). - MapTransformer - looks for <key> elements in a specific namespace, and transforms the value(s) returned by the map into the <key> element. The names are a little confusing because the use of 'map' in cocoon usually refers to the sitemap, but a change is just a simple refactoring away. If anyone is interested in this functionality I'd be happy to donate it. If you think this is not the right way, or there are other ways to do this in Cocoon, let me know. --- [RT] I tried to make this mapping very generic. It could be keyword > related document, keyword > explanation, document > related document, or url > metadata. A first extension would be keys with wildcards or RE's although that would force me to loose the map model. Googleing xml and relations quickly brought me another subject that I haven't seen discussed much here - XML topic maps. On of the big advantages of topic maps over my simple mapping is the amount of semantics that topic maps allow. Topic maps allow one thing to be related to another, and also describe what the one thing is, what the other thing is, and what kind of relation they have. So the next step would be to implement a topic map transformer. There is a apache-license topic map project at. I'm definitely going to look into it myself, but need to do some reading first, and I would like to discuss it. By the way, if you don't like topic maps, I would like to know too - I wasn't able to find any criticism on the matter (googleing 'why topic maps are bad' or 'topic maps suck' didn't help) With kind regards / Met vriendelijke groeten, Rogier Peters --------------------------------------------------------- Content Management Department Hippo Webworks Rogier(at)hippo(dot)nl /
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200310.mbox/%3C84F0A43A4248CE45B5C0E20F4C40779C05F3BE@naomi.webworks.nl%3E
CC-MAIN-2016-26
refinedweb
479
68.1
Thank! Is the pi resetting when it loses connection? Power supplies have been an issue in the past for similar problems. If not we can troubleshoot some network settings. Have a run through this post as well The Pi itself is not having connection issues. It is being recognized and read. The Arduino Uno that is using the Pi for Cayenne access is the one having trouble communicating via serial-USB port. I took it home this weekend to trouble shoot and found that when on my home wifi network there is no issue. Can you recommend what I should look into? On a side note, after about 20 minutes of good, fluid readings while connected at home, the widgets for my Arduino froze. It was still being recognized by Cayenne, but was no longer updating the values assigned to the sensors. Hello newbie here who is trying to install a dht22 to monitor humidity … I was wondering with this method would I be able to view both the raspberry pi and arduino on the same caynee dash board ? Also is the dht sensor visable in the iOS app ? Sorry to bother Total newbie at it again , here is the error i am getting while trying to add the sketch to my arduino Here are the error messages i have adeed the cayenne libary per instructions is there anything else and updated with my token. Arduino: 1.8.3 (Windows 10), Board: “Arduino/Genuino Uno” C:\Users\le93060\Documents\Arduino\sketch_aug16a\sketch_aug16a.ino:1:27: fatal error: CayenneSerial.n: No such file or directory #include <CayenneSerial.n> ^ compilation terminated. exit status 1 Error compiling for board Arduino/Genuino Uno. This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences. Hello mate, In the first line you have #include <CayenneSerial.n> and it should be #include <CayenneSerial.h> Regards Yes, it is possible. You can add as much devices as you want on the same dashboard. First ensure that they are connected to the Cayenne and sensors are sending data as you expect. Then you can create a new project and drag and drop devices and sensors that you want to display. This is indeed a cool function! See the picture bellow, for creating a new project: @joaoduarte_89 @ognqn.chikov Thank you Very much it took the sketch when I copied exactly what @akers.kenneth66 posted and changed my key. I installed the cayenne library, but how and where do I place the code for this? Also, how do I run the command on the PI for cayenne-ser.sh" , do I use sudo apt git ? I am very new to this and have only been able to Succfussly add a relay and one wire temp sensor. My goal is to get my relays and ds18b20 working as well as my DHT22 all on one cayenne dash board exactly like @ognqn.chikov . I purchased my Arduino to help with this project since i did not want to use the mattq feature. I am sorry for so many questions. You can read this comment, and follow the same procedure: I am working of that post but do not understand how to run the script . I have included a snap shot of my directory for you and also the error I am getting while trying to run the script … I am positive i am doing something wrong and help is greatly appreciated Looks like you don’t have the script to run it. You can download it from here Thank you Adam , would I use git clone and then the URL ? Yes, that will work. Or you can right click it and save link as if you want to do it from a browser. Thank you adam i am trying to do this with putty . Buti got the following error Hello, Try to manually copy it. I was also trying with github but with no success. I used a VNC and make a copy/paste via the graphic user interface. Try this command: wget
http://community.mydevices.com/t/arduino-and-raspberry-together/1010/41
CC-MAIN-2017-43
refinedweb
678
73.98
Fracturing Search Author: Benjamin Qi A simple solution to "Robotic Cow Herd" that generalizes. Prerequisites - Gold - Minimum Spanning Trees - some familiarity with "Robotic Cow Herd" analysis General OutlineGeneral Outline ProblemProblem Suppose that you have a rooted tree where each vertex has a value . Also, if is not the root then has a parent satisfying . Given that each vertex has at most children, find the smallest values in the tree. ApproachesApproaches Approach 1: Use a priority queue initially containing only the root. At each step, extract the vertex with smallest value from the priority queue and insert all of its children into the queue. Since we insert vertices in the priority queue, this runs in time. You can think of this as Dijkstra on a tree. Approach 2: Suppose that we know that the -th smallest value is an integer in the range . Then for any we can check whether there are less than values in the tree less than or equal to in time with a simple DFS that breaks once you find values. This approach runs in time. We'll focus on the first approach. GeneralizingGeneralizing Suppose that you want to find the objects with the smallest values in some (potentially very large) search space. - First, we need to impose a tree structure satisfying the properties mentioned above. Say that lies in the subtree of if lies above (or is equal to) in the tree. - Let the "root" be the object of smallest value. Every object must lie in the subtree of the root. - The children of the root should partition the entire search space (aside from the root) into a bounded number of disjoint subspaces. - Of course, each child should also have the smallest value in its subtree. Essentially, we start with the entire search space and then we fracture it into subspaces based on the children of the root. Then we can finish with either of the two approaches. -th Smallest Spanning Tree (USACO Camp 2018) Let's look at an example. ProblemProblem Given a graph with vertices and at most edges, find the -th () smallest spanning tree. SolutionSolution For this problem, the objects are spanning trees. The root is the minimum spanning tree (which can be calculated with Kruskal's algorithm), and contains all objects in its subtree. The idea is to designate a small number of children of the root, each of which should be formed by modifying the root slightly. If we can somehow ensure that each object has at most "children" then we only need to consider spanning trees in order to find the -th smallest. The first step is to consider the easier problem of finding the second MST. To do this, we can choose to exclude one edge of the MST and then find the smallest possible replacement for it. Let the edges in the MST be labeled . Then one idea is to let the -th child subspace of the root to consist of all spanning trees not including edge of the minimum spanning tree for each . Unfortunately, this doesn't work because the child subspaces overlap. We can instead let the -th child subspace contain all spanning trees that - include the first edges of the MST - do not include the -th edge of the MST for each . Every spanning tree other than the root is contained within exactly one of these child subspaces, which is what we want. After sorting the edges in increasing order of weight once, we can compute the MST within each child subspace in time with DSU. Overall, the runtime is for storing the information about each spanning tree and for maintaing the priority queue of objects so that we can extract the minimum. Note that with the second approach mentioned in the first section the running time would instead be , which may be too slow. My Solution Robotic Cow HerdRobotic Cow Herd Focus Problem – try your best to solve this problem before continuing! As with the analysis, for each location you should - sort the controllers of that location by cost - add the controller of minimum cost for each location to the cost of the cheapest robot - subtract that minimum cost from every controller at that location (so now the minimum cost controller for each location is just zero) Importantly, we should then sort the locations by their respective second-minimum controller costs. Approach 1Approach 1 Binary search on the cost of the -th robot. If we can compute the costs of all robots with cost at most or say that there are more than in time, then we can solve this problem in time (similar to "Approach 2" above). This is the approach that the first analysis solution takes, although it includes an extra factor due to upper_bound. I have removed this in my solution below. #include <bits/stdc++.h>using namespace std;typedef long long ll;typedef vector<int> vi;typedef pair<ll,ll> pl;#define f first#define s second Approach 2Approach 2 There's also an time solution with a priority queue that constructs the robots in increasing order of cost. As before, we want each robot to have a bounded number of "child" robots. However, if you look at my DFS function above, it seems that every robot can have up to children! Nevertheless, the DFS takes rather than time due to the break statement, which works since we sorted by second-cheapest robot. In fact, we can modify the DFS function so that every robot has at most three rather than children. void dfs(int pos, ll cur, int id) {if (cur > mx || num == K) return;res += cur; num ++;if (id+1 < v[pos].size())dfs(pos,cur+v[pos][id+1]-v[pos][id],id+1);if (pos+1 < v.size()) {if (id == 1) dfs(pos+1,cur-v[pos][1]+v[pos+1][1],1);if (id) dfs(pos+1,cur+v[pos+1][1],1);}} Now I'll describe what how the priority queue solution works: First start with the robot of minimum cost. The robot with second-minimum cost can be formed by just choosing the second-minimum controller for the first location. After this, we have a few options: - We can choose the third-minimum controller for the first location. - We can discard the second-minimum controller for the first location and select the second-minimum controller for the second location (and never again change the controller selected for the first location). - We can keep the second-minimum controller for the first location and select the second-minimum controller for the second location (and never again change the controller selected for the first location). None of these options can result in a robot of lower cost. In general, suppose that we have a robot and are currently selecting the -th cheapest controller for the -th location. Then the transitions are as follows: - Select the -th cheapest controller for the -th location instead. - If , select the -st cheapest controller for the -th location instead and also select the -nd cheapest controller for the -st. - Keep the -th cheapest controller for the -th location and also select the -nd cheapest controller for the -st. Since there exists exactly one way to get from the cheapest robot to every possible robot, we can use a priority queue. #include <bits/stdc++.h>using namespace std;typedef long long ll;typedef pair<int,int> pi;typedef vector<int> vi;typedef pair<ll,pi> T;#define f first#define s second Other ProblemsOther Problems Module Progress: Join the USACO Forum! Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!
https://usaco.guide/adv/fracturing-search?lang=cpp
CC-MAIN-2022-40
refinedweb
1,280
60.95
Extending logging functionality If you have already adopted some method for logging events, you may want to use that method to log experiment-related events, such as exposures and experiment-specific outcomes. You can do this by extending the Experiment abstract class and overriding the log method. Overriding the log method To log exposures using your existing logging system, just override the log method when extending the Experiment abstract class. For example, if you write to your logs with MySQLLogger, then you might reimplement log as follows. def log(self, data): # self.MySQLLogger may be defined here or in configure_logger() self.MySQLLogger.log(data) Writing a log configuration method Since all code in log() gets called every time a log event is triggered, you may wish to set up a connection to your logging infrastructure in advance, immediately before the first time you need to log the data. To do this, you can override the configure_logger() method. In SimpleExperiment configure_logger() actually sets a class variable, once per experiment name, so that a connection to the logging module is only made once per interpreter session. Adding caching By default, each instance of an Experiment class will log auto-exposure once per instance. But this can still result in a lot of writing when there are many instances created for a particular unit’s assignment (for example, if an experiment parameter is retrieved each time a person loads the home page). So you may want to add some caching (e.g., with memcache) to prevent unnecessary logging. This can be done by overriding the previously_logged() method. More information Additional documentation for the Experiment class and SimpleExperiment class can be found in the source code.
http://facebook.github.io/planout/docs/extending-logging.html
CC-MAIN-2019-13
refinedweb
282
53.1
tag:blogger.com,1999:blog-3945433340473224396.post657468637144522126..comments2017-02-16T05:41:21.257-08:00Comments on Make It Easy: Date filtering and formatting in Angular js.Prashobh PSnoreply@blogger.comBlogger14125tag:blogger.com,1999:blog-3945433340473224396.post-89075233980832312742016-01-24T22:40:33.751-08:002016-01-24T22:40:33.751-08:00For timezone you may need to use some jquery plugi...For timezone you may need to use some jquery plugin ,something like moment js .Prashobh PS it help you Glad it help you Prashobh PS, I used your blog to fix one of my issue.Friend, I used your blog to fix one of my issue.nishi want to display time as 19-November-2015 01:05 P...i want to display time as 19-November-2015 01:05 PM IST<br /> how to display the timezone as "IST"Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-3945433340473224396.post-87173996809044850112015-09-02T01:28:46.978-07:002015-09-02T01:28:46.978-07:00I found a free online javascript formatter, I used...I found a <a href="" rel="nofollow">free online javascript formatter</a>, I used it for a long time.buyi wen, its very useful. but i want to customize a dat...hi, its very useful. but i want to customize a date .<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-3945433340473224396.post-78476046311450114932015-05-30T00:30:22.276-07:002015-05-30T00:30:22.276-07:00Thanks Thanks Prashobh PS Another example: angular.module('filt...Thanks<br /><br />Another example:<br /><br />angular.module('filters',[])<br /> .filter('dateParse', function($filter) {<br /> return function(input,format,timezone) {<br /> return (!!input) ? $filter('date')( Date.parse(input), format, timezone) : '';<br /> };<br /> });<br /><br /><br />{{ publication['Product']['created'] | dateParse:'dd/MM/yyyy - hh:mm a'}}<br /><br /><br />publication['Product']['created'] = 2015-01-19 14:12:15romel javier gomez herrera you very muchThank you very muchAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-3945433340473224396.post-44517532764342884392014-11-05T21:41:38.041-08:002014-11-05T21:41:38.041-08:00It might help to others might help to others<br /> anyone tried this with Kendo UI grid? I have a...Has anyone tried this with Kendo UI grid? I have a column with the dates and time being passed down from the database. Is it possible to make this work?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-3945433340473224396.post-44429649553308573392014-07-17T16:19:48.365-07:002014-07-17T16:19:48.365-07:00I am not sure if my last comment got held for mode...I am not sure if my last comment got held for moderation or if something happened to it. So here it goes again. I am interested in your Show local time zone example but I am not able to get it to work and it is not on the fiddle that you shared. Any possibility of getting you to add that to the fiddle example?Rob Allred, Very useful. Thanks. But, What if I want to cu...Hi, Very useful. Thanks.<br />But, What if I want to customize a date, which is in the following string format, "2014-05-26 17:22:35". Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-3945433340473224396.post-85623344622151857942014-05-01T23:53:51.935-07:002014-05-01T23:53:51.935-07:00Its very usefulIts very usefulAnonymousnoreply@blogger.com
http://www.angulartutorial.net/feeds/657468637144522126/comments/default
CC-MAIN-2017-09
refinedweb
554
52.15
Hi, Just an update on where we are with the PostCodeValidator and PostCodeFormatter classes. The some outstanding questions at the end of this email you can skip to. Compared to the existing components these components. 1. Supports a wide range of postcode formats both numeric and alpha numeric 2. Provide convenience functions to obtain formats for common locales 3. Provides a mechanism for user defined validation 4. Supports fullwidth characters (as it uses flash.globization classes for string comparisons) 5. Easier to extend (although less need to do so as they are more flexible) Code has been: 1. Reviewed by a couple of people on the list and code has been updated based on those reviews. There are some architectural changes that could be made but they they would probably have to be made to all Validators. It easier to keep the style in line with the other validators for now (IMO). 2. Generates nice ASdocs. 3. Working examples has been provided. 4. Code is unit tested including fullwidth characters (although could do with some alpha fullwidth character tests) 5. Code is better quality than existing ZipCode validator components (IMO). Like all code there is room for improvement and anyone can submit patches etc to do this. Still outstanding: 1. Any other feedback on code is welcome. 2. The generated ASdocs need a review. 3. Add some simple examples to the generated AS docs. 4. Alpha fullwidth character tests. Anyone want to help out here? 5. Format code via flex formatter (or the like) to ensure it follows Adobe style. Anything missing from this list? Or anything that people would like to see? Next steps/Questions: 1. Decide on if this component should be added to the SDK. How do we go about this? Would it require a vote or should I just check it in once all the above is done? As we are still waiting on donation of code from Adobe it would be checked into the patches branch not the trunk if and when if it is checked in. 2. If so what name space? While they are more in the style of mx validator they do use flash.globilisation classes like spark validation classes (although not in exactly the same way) and work fine with spark components (see example) or do we go for the new apache.flex.validators namespace? I'm leaning toward mx.validators which is reflected in the current code. 3. Where should unit tests live in the current SDK framework structure? 4. Should the old Zip validator/formatter be marked as "deprecated'? Anyone have any views or opinions on the above? Thanks, Justin
http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201203.mbox/%3C1B7E8DB1-A113-48B2-AEC8-66B67CF7E043@classsoftware.com%3E
CC-MAIN-2015-18
refinedweb
441
68.67
I am facing this problem while trying to code a Sudoku solver (with some parts referencing to) Here's the code I have made so far with reference to the above URL. puzzle = '003198070890370600007004893030087009079000380508039040726940508905800000380756900' cell = '123456789' cell_break = ['123','456','789'] def generate_keys(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] #print generate_keys(cell,cell) def dict_puzzle(puzzle,cell): 'Making a dictionary to store the key and values of the puzzle' trans_puzzle = {} key_list = generate_keys(cell,cell) i=0 for x in puzzle: trans_puzzle[str(key_list[i])] = x i = i + 1 return trans_puzzle dict_puzzle(puzzle,cell)['11'] = 'die' print dict_puzzle(puzzle,cell)['11'] You're calling the function again, so it returns a new dictionary. You need to assign the result of the first call to a variable and mutate that. result = dict_puzzle(puzzle,cell) result['11'] = 'die' print(result)
https://codedump.io/share/8EK9c7rEFBLb/1/unable-to-update-dictionary
CC-MAIN-2016-50
refinedweb
153
54.15
In our last blog, we had a discussion about the latest version of Spark i.e 2.4 and the new features that it has come up with. While trying to come up with various approaches to improve our performance, we got the chance to explore one of the major contenders in the race, Apache Flink. Apache Flink is an open source platform which is a streaming data flow engine that provides communication, fault-tolerance, and data-distribution for distributed computations over data streams.. It is a scalable data analytics framework that is fully compatible with Hadoop. Flink can execute both stream processing and batch processing easily. In this blog, we will try to get some idea about Apache Flink and how it is different when we compare it to Apache Spark. If you guys want to know more about Apache Spark, you can go through some of our blogs about Spark RDDs and Spark Streaming. Apache Spark vs Apache Flink /> Apache Spark and Apache Flink are both open- sourced, distributed processing framework which was built to reduce the latencies of Hadoop Mapreduce in fast data processing. Both Spark and Flink support in-memory processing that gives them distinct advantage of speed over other frameworks. By the time Flink came along, Apache Spark was already the de facto framework for fast, in-memory big data analytic requirements for a number of organizations around the world. This made Flink appear superfluous. But keep in mind that Apache Flink is closing this gap by the minute. More and more projects are choosing Apache Flink as it becomes a more mature project. /> When to choose Apache Spark : - When it comes to real-time processing of incoming data, Flink does not stand up against Spark, though it has the capability to carry out real-time processing tasks. - If you don’t need bleeding edge stream processing features and want to stay on the safe side, it may be better to stick with Apache Spark. It is a more mature project it has a bigger user base, more training materials, and more third-party libraries. - In case you want to move over to a somewhat “more reliable” technology, one would choose Spark as it has a much active and wider community which is constantly increasing. When to choose Apache Flink : - When it comes to speed, Flink gets the upper hand as it can be programmed to process only the data that has changed, which is where it comes out on top of Spark. The main reason for this is its stream processing feature, which manages to process rows upon rows of data in real time – which is not possible in Apache Spark’s batch processing method. This makes Flink faster than Spark. - If you need to do complex stream processing, then using Apache Flink would be highly recommended. - Moreover, if you like to experiment with the latest technology, you definitely need to give Apache Flink a shot. Features of Apache Flink /> - Stream processing Flink is a true streaming engine, can process live streams in the sub-second interval. - Easy and understandable Programmable APIs Flink’s APIs are developed in a way to cover all the common operations, so programmers can use it efficiently. - Low latency and High Performance Apache Flink provides high performance and Low latency without any heavy configuration. Its pipelined architecture provides the high throughput rate. It processes the data at lightning fast speed, it is also called as 4G of Big Data. - Fault Tolerance The fault tolerance feature provided by Apache Flink is based on Chandy-Lamport distributed snapshots, this mechanism provides strong consistency guarantees. Also, the failure of hardware, node, software or a process doesn’t affect the cluster. Ease of use The Flink APIs make it easier to use than programming for MapReduce and it is easier to test as compared to Hadoop. - Memory Management The memory management in Apache Flink provides control on how much memory we use in certain runtime operations. Thus we can say that Flink works in managed memory and never get out of memory exception. - Iterative processing Apache Flink also provides the dedicated support for iterative algorithms (machine learning, graph processing) - Scalable Flink is highly scalable. With increasing requirements, we can scale Flink cluster. Easy Integration We can easily integrate Apache Flink with other open source data processing ecosystem. It can be integrated with Hadoop, streams data from Kafka, It can be run on YARN. - Exactly-once Semantics Another important feature of Apache Flink is that it can maintain custom state during computation. - Rich set of operators Flink has lots of pre-defined operators to process the data. All the common operations can be done using these operators Simple WordCount Program in Scala /> The example project contains a WordCount implementation, the “Hello World” of Big Data processing systems. The goal of WordCountis to determine the frequencies of words in a text. Initially, we will require to add the dependency for Flink streaming in Scala in build.sbt : libraryDependencies += "org.apache.flink" %% "flink-streaming-scala" % "1.7.0" Note: in our example, we will be using the latest version of the dependency i.e. 1.7.0 Second thing import the required classes into your code : import org.apache.flink.api.java.utils.ParameterTool import org.apache.flink.streaming.api.scala._ Here, the ParameterTool is only used as it provides the utility methods for reading and parsing program arguments from different sources. Once we have made all the imports, we require 2 major things - Input Parameter val params = ParameterTool.fromArgs(args) - Execution environment val env = StreamExecutionEnvironment.getExecutionEnvironment Once you have the environment and the params, we need to make these parameters available, we need to add the following: env.getConfig.setGlobalJobParameters(params) Now time to get the input data for streaming, we can either give an input file or we can have a predefined input data. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Once we have the input data, we will now apply the various operations on the input in order to obtain the word count for each word. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Now that we have got the counts for each word, we can have the output as an output file or as console output. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters To finally execute the program simply call the execute method along with the jobName env.execute(jobName = "WordCount01") /> Now to test this simple program, simply run the sbt run command from your terminal and you are ready to go. I hope now you guys have some idea about Apache Flink and how is it different from Apache Spark. We have also tried to cover up a simple wordcount code using Flink. We have also added the code for this demo as well as the sample data (WordCountData.WORDS) for your reference here. For more details, you can refer to the official documentation for Apache Flink. Hope this helps. Stay tuned for more 🙂 1 thought on “Is Apache Flink the future of Real-time Streaming?6 min read”
https://blog.knoldus.com/apache-flink-the-future-of-real-time-streaming/
CC-MAIN-2022-27
refinedweb
1,265
62.27
Log message: . Log message: Update to version 2.1.2 Log message: Drop superfluous PKG_DESTDIR_SUPPORT, "user-destdir" is default these days. Mark packages that don't or might probably not have staged installation. Log message: Update to 1.9.4 Now the package buils fine Log message: Update maintainer email address to valid address. Log message: Update 1.9.2 -> 1.9.3 Changes: 1.9.3 (11/08/2010) + Added feature #43, now task supports relative dates like '3wks', '1 month', '4d' for 'due', 'wait' and 'until' dates. Essentially durations are now allowed where dates are expected, and are treated as relative to the current date/time. + Added feature #189, that records the start and stop times as an annotation for a task. + Added features #244, #272, #273, #274, #275 and #279, which support import and export of YAML 1.1. YAML is now the default export format for task. + Added feature #391, now the 'task color legend' command will show samples of all the defined colors and color rules from your .taskrc and theme. + Added feature #410, and now task supports dependencies between tasks with the syntax 'task 1 depends:2' to add a dependency, or 'task 1 depends:-2' to remove a dependency. + Added feature #421, and now task can sync data files from two sources via the 'merge' command. + Added feature #423, now custom report filters allow rc overrides. + Added feature #428, preparing the new structure for the NEWS file. + Added feature #429, which improves the 'all' report to exclude deleted. tasks, provide a new sort order and include the 'end' column. + Added feature #431, which improves feedback after running the 'log' command. + Added feature #446, task supports now 'sow', 'som' and 'soy' as dates for 'due', 'wait' and 'until' (thanks to T. Charles Yun). Added as well synonyms soww/eoww plus new socw/eocw for calendar weeks. + Fixed bug #467, where recurring tasks were not honoring wait values. + Added feature #471, which makes greater use of projects by reporting changes to the completion percentage when it changes. + Added feature #478, which uses the colorization rules in the 'info' + Added feature #481, allowing for user control of the color rule order of precedence via the 'rule.precedence.color' configuration variable. + Fixed bug #493, which made waiting, recurring tasks invisible (thanks to Alexander Schremmer). + Added feature #499, giving an extra line in the message output when doing bulk done changes (thanks to T. Charles Yun). + New 'depends' column for custom reports. + New 'blocked' report for showing blocked tasks. + New 'unblocked' report for showing tasks that are not blocked. + Improved man pages (thanks to Andy Lester). + Default .taskrc files are now largely empty, and rely almost completed on default values. + Special tags 'nocal', 'nocolor' and 'nonag' are implemented. + The 'tags' command highlights special tags. + The 'stats' and 'info' reports not obey color.alternate. + New fish shell tab completion script (thanks to Mick Koch). + Color rules now obey the rc.search.case.sensitive configuration option. + The color.keyword.XXX color rule now applies to annotations too. + Importing the same YAML twice now generates an error. + Two new color themes (thanks to Kathryn Andersen). + More localized holiday files for US, CA, SE, DE, FR, UK, ES, NL and NO (thanks to T. Charles Yun, Jostein Berntsen). + Added new 'diagnostics' command to help with bug submission, testing. + Fixed bug #427, preventing the task edit command to parse annotation dates with spaces. + Fixed bug #433, making task command output more consistent. + Fixed bug #434, allowing users to complete tasks with status 'waiting' + Fixed bug #438, correcting the sorting of the entry_time, start_time and end_time columns (thanks to Michelle Crane). + Fixed bug #439, which ignored dateformat.annotation for sparse annotations. + Fixed bug #440, which prevented simultaneous append/prepend and substitution. + Fixed bug #441, which misparsed '/a/a:/' as an attribute, rather than a substitution (thanks to Michelle Crane). + Fixed bug #444, which made task shell unusable after canceling out of an undo command. + Fixed bug #445, which caused task to not notice that the command 'h' is ambiguous. + Fixed bug #449, so the wait: attribute can be applied to a task at any time, not just on add. + Fixed bug #452, which defines a higher resolution division between due and overdue. + Fixed bug #459, which showed a confusing message when 'limit:page' was used, with few tasks. + Fixed bug #461, in which the filter 'due:today' failed, but 'due.is:today' worked. + Fixed bug #466, which gave the wrong error message when a custom report was missing a direction indicator for the sort order. + Fixed bug #470, which caused task to not support the color 'none'. + Fixed bug #476, so that task now issues a warning when a wait date falls after a due date (thanks to T. Charles Yun). + Fixed bug #480, which didn't properly support @ characters in tags. This also now supports $ and #. + Fixed bug #489, which caused the filter 'tags.none:' to fail. + Fixed bug #494, causing imported text files to ultimately lack uuids (thanks to Elizabeth Maxson). + Fixed problem with command line configuration overrides that had no values. + Fixed problem with the 'undo' command not observing the rc.color or the rc._forcecolor settings. + Fixed problem with extra blank line in the ghistory reports. + Fixed a precision problem with average age on the summary report. + Clarified the documentation regarding the project name (taskwarrior) and the program name (task). Log message: Update task 1.9.1 -> 1.9.2. Changes: - Added feature #320, so the command "task 123" is interpreted as an implicit "task info 123" command (thanks to John Florian). - Added feature #326, allowing tasks to be added in the completed state, by using the 'log' command in place of 'add' (thanks to Cory Donnelly). - Added features #36 and #37, providing annual versions of the 'history' and 'ghistory' command as 'history.annual' and 'ghistory.annual'. - Added feature #363 supporting iCalendar/vcalendar (RFC-2445, RFC-5545, RFC-5546) export via the 'export.ical' command. - Added feature #390, an extra dateformat for annotations (thanks to Cory Donnelly). - Added feature #407, a new 'task show' command to display the current configuration settings or just the ones matching a search string. 'task config' is now only used to set new configuration values. - Added feature #298, supporting a configurable number of future recurring tasks that are generated. - Added feature #412, which allows the 'projects' and 'tags' commands to be list all used projects/tags, not just the ones used in current pending tasks. Controlled by the 'list.all.projects' and 'list.all.tags' configuration variables (thanks to Dirk Deimeke). - Added feature #415, which supports displaying just a single page of tasks, by specifying either 'limit:page' to a command, or 'report.xxx.limit:page' in a report specification (thanks to T. Charles Yun). - Improvements to the man pages (thanks to T. Charles Yun). - Modified the 'next' report to only display one page, by default. - Added feature #408, making it possible to delete annotations with the new denotate command and the provided description (thanks to Dirk Deimeke). - Added support for more varied durations when specifying recurring tasks, such as '3 mths' or '24 hrs'. - The ghistory graph bars can now be colored with 'color.history.add', 'color.history.done' and 'color.history.delete' configuration variables. - Added feature #156, so that task supports both a 'side' and 'diff' style of undo. -. - Fixed bug #411, clarifying that the 'projects' command only lists projects for which there are pending tasks (thanks to Dirk Deimeke). - Fixed bug #414, that caused filtering on the presence or absence of tags containing Unicode characters to fail (thanks to Michal JosÃfko).* Fixed bug #416, which caused sorting on a date to fail if the year was not included in the dateformat (thanks to Michelle Crane). - Fixed bug #417, which caused sorting on countdown and age fields to be wrong (thanks to Michell Crane). - Fixed bug #418, which caused the attribute modifier 'due.before' to fail if the year was not included in the dateformat (thanks to Michelle Crane).* Fixed bug #132, which failed to set a sort order so that active tasks sort higher than inactive tasks, all things being equal. - Fixed bug #405, which incorrectly compared dates on tasks created by versions earlier than 1.9.1 to those created by 1.9.1 or later (thanks to Ivo Jimenez). - Fixed bug #420, missing 'ID' from help text (thanks to Ed Neville). - Fixed bug that prevented 'task list priority.above:L' from working. - Fixed bug that miscalculated terminal width for the ghistory.annual - Fixed wording (support issue #383) when modifying a recurring task (thanks to T. Charles Yun). Log message: Update to version 1.9.1 Changes since 1.9.0: - Summary report bar colors can now be specified with color.summary.bar and col or.summary.background configuration variables. - The 'edit' command now conveniently fills in the current date for new annotations. - Deleting a task no longer clobbers any recorded end date (thanks to Seneca Cunningham). - The following holidays are now computed automatically and can be used in the definitions for the calendar holidays: Good Friday (goodfriday), Easter (easter), Easter monday (eastermonday), Ascension (ascension), Pentecost (pentecost). The date is configured with the given keyword. - The configure script is more portable (thanks to Emil Sköldberg). - Updated task-faq.5 man page. - Fixed bug #382 in which the annotate command didn't return an error message when called without an ID. - Fixed bug #402 which failed compilation on Arch Linux (thanks to Johannes Schlatow). - Fixed bug #401 that ignored the search.case.sensitive configuration setting when filtering on project names (thanks to John Florian). - Fixed bug #395 that prevented the upgrade of a pending task to a recurring task (thanks to T. Charles Yun).
https://pkgsrc.se/wip/task
CC-MAIN-2021-25
refinedweb
1,622
67.76
I guess I'm in the minority here. I tend to use custom classes because I can tweak the API to make it easier for people writing to the API. I'll duck type all over the place to make things act like what someone might expect, but I don't like forcing people to create raw data structures when there are semantics that can make things easier. In this case at hand, I was going to say that making a doc a hash makes adding fields sequentially difficult. But ruby's nice enough that it simply makes it a little ugly: doc[:contents].to_a.push data I like being able to write doc[:contents] = data where I know there's no other data for that field but I like being able to write doc << { :content => data } A doc can certainly act like a hash in some cases, but it's more than a hash. One of the first tests I wrote (a long time ago, with less ruby under my belt) for the jruby interface for adding docs was: def test_add_lists @index << [ :contents, "the quick brown fox jumped over the lazy dog" ] \ << [ :contents, "Alas poor Yorick,", \ :contents, "I knew him Horatio" ] \ << [ :contents, [ "To be,", "or not ", "to be" ] ] end Was never too happy with the middle case. Maybe an extra list level? This doesn't use an explicit doc object but it makes one internally. That nice little cool (pronounced "scary") ability in ruby to say class Array def to_lucene_doc ... end end class Hash def to_lucene_doc ... end end module Lucene class Document def to_lucene_doc self end end class Index def << *docs docs.map! { |doc| doc.to_lucene_doc } ... end end I haven't had as much time as I would like, either, to follow solrb (and I guess I'm also in the minority thinking that solrb was a clever name). -----Original Message----- From: Erik Hatcher [mailto:erik@ehatchersolutions.com] Sent: Friday, February 16, 2007 5:43 PM To: ruby-dev@lucene.apache.org Subject: Fwd: NO_NORMS and TOKENIZED? A recent e-mail from Mr. KinoSearch to java-user has a quote that I wanted to point out here: Begin forwarded message: > KS 0.20 doesn't even have Document or Field classes. :) They've > been eliminated, and native Perl hashes are now used to transport > document data. I think we could simplify (wow, even at this early stage) the solrb code a bit by simply representing a document as a Hash. For multiValued data, the values would be arrays. Do we really need any other semantics at the solrb level, or does a Hash convey it all? Just thinking out loud here, so feel free to ignore me. Marvin makes some other great points about fixed schemas, which maps to the schema.xml facility of Solr I believe. I am interested in exploring how field names get mapped, along with client knowledge of Solr's schema.xml structure, can make an elegant API. Erik p.s. I've queued up several ruby-dev e-mails to respond to over the next several days. I'm happily swamped and eager to keep the momentum of solrb and Flare going strong.
http://mail-archives.apache.org/mod_mbox/lucene-ruby-dev/200702.mbox/%3C392521EA2692A2418DF48C331E61E32506ABB4@professorville.windows.esseff.org%3E
CC-MAIN-2019-35
refinedweb
529
71.75
28 June 2012 08:53 [Source: ICIS news] By Jasmine Khoo ?xml:namespace> SINGAPORE The producer quoted falling domestic feedstock propylene costs and weak downstream demand as reasons for the decrease in prices, market participants said. Shandong Haili Chemical declined to comment. The decline in Chinese domestic ECH prices has caught the regional sellers outside of The majority of these producers and traders were unwilling to drop their offers and want to sell the material at $1,850/tonne CFR (cost & freight) China Main Port (CMP) and above, mainly due to feedstock propylene cost pressure. Propylene prices in northeast Asia were largely stable at $1,230-1,270/tonne CFR northeast (NE) Most of these ECH sellers have turned their attention away from the ‘It is very hard to sell into Transactions for cargoes going into The deals were done at $1,800/tonne CFR China for June-loading cargoes of 100, 300 and 400 tonnes, according to the regional producer. ‘[The price of] $1,800/tonne CFR China price is too low,’ said another northeast Asia-based producer, adding that this price level will compromise its profit margins and sales targets. Other producers voiced similar sentiments and maintained their offers at above $1,850/tonne CFR China. Meanwhile, ECH import data from China Customs showed that 10 out of 16 ECH importers in April stopped importing ECH in May. These 10 companies imported approximately 2,160 tonnes of ECH in April, the data showed. In addition, the companies that continued to import ECH in May reduced their import volumes, according to the data. With the Chinese domestic ECH price downtrend showing no signs of rebound, the Chinese import market activity is likely to remain subdued for the time being,
http://www.icis.com/Articles/2012/06/28/9573360/chinas-ech-import-outlook-uncertain-amid-wide-buy-sell-gap.html
CC-MAIN-2015-14
refinedweb
290
54.76
Twitter is the world biggest repository of short messages from people with nothing to say – and now you too can contribute to that epic project with an automated Twitter bot, powered by your Raspberry Pi. I’m kidding, of course – some people actually tweet interesting things. I’m not one of them though – I use my mine for shameless product promotion in exchange for free stuff, competition entries, and auto-posting new episodes of our very own Technophilia Podcast. Whatever – my followers love me! @w0lfiesmith I hate your Twitter account. So much. — Justin Pot (@jhpot) August 21, 2013 Now. Image credit: adafruit/flickr 49 Comments - joel I Reaaly don’t Understand that .. Can u please do it with video . ? Patrick Yes, could you video yourself writing the code on paper? ROFL! Cool stuff with the Raspberry. i wish I could really find a use for one. R Sail is this like an automated spamming machine.. RasPi Can you show how to get successful response after sending tweets and not exceeding 140 characters limit? Thank you. John you can limit the text of your status just like this: twitter.update_status(status=twitter_status[:140]) Jim Easterbrook To limit the tweet to 140 characters is very easy. Change api.update_status(status=sys.argv[1]) to api.update_status(status=sys.argv[1][:140]) James Nachaski I realize that I might be labeled as a “hater” but really this is not that interesting. You can do the same thing with any computer… I don’t know why adding “raspberry pi” to the end of stuff makes it cool now. There are too many projects involving the Pi doing stuff that is just normal computer use that try to sound fresh and cool. Such as: “Display stock prices on your television using Raspberry Pi” – Not a real problem or a cool project. Use cnbc or, you know the Internet and an rss feed plus reader. “Read your email on your Raspberry Pi” – Wow, it’s a computer with an email client! How innovative! “Send tweets using the Twitter API and rPI” – Essentially this article. Interesting uses: Media center – The Pi media center is pretty darn cool. Network attached home security and surveillance. Raspberry pi connected to a PIR array via usb2serial to an arduino. If motion is detected, a signal is sent down the serial cable and the PI sends a text to my phone as well as emailing me 8 images from 4 cameras I have. Total cost – $73. Let’s MakeUseOf technology to do something interesting. Using the twitter api can be done from any computer and OS’s are multitasking so you can have background processes. No need for a Pi when you can run the same job in the background from any Linux box. Anyhow, this is just my opinion. Rob Thanks for sharing this. I think posting stuff this is really useful. I am just an amateur t this, so I appreciate any instructions that you can provide. The Pi is a fun device to tinker with. The projects take a while, even the simple ones. Lots of time spent checking and double checking the commands…worth it. Keep posting your ideas! Kris De Rocker Dear, I have my first Raspberry PI here and i have some questions about this script (for tweeting the temperature). Can you also give other temperatures such as motherboard temps? Or amount of RAM (and how much free), the amount of disk space (and how much free), CPU load etc? Best regards, Kris Kris De Rocker PS : i just tried to have my CPU temp twittered, and i get this error (my script is named iamrpi.py) root@raspberrypi:/home/test/Tweeter# python iamrpi.py File “iamrpi.py”, line 3 import sys ^ What did i do wrong? Best regards, Kris Atif Sheikh Raspberry Pi tweets would be visible to all? mean can it be customized to send msgz only to me ? Luke What happened to the link? It’s got a line through it.. Ajit I like this! But does it not need some form of connectivity on the Pi(ex wifi) else how would it authenticate to twitter. many thanks julian Great tutorial very easy to follow had it up and tweatin in 5mins thanks . ajit Many thanks! this worked perfectly and is a great motivator for students. For the CPU temp – we got an error ‘incompatible VCHIQ library’ but needed a reboot and was fixed Going to try webcam tomorrow. But great instructions. thanks! ajit All worked perfectly including the webcam. Thanks. You have a way to post to facebook also? Many thanks. Keep up the good work rgds ajit ajit jaokar @James – thanks! will try and see how far we get. keep up your good work :) Dan Great post, is it possible to read my tweets on the Pi too? paul f James, this is a e what you are doing to Meyer th buildings sounds really good – kids and headmaster both excited! I got a little lost around what to do with pygame. Where does the code go ie import pygame …? In nano? I really want to get this going to excite my kids at home. Cheers David Saul Have tried setting it up the other way around – ie so the rpi can receive Tweets in to a Python app ? James B Yep. Use this API call: Francois Wonderfull tutorial! However it worked 3 times and now I have this error message that I abbreviate ” Twitter API returned a 403 (forbidden), User is over daily status update limit.” I read a bit the API documentation and it seems that Twitter changed the permission rules and that one need now the read, write and direct message but I am not sure. anyway I change to read, write and direct message but error message is still here and it does not tweet anymore. Any coding modifications? best Francois, Bordeaux, France anonymous very nice, thank you, my raspi is tweeting… :) xsatria thanks bro, greetings from Indonesia :) Adrian Good Tuturial. Everything worked fine. First stuff done with my RPI. Thanks Aik is it possible to make bot to retweet some other people tweets every 10 minutes (maybe random time every 10 – 15 minutes) and doing this by searching phrase I am interested in… For example every 10-15 min retweeting something about #raspberrypi… ? Geo Seems like authentication is always failing. Am I missing something? c3ntry How do I register the Application now? Why is ” from this link” deactivated? gpem Great tutorial worked first time, just wandering how do I add a #tag to the to the tweet Many thanks for all your hard work Paul Great tutorial and the example works great. There are some small changes made to the Twitter dev page which can be a little confusing. How would I go about using non-ANSI characters in a tweet? I cannot for the life of me figure it out.
http://www.makeuseof.com/tag/how-to-build-a-raspberry-pi-twitter-bot/
CC-MAIN-2014-15
refinedweb
1,155
75
Created on 2017-08-20 19:03 by samuelcolvin, last changed 2018-11-27 07:42 by serhiy.storchaka. This issue is now closed. With Python 3.5 and 3.6 list comprehensions, generators and tuples have the col_offset for their ast nodes off by 1: ``` import ast ast.parse('{a for a in range(3)}').body[0].value.col_offset >> 0 # set comprehension correct ast.parse('{a: 1 for a in range(3)}').body[0].value.col_offset >> 0 # dict comprehension correct ast.parse('[a for a in range(3)]').body[0].value.col_offset >> 1 # list comprehension wrong! ast.parse('(a for a in range(3))').body[0].value.col_offset >> 1 # generator comprehension wrong! ast.parse('[1, 2, 3]').body[0].value.col_offset >> 0 # list correct ast.parse('{1, 2, 3}').body[0].value.col_offset >> 0 # set correct ast.parse('{1: 1, 2: 2, 3: 3}').body[0].value.col_offset >> 0 # dict correct ast.parse('(1, 2, 3)').body[0].value.col_offset >> 1 # tuple wrong! ``` I haven't tried 3.4, the issue could be there too. There are some other related issues #16806 and #21295 but they don't seem quite the same. For list comprehensions and generator expressions this is definitely a bug. But tuples syntax technically does not include surrounded parentheses. There is also a problem with generator expression passes as a single argument. Generator expression parentheses can be collapsed with function call parentheses: f(a for a in b). PR 10633 makes the following changes: * Fixes position for list comprehensions and generator expressions. * If generator expression parentheses are be collapsed with function call parentheses, the position of the AST node for the generator expression points to the left parenthesis. * For tuples surrounded with parentheses, the position of the AST node points to the left brace. For tuples without parentheses, it points to the position of the first tuple item. I am not sure whether these changes should be backported to maintained versions. I am not sure what parts of this PR should be backported if either. Yeah, it's a tough call because it's one of those things others have probably worked around already, so backporting would break the work-arounds. If you don't want to bother backporting, Serhiy, I think it would be fine to not do it. New changeset b619b097923155a7034c05c4018bf06af9f994d0 by Serhiy Storchaka in branch 'master': bpo-31241: Fix AST node position for list and generator comprehensions. (GH-10633)
https://bugs.python.org/issue31241
CC-MAIN-2020-40
refinedweb
406
62.24
Eclipse Community Forums - RDF feed Eclipse Community Forums Re: SVNKit does not install in Eclipse Oxygen <![CDATA[In the bug tracker there is a work-around mentioned to install SVNKit:]]> Jan Peter Stotz 2017-07-03T09:51:03-00:00 Re: SVNKit does not install in Eclipse Oxygen <![CDATA[Same issue here on Mac.]]> Jose M Beleta 2017-06-30T07:12:23-00:00 Re: SVNKit does not install in Eclipse Oxygen <![CDATA[Same issue here, Windows 10 64 Bit all latest updates installed. Attempting to install any or all connectors, a window pops up briefly and flashes away again, no connectors can be installed. Best regards - Mike]]> Michael Stiefler 2017-06-29T17:48:24-00:00 Re: SVNKit does not install in Eclipse Oxygen <![CDATA[I am having the same issue.]]> Reuben Sivan 2017-06-29T15:46:08-00:00 SVNKit does not install in Eclipse Oxygen <![CDATA[I've just updated my installation of Eclipse to Oxygen 4.7.0 and I cannot get the SVNKIT connectors installed. The Subversion Connector Discovery dialog opens and lets me select SVN Kit 1.8.14 but when I click on Finish the next window just only quickly appears and disappears. I have tried to just copy the plugins from another installation, and put them in the plugin folder, but it does not work. OS is MacOS X Sierra]]> Gabriella Turek 2017-06-29T02:50:09-00:00 Re: Errors while offline <![CDATA[I had this problem when my repository was not up-to-date and I tried to change something in conflicted resources.]]> 2017-05-18T06:38:56-00:00 Re: precommit hook client side <![CDATA[I am using eclipse-SDK Mars(4.5) Plug-in development environment to create the plugin, and then install the plug-in in the Eclipse IDE for Developers Mars(4.5.2) through the dropins directory in eclipse folder. I have tried to implement the precommit-hook for SVN using the above code to extend the DefaultCommitActionFactory, and returns DefaultDialog.DIALOG_FAILED; statement, but after I install my plugin and test ( by right click file and team->commit ), the commit Dialog shows up as usual, and allows me to commit changes to the svn repo. I have also tried to implement the class ICommitActionFactory interface, but still couldn't prevent the commit dialog from showing up. I know the plugin is installed properly, so I don't know why the method for commit dialog is not being overridden by my plugin. here is my code, any help with this will be appreciated! package testtwo; import java.util.Collection; import org.eclipse.swt.widgets.Shell; import org.eclipse.team.svn.core.operation.CompositeOperation; import org.eclipse.team.svn.core.operation.IActionOperation; import org.eclipse.team.svn.core.operation.IRevisionProvider; import org.eclipse.team.svn.ui.dialog.DefaultDialog; import org.eclipse.team.svn.ui.extension.factory.ICommentDialogPanel; import org.eclipse.team.svn.ui.extension.factory.ICommitActionFactory; import org.eclipse.team.svn.ui.extension.factory.ICommitDialog; import org.eclipse.team.svn.ui.extension.impl.DefaultCommitActionFactory; import org.eclipse.ui.IWorkbenchPart; public class CommitActionFactory1 extends DefaultCommitActionFactory { @Override public ICommitDialog getCommitDialog(final Shell shell, Collection allFilesToCommit, final ICommentDialogPanel commentPanel) { return new ICommitDialog() { public String getMessage() { return commentPanel.getMessage(); } public int open() { boolean isCommitValid = performSomeValidation(); if (!isCommitValid) { return DefaultDialog.DIALOG_FAILED; } return new DefaultDialog(shell, commentPanel).open(); } private boolean performSomeValidation() { // TODO Auto-generated method stub return false; } }; } }]]> Aruna Chen 2017-05-10T16:10:49-00:00 resource does not exist in the HEAD revision of the repository <![CDATA[Hello, I'm using Eclipse + CDT version Neon 2. I'm modifying a cpp file and when selecting a piece of code an error occured. The error is attached to the topic. It's indicates that : The selected resource does not exist in the HEAD revision of the repository and requested operation will be limited by the working copy revision. After verification, the file already exists in the repository. What is the explanation about this error ? Best Regards, CFOE]]> Christian Foesser 2017-04-25T08:27:00-00:00 Re: Subversive unable to connect to project error immediately after successful commit <![CDATA[No telling if there were or not known issues, even after my combing through the bugzilla. However, experimentation has resulted in several issue-free commits while configured as PHP using the SVNKit connector instead (SVNKit 1.8.14), so the issue could well be in JavaHL, either 1.8.15 specifically or any range of versions from 1.8.15 back to 1.8.2 at the oldest. What's more, simply switching to SVNKit has proven a sufficient solution. So there's that.]]> Daniel Wilson 2017-03-24T22:40:49-00:00 Re: Installing in Luna CDT problem <![CDATA[Sometimes the marketplace can be a toilet -- my organization's firewall blocks the darn thing, for starters. To get around that, things can get a bit manual. You'll want to download the update site archive from here. Grab the latest stable or the release build archive zip. At the current moment, you'll probably want "Archived Update Site: Subversive-4.0.2.I20160902-1700.zip" under "Neon (Eclipse 4.6) Release". You'll also need the Polarion connector jars from here. Go down to archives and grab the one that matches the eclipse version: (" Subversive Connector Archives for Subversive 4.0" at the moment). Only three of them matter if you're using the native JavaHL connector: javahl18.win64_[...]-1700 javahl18_[...]-1700 connector_[...]-1700 these go into the eclipse\dropins folder. Then, point the new software wizard at the site archive and have it install. It's a bit dumb, but it gets around marketplace issues.]]> Daniel Wilson 2017-03-06T20:53:44-00:00
https://www.eclipse.org/forums/feed.php?mode=m&l=1&basic=1&frm=73&n=10
CC-MAIN-2017-30
refinedweb
953
52.15
Continuous delivery (CD) means frequently delivering updates to your software application. The idea is that by updating more often, you do not have to wait for a specific timed period, and your organization gets better at the process of responding to change. Some Ansible users are deploying updates to their end users on an hourly or even more frequent basis – sometimes every time there is an approved code change. To achieve this, you need tools to be able to quickly apply those updates in a zero-downtime way. This document describes in detail how to achieve this goal, using one of Ansible’s most complete example playbooks as a template: lamp_haproxy. This example uses a lot of Ansible features: roles, templates, and group variables, and it also comes with an orchestration playbook that can do zero-downtime rolling upgrades of the web application stack. The playbooks deploy Apache, PHP, MySQL, Nagios, and HAProxy to a CentOS-based set of servers. We’re not going to cover how to run these playbooks here. Read the included README in the github project along with the example for that information. Instead, we’re going to take a close look at every part of the playbook and describe what it does. Let’s start with site.yml. This is our site-wide deployment playbook. It can be used to initially deploy the site, as well as push updates to all of the servers: --- # This playbook deploys the whole application stack in this site. # Apply common configuration to all hosts - hosts: all roles: - common # Configure and deploy database servers. - hosts: dbservers roles: - db # Configure and deploy the web servers. Note that we include two roles # here, the 'base-apache' role which simply sets up Apache, and 'web' # which includes our example web application. - hosts: webservers roles: - base-apache - web # Configure and deploy the load balancer(s). - hosts: lbservers roles: - haproxy # Configure and deploy the Nagios monitoring node(s). - hosts: monitoring roles: - base-apache - nagios Note If you’re not familiar with terms like playbooks and plays, you should review Working With Playbooks. In this playbook we have 5 plays. The first one targets all hosts and applies the common role to all of the hosts. This is for site-wide things like yum repository configuration, firewall configuration, and anything else that needs to apply to all of the servers. The next four plays run against specific host groups and apply specific roles to those servers. Along with the roles for Nagios monitoring, the database, and the web application, we’ve implemented a base-apache role that installs and configures a basic Apache setup. This is used by both the sample web application and the Nagios hosts. By now you should have a bit of understanding about roles and how they work in Ansible. Roles are a way to organize content: tasks, handlers, templates, and files, into reusable components. This example has six roles: common, base-apache, db, haproxy, nagios, and web. How you organize your roles is up to you and your application, but most sites will have one or more common roles that are applied to all systems, and then a series of application-specific roles that install and configure particular parts of the site. Roles can have variables and dependencies, and you can pass in parameters to roles to modify their behavior. You can read more about roles in the Roles section. Group variables are variables that are applied to groups of servers. They can be used in templates and in playbooks to customize behavior and to provide easily-changed settings and parameters. They are stored in a directory called group_vars in the same location as your inventory. Here is lamp_haproxy’s group_vars/all file. As you might expect, these variables are applied to all of the machines in your inventory: --- httpd_port: 80 ntpserver: 192.0.2.23 This is a YAML file, and you can create lists and dictionaries for more complex variable structures. In this case, we are just setting two variables, one for the port for the web server, and one for the NTP server that our machines should use for time synchronization. Here’s another group variables file. This is group_vars/dbservers which applies to the hosts in the dbservers group: --- mysqlservice: mysqld mysql_port: 3306 dbuser: root dbname: foodb upassword: usersecret If you look in the example, there are group variables for the webservers group and the lbservers group, similarly. These variables are used in a variety of places. You can use them in playbooks, like this, in roles/db/tasks/main.yml: - name: Create Application Database mysql_db: name: "{{ dbname }}" state: present - name: Create Application DB User mysql_user: name: "{{ dbuser }}" password: "{{ upassword }}" priv: "*.*:ALL" host: '%' state: present You can also use these variables in templates, like this, in roles/common/templates/ntp.conf.j2: driftfile /var/lib/ntp/drift restrict 127.0.0.1 restrict -6 ::1 server {{ ntpserver }} includefile /etc/ntp/crypto/pw keys /etc/ntp/keys You can see that the variable substitution syntax of {{ and }} is the same for both templates and variables. The syntax inside the curly braces is Jinja2, and you can do all sorts of operations and apply different filters to the data inside. In templates, you can also use for loops and if statements to handle more complex situations, like this, in roles/common/templates/iptables.j2: {% if inventory_hostname in groups['dbservers'] %} -A INPUT -p tcp --dport 3306 -j ACCEPT {% endif %} This is testing to see if the inventory name of the machine we’re currently operating on ( inventory_hostname) exists in the inventory group dbservers. If so, that machine will get an iptables ACCEPT line for port 3306. Here’s another example, from the same template: {% for host in groups['monitoring'] %} -A INPUT -p tcp -s {{ hostvars[host].ansible_default_ipv4.address }} --dport 5666 -j ACCEPT {% endfor %} This loops over all of the hosts in the group called monitoring, and adds an ACCEPT line for each monitoring hosts’ default IPv4 address to the current machine’s iptables configuration, so that Nagios can monitor those hosts. You can learn a lot more about Jinja2 and its capabilities here, and you can read more about Ansible variables in general in the Using Variables section. Now you have a fully-deployed site with web servers, a load balancer, and monitoring. How do you update it? This is where Ansible’s orchestration features come into play. While some applications use the term ‘orchestration’ to mean basic ordering or command-blasting, Ansible refers to orchestration as ‘conducting machines like an orchestra’, and has a pretty sophisticated engine for it. Ansible has the capability to do operations on multi-tier applications in a coordinated way, making it easy to orchestrate a sophisticated zero-downtime rolling upgrade of our web application. This is implemented in a separate playbook, called rolling_update.yml. Looking at the playbook, you can see it is made up of two plays. The first play is very simple and looks like this: - hosts: monitoring tasks: [] What’s going on here, and why are there no tasks? You might know that Ansible gathers “facts” from the servers before operating upon them. These facts are useful for all sorts of things: networking information, OS/distribution versions, etc. In our case, we need to know something about all of the monitoring servers in our environment before we perform the update, so this simple play forces a fact-gathering step on our monitoring servers. You will see this pattern sometimes, and it’s a useful trick to know. The next part is the update play. The first part looks like this: - hosts: webservers user: root serial: 1 This is just a normal play definition, operating on the webservers group. The serial keyword tells Ansible how many servers to operate on at once. If it’s not specified, Ansible will parallelize these operations up to the default “forks” limit specified in the configuration file. But for a zero-downtime rolling upgrade, you may not want to operate on that many hosts at once. If you had just a handful of webservers, you may want to set serial to 1, for one host at a time. If you have 100, maybe you could set serial to 10, for ten at a time. Here is the next part of the update play: pre_tasks: - name: disable nagios alerts for this host webserver service nagios: action: disable_alerts host: "{{ inventory_hostname }}" services: webserver delegate_to: "{{ item }}" loop: "{{ groups.monitoring }}" - name: disable the server in haproxy shell: echo "disable server myapplb/{{ inventory_hostname }}" | socat stdio /var/lib/haproxy/stats delegate_to: "{{ item }}" loop: "{{ groups.lbservers }}" Note serialkeyword forces the play to be executed in ‘batches’. Each batch counts as a full play with a subselection of hosts. This has some consequences on play behavior. For example, if all hosts in a batch fails, the play fails, which in turn fails the entire run. You should consider this when combining with max_fail_percentage. The pre_tasks keyword just lets you list tasks to run before the roles are called. This will make more sense in a minute. If you look at the names of these tasks, you can see that we are disabling Nagios alerts and then removing the webserver that we are currently updating from the HAProxy load balancing pool. The delegate_to and loop arguments, used together, cause Ansible to loop over each monitoring server and load balancer, and perform that operation (delegate that operation) on the monitoring or load balancing server, “on behalf” of the webserver. In programming terms, the outer loop is the list of web servers, and the inner loop is the list of monitoring servers. Note that the HAProxy step looks a little complicated. We’re using HAProxy in this example because it’s freely available, though if you have (for instance) an F5 or Netscaler in your infrastructure (or maybe you have an AWS Elastic IP setup?), you can use modules included in core Ansible to communicate with them instead. You might also wish to use other monitoring modules instead of nagios, but this just shows the main goal of the ‘pre tasks’ section – take the server out of monitoring, and take it out of rotation. The next step simply re-applies the proper roles to the web servers. This will cause any configuration management declarations in web and base-apache roles to be applied to the web servers, including an update of the web application code itself. We don’t have to do it this way–we could instead just purely update the web application, but this is a good example of how roles can be used to reuse tasks: roles: - common - base-apache - web Finally, in the post_tasks section, we reverse the changes to the Nagios configuration and put the web server back in the load balancing pool: post_tasks: - name: Enable the server in haproxy shell: echo "enable server myapplb/{{ inventory_hostname }}" | socat stdio /var/lib/haproxy/stats delegate_to: "{{ item }}" loop: "{{ groups.lbservers }}" - name: re-enable nagios alerts nagios: action: enable_alerts host: "{{ inventory_hostname }}" services: webserver delegate_to: "{{ item }}" loop: "{{ groups.monitoring }}" Again, if you were using a Netscaler or F5 or Elastic Load Balancer, you would just substitute in the appropriate modules instead. In this example, we use the simple HAProxy load balancer to front-end the web servers. It’s easy to configure and easy to manage. As we have mentioned, Ansible has built-in support for a variety of other load balancers like Citrix NetScaler, F5 BigIP, Amazon Elastic Load Balancers, and more. See the Working With Modules documentation for more information. For other load balancers, you may need to send shell commands to them (like we do for HAProxy above), or call an API, if your load balancer exposes one. For the load balancers for which Ansible has modules, you may want to run them as a local_action if they contact an API. You can read more about local actions in the Delegation, Rolling Updates, and Local Actions section. Should you develop anything interesting for some hardware where there is not a core module, it might make for a good module for core inclusion! Now that you have an automated way to deploy updates to your application, how do you tie it all together? A lot of organizations use a continuous integration tool like Jenkins or Atlassian Bamboo to tie the development, test, release, and deploy steps together. You may also want to use a tool like Gerrit to add a code review step to commits to either the application code itself, or to your Ansible playbooks, or both. Depending on your environment, you might be deploying continuously to a test environment, running an integration test battery against that environment, and then deploying automatically into production. Or you could keep it simple and just use the rolling-update for on-demand deployment into test or production specifically. This is all up to you. For integration with Continuous Integration systems, you can easily trigger playbook runs using the ansible-playbook command line tool, or, if you’re using Red Hat Ansible Tower, the tower-cli or the built-in REST API. (The tower-cli command ‘joblaunch’ will spawn a remote job over the REST API and is pretty slick). This should give you a good idea of how to structure a multi-tier application with Ansible, and orchestrate operations upon that app, with the eventual goal of continuous delivery to your customers. You could extend the idea of the rolling upgrade to lots of different parts of the app; maybe add front-end web servers along with application servers, for instance, or replace the SQL database with something like MongoDB or Riak. Ansible gives you the capability to easily manage complicated environments and automate common operations. See also
https://docs.ansible.com/ansible/devel/user_guide/guide_rolling_upgrade.html
CC-MAIN-2019-30
refinedweb
2,290
60.14
in reply to INI::Library Hi, I was thinking about your package name and was wondering whether you would consider Library::INI or Library::Config::Ini. Because then you have the kind of namespace you could add to if need be (as your project grows for example). You could also call it Config::Ini and pair it up with Config::IniFiles (where that uses name=value pairs) though I personally wouldn't :P. Nice snippet though :) My savings account My retirement account My investments Social Security Winning the lottery A Post-scarcity economy Retirement?! You'll have to pull the keyboard from my cold, dead hands I'm independently wealthy Other Results (75 votes), past polls
http://www.perlmonks.org/?node_id=185947
CC-MAIN-2014-42
refinedweb
116
58.62
Pipeline is a package to build multi-staged concurrent workflows with a centralized logging output.. It's tiny by design and is valuable when used as a glue rather than a container. $ go get gopkg.in/myntra/pipeline.v1 The package has three building blocks to create workflows : Pipeline, Stage and Step . A pipeline is a collection of stages and a stage is a collection of steps. A stage can have either concurrent or sequential steps, while stages are always sequential. The step block is where the actual work is done. Stage and pipeline act as flow governors. Step is the unit of work which can be concurrently or sequentially staged with other steps. To do that, we need to implement the Stepinterface. type Step interface { Out Exec(*Request) *Result Cancel() error } To satisfy the interface we need to embed pipeline.StepContextand implement Exec(*Request)*Result, Cancel()errormethods in the target type. For e.g: type work struct { pipeline.StepContext } func (w work) Exec(request *pipeline.Request) *pipeline.Result { return &pipeline.Result{} } func (w work) Cancel() error { return nil } The pipeline.StepContexttype provides a Statusmethod which can be used to log to the outchannel. The current step receives a Requestvalue passed on by the previous step. Internally data( Request.Dataand Request.KeyVal) is copied from the previous step's Result. The api NewStage(name string, concurrent bool, disableStrictMode bool) is used to stage work either sequentially or concurrently. In terms of the pipeline package, a unit of work is an interface: Step. The following example shows a sequential stage. For a more complex example, please see: examples/advanced.go package main import ( "fmt" "time" "github.com/myntra/pipeline" ) type work struct { pipeline.StepContext id int } func (w work) Exec(request *pipeline.Request) *pipeline.Result { w.Status(fmt.Sprintf("%+v", request)) duration := time.Duration(1000 * w.id) time.Sleep(time.Millisecond * duration) msg := fmt.Sprintf("work %d", w.id) return &pipeline.Result{ Error: nil, Data: struct{msg string}{msg:msg}, KeyVal: map[string]interface{}{"msg": msg}, } } func (w work) Cancel() error { w.Status("cancel step") return nil } func readPipeline(pipe *pipeline.Pipeline) { out, err := pipe.Out() if err != nil { return } progress, err := pipe.GetProgressPercent() if err != nil { return } for { select { case line := Checkexamplesdirectory for more. Logging and Progress pipeline.Out(): Get all statuses/logs. pipeline.Progress: Get progress in percentage. Output of the above example:
https://xscode.com/myntra/pipeline
CC-MAIN-2021-10
refinedweb
394
54.9
Listener and Adapters are two different way to accomplish the event handling in java. all the event sources have different type of class support. There are mouse and key events, window and focus events, srcoll bar and checkboxes event and many more. Events Handling is a powerful aspect of Java language. It allows you to create the Graphical Applications with easy to do operations. Event handling means, to create a reaction for every action one does with any component on the application screen. There are different event classes but we shall look at them briefly after we define the element of event handling mechanism. What is Event ? Event, in deep microprocessor terms is an interrupt signal to the processor, but let us not go deep down in computer hardware and The event is actually an object in Java which represents the state change of the component. This state change could be the clicking of any button, changing size of window, minimizing, maximizing or closing of frame, moving scrollbar or moving mouse, clicking mouse, pressing keyboard and many more. All these actions generate the event object. What are Event sources? Event Sources are the components on which the action is performed, for example if we are clicking the button, the source of event would be the button. It will generate a MouseClicked event or ActionEvent. These sources are binded with event listeners, don't worry we are going to describe listeners next. But when a event occurs and event source generates an event it passes it to EventListener to handle. What are Event Listener? Event Listener are the Objects that gets notification when any event is created. Java provide different type of listener for different type of objects. Also you must remember to bind the listener with the event source so that listener know if an event is generated. Java provides support for various event types. All the event classes are decedent from EventObject class and for each type of event class we also have corresponding Listener interface and Adapter class also. Here is how we brief the Event classes we have got. Action Event: Generated when a button is press, list item is double clicked or a menu is selected. AdjustmentEvent: Generated when a scroll bar is moved. ComponentEvent: Generated when a component is set to non-visibility or visibility, moved or resized. ContainerEvent: Generated when a component is added to or removed from a container. FocusEvent: Generated when a component receives or loses focus. InputEvent: It is an abstract class for Input type of events. ItemEvent: Generated when a check box or list item is clicked also when menu item is selected or deselected. KeyEvent: Generated when input is received from keyboard. MouseEvent and MouseWheeelEVent Generated when the mouse action is performed like click, move or wheel scroll etc. TextEvent: Generated when value of text is changed in text field or area. WindowEvnet: Generated when a window is active, closed, minimized, restored etc. Each of these class has its own meaning, they contains the methods and MASKs which helps to work with the event on machine level. There are two well known ways to work with events. Using the EventListener interfaces and using the adapter classes. Now we will be describing the two ways separately. First let us look at the listeners. package events; import java.awt.event.*; import java.awt.*; public class ListenersEvent extends Frame implements ActionListener,MouseMotionListener{ Button b; ListenersEvent(){ super("listener demo"); setLayout(new FlowLayout()); setSize(300,300); setVisible(true); b = new Button("click me"); b.addActionListener(this); add(b); addMouseMotionListener(this); } @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource()== b){ System.out.println("button clicked"); } } @Override public void mouseDragged(MouseEvent me) { System.out.println("mouse was dragged"); } @Override public void mouseMoved(MouseEvent me) { System.out.println("mouse was moved"); } public static void main(String[] args){ new ListenersEvent(); } } In this program the Frame will look like this and the output will look somewhat like this mouse was moved mouse was moved mouse was moved mouse was moved button clicked mouse was dragged mouse was dragged mouse was dragged Well this is just an example however the output you may observe will be according to your action on the frame. You will have to close the frame using either ctrl+c or stop icon on your IDE. Anyway let us divert our focus to the program and event. First we have implement two type of listeners ActionListener and MouseMotionListener these relate to MouseEvent and ActionEvent class. Well, there is only one method in ActionListener interface and two in MouseMotionListener interface. As you already know that we have to implement all the method of an interface weather we want it or not. We create frame and a button on the frame. Then we bind action listener with the button and MouseMotionListener with the Frame, so when we move or drag mouse on the Framed window we will be generating the events for MouseEvent type. Which may be handled in the corresponding method provided by the interface. You might notice that we have done something with the action event in actionPerformed method. Well, getSource() is method provided in the class EventObject so it can be used on any type of the event class. Here we try and check if the action event was performed on the button we created. It is good in case you want to make sure the button action does not overlap. We are done with the Listeners now let us tell you about the Adapters. Adapter are the classes which helps to reduce the code when we don't want all the method of an interfaces implemented. The methods in the adapter classes are same as in the interface but You need not to implemented all of them if you need only one or two In following program we are going to use anonymous class concepts to display the use of adapter class. We will be creating an inner class and and anonymous class which will help you reduce the code according to some level. package events; import java.awt.event.*; import java.awt.*; public class AdapterEvent extends Frame{ AdapterEvent(){ super("Adapter Event Demo"); setSize(300,300); setVisible(true); setLayout(new FlowLayout()); //event handling using anonymous class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we){ System.exit(0); } }); addMouseMotionListener(new MouseInnerClass()); } //Inner class to do event handling class MouseInnerClass extends MouseMotionAdapter{ public void mouseDragged(MouseEvent me){ System.out.println("mouse was dragged"); } } public static void main(String[] args){ new AdapterEvent(); } } In this program we have created an Inner class and an anonymous inner class. The anonymous inner class creates a listener for the window event which will close the program when we create the frame by clicking close button. mouse was dragged mouse was dragged mouse was dragged mouse was dragged mouse was dragged mouse was dragged mouse was dragged mouse was dragged We have added the windowListener to the frame and then we create a anonymous class inside that. This class uses the WindowApapter class and then override the windowClosing() method which takes the WindowEvent type reference as parameter. This will do for the anonymous class. When we create Inner class for event handling all we need to do is to pass the object of the inner class when we bind the event. We are binding mouse motion listener with the frame and because we are going to use mouse motion adapter to accomplish the work we will be passing the object of inner class as the parameter in the binding method. rest remains same as the anonymous class.
http://www.examsmyantra.com/article/70/java/event-handling-in-java-using-listener-and-adapters
CC-MAIN-2018-51
refinedweb
1,266
63.09
Key Takeaways - Kubernetes itself is not a platform but only the foundational element of an ecosystem not only of tools, and services, but also offering support as part of a compelling internal product. - Platform teams should provide useful abstractions of Kubernetes complexities to reduce cognitive load on stream teams. - The needs of platform users change and a platform team needs to ease their journey forward. - Changes to the platform should meet the needs of stream teams, prompting a collaborative discovery phase with the platform team followed by stabilizing the new features (or service) before they can be consumed by other stream teams in a self-service fashion. - A team-focused Kubernetes adoption requires an assessment of cognitive load and tradeoffs, clear platform and service definitions, and defined team interactions. I read a lot of articles and see presentations on impressive Kubernetes tools, automation, and different ways to use the technology but these often offer little context about the organization other than the name of the teams involved. We can’t really judge the success of technology adoption, particularly Kubernetes, if we don't know who asked for it, who needs it, and who is implementing it in which ways. We need to know how teams are buying into this new offering — or not. In Team Topologies, which I wrote with Matthew Skelton, we talk about fundamental types of teams, their expected behaviors and purposes, and perhaps more importantly about the interactions among teams. Because that's what's going to drive adoption of technology. If we don't take that into consideration, we might fall into a trap and build technologies or services that no one needs or which have no clear use case. Team cognitive load has a direct effect on platform success and team interaction patterns can help reduce unnecessary load on product teams. We’ll look at how platforms can minimize cognitive load and end with ideas on how to take a team-centric approach to Kubernetes adoption. Is Kubernetes a platform? In 2019, Melanie Cebula, an infrastructure engineer at Airbnb, gave an excellent talk at Qcon. As DevOps lead editor for InfoQ, I wrote the story about it. In the first week online, this story had more than 23,000 page views. It was my first proper viral story, and I tried to understand why this one got so much attention. Yes, Airbnb helped, and Kubernetes is all the rage, but I think the main factor was that the story was about simplifying Kubernetes adoption at a large scale, for thousands of engineers. The point is that many developers and many engineers find it complicated and hard to adopt Kubernetes and change the way they work with the APIs and the artifacts they need to produce to use it effectively. The term “platform” has been overloaded with a lot of different meanings. Kubernetes is a platform in the sense that it helps us deal with the complexity of operating microservices. It helps provide better abstractions for deploying and running our services. That's all great, but there's a lot more going on. We need to think about how to size our hosts, how and when to create/destroy clusters, and how to update to new Kubernetes versions and who that will impact. We need to decide on how to isolate different environments or applications, with namespaces, clusters, or whatever it might be. Anyone who has worked with Kubernetes can add to this list: perhaps worrying about security, for example. A lot of things need to happen before we can use Kubernetes as a platform. One problem is that the boundaries between roles are often unclear in an organization. Who is the provider? Who is the owner responsible for doing all of this? Who is the consumer? What are the teams that will consume the platform? With blurry boundaries, it's complicated to understand who is responsible for what and how our decisions will affect other teams. Evan Bottcher defines a digital platform as “a foundation of self-service APIs, tools, and services, but also knowledge and support, and everything arranged as a compelling internal product.” We know that self-service tools and APIs are important. They're critical in allowing a lot of teams to be more independent and to work autonomously. But I want to bring attention to his mention of “knowledge and support”. That implies that we have teams running the platform that are focused on helping product teams understand and adopt it, besides providing support when problems arise in the platform. Another key aspect is to understand the platform as “a compelling internal product”, not a mandatory platform with shared services that we impose on everyone else. As an industry, we've been doing that for a long time, and it simply doesn't work very well. It often creates more pain than the benefits it provides for the teams forced to use a platform that is supposed to be a silver bullet. And we know silver bullets don’t exist. We have to think about the platform as a product. It's meant for our internal teams, but it's still a product. We're going to see what that implies in practice. The key idea is that Kubernetes by itself is not a platform. It's a foundation. Yes, it provides all this great functionality — autoscaling, self-healing, service discovery, you name it — but a good product is more than just a set of features. We need to think about how easy it is to adopt, its reliability, and the support for the platform. A good platform, as Bottcher says, should create a path of least resistance. Essentially, the right thing to do should be the easiest thing to do with the platform. We can’t just say that whatever Kubernetes does is the right thing. The right thing depends on your context, on the teams that are going to consume the platform, which services they need the most, what kind of help they need to onboard, and so on. One of the hard things about platforms is that the needs of the internal teams are going to change, with respect to old and new customers. Teams that are consuming the platform are probably going to have more specific requests and requirements over time. At the same time, the platform must remain understandable and usable for new teams or new engineers adopting it. The needs and the technology ecosystem keep evolving. Figure 1: Avoid creating isolated teams when bringing Kubernetes into the organization. Team cognitive load Adopting Kubernetes is not a small change. It's more like an elephant charging into a room. We have to adopt this technology in a way that does not cause more pain than the benefits it brings. We don't want to end up with something like Figure 1, that resembles life before the DevOps movement, with isolated groups. It’s the Kubernetes team now rather than the operations team, but if we create an isolationist approach where one group makes decisions independent from the other group, we’re going to run into the same kinds of problems. If we make platform decisions without considering the impact on consumers, we're going to increase pain in the form of their cognitive load, the amount of effort our teams must put out to understand and use the platform. John Sweller formulated cognitive load as “the total amount of mental effort being used in the working memory”. We can break this down into three types of cognitive load: intrinsic, extraneous, and germane. We can map these types of cognitive load in software delivery: intrinsic cognitive load is the skills I need to do my work; extraneous load is the mechanics, things that need to happen to deliver the value; and germane is the domain focus. Intrinsic cognitive load, if I’m a Java developer, is knowing how to write classes in Java. If I don't know how to do that, this takes effort. I have to Google it or I have to try to remember it. But we know how to minimize intrinsic cognitive load. We can have classical training, pair programming, mentoring, code reviews, and all techniques that help people improve their skills. Extraneous cognitive load includes any task needed to deliver the work I'm doing to the customers or to production. Having to remember how to deploy this application, how to access a staging environment, or how to clean up test data are all things that are not directly related to the problem to solve but are things that I need to get done. Team topologies and platform teams in particular can minimize extraneous cognitive load. This is what we're going to explore throughout the rest of this article. Finally, germane cognitive load is knowledge in my business domain or problem space. For example, if I'm working in private banking, I need to know how bank transfers work. The point of minimizing extraneous cognitive load is to free up as much memory available for focus on the germane cognitive load. Jo Pearce’s “Hacking Your Head” articles and presentations go deeper into this. The general principle is to be mindful of the impact of your platform choices on your teams’ cognitive loads. Case studies I mentioned Airbnb engineer Melanie Cebula’s excellent talk at Qcon so let’s look at how that company reduced the cognitive load of their development teams. “The best part of my day is when I update 10 different YAML files to deploy a one-line code change,” said no one, ever. Airbnb teams were feeling this sort of pain as they embarked on their Kubernetes journey. To reduce this cognitive load, they created a simple command-line tool, kube-gen, which allows the application teams or service teams to focus on a smaller set of configurations and details, which are specific to their own project or services. A team needs to configure only those settings like files or volumes specifically related to the germane aspect of their application. The kube-gen tool then generates the boilerplate code configuration for each environment, in their case: production, canary, and development environments. This makes it much easier for development teams to focus on the germane parts of their work. Figure 2: Airbnb uses kube-gen to simplify their Kubernetes ecosystem. As Airbnb did, we essentially want to clarify the boundaries of the services provided by the platform and provide good abstractions so we reduce the cognitive load on each service team. In Team Topologies, we talk about four types of teams, shown in Figure 3. Stream-aligned teams provide the end-customer value, they’re the heartbeat that delivers business value. The three other types of teams provide support and help reduce cognitive load. The platform team shields the details of the lower-level services that these teams need to use for deployment, monitoring, CI/CD, and other lifecycle supporting services. Figure 3: Four types of teams. The stream-aligned team resembles what organizations variously call a product team, DevOps team, or build-and-run team — these teams have end-to-end ownership of the services that they deliver. They have runtime ownership, and they can take feedback from monitoring or live customer usage for improving the next iteration of their service or application. We call this a “stream-aligned team” for two reasons. First, “product” is an overloaded term; as our systems become more and more complex, the less precise it is to define a standalone product. Second, we want to acknowledge the different types of streams beyond just the business-value streams; it can be compliance, specific user personas, or whatever makes sense for aligning a team with the value it provides. Another case study is uSwitch, which helps users in the UK compare utility providers and home services and makes it easy to switch between them. A couple of years ago, Paul Ingles, head of engineering at uSwitch, wrote “Convergence to Kubernetes”, which brought together the adoption of Kubernetes technology, how it helps or hurts teams and their work, and data for meaningful analysis. Figure 4, from that article, measures all the different teams’ low-level AWS service calls at uSwitch. When uSwitch started, every team was responsible for their own service, and they were as autonomous as possible. Teams were responsible for creating their own AWS accounts, security groups, networking, etc. uSwitch noticed that the number of calls to these services was increasing, correlated with a feeling that teams were getting slower at delivering new features and value for the business. Figure 4: Use of low-level AWS services over time. What uSwitch wanted to do by adopting Kubernetes was not only to bring in the technology but also to change the organizational structure and introduce an infrastructure platform team. This would address the increasing cognitive load generated by teams having to understand these different AWS services at a low level. That was a powerful idea. Once uSwitch introduced the platform, traffic directly through AWS decreased. The curves of calls in Figure 5 is a proxy for the cognitive load on the application teams. This concept aligns with a platform team’s purpose: to enable stream-aligned teams to work more autonomously with self-service capabilities and reduced extraneous cognitive load. This is a very different conceptual starting point from saying, "Well, we're going to put all shared services in a platform." Ingles also wrote that they wanted to keep the principles they had in place before around team autonomy and teams working with minimal coordination, by providing a self-service infrastructure platform. Figure 5: The number of low-level AWS service calls dropped after uSwitch introduced their Kubernetes-based platform. Treat the platform as a product We talk about treating the platform as a product — an internal product, but still a product. That means that we should think about its reliability, its fit for purpose, and the developer experience (DevEx) while using it. First, for the platform to be reliable, we need to have on-call support, because now the platform sits in the path of production. If our platform’s monitoring services fail or we run out of storage space for logs, for example, the customer-facing teams are going to suffer. They need someone who provides support, tells them what's going on, and estimates the expected time for a fix. It should also be easy to understand the status of the platform services and we should have clear, established communication channels between the platform and the stream teams in order to reduce cognitive load in communications. Finally, there needs to be coordination with potentially affected teams for any planned downtime. Secondly, having a platform that's fit for purpose means that we use techniques like prototyping and we get regular feedback from the internal customers. We use iterative practices like agile, pair programming, or TDD for faster delivery with higher quality. Importantly, we should focus on having fewer services of higher quality and availability rather than trying to build every service that we can imagine to be potentially useful. We need to focus on what teams really need and make sure those services are of high quality. This means we need very good product management to understand priorities, to establish a clear but flexible roadmap, and so on. Finally, development teams and the platform should speak the same language in order to maximize the experience and usability. The platform should provide the services in a straightforward way. Sometimes, we might need to compromise. If development teams are not familiar with YAML, we might think of the low cost, low effort, and long-term gain of training all development teams in YAML. But these decisions are not always straightforward and we should never make them without considering the impact on the development teams or the consuming teams. We should provide the right levels of abstraction for our teams today, but the context may change in the future. We might adopt better or higher levels of abstraction, but we always should look at what makes sense given the current maturity and engineering practices of our teams. Kubernetes helped uSwitch establish these more application-focused abstractions for things like services, deployments, and ingress rather than the lower-level service abstractions that they were using before with AWS. It also helped them minimize coordination, which was another of the key principles. I spoke with Ingles and with Tom Booth, at the time infrastructure lead at uSwitch, about what they did and how they did it. Some of the things that the platform team helped the service teams with were providing dynamic database credentials and multi-cluster load balancing. They also made it easier for service teams to get alerts for their customer-facing services, define service-level objectives (SLOs), and make all that more visible. The platform make it easy for teams to configure and monitor their SLOs with dashboards — if an indicator drops below a threshold, notifications go out in Slack, as shown in Figure 6. Figure 6: An example of a SLO threshold notification in Slack at uSwitch. Teams found it easy to adopt these new practices. uSwitch teams are familiar with YAML and can quickly configure these services and benefit from them. Achievements beyond the technical aspects uSwitch’s journey is fascinating beyond the technical achievements. They started this infrastructure adoption in 2018 with only a few services. They identified their first customer to be one team that was struggling without any centralized logging, metrics, or autoscaling. They recognized that growing services around these aspects would be a successful beginning. In time, the platform team started to define their own SLAs and SLOs for the Kubernetes platform, serving as an example for the rest of the company and highlighting the improvements in performance, latency, and reliability. Other teams could observe and make an informed decision to adopt the platform services or not. Remember, it was never mandated but always optional. Booth told me that uSwitch saw traffic increasing through the Kubernetes platform versus what was going directly through AWS and this gave them some idea of how much adoption was taking place. Later, the team addressed some critical cross-functional gaps in security, GDPR data privacy and handling of alerts and SLOs. One team, one of the more advanced in both engineering terms and revenue generation, was already doing everything that the Kubernetes platform could provide. They had no significant motivation to adopt the platform — until they were sure that it provided the same functionality with the increased levels of reliability, performance, and so on. It no longer made sense for them to take care of all these infrastructure aspects on their own. The team switched to use the Kubernetes platform and increased its capacity to focus on the business aspects of the service. That was the “ultimate” prize for the platform team, to gain the adoption from the most advanced engineering team in the organization. Four Key Metrics Figure 7: Four key metrics from the Accelerate book. Having metrics can be quite useful. As the platform should be considered a product, we can look at product metrics — and the categories in Figure 7 come from the book Accelerate by Nicole Forsgren, Jez Humble, and Gene Kim. They write that high-performing teams do very well at these key metrics around lead time, deployment frequency, MTTR, and change failure rate. We can use this to help guide our own platform services delivery and operations. Besides the Accelerate metrics, user satisfaction is another useful and important measurement. If we're creating a product for users, we want to make sure it helps them do their job, that they're happy with it, and that they recommend it to others. There's a simple example from Twilio. Every quarter or so, their platform team surveys the engineering teams with some questions (Figure 8) on how well the platform helps them build, deliver, and run their service and how compelling it is to use. Figure 8: The survey that Twiliio’s platform team sends out to engineering teams. With this simple questionnaire, you can look at overall user satisfaction over time and see trends. It’s not just about the general level of satisfaction with the technical services, but also with the support from the platform team. Dissatisfaction may arise because the platform team was too busy to listen to feedback for a period of time, for example. It's not just about the technology. It's also about interactions among teams. Yet another important area to measure is around platform adoption and engagement. In the end, for the platform to be successful, it must be adopted. That means it’s serving its purpose. At the most basic level, we can look at how many teams in the organization are using the platform versus how many teams are not. We can also look at adoption per platform service, or even adoption of a particular service functionality. That will help understand the success of a service or feature. If we have a service that we expected to be easily adopted but many teams are lagging behind, we can look for what may have caused that. Finally, measuring the reliability of the platform itself, as uSwitch did, is important as well. They had their own SLOs for the platform and this was available to all teams. Making sure we provide that information is quite important. Figure 9: Useful metrics for your platform as a product. Figure 9 shows some examples of the metrics categories. Each organization with its own context might have different specific metrics, but the types and categories that we should be looking at should be more or less the same. Team interactions The success of the platform team is the success of the stream-aligned teams. These two things go together. It's the same for other types of supporting teams. Team interactions are critical because the definition of success is no longer just about making technology available, it’s about helping consumers of that technology get the expected benefits in terms of speed, quality, and operability. Figure 10: Airbnb’s platform team provides an abstraction of the underlying Kubernetes architecture. Airbnb effectively had a platform team (although internally called Infrastructure team) to abstract a lot of the underlying details of the Kubernetes platform, as shown in Figure 10. This clarifies the platform’s boundaries for the development teams and exposes those teams to a much smaller cognitive load than telling them to use Kubernetes and to read the official documentation to understand how it works. That's a huge task that requires a lot of effort. This platform-team approach reduces cognitive load by providing more tightly focused services that meet our teams’ needs. To accomplish this, we need adequate behaviors and interactions between teams. When we start a new platform service or change an existing one, then we expect strong collaboration between the platform team and the first stream-aligned teams that will use the new/changed service. Right from the beginning of the discovery period, a platform team should understand a streaming team’s needs, looking for the simplest solutions and interfaces that meet those needs. Once the stream-aligned team starta using the service, then the platform team’s focus should move on to supporting the service and providing up-to-date, easy to follow documentation for onboarding new users. The teams no longer have to collaborate as much and the platform team is focused on providing a good service. We call this interaction mode X-as-a-Service. Note that this doesn't mean that the platform hides everything and the development teams are not allowed to understand what's going on behind the scenes. That's not the point. Everyone knows that it's a Kubernetes-based platform and we should not forbid teams from offering feedback or suggesting new tools or methods. We should actually promote that kind of engagement and discussion between stream-aligned teams and platform teams. For example, troubleshooting services in Kubernetes can be quite complicated. Figure 11 shows only the top half of a flow chart for diagnosing a deployment issue in Kubernetes. This is not something we want our engineering teams to have to go through every time there's a problem. Neither did Airbnb. Figure 11: Half of a Kubernetes deployment troubleshooting flow chart. Airbnb initiated a discovery period during which teams closely collaborated to understand what kind of information they needed in order to diagnose a problem and what kinds of problems regularly occurred. This led to an agreement on what a troubleshooting service should look like. Eventually, the service became clear and stable enough to be consumed by all the stream-aligned teams. Airbnb already provided these two services in their platform: kube-gen and kube-deploy. The new troubleshooting service, kube-diagnose, collected all the relevant logs, as well as all sorts of status checks and other useful data to simplify the lives of their development teams. Diagnosing got a lot easier, with teams focused on potential causes for problems rather than remembering where all the data was or which steps to get them. Figure 12: Services provided by the infrastructure (platform) team at Airbnb. Figure 13: The cloud-native landscape. Figure 13 shows just how broad the cloud-native landscape is. We don’t want stream-aligned teams to have to deal with that on their own. Part of the role of a platform team is to follow the technology lifecycle. We know how important that is. Let’s imagine there's a CNCF tool that just graduated which would help reduce the amount of custom code (or get rid of an older, less reliable tool) in our internal platform today. If we can adopt this new tool in a transparent fashion that doesn’t leak into the platform service usage by stream-aligned teams, then we have an easier path forward in terms of keeping up with this ever-evolving landscape. If, on the contrary, a new technology we’d like to adopt in the platform implies a change in one or more service interfaces that means we need to consult the stream-aligned teams to understand the effort required of them and evaluate the trade-offs at play. Are we getting more benefit in the long run than the pain of migration/adaptation today? In any case, the internal platform approach helps us make visible the evolution of the technology inside our platform. Figure 14: uSwitch open-sourced Heimdall tool that their platform team created for internal use initially. The same goes for adopting open source solutions. For example, uSwitch open sourced the Heimdall application that provides the chat tool integration with the SLOs dashboard service. And there are many more open-source tools. Zalando, for example, has really cool stuff around cluster lifecycle management. The point being that if a piece of open-source technology makes sense for us, we can adopt it more easily if they sit under a certain level of abstraction in the platform. And if it is not a transparent change, we can always collaborate with stream-aligned teams to identify what would need to change in terms of their usage of the affected service(s). Starting with team-centric approach for Kubernetes adoption There are three keys to a team-focused approach to Kubernetes adoption. We start by assessing the cognitive load on our development teams or stream-aligned teams. Let’s determine how easy it is for them to understand the current platform based on Kubernetes. What abstractions do they need to know about? Is this easy for them or are they struggling? It's not an exact science, but by asking these questions we can get a feel for what problems they're facing and need help with. The Airbnb case study is important because it made it clear that a tool-based approach to Kubernetes adoption brings with it difficulties and anxiety if people have to use this all-new platform without proper support, DevEx, or collaboration to understand their real needs. Next, we should clarify our platform. This often is simple, but we don't always do it. List exactly all services we have in the platform, who is responsible for each, and all the other aspects of a digital platform that I’ve mentioned like responsibility for on-call support, communication mechanisms, etc. All this should be clear. We can start immediately by looking at the gaps between our actual Kubernetes implementation and an ideal digital platform, and addressing those. Finally, clarify the team interactions. Be more intentional about when we should collaborate and when should we expect to consume a service independently. Determine how we develop new services and who needs to be involved and for how long. We shouldn't just say that we're going to collaborate and leave it as an open-ended interaction. Establish an expected duration for the collaboration, for example two weeks to understand what teams need from a new platform service and how the service interface should look like, before we’re actually building out such service. Do the necessary discovery first, then focus on functionality and reliability. At some point, the service can become “generally available” and interactions evolve to “X as a service”. There are many good platform examples to look at from companies like Zalando, Twilio, Adidas, Mercedes, etc. The common thread among them is a digital platform approach consisting not only of technical services but good support, on-call, high quality documentation, and all these things that make the platform easy for their teams to use and accelerate their capacity to deliver and operate their software more autonomously. I also wrote an article for TechBeacon that goes a bit deeper into these ideas. About the Author Manuel Pais is an independent IT organizational consultant and trainer, focused on team interactions, delivery practices, and accelerating flow. He is co-author of the book Team Topologies: Organizing Business and Technology Teams for Fast Flow. He helps organizations rethink their approach to software delivery, operations, and support via strategic assessments, practical workshops, and coaching. >
https://www.infoq.com/articles/kubernetes-successful-adoption-foundation/?topicPageSponsorship=f0ce4967-61ed-453d-a07c-590c05faa580&itm_source=articles_about_Kubernetes&itm_medium=link&itm_campaign=Kubernetes
CC-MAIN-2021-25
refinedweb
5,051
52.29
If you are having problems with a hard drive, volume, or mounted drive, check ____ for events about the drive that might have been recorded there. Event Viewer Depending on how fragmented the drive and how large the drive, defragmenting it can take less than an hour or as long as all night TRUE To make sure the drive is healthy, you need to search for and repair file system errors using the Windows ____ utility. Chkdsk ____________________ restores the system to its condition at the time a snapshot was taken of the system settings and configuration. System Rsestore Besides backing up user data or system files, you can also back up the entire hard drive using Windows Vista ____. Complete PC backup The user folder for an account contains a group of subfolders called the user ____. Profile namespace When you back up the system state, the registry is also backed up to the folder ____. %sysemRoot%\repair\RegBack ____ creates restore points at regular intervals and just before you install software or hardware. System Protection If you enter a command and want to terminate its execution before it is finished, you can press ____ to do so. Ctr+Break An extra copy of a data or software file that you can use if the original file becomes damaged or destroyed Backup A volume that can be accessed by way of a folder on another volume so that the folder has more available space Mounted drive Windows needs free space on the hard drive for normal operation, for defragmenting the drive, for burning CDs and DVDs, and for a variety of other tasks, so it's important to delete unneeded files occasionally. TRUE To protect a system against malicious attack, you need to verify that ____ software is configured to scan the system regularly and that it is up-to-date. antivirus As you work at the command prompt, you can use ____________________ characters in a filename to say that the command applies to a group of files or to abbreviate a filename if you do not know the entire name. Wildcard ____________________ happens over time as Windows writes files, deletes files, and writes new files to your drive. Fragmentation To view and manually install updates, click ____, and then follow the directions on-screen. Start, All programs, and Windows Updates ____________________ restores the system to its condition at the time a snapshot was taken of the system settings and configuration. system restore
http://quizlet.com/10102957/mxw-computer-chapter-4-flash-cards/
CC-MAIN-2014-42
refinedweb
414
50.4
Considering the QR decomposition of A we have that Ax=b becomes multiplying by Q^T we obtain and since Q^T is orthogonal (this means that Q^T*Q=I) we have Now, this is a well defined system, R is an upper triangular matrix and Q^T*b is a vector. More precisely b is the orthogonal projection of b onto the range of A. And, The function linalg.lstsq() provided by numpy returns the least-squares solution to a linear system equation and is able to solve overdetermined systems. Let's compare the solutions of linalg.lstsq() with the ones computed using the QR decomposition: from numpy import * # generating a random overdetermined system A = random.rand(5,3) b = random.rand(5,1) x_lstsq = linalg.lstsq(A,b)[0] # computing the numpy solution Q,R = linalg.qr(A) # qr decomposition of A Qb = dot(Q.T,b) # computing Q^T*b (project b onto the range of A) x_qr = linalg.solve(R,Qb) # solving R*x = Q^T*b # comparing the solutions print 'qr solution' print x_qr print 'lstqs solution' print x_lstsqThis is the output of the script above: qr solution [[ 0.08704059] [-0.10106932] [ 0.56961487]] lstqs solution [[ 0.08704059] [-0.10106932] [ 0.56961487]]As we can see, the solutions are the same. Thanks! This is helping me get some image processing homework done. I'm always happy to help you David :) Succinct. Thank you. If speed is important to you, you can use the triangular nature of the `R` matrix and solve it much faster using solve_triangular (in scipy.linalg): import scipy x_qr2 = scipy.linalg.solve_triangular(R, Qb, check_finite=False) This is 5.5x (or more) faster than numpy.linalg.solve, for 160 by 160 matrixes at least. Is there a way to get nonnegative solution for underdertermined system for Ax=b Is there a way to get nonnegative solution for underdertermined system for Ax=b Of course, but it is a different kind of optimization problem.
http://glowingpython.blogspot.it/2012/03/solving-overdetermined-systems-with-qr.html
CC-MAIN-2017-30
refinedweb
332
58.69
BackupAgentHelper You should build your backup agent using BackupAgentHelper if you want to back up complete files from either SharedPreferences or internal storage. Building your backup agent with BackupAgentHelper requires far less code than extending BackupAgent, because you don't have to implement onBackup() and onRestore(). Your implementation of BackupAgentHelper must use one or more backup helpers. A backup helper is a specialized component that BackupAgentHelper summons to perform backup and restore operations for a particular type of data. The Android framework currently provides two different helpers: SharedPreferencesBackupHelperto back up SharedPreferencesfiles. FileBackupHelperto back up files from internal storage. You can include multiple helpers in your BackupAgentHelper, but only one helper is needed for each data type. That is, if you have multiple SharedPreferences files, then you need only one SharedPreferencesBackupHelper. For each helper you want to add to your BackupAgentHelper, you must do the following during your onCreate() method: - Instantiate up SharedPreferences When you instantiate a SharedPreferencesBackupHelper, you must include the name of one or more SharedPreferences files. For example, to back up a SharedPreferences file named user_preferences, a complete backup agent using BackupAgentHelper looks like public class MyPrefsBackupAgent extends BackupAgentHelper { // The name of the SharedPreferences file static final String PREFS = "user_preferences"; // A key to uniquely identify the set of backup data static final String PREFS_BACKUP_KEY = "prefs"; // Allocate a helper and add it to the backup agent @Override public void onCreate() { SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS); addHelper(PREFS_BACKUP_KEY, helper); } }. To ensure that your backup agent does not read or write your files at the same time as your activities, you must use synchronized statements each time you perform a read or write. For example, in any activity where you read and write the file, you need an object to use as the intrinsic lock for the synchronized statements: try { synchronized (MyActivity.sDataLock) { File dataFile = new File(getFilesDir(), TOP_SCORES); RandomAccessFile raFile = new RandomAccessFile(dataFile, "rw"); raFile.writeInt(score); } } catch (IOException e) { Log.e(TAG, "Unable to write to file"); } You should synchronize your read statements with the same lock. Then, in your BackupAgentHelper, you must override onBackup() and onRestore() to synchronize the backup and restore operations with the same intrinsic lock. For example, the MyFileBackupAgent example from above needs the following methods: synchronized (MyActivity.sDataLock) { super.onBackup(oldState, data, newState); } } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { // Hold the lock while the FileBackupHelper restores the file synchronized (MyActivity.sDataLock) { super.onRestore(data, appVersionCode, newState); } } up and how each portion is then restored to the device. This can also help you manage different versions, because you read and write your data as unique entities, rather than complete files. - Back up data in a database. If you have an SQLite database that you want to restore when the user re-installs your app, you need to build a custom BackupAgentthat reads the appropriate data during a backup operation, then create your table and insert the data during a restore operation. If you don't need to perform any of the tasks above and want to back up complete files from SharedPreferences or internal storage,, you can initiate an immediate backup operation from the Backup Manager with the bmgr tool. When the Backup Manager calls your onBackup() method, it passes three parameters: oldState - An open, read-only ParcelFileDescriptorpointing to the last backup state provided by your app. This is not the backup data from cloud storage, but a local representation of the data that was backed up the last time onBackup()was called, as defined by newStateor from onRestore(). onRestore()is covered in the next section. Because onBackup()does not allow you to read existing backup data in the cloud storage, you can use this local representation to determine whether your data has changed since the last backup. data - A BackupDataOutputobject, which you use to deliver your backup data to the Backup Manager. newState - An open, read/write ParcelFileDescriptorpointing to a file in which you must write a representation of the data that you delivered to data. A representation can be as simple as the last-modified timestamp for your file. This object is returned as oldStatethe next time the Backup Manager calls your onBackup()method. If you don't write your backup data to newState, then oldStatewill point to an empty file next time Backup Manager calls onBackup(). Using these parameters, implement your onBackup() method to do the following: Check whether your data has changed since the last backup by comparing oldStateto your current data. How you read data in oldStatedepends on how you originally wrote it to newState(see step 3). The easiest way to record the state of a file is with its last-modified timestamp. For example, here's how you can read and compare a timestamp from oldState: // Get the oldState input stream FileInputStream instream = new FileInputStream(oldState.getFileDescriptor()); DataInputStream in = new DataInputStream(instream); try { // Get the last modified timestamp from the state file and data file long stateModified = in.readLong(); long fileModified = dataFile.lastModified(); if (stateModified != fileModified) { // The file has been modified, so do a backup // Or the time on the device changed, so be safe and do a backup } else { // Don't back up because the file hasn't changed return; } } catch (IOException e) { // Unable to read state file... be safe and do a backup } If nothing has changed and you don't need to back up, skip to step 3. If your data has changed, compared to oldState, write the current data to datato back it up to the cloud storage. You must write each chunk of data as an entity in the BackupDataOutput. An entity is a flattened binary data record that is identified by a unique key string. Thus, the data set that you back up is conceptually a set of key-value pairs. To add an entity to your backup data set, you must: Call writeEntityHeader(), passing a unique string key for the data you're about to write and the data size. Call writeEntityData(), passing a byte buffer that contains your data and the number of bytes to write from the buffer, which should match the size passed to writeEntityHeader(). For example, the following code flattens some data into a byte stream and writes it into a single entity:core); // Send the data to the Backup Manager via the BackupDataOutput byte[] buffer = bufStream.toByteArray(); int len = buffer.length; data.writeEntityHeader(TOPSCORE_BACKUP_KEY, len); data.writeEntityData(buffer, len); Perform this for each piece of data that you want to back up. How you divide your data into entities is up to you. You might even use just one entity. Whether or not you perform a backup (in step 2), write a representation of the current data to the newState ParcelFileDescriptor. The Backup Manager retains this object locally as a representation of the data that is currently backed up. It passes this back to you as oldStatethe next time it calls onBackup()so you can determine whether another backup is necessary, as handled in step 1. If you data, the Backup Manager calls your backup agent's onRestore() method. When it calls this method, the Backup Manager delivers your backup data so you can restore it onto the device. Only the Backup Manager can call onRestore(), which happens automatically when the system installs the restore data version. newState - An open, read/write ParcelFileDescriptorpointing to a file in which you must write the final backup state that was provided with data. This object is returned as oldStatethe next time onBackup()is called. Recall that you must also write the same newStateobject in the onBackup()callback—also doing it here ensures that the oldStateobject given to onBackup()is valid even the first time onBackup()is called after the device is restored. In your implementation of onRestore(), you should call readNextHeader() on the data to iterate through all entities in the data set. For each entity found, do the following: - Get the entity key with getKey(). Compare the entity key to a list of known key values that you should have declared as static final strings inside your BackupAgentclass. When the key matches one of your known key strings, enter into a statement to extract the entity data and save it to the device: - Get the entity data size with getDataSize()and create a byte array of that size. - Call readEntityData()and pass it the byte array, which is where the data will go, and specify the start offset and the size to read. - Your byte array is now full. Read the data and write it to the device however you like. After you read and write your data back to the device, write the state of your data to the newStateparameter the same as you do during onBackup(). For example, here's how you can restore the data backed up by the example in the previous section: @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { // There should be only one entity, but the safest // way to consume it is using a while loop while (data.readNextHeader()) { String key = data.getKey(); int dataSize = data.getDataSize(); // If the key is ours (for saving top score). Note this key was used when // we wrote the backup entity header if (TOPSCORE_BACKUP_KEY.equals(key)) { // Create an input stream for the BackupDataInput byte[] dataBuf = new byte[dataSize]; data.readEntityData(dataBuf, 0, dataSize); ByteArrayInputStream baStream = new ByteArrayInputStream(dataBuf); DataInputStream in = new DataInputStream(baStream); // Read the player name and score from the backup data playerName = in.readUTF(); playerScore = in.readInt(); // Record the score on the device (to a file or something) recordScore(playerName, playerScore); } else { // We don't know this entity key. Skip it. (Shouldn't happen.) data.skipEntityData(); } } // Finally, write to the state blob (newState) that describes the restored data FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor()); DataOutputStream out = new DataOutputStream(outstream); out.writeUTF to true then the Backup Manager will ignore the android:versionCode and call your onRestore() method in all cases. In doing so, you can manually check for the version difference in your onRestore() method and take any steps necessary to make the data compatible if the versions.
https://developer.android.com/guide/topics/data/keyvaluebackup?hl=ar
CC-MAIN-2021-39
refinedweb
1,686
51.89
03 March 2011 23:09 [Source: ICIS news] HOUSTON (ICIS)--Here is Thursday’s end of day ?xml:namespace> CRUDE: Apr WTI: $101.91/bbl, down 32 cents; Apr Brent: $114.79/bbl, down $1.56 NYMEX WTI crude futures retreated from recent lofty highs on a downside correction to overbought conditions. The market was keeping an eye on various proposals to mediate in the Libyan crisis. RBOB: Apr: $3.0262/gal, down 0.33 cents Reformulated gasoline blendstock for oxygenate blending (RBOB) was choppy as initial hopes of a NATURAL GAS: Apr: $3.778/MMBtu, down 4.0 cents After a morning of erratic trading in response to the government’s announcement of a narrow storage draw last week, the afternoon brought a lull in activity as the NYMEX front month remained under $3.80/MMBtu and finished down for a third straight session. ETHANE: down at 66.75-68.50 cents/gal Mont Belvieu ethane continued to move lower after seeing a price spike at the end of February from short-covering. There has been lower demand for ethane from the chemical industry. AROMATICS: benzene flat at $4.20-4.25/gal Benzene activity was thin on Thursday afternoon. Spot prices were unchanged from the previous day. OLEFINS: ethylene down at 52.00-53.50 cents/lb US March ethylene was heard traded on the Equistar pipeline at 53.50-53.75 cents/lb, at the low end of a 53.5-55.0 cent/lb bid/offer range heard earlier in the day. Propylene contracts remained unsettled, with sellers concerned about rising refinery-grade propylene (RGP) prices, sources said.
http://www.icis.com/Articles/2011/03/03/9440698/evening-snapshot-americas-markets-summary.html
CC-MAIN-2014-52
refinedweb
272
69.79
> I am making a game, and It was working just fine. My computer has 16gigs of ram. 2TB of HDD space, 4.2ghz processor. So I highly doubt my computer is the issue since i can do just about anything on it and there is not much stuff in the scene so far. I can't figure out why all of a sudden it has a lag? or some sort of conflict that is making everything glitchy. I found that the player is the issue. The movement script laggs the game dramaticly. What in this script is causing the problem? using UnityEngine; using System.Collections; public class PlayerControl : MonoBehaviour { public float speed = 10.0F; public float rotationSpeed = 100.0F; void Update() { float translation = Input.GetAxis("Vertical") * speed; float rotation = Input.GetAxis("Horizontal") * rotationSpeed; translation *= speed * Time.deltaTime; rotation *= rotationSpeed * Time.deltaTime; transform.Translate(0, 0, translation); transform.Rotate(0, rotation, 0); if (Input.GetKey (KeyCode.W) || Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.S) || Input.GetKey (KeyCode.D)) { animation.Play ("Run"); } else { animation.Play("Idle"); } } } Answer by whydoidoit · Mar 14, 2014 at 08:45 PM You are calling the animation system every frame. That's not a good plan. Presumably you are starting the Idle animation every frame again and again - also when you press a key you are starting the Run animation every frame the keys are held down. You want to call the Play on the animation when something changes, not every frame. How would you suggest i do that? Hold some kind of state for the current mode of the character. Like an enum variable or an int. When you are in the idle state detect a move to run, when you stop running move back to idle. Play your animation on each of those changes. Or use mecanim which kind of does this. Can I make animations snap to a frame? 2 Answers Why does my animation jump/lag when activating a game object? 0 Answers What kind of performance impact does looping anmiations have on a game? 1 Answer Unity Game preview lags on new laptop 1 Answer Trigger plus Key Activation. 0 Answers
https://answers.unity.com/questions/664172/lag-type-issue.html
CC-MAIN-2019-13
refinedweb
359
69.79
Related to bug 474054 where we show a preview of the tabs, but this is to actually show the full size contents of the actual tab (incase another tab is actually focused in that window). This is supposed to be just a preview, so we probably don't want to actually switch tabs for the user when the hover leaves the tab preview without selecting a tab. It looks like ITaskbar3::RegisterTab wants a native window for every tab. I don't think we currently do this. So we can't just show the window (native window?) containing the tab and internally switch the current tab to be the desired tab?! Maybe it would be possible to list the opened tabs in the jump list? (In reply to comment #3) >! From my limited usage of IE8 on Windows 7, I agree. Tab switching should be left to the application or at least be optional. However, I believe your comment would be more suitable for bug 474054. That's why it can be disabled via the internet options for IE and I would do that if I use it. But I think it would be good to have that option for those who like it. Changing the name to better reflect the intention to create a front end feature (bug 501490 adds the backend support). Created attachment 390086 [details] [diff] [review] v1.0 First RC. There is still a bug when activating a minimized window's tabs but I'm not sure where the bug is for that (could be in the backend). Rob, maybe we should change the aeropeek component to something generic like taskbar? I'm no longer in need of something in mozapps, but now I'll need a place up in browser for jump lists. How does wintaskbar sound? It's consistent with the interface name. (In reply to comment #10) > How does wintaskbar sound? It's consistent with the interface name. WFM! Dao may be interested in reviewing this. Why are you selecting the tab to preview it? I don't think we should do that, given the tabbrowser.xml hacks it implies. Is the expected UI documented somewhere, btw? I'm having problems getting any previews from IE8 on Win7 RC1. With IE it should look like You may not see the previews if you don't have Aero turned on (which can happen if you're running Win7 in a vm where there is no hardware acceleration). Right, this is a VM :( (In reply to comment #13) > Why are you selecting the tab to preview it? I don't think we should do that, > given the tabbrowser.xml hacks it implies. Rob and I discussed this. I think it's the only way to achieve the affect that we want. In particular, we wanted most of the browser UI to be displayed as though the tab was selected (back/forward state, selected tab in the tab bar, URL bar value, etc.). Alternate suggestions would be welcome, though. Ok, now that I've watched a video on aero peek, I understand the desired effect. I guess we could live with maintaining that mode in tabbrowser. The TabSelect shouldn't be dispatched, though. Otherwise you would have to update the code that's listening to that event, and extensions would have to do that as well. Yeah, that makes sense. I didn't know if extensions might want to update their UI depending on the selected tab. I think we'd want to preview that. Perhaps I'm mis-reading, but what good is the Aero-tab-Preview, if clicking on the tab doesn't select the highlighted tab ? Some may not want to inconvience of the extra click, or clicking on the task-bar, but there are those that will use the feature. Just displaying a panel of tabs however, and not being able to select that tab is a waste of coding efforts IMO. If the intent is to only display the tab, then there needs to be a way to 'kill' the feature as its useless. (In reply to comment #20) > I didn't know if extensions might want to update their UI depending on the > selected tab. I think we'd want to preview that. I think we can live with not previewing that, for the sake of not breaking other stuff. There are definitely TabSelect-dependent actions that should not happen in this case, comparable to the stuff that you made mInPreview-dependent. (In reply to comment #21) > Perhaps I'm mis-reading, but what good is the Aero-tab-Preview, if clicking on > the tab doesn't select the highlighted tab ? Clicking on the tab will select the tab. Previewing a tab will not leave that tab selected however. This feature operates the same way that it does for IE8 with exception that we update the browser chrome when previewing a tab. > If the intent is to only display the tab, then there needs to be a way to > 'kill' the feature as its useless. There is a hidden pref, aeropeek.enable, to turn the feature off. No restart required either. (In reply to comment #22) > I think we can live with not previewing that, for the sake of not breaking > other stuff. There are definitely TabSelect-dependent actions that should not > happen in this case, comparable to the stuff that you made > mInPreview-dependent. Ok, sounds fine then. I find it very interesting bug 465076 to implement Ctrl+Tab view is almost the same functionality built directly into the browser. I'd recommend mentioning the fake tab selections in the dev docs (even if you don't send TabSelect events, some extensions may get confused by this). Created attachment 393028 [details] [diff] [review] v1.5 Now with more comments and (hopefully) better style. Moved from browser/components/aeropeek to browser/components/wintaskbar. Simplified some code (thumbnails are now drawn from the previews) and other minor polish work. Needed for Windows 7 parity with Chrome, IE and Safari Comment on attachment 393028 [details] [diff] [review] v1.5 No tests yet, but with the upcoming code freeze I'd like some review so that this might make it in for beta. Comment on attachment 393028 [details] [diff] [review] v1.5 Note that I cannot test this, since I have Win 7 only on a VM. So I don't feel comfortable being the only reviewer. You're putting modules in browser/components/. You should probably use browser/modules/ instead. >+ <field name="mInPreview"> >+ false >+ </field> >+ >+ <property name="previewmode"> >+ <getter> >+ return this.mInPreview; >+ </getter> >+ <setter> >+ <![CDATA[ >+ this.mInPreview = val; >+ return val; >+ ]]> >+ </setter> >+ </property> Just make this one public field, previewMode. No need for a private field and a public property. >+//// WinTaskbarHelper >+ >+/* >+ * This object is for helping clients of the nsIWinTaskbar initialize >+ * themselves. The taskbar service is not initially available - it requires >+ * Windows to notify us when it's ready to accept API calls. Are we going to have multiple nsIWinTaskbar clients? >+var WinTaskbarHelper = { >+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), I don't think you need to implement QueryInterface here. >+++ b/browser/components/wintaskbar/preview-per-tab.jsm >+// Pref to enable/disable preview-per-tab >+const kTogglePrefName = "aeropeek.enable"; constants should be uppercase without the k prefix, e.g. TOGGLE_PREF_NAME >+//// Various utility functions >+var Util = { >+ get ioSvc () { >+ delete this.ioSvc; >+ return this.ioSvc = Cc["@mozilla.org/network/io-service;1"] >+ .getService(Ci.nsIIOService); >+ }, [...] I'm not sure that the Util wrapper is useful, you could just dump this stuff in the global scope. E.g. XPCOMUtils.defineLazyServiceGetter(this, "_ioService", "@mozilla.org/network/io-service;1", "nsIIOService"); ... function _imageFromURI(uri) { ... } >+var PreviewController = function (win, tab) { >+ this.win = win.QueryInterface(Ci.nsIDOMWindowInternal);; >+ this.tab = tab; >+ let linkedBrowser = tab.linkedBrowser; >+ this.tabbrowser = linkedBrowser.getTabBrowser(); >+ this.shell = win.gBrowser.docShell; Use win.gBrowser instead of linkedBrowser.getTabBrowser(). >+ this.canvasPreview = >+ doc.createElementNS("", "html:canvas"); Just "canvas", without "html:". >+ get wrappedJSObject() { >+ return this; >+ }, I'm not sure I understand your use of wrappedJSObject. Can you just get rid of it? >+ onTabPaint: function (rect) { >+ // Ignore spurious dirty rects >+ if (!rect.width || !rect.height) return; \n before return >+ onLocationChange: function (aBrowser, webProgress, request, location) { >+ }, >+ onProgressChange: function (aBrowser, webProgress, request, curSelfProgress, >+ maxSelfProgress, curTotalProgress, >+ maxTotalProgress) { >+ }, >+ onSecurityChange: function (aBrowser, aWebProgress, aRequest, aState) { >+ }, >+ onStateChange: function (aBrowser, aWebProgress, aRequest, >+ aStateFlags, aStatus) { >+ }, >+ onStatusChange: function (aBrowser, aWebProgress, aRequest, >+ aStatus, aMessage) { >+ }, You can spare the argument lists. >+ onRefreshAttempted: function (aBrowser, webProgress, aRefreshURI, >+ aMillis, aSameURI) { >+ return true; >+ }, You don't need to implement onRefreshAttempted. >+TabWindow.prototype = { >+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMEventListener]), Also not needed. >+ // nsIDOMEventListener >+ handleEvent: function (evt) { >+ switch(evt.type) { >+ case "TabOpen": >+ case "TabClose": >+ case "TabSelect": >+ case "TabMove": >+ let tab, preview; >+ tab = evt.originalTarget; >+ preview = AeroPeek.previews[tab]; Move this up and reduce the two switches to one? >+ case "TabMove": >+ let controller = preview.controller.wrappedJSObject; >+ let idx = Array.indexOf(controller.tabbrowser.mTabs, tab); >+ let next = null >+ // Check if there is a next preview >+ if (idx+1 < controller.tabbrowser.mTabs.length) { >+ next = AeroPeek.previews[controller.tabbrowser.mTabs[idx+1]]; >+ } use tab.nextSibling instead of controller.tabbrowser.mTabs[idx+1] >+var EXPORTED_SYMBOLS = ["AeroPeek"] I think this belongs to the top of the file. Also add a semicolon. Comment on attachment 393028 [details] [diff] [review] v1.5 >+function TabWindow(win) { >+ for each (let evtName in this.events) { >+ tabbrowser.addEventListener(evtName, this, false); add the event listeners on tabbrowser.tabContainer Also please drop the curly brackets around single lines... Created attachment 404560 [details] [diff] [review] v2.0 Notable changes since last patch: Review comments addressed (dao's and others from IRC/email). init.jsm removed due to underlying API changes in bug 501490's latest patch. Large block of module documentation in preview-per-tab.jsm. Feature changes: Time-based tab content cache expiration. Magic number based auto-disabling (see large comment in preview-per-tab.jsm). Implementation changes: Removed global mapping of <tab> to nsITaskbarPreview. There is now a mapping in each TabWindow of <tab> to nsITaskbarPreview via the tab position. The ChromeWindow to TabWindow mapping is now done via property of the ChromeWindow (used only in the case of a closing window). Lots more lazy getters to avoid new window/tab performance regressions. Dirty regions are now clipped to the canvas area to avoid some spurious rectangles causing drawWindow to throw. Tab ordering refreshed for all tabs in a window after move/open/close operations. General code cleanup and simplification. Tests now included. Probably a few other things I've forgotten to mention here. Comment on attachment 404560 [details] [diff] [review] v2.0 Switching review to Rob Strong per conversation with Dão on IRC. Rob, we need to sync up on where this code lands. I've currently got: components/taskbar with make clipping out the taskbar dir in browser/components/Makefile.in. The install location I have is dist/bin/modules/(jsm files). Any issues with that? Comment on attachment 404560 [details] [diff] [review] v2.0 >+ <field name="previewmode"> nit: previewMode >+DIRS += wintaskbar Jim uses "taskbar"... Please make sure that you're on the same page. >+// Pref to enable/disable preview-per-tab >+const TOGGLE_PREF_NAME = "aeropeek.enable"; >+// Pref to determine the magic auto-disable threshold >+const DISABLE_THRESHOLD_PREF_NAME = "aeropeek.maxpreviews"; >+// Pref to control the time in seconds that tab contents live in the cache >+const CACHE_EXPIRATION_TIME_PREF_NAME = "aeropeek.cachetime"; Did you intentionally not add default values for these prefs? It seems like you should (and then don't try/catch when you read them). +function PreviewController(win, tab) { + win.tabbrowser.addTabsProgressListener(this); Can you do this only once per window? >+ updateCanvasPreview: function () { >+ let win = this.linkedBrowser.contentWindow.QueryInterface(Ci.nsIDOMWindowInternal); You don't seem to be using nsIDOMWindowInternal. >+ case "DOMTitleChanged": >+ // The tab's label is sometimes empty when dragging tabs between windows >+ let htmldoc = evt.originalTarget.defaultView.top.document; >+ let title = htmldoc.title || '(Untitled)'; You shouldn't hardcode '(Untitled)'. Perhaps calling tabbrowser.setTabTitle(tab) fixes the issue? And add a comment with a bug number for the empty label bug. >+ onLinkIconAvailable: function (aBrowser) { >+ if (aBrowser != this.tab.linkedBrowser) >+ return; >+ let img = getFaviconAsImage(aBrowser.mIconURL); >+ this.preview.icon = img add a semicolon >+XPCOMUtils.defineLazyGetter(PreviewController.prototype, "canvasPreviewFlags", >+ function () { let canvasInterface = Ci.nsIDOMCanvasRenderingContext2D; >+ return canvasInterface.DRAWWINDOW_DRAW_VIEW >+ | canvasInterface.DRAWWINDOW_DRAW_CARET >+ | canvasInterface.DRAWWINDOW_DO_NOT_FLUSH; >+}); This is only used once, and you have a context there, so you could probably just do this: let flags = ctx.DRAWWINDOW_DRAW_VIEW | ctx.DRAWWINDOW_DRAW_CARET | ctx.DRAWWINDOW_DO_NOT_FLUSH; instead of: let flags = this.canvasPreviewFlags; >+ handleEvent: function (evt) { >+ let tab = evt.originalTarget; >+ switch(evt.type) { nit: add a space after 'switch' >+function TabWindow(win) { >+ this.win = win.QueryInterface(Ci.nsIDOMWindowInternal); Another useless QueryInterface? Otherwise looks good to me code-wise, but I can't test this, so you should definitely try to get a second review. Comment on attachment 404560 [details] [diff] [review] v2.0 >diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js >+#ifdef AERO_PEEK >+ Cu.import("resource://gre/modules/wintaskbar/preview-per-tab.jsm"); >+ >+ AeroPeek.onOpenWindow(window); >+#endif > } > > function BrowserShutdown() > { >+#ifdef AERO_PEEK >+ AeroPeek.onCloseWindow(window); >+#endif I'd like to see on(Open|Close)Window wrapped in something that can handle the .available logic and not bother importing the module if we're on an unsupported windows version. >diff --git a/browser/components/wintaskbar/preview-per-tab.jsm b/browser/components/wintaskbar/preview-per-tab.jsm >+ * This module implements the front end behavior for AeroPeek. Starting in >+ * Windows Vista, the taskbar begin showing live thumbanil previews of windows nit: began/thumbnail >+var EXPORTED_SYMBOLS = ["AeroPeek"] nit: missing semicolon >+Cu.import("resource://gre/modules/NetUtil.jsm"); >+//// Various utility properties >+XPCOMUtils.defineLazyServiceGetter(this, "ioSvc", >+ "@mozilla.org/network/io-service;1", >+ "nsIIOService"); Purely followup fodder: NetUtil now has an ioService property, but it's only on trunk. >+function _imageFromURI(uri) { >+ let channel = ioSvc.newChannelFromURI(uri); >+ >+ let out_img = { value: null }; >+ let inputStream = channel.open(); >+ try { >+ imgTools.decodeImageData(inputStream, channel.contentType, out_img); I noticed a couple sites (BBC, f.e.) that trip this up by serving their favicon with a non-image-y MIME type. Maybe we want to attempt (in a followup) overriding the server's type with image/x-icon or falling back to asking the favicon service. >+TabWindow.prototype = { >+ _enabled: false, >+ events: ["TabOpen", "TabClose", "TabSelect", "TabMove"], Probably want to listen for and invalidate the taskbar previews on window resizes as well. When I was testing this, only the active tab preview was invalidated, leaving differently sized thumbnails that changed size on hover. Looks good! Created attachment 404750 [details] [diff] [review] v2.1 Updated per Dão and Ryan's comments. Pushed to mozilla-central: Pushed to mozilla-1.9.2: Created attachment 404786 [details] [diff] [review] test fix for non-windows 7 machines This fixes the mochitests when run on machines that aren't Windows 7. Wasn't caught by earlier run through try server because previous versions of the patch always had AeroPeek defined. i've pushed this additional changeset on central to fix persistent timeout While I was playing around with the jump lists patch, I noticed this error show up in the error console: Error: win is not defined Source File: Line: 399 (In reply to comment #40) > While I was playing around with the jump lists patch, I noticed this error show > up in the error console: > > Error: win is not defined > Source File: > > Line: 399 and this one: Error: preview is undefined Source File: Line: 432 This error seems to happen if you have other windows besides the main browser window open and you close the browser window. I haven't been able to reproduce the first yet. running W7 RTM and I do not get taskbar thumbnail previews for individual tabs. And btw, Aeropeek is the ability in W7 to hover over the box at the very right of the taskbar to make all windows transparent in order to see the desktop. It has nothing to do with taskbar thumbnail previews. Created attachment 404861 [details] [diff] [review] Small bug fixes that should have been caught before checkin Both errors fixed - this should have been caught before checkin. (In reply to comment #42) > running W7 RTM and I do not get taskbar thumbnail previews for individual tabs. How many tabs do you have? If you have more than 20, the preview-per-tab feature is disabled to avoid cluttering your UI. Change aeropeek.maxpreviews to modify the threshold. > And btw, Aeropeek is the ability in W7 to hover over the box at the very right > of the taskbar to make all windows transparent in order to see the desktop. It > has nothing to do with taskbar thumbnail previews. The Engineering Windows 7 blog does indeed refer to the live preview as Aero Peek (see). The button the taskbar is also part of the Aero Peek feature.? The term Aero peek has different meanings depending on where you look. The option for turning AP on is described as "Use Aero Peek to preview the desktop". I like to call it thumbnail previews just as it's always been. I suppose the added ability to hover over the thumbnail and see it fullscreen is sort of a "Peek". Anyways, I can't get it working if I understand it the way I stated. (In reply to comment #45) >? It works for me on the nightly trunk build from this morning. What build are you running? Do you see any errors in the Error Console? i'm on branch which states the fix is there. Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2b1pre) Gecko/20091006 Namoroka/3.6b1pre Firefox/3.5.3 - Build ID: 20091006045110 nothing in the error console Comment on attachment 404861 [details] [diff] [review] Small bug fixes that should have been caught before checkin > for (let i = 0; i < tabs.length; i++) >- this.removeTab(tabs[i]); >+ this.removeTab(tabs[i], true); Set this._destroying instead of adding the dontSplice argument. OK, I must be confusing this fix with which did come in with last nights trunk. Tried Trunk and tab previews works! Only thing I found is that when first hovering over a preview thumbnail the screen flickers. (In reply to comment #50) > Tried Trunk and tab previews works! Only thing I found is that when first > hovering over a preview thumbnail the screen flickers. I have the same problem, so I tried with IE8. With IE8 when you hover a tab preview, only the content (and the window caption) changes. (In reply to comment #52) > See bug: which has a fix pending approval. Not sure if this fix will fix the issue of the loading icon showing up or not, may be another bug. This only partly works in 3.6pre. Out of the ten tabs that I have, only the last one currently has a preview, all others just display a progress circle. New tabs get a preview though. Could it be that the previews are never generated for startup tabs or something? Previews are generated on demand. Is there anything in your error console? Also, if you wait a minute or two (without having clicked the taskbar icon), do the progress circles resolve into a preview? Please followup to bug 522262. Just wondering: both Aero Peek and Jumplists seem to have been disabled in latest mozilla-1.9.2 nightlies. Is that the case, or has something just broke? (In reply to comment #56) > Just wondering: both Aero Peek and Jumplists seem to have been disabled in > latest mozilla-1.9.2 nightlies. Is that the case, or has something just broke? Jumplists are not yet landed on 1.9.2; see bug 473045, bug 518666 comment 81 and bug 521304 comment 9. Aero peek for tab previews are dependent on about:config preferences browser.taskbar.* and the width of your display and the number of tabs you open. For example if the using the default, you might find 8 previews at 1024x768, adding more moves it the list view upto the max, then disappears all together after that, no list, no previews. Loading a ton of bookmarks via "open all in tabs" > max list only seems to preview the first tab or runs the window preview again vs tab previews. Also stuck aero peek tab previews is still open in bug 522506 on both trunk and branch. (In reply to comment #57) > (In reply to comment #56) > > Is that the case, or has something just broke? > > Also stuck aero peek tab previews is still open in bug 522506 on both trunk and > branch. Oops.. that should be bug 522262, and bug 522506 is actually for aero peek previews resolving into generic thumbnail icons. What was fixed recently was bug 522416, which resolved loading http requests as async vs sync so we don't see all aero peek previews running together which caused the browser bugs like comment 54 and caused the browser to eventually hang.
https://bugzilla.mozilla.org/show_bug.cgi?id=474056
CC-MAIN-2017-22
refinedweb
3,465
59.19
I am using the GMP multiple precison package. I need to input very large integers as strings, for example will set x to that large integer in quotes (10 gives the base.)will set x to that large integer in quotes (10 gives the base.)Code: mpz_init_set_str(x,"1234567890",10) I want to be able to have the user enter the value, so I did something like: but this causes g++ to give the following error:but this causes g++ to give the following error:Code: #include <string> #include <gmpxx.h> // GMP string num; std::cin >> num; mpz_init_set_str(x,num,10) error: cannot convert `std::string' to `const char*' for argument `2' to `int __gmpz_init_set_str(__mpz_struct*, const char*, int)' Any ideas how to input a data type that will work? I am using Ubuntu on an AMD64. Thanks!
http://cboard.cprogramming.com/cplusplus-programming/69065-string-char*-problem-gmp-printable-thread.html
CC-MAIN-2015-18
refinedweb
138
67.38
In this tutorial you will learn how to write to file from string.. You can also passed the FileWriter object to the higher level output stream instance such as BufferedWriter, PrintWriter to write efficiently. Here I am going to give a simple example in which I have created a new text file using the File constructor and then pass this file object to the FileWriter instance to write characters into the file. Next I have passed the FileWriter object to the BufferedWriter instance which write method writes the characters more efficiently. Example : WriteFileFromString.java import java.io.File; import java.io.BufferedWriter; import java.io.FileWriter; class WriteFileFromString { public static void main(String args[]) { String str = "This example demonstrates you how to write a file from string"; File file = null; try { file = new File("writeToFileFromString.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(str); bw.close(); } catch(Exception e) { System.out.println(e); } System.out.println("String is written into file successfully"); } } How to Execute this example : After doing the basic process to execute a java program write simply on command prompt as : javac WriteFileFromString.java to compile the program And after successfully compilation to run simply type as : java WriteFileFromString Output : When you will execute this example a text file will be created on the specified place as the path given by you with containing the text that you are trying to write in that file by java program like as : From String Post your Comment
http://roseindia.net/java/examples/io/writeToFileFromString.shtml
CC-MAIN-2015-32
refinedweb
249
52.39
I am trying to use this function: these variables are stored in datetime format of mysql. var1:2012-02-01 01:39:32 var2:2012-02-02 01:47:11 if (date('Ymd', $var1) == date('Ymd', $var2) {... I am trying to use this function: these variables are stored in datetime format of mysql. var1:2012-02-01 01:39:32 var2:2012-02-02 01:47:11 if (date('Ymd', $var1) == date('Ymd', $var2) {... Well I got it working. Found out that apparently renaming the form method to something other than post will break it.. ha. I did a little bit more editing and I just tried taking out the JavaScript all together from my newsInsert.php page. So now all I have in there is <? //the below section contains password... So truly I have no need to do anything with the values client side. The only trouble is that, well I guess since I was following the guidelines from that website, he advised that users send the form... Soo... I'm a newb and need some help. I know this is a java forum, but I've yet to find anywhere else with such great members and support. =P I know this is a lot of information, so thank you for... Alright, yet another question. Below I have a sample of a JTabbedPane I've been working on. Every time the user clicks the sword icon it counts up. I used this code to make it update the count... I found it :) .setLocationRelativeTo(null); Makes it centered. I looked and I found CENTER_ALIGNMENT here: JDialog (Java Platform SE 6) well it says this anyway: Fields inherited from class java.awt.Component BOTTOM_ALIGNMENT, CENTER_ALIGNMENT,... Do you know of a way to make these center in the screen when they are first loaded? Thank you. Totally forgot about that for some reason. =/ I'll try it out. Works! =] Wow it works! =D and it runs a lot smoother! Thanks so much for showing me that :) Yea true. I will try the dialog boxes, and see if it doesn't freeze anymore. Well I haven't heard of or seen JDialog before. But I tried the cod you provided in the program, and it works, except that the dialogbox wont let me work with the other jframes I already made.. It... Yes, a modal dialog windows would works just fine. But they are so ugly and unattractive with so minimal customization that it kind of defeats the point of making a GUI in the first place. :( Plus... Also, I'd really like to know how to make the other frames disappear once I've collected the Users response. Any ideas how to set it up like this? Source Alrighty first off here is this for fun: Anyway here is how the program flows: The user will first be given an option of what to do: Login.java ->... NewCheckInfo is called near the beginning of CheckInfo... Oh i forgot i changed it just to test something. I told it to call the login stuff again in CheckInfo lines 29-32. Before I did that it use... It heads over to CheckInfo, there it sees that it needs more info so it loads up NewCheckInfo class. But that class just freezes. I added println statements like you said and it will go until the end... Sorry here is the source Source I have no idea if I'm setting this up 'properly' and I can't figure out why after you login it wont load the next window. It's just white on my computer. =/ As far... Yup. Look at the link I posted above its a jar file with working so far. well with a mouse listener you can't use event.isMetaDown() or event.isAltDown()? or whatever to tell if they are clicking on the field? or even use cordinates to make sure if they click in the right... Wouldn't that work for what your trying to do? So I checked my book and it looks like you can do a KeyListener for the frame.. import java.awt.event.*; addKeyListener( this ); public void keyPressed(KeyEvent event) I'm curious how to do this as well. I'd like it if you could just auto-update simply because new text was put into the field at all. Sounds like you just need to come up with some good algorithms based on math that determine how many they want to take from the pile. Obviously they don't want to take the last one if it can be...
http://www.javaprogrammingforums.com/search.php?s=58c23dd679e80ef8686d572eb0a054ed&searchid=2053030
CC-MAIN-2016-07
refinedweb
765
83.96
Tutum is a container platform that enables easy management of docker-backed services on node clusters running on platforms such as Digital Ocean, AWS, and Azure. You can also use Bring your own node to use any Linux host as a node to deploy containers to. In this tutorial, we will be deploying a simple Node.js application on Digital Ocean. The application, Tweedapp.io, is a simple RSS feeds and tweets aggregator for popular tech sites. You can checkout the source code at github which you should go ahead and grab a local copy by running: git clone git@github.com:kelonye/tutum-tweed.git Assuming that we have already created a Tutum account, we first need to login into our private Tutum docker registry with: $ docker login tutum.co Username Password Email Login Succeeded We will be using the Tutum REST API to easily deploy the application to a single node cluster composed of the following services: - A Web service built in Node and Ember.js - Redis cache service that stores the updates - Tweets worker that subscribes to matching tweets - Feeds worker that periodically fetches feeds You can see that each of the services is located in its own directory under the lib directory: In order to realize a successful deployment, we need to carry out the following tasks: - Create the node cluster if non existent - Build and push the 4 service images to the registry - Create the 4 services if not available - Start the services if not running - Update the services configuration - Redeploy the services Deploying To deploy the application, assuming that you have linked your Digital Ocean account to Tutum, create a twitter developer application at apps.twitter.com and go to the application’s Keys and Access Tokens tab. Run the following in your favorite shell emulator using the four provided credentials: export TUTUM_TWEED_TWITTER_CONSUMER_KEY="" export TUTUM_TWEED_TWITTER_CONSUMER_SECRET="" export TUTUM_TWEED_TWITTER_ACCESS_TOKEN="" export TUTUM_TWEED_TWITTER_ACCESS_TOKEN_SECRET="" This set’s environment variables that will be used by the tweets service to access Twitter’s streaming APIs. We also need to define two more settings to be used during deployment: export TUTUM_USER="" export TUTUM_APIKEY"" export TUTUM_TWEED_CLUSTER="" # the desired name of your new cluster The Tutum API key can be obtained by logging into Tutum, clicking on the menu on the upper right corner of the screen, selecting Account info and then lastly selecting Api Key. Use your Tutum username to define the TUTUM_USER setting. All the settings defined above can alternatively be set in either the .bashrc or .bash_profile files located in your home directory for convenience. We will be using tutum-deploy which enables a fig like management of node clusters using the Tutum API. So go ahead and install Node.js. The simplest installation step is to use your platforms package manager to install nodejs. For example, on MAC OSX, you’d use brew to install it as: brew install node This also installs npm, the Node.js package manager which in turn can be used to install the utility with: npm install -g tutum-deploy This adds the utility executable name, td, to your shell’s PATH so that it can be executed globally. You can the use the utility to first build and push the service images to your provided private Tutum registry with: td build td push Once the images have been pushed, we can let Tutum use the images to deploy the services to the cluster with: td up For convenience, all these commands have been defined in the Makefile at the root for the project. deploy: @$(MAKE) build push up build: @td build push: @td push up: @td up We can then just deploy the application once by simply running: make up We can then hopefully visit the deployed app using the hostname provided in the the web interface! tl;dr How did that work .. really, what happened? As mentioned earlier, tutum-deploy utility, when run, checks and ensures that services in a given cluster or custom node are running as required. We simply needed to define the expected state of our cluster in a tutum.yaml configuration file as: --- clusters: - name: "{{TWEED_CLUSTER}}" region: ams2 type: 512mb nodes: 1 tags: - tweed services: - name: redis image: "tutum.co/{{USER}}/redis" build: lib/redis containers: 1 tags: - tweed - name: tweets image: "tutum.co/{{USER}}/tweets" build: lib/tweets containers: 1 env: TWEED_TWITTER_CONSUMER_KEY: "{{TWEED_TWITTER_CONSUMER_KEY}}" TWEED_TWITTER_CONSUMER_SECRET: "{{TWEED_TWITTER_CONSUMER_SECRET}}" TWEED_TWITTER_ACCESS_TOKEN: "{{TWEED_TWITTER_ACCESS_TOKEN}}" TWEED_TWITTER_ACCESS_TOKEN_SECRET: "{{TWEED_TWITTER_ACCESS_TOKEN_SECRET}}" require: - redis tags: - tweed - name: feeds image: "tutum.co/{{USER}}/feeds" build: lib/feeds containers: 1 require: - redis tags: - tweed - name: web image: "tutum.co/{{USER}}/web" build: lib/web containers: 1 ports: - inner_port: 80 outer_port: 80 port_name: http protocol: tcp published: true env: NODE_ENV: production MINIFY: 1 PORT: 80 require: - redis tags: - tweed Reading from the top, we specified that we wished to have a deployed cluster on Digital Ocean with a single 512mb sized node. The configuration also defined the 4 services that used docker images that were pushed to our private registry. This configuration file, as shown, may contain variables which get passed in through environment variables. For example, the {{TWEED_CLUSTER}} variable got replaced with TUTUM_TWEED_CLUSTER. Notice that the environment variables have to be prefixed with TUTUM_. When the deployment command, make up was run, we first built the service images using the corresponding Dockerfiles whose locations were specified by the build attribute, and then pushed them to the registry. Note that the image names are namespaced as tutum.co/my-tutum-username/my-image since we are using the Tutum-provided private registry. Next, the td up began the actual deployment step where we first ensured that our cluster was created and deployed as expected. If no cluster existed, the new cluster was created and deployed appropriately. Just like in the case of the node cluster, each of the services were created, started and deployed if necessary. A service is a group of containers that provide a specific resource, for example, database storage. Services are run in multiple containers that can span multiple nodes and even clusters. Services make themselves available to each other using service links. Keep in mind that three of our services need to connect to the Redis service. Fortunately, Tutum makes docker container linking easy. A service’s linked_to_service property contains all services that it depends on. With tutum-deploy, we only need to define the links via the require property. In the example above, through linking, the web service, it contained the REDIS_PORT environment variable which was then used to connect to the redis store. Notice that with service links, we did not need to expose the Redis service port. Lastly, the web service exposes a tcp port that serves the traffic on port 80. We simply needed to specify the node and container ports as: ports: - guest: 80 host: 80 name: http protocol: tcp published: true Re-deploying Tutum supports hot redeployment of services. If we needed to deploy a new version of the application, running tutum-deploy would redeploy the application using the newly built images by replacing the old services. This ensures that our servers remains immutable and hence less likely to experience problems. There’s more that can be done with Tutum’s API and so have fun experimenting with it. Reblogged this on Dinesh Ram Kali.. Does tutum provide api to scale application? In the above example if I want to scale my web container to 2 instances does tutum provide api for that? Yes. You can scale several resources .e.g. : – services to multiple nodes/clusters – number of containers in a service (see `target_num_containers` at)
https://blog.tutum.co/2015/01/20/easy-docker-deployments-using-tutum-api/
CC-MAIN-2017-13
refinedweb
1,261
51.38
Hide Forgot Description of problem: Users with appropriate roles are continually hitting `[security_exception] no permissions for [indices:data/read/field_caps]` errors when accessing Kibana. Deleting/Restoring Kibana user index resolves issue momentarily, but issue reoccurs repeatedly. Version-Release number of selected component (if applicable): OCP 3.11.154-1 How reproducible: Customer is able to reproduce easily Steps to Reproduce: 1. User with appropriate roles gets `[security_exception] no permissions for [indices:data/read/field_caps]` message when accessing Kibana 2. Affected user's Kibana index is deleted and restored 3. Affected user is able to access Kibana without error 4. Days later, the issue occurs again, repeat steps Actual results: User indices continue to need to be deleted and restored, even in green status, in order for users to access Kibana without issues. Expected results: The Kibana user indices should not need to be deleted and restored originally, let alone multiple times, just for the issue to continue to reoccur Additional info: Adding customer specific details as private notes in BZ Consider asking them to try and access Kibana again and without 60s run the following script [1]. Clone the entire repo and execute with someone who has permissions to access Elasticsearch. This will show you the state of all permissions. * Is the user trying to access anything other then the discover tab? * What is their role? Can they see the default namespace? [1] What exactly is the user doing when they see this error? Is it trying to get access to their kibana index? Is it trying to query logs by using an index pattern? If so, please list the index-pattern What is user's role? Following is a diagram of how a user's role is determined, how the permissions are seeded [1] You might temporarily workaround this issue by: 1. exec into an es pod 2. edit sgconfig/sg_action_groups.yaml and add 'indices:data/read/field_caps' to the list for "INDEX_KIBANA" 3. reseed the permissions by 'es_seed_acl' If this resolves the issue we can modify it for release Received update from customer: ~~~ After working with Engineering, we shortened retention times and fine tuned some settings and did not see issues immediately after. When updating our environment, all changes were reset and issue was observed again. We need a solution/process to correct this that will either persist thru OCP version updates, or that can be automated against our environment after OCP version update. ~~~ "Working with Engineering" is referring to c#17. This worked, until an update, and everything was reset. Is there a way to achieve this goal that will persist through upgrades? (In reply to Greg Rodriguez II from comment #19) > Received update from customer: > > "Working with Engineering" is referring to c#17. This worked, until an > update, and everything was reset. Is there a way to achieve this goal that > will persist through upgrades? You say these issues occur after update which is when all permissions are reseeded. Did #c9 resolve the problem and it was only an issue after upgrade? This would make sense then because you are then reverting what is allowed and we should update to make the change permanent. It's easy enough to test by applying #c9, reseed, test and then reverting #c9, reseed, test; the problem would disappear and come back. Can they confirm? The might also consider accessing Kibana with a "private" browser to ensure they are not experiencing issues related to caching. The output doesn't answer my question from #c20. Does making the change and reseeding the permissions resolve the issue until the pods get restarted? Customer is requesting update. Has there been any further progress at this time? Are there any updates that can be provided regarding this issue? Customer is pushing for movement on this issue. Are there any updates that can be provided? Issue appears to hit a stand still. Are there any updates in this case? Customer is still affected and requesting to move forward. Customer is still impacted by this issue. Is there anything whatsoever that can be communicated to the customer regarding the status of this issue or workarounds? I'm not exactly sure where the idea originated that a user's kibana index is "corrupted" and needs to be removed and replaced in order to fix the problem. Ultimately I believe the issue relates to a user's oauth token expiring and possibly an unexpired cookie in the user's browser and the interplay between the two. We are currently working through some odd behavior for another customer related to addressing oauth tokens, cookie expiration and sign off which I believe may mitigate some of the frustrations user's experience. I have captured screen shots of behavior I see when my oauth token expires [1] on a 4.4 cluster which is the same logging stack. The first issue occurs by using the discover tab and allowing the browser to refresh until the token expires. The second issue occurs when navigating to the management tab, choosing an index pattern and then clicking the refresh button. You will note the last is the same error though it lists the kibana certs instead of the user. I was able to solve these issues by clicking the logout link in the upper right corner and then signing back in to get a new oauth token. * What is the user doing to retrieve logs? When they come back to Kibana at a "later" time are they asked to re-enter their credentials? * How much "later" do they see the error message occur? * What is the expiration time for tokens for the ocp cluster? * Have they tried accessing Kibana in a private browser to see if there is still an issue? * Have they tried to delete their browser cookies and do they still see the issue? [1] I also experimented with, after my token expires, closing the window, opening a new one and navigating to Kibana. I discovered the same error reported here related to field_caps and I resolved by signing_out and then signing back in again to refresh my oauth token. I'm asking our docs team to document this as a known issue as we are unlikely to resolve it because of the nature of Kibana. If signing back in resolves error and/or along with #c29, I am inclined to close this issue as WONTFIX Hello team, Several IBM Cloud Openshift customers are impacted by defect. But 1835396 has been closed as a duplicate of this issue. So would someone be able to give a status on this issue please? Thanks in advance. Brian. IBM Cloud Support. @Brian, Please ref . I don't believe this is an issue but user's needing to clear their browser cache @Jeff Cantrell is it just me but I cannot see c29 even after I logged in. Can you help me to find that comment? So to be clear, is just a Kibana issue? Have we confirmed that all log entries from fluentd are being stored in logstash ? @Jeff Cantrill Helo, Jeff, we have one of our customers also having the same issue on IBM Cloud IKS Version: 4.3.12_1520_openshift. Please investigate this further? 1. Configured the es but still failed. The procedure as below: a. exec into an es pod b. edit sgconfig/sg_action_groups.yaml and add 'indices:data/read/field_caps' to the list for "INDEX_KIBANA" c. reseed the permissions by 'es_seed_acl' 2. Cleared the browser and login the Kibana but still failed. Please see my comment #c33. I made the ref'd comment public and don't believe this to be a bug. Moving to UpcomingSprint Following comment 29, I can fix the Kibana permissions error by log out and log in. so move the bug to Verified. Note: The logout navigates to. but you couldn't log in via '. you must log in Kibana via ''. @grodrigu@redhat.com @brian_mckeown@ie.ibm.com, feel free to re-open this bug if you hit that again. and please provide the oauthaccesstoken too. you can get the token by 'oc get oauthaccesstoken|grep $username' (In reply to Devendra Kulkarni from comment #39) > Hello @Jeff and @Anping, > > For case 02629833, the issue still persists and reoccurs once in a week and > the only way to recover is to delete the kibana user index and then re-login. Please verify what the version and sha of the images the customer tested. I don't see where they would have had access to the image verified by QE as it was not added to the errata until after.
https://bugzilla.redhat.com/show_bug.cgi?id=1791837
CC-MAIN-2021-21
refinedweb
1,431
65.42
MBA admission help Ranked #10,097 in How-To, #102,177 overall How to win at the IIM and other MBA Group Discussion and Personal Interview The Topic for this GD is : It is HIGH TIME to make the Rupee Convertible 3 minutes to think 3 minutes to speak 3 chances to make an impression The MBA Group Discussion is a 3 minute Game CONTENT IS EVERYTHING - CAN U SPEAK CONFIDENTLY USING ECONOMIC CONCEPTS - IF NOT ....... GET THE FREE EBOOK ON Learn How to Speak in the Group Discussion using Economic concepts 3 secrets on identifying GD/PI topics for the IIM admission admission test for some time well in advance may already have started to read economic news and business magazines and may be more prepared than just the average novice. For such MBA candidates the level of preparation should now be towards identifying likely IIM Group Discussion topics. Here are 3 secrets for identifying likely IIM GD/PI topics: 1) Employment: Which sectors of the economy are adding most to employment and which are not. This will immediately point you into the direction of such hot sectors such as the retail trade sector and BPO. Now you should identify major issues related to these sectors 2) Resolved Disputes: How did a major argument get resolved- IIM's love such topics as they present good case studies. Identify how Mittal gained control of Arcelor Steel, how Tata finally nailed Corus, what prompted Jet airways to take over Sahara, what changes did BCCI introduce after Team India's dismal performance 3) Capital market changes- Business revolves around money. What are the changes being introduced that allows Corporate India to raise money domestically and abroad, identify changes in Indian bond markets, currency markets, stock exchanges, commodities exchanges. Try to determine how corporates are likely to benefit. For example a better bond market allows more Corporate Bond trading and encourages corporates to raise money domestically, or proposed Rupee exchange futures allows corporates to hedge their import requirements. As you can see; thinking contra may lead you to preparing for the very IIM GD/PI topics which you may cleverly prepare very well in advance. Continue to keep an eye out for such topics and you may find the MBA GD/PI topics to be smooth sailing. 2 surefire preparation tips on Abstract GD/PI topics admission test is determining the kind of preparation required for Abstract topics The problem with abstract topics is that you can say anything and nothing is wrong. So what exactly are you supposed to say and be tested upon. If you try to understand what the GD panel is trying to test you on you can perform better at the Abstract GD topics Here are some tips on preparing for an Abstract GD topics such as "Deeper shades of Black" 1) Add structure: The reasons why IIM's favour abstract topics is that business decisions do not present themselves as clear cut problems with identfiable methods of solution. So suppose you say -"ladies and gentlemen when companies are in profits the books are in the black, in that case then the latest Q4 financial results of corporate India display deeper shades of black- as the profits are up 47.36% as per the data in the newspaper Mint on 11 June 07" 2) Add clarity: You will be looked favourably upon for adding clarity for the other participants. So you could explain by saying "Ladies and Gentlemen - the term Deeper shades of black seem to imply that the issue is important as it has been marked distinctly and boldly - thus making it a point for immediate action. For example a quick glance of the daily news papers show how Inflation is always boldy mentioned across all newspaper headlines which underlies the importance of it to the economy in general. Using the above tips you can make the most Abstract of IIM GD/PI topics look like a simple and effective means of getting noticed favourably by the MBA Group Discussion and Personal Interview panel 3 methods to prepare for IIM GD/PI topics common admission test, it is time you began your preparation for the IIM GD/PI To begin your preparation use the following tips on identifying likely IIM GD/PI topics that may be asked 1) State of the Economy : Since you are the be a Master of BUSINESS administration it is crucial you have more than just working knowledge of the economy. List 10 aspects of the economy such as infrastructure, real estate, SEZ, retail, Agri commodities, etc and identify the 5 most important news items related to those 10 aspects to get started. 2) Major Disputes and Mergers: Keep a close eye out for any major trade disputes and failed merger attempts. These are always hot topics for the IIM MBA Group Discussion. For example the merger of Sahara Airlines with Jet airways or the dispute between the developing nations against the g7 conutries at the WTO trade meetings. Learn the 3 most important aspects of these issues 3) Stock market and commodities market: Unless you have been living under a rock you should know that India right now is hot property. Know the changes that are taking place in terms of improving the stock market, the growth of commodity exchanges in India and how introduction of hegde funds and liberalising foreign exchange controls will impact the markets. While all this may seem like a whole lot work, start by breaking down things into 10 aspects, then choose 5 from each and furthr break down into 3 points that you memorise. You will notice that you will learn a lot faster and retain better this way than simply reading 10 newspapers daily. Get FREE readymade Group Discussion strategies for IIM GD/PI topics that have appeared previously at the IIM Group Discussion and Personal Interview MBA Prepartion toolkit SUWELE-MBA 0 points New Orbitz! How to use Economic news for IIM GD/PI topics GD/PI round of admission test is a good understanding of the economy. Now you only need to know whats happening in the economy and dont have to be an expert at economics which is a separate field of study itself, unless you are a Commerce or Economics graduate. The most burning issue facing non Commerce candidates such as engineers and arts graduates is understanding the basic information of the economy. Here are some tips that may help. 1) Break down the economy: Prepare smart- thats the key. First break down the economy into its components. You can start by focussing on 15 topics - Construction, Exports, Foreign Exchange, Agriculture, etc...identify 3 topics from each 15 to get started 2) Dont immediately read the Editorial section: Most people choose to start by going into the heavy duty editorial section. That is best for those who have been following the issue for some time and already have a good idea of the issue. Start with your 45 chosen topics and skim through the newspapers to identify the 3 most lastest news related to that topics 3) Now you have 135 pieces of information on specific areas of the economy. Now all you need to do is prepare these 135 pieces of information and get a group of 5 people to conduct mock GD and Personal interviews. Ask your mom or dad to supervise to make it serious and add that element of pressure to perform well Strong preparation is the key to success in the IIM Group Discussion and Personal Interview, get started and you will gain the confidence on a vast number of the MBA GD/PI topics. MBA MBA Blogs - IIMs: Prometric bags $40 million deal to computerize CAT 2009 ... - Over 2 lakh students take up the CAT every year though only 1500 get admissions into the IIMs, makin... - Right time to join coaching inst. for CAT 2010 - TESTfunda Forums ... - TESTfunda Forums: Online Preparation for CAT, XAT, SNAP, FMS , JMET, IIFT for admissions to IIMs and... - Contradictory proverbs....Interesting ! - TESTfunda Forums: Online ... - Go Back, TESTfunda Forums: Online Preparation for CAT, XAT, SNAP, FMS , JMET, IIFT for admissions to... 3 reasons why GD/PI prep providers are useful Launcher, IMS, TIME, Ascent,PT Tutorials which provide written CAT test exam preparation and CAT GD/PI preparation. Which exam prep provider is the best is subject to your evaluation, however do you even need CAT GD/PI preparation when all you need to do is read newspapers and business magazines? 1) A mirror can't talk back: Preparing in front of a mirror can be deceptive. At the Group Discussion the participants may try to make your points look stupid, they will interrupt even before you finish your sentence, and they may speak so loudly that you can hardly hear yourself. 2) A stranger makes you nervous: If all you did was participate with freinds and family- then all you did was giggle and laugh. When the real deal comes, when engineers from IIT, toppers from St Stephens sit down with blood in their eyes- you will wince. Don't go with the notion that engineers are poor communicators, you will be disappointed thoroughly. 3) CAT GD/PI preparation providers give you a feel of all the above 2 weeks in advance. Nothing works better than real life testing, and actual competition from competing strangers. Because you don't have to be nice to them and can judge your mistakes objectively you will be in a better position to evaluate your likely performance at the actual IIM Group Discussion and Personal Interview. Examining your performance can help you make extra preparation and careful strategies to win at the IIM GD/PI . Use strategies based on Economic concepts for your CAT GD/PI topics preparation for best results MBA Marketing Management Marketing Management Amazon Price: $95.00 (as of 07/05/2009) Sales & Marketing Management Amazon Price: $48.00 (as of 07/05/2009) International Journal of Sport Management and Marketing Amazon Price: $1,138.17 (as of 07/05/2009) Marketing Management Journal Amazon Price: $35.00 (as of 07/05/2009) 3 mistakes to avoid on IIM CAT GD/PI preparation with GD/PI call letters in hand must have already started preparation for the IIM GD/PI in advance. While there is a lot of advice on what you should do, here are a list of things that you should not do when preparing for the MBA Group Discussion and Personal Interview. 1) Not timing yourself: Many candidates overlook this singular most important aspect. Its not just about a time limit to the overall Group Discussion but timing your repsonses to keep it curt and relevant. It is a fact that the average retention of the human mind is 2 minutes of what you said. Same applies to the GD panel 2) Manage your accent: Due to the diversity of the India and its regional languages, English is spoken with a regional touch. Be careful to get your phonetics correct and vowels easy to understand. Ask 5 people who don't like you to know how you really sound. Try and improve your best by listening to TV News broadcasters and emulate their accent and mannerism's of speaking. Remember embarrasment here is better than rejection at the IIM's 3) MBA Financial Management SAP SEM: Strategic Enterprise Management Official Certification Course Amazon Price: (as of 07/05/2009) Streetsmart Financial Basics for Nonprofit Managers Amazon Price: $26.73 (as of 07/05/2009) Retire Happy: What You Can Do Now to Guarantee a Great Retirement (USA TODAY/Nolo Series) Amazon Price: $14.99 (as of 07/05/2009) Hospitality Financial Managment Amazon Price: $50.51 (as of 07/05/2009) How to define your goals for the IIM Personal Interview achieve in life is the starting point of all Interview questions. It forms the basis for all other questions that will be asked in the IIM Personal Interview. For those of you who have just finished college, defining your goals is one of the toughest questions to deal with. Most college graduates are unsure of exactly how to determine what they want in life much less define their goals immediately. Here are a few pointers on how to define your Goals/Statement of Purpose: 1) Your goals must be measurable: Always define your SOP in terms of the achievement and how it is measured. Suppose your SOP is to create a career in Finance. Then be prepared to answer questions on: -Which field do you wish to enter in Finance, i.e. Investment Banking, Private Equity, Trade Finance? -What kind of qualifications and knowledge base is required to perform the activities particular to that field of Corporate Finance? - How does your undergraduate and graduate education augment your ability to stand out in that field of Corporate Finance? 2) Your goals must have a certain deadline: Always state the timeline by which you aim to achieve your goals. Suppose you want to enter in the field of Private Equity. Then state what kind of deals do you envision yourself performing 1 year from now, and 3 years from now? 3) What further steps are you taking for progressive realisation of your goals: Suppose you want to enter into the field of Investment Banking, then what are steps have you taken in addition to reach your goals? You could state that you intend to pursue CFA to further enhance your knowledge base suited to the specifics of Investment Banking Defining goals is hard work. The reason why we put it off is because when we decide to make any goals we are afraid of failing. So when you write your goals approach it with an attitude of having already achieved the goals. This will put you at ease and allow you to truly determine what you wish to do. Using the above guidelines will then allow you to further define your SOP for the IIM Personal Interview. How average students can win at the IIM Personal Interview literature about preparation for the IIM Personal interview questions . You must have noticed that all MBA Personal Interview questions state that having achievements and awards aid in the IIM Personal Interview process . However dont punish yourself mentally if the initial answers you write don't seem impressive enough. Keep practising
http://www.squidoo.com/win-iim-group-discussion-personal-interview
crawl-002
refinedweb
2,398
55.58
My .. Category : math I am sure about that there aren’t any mistakes in my class. I can’t give all codes because the program is big. The program is about radical numbers. Such as converting √8 to 2√2. I am going to use this class in my main python file. Here are the codes: def kokluyazdir(self,number): i = 1 .. I .. The Problem Statement is: You’ve to display the digits of a number. Take as input "n", the number for which digits have to be displayed. Print the digits of the number line-wise. #include<iostream> #include<cmath> using namespace std; int main(){ int n; cin>>n; int nod = 0; int temp = n; while(temp != 0){ temp = .. I implemented a CS paper to solve for geodesics on meshes. When I disable all optimizations I get exactly what I expect. If I enable optimizations however I get either NAN’s, infinity, or any number of weird results. I have checked all the stages of the algorithm and the error seems to happen on the .. I am currently working on a project for my Data Structures Course that involves a Binary Search Tree built using a doubly linked list-type format (where each node has a left, right, and parent pointer). The class managing the tree also has a root pointer and a current pointer (like a cursor). One of the .. I need to raise a fixed-point number to the third and fifth power, but the standard pow method doesn’t work. what to do in this situation Source: Windows Que.. Hey bro I need help to find prime numbers in to 10 Fibonacci numbers I mean between (0-1-1-2-3-5-8-13-21 -34). I think I should make two functions first for 10 Fibonacci numbers and second for how to find prime numbers and actually I know how to write them but how can I combine them??? (I need .. I am working on finding out the solution for problem 22 for project Euler in C++. This is the problem: Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this .. Recent Comments
https://windowsquestions.com/category/math/
CC-MAIN-2021-21
refinedweb
386
73.78
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Programming languages are ultimately interfaces for people to interact with the world of computational possibilities. In that backdrop, I've recently been interested in the influence of cognitive models on programming language design and would like to hear the thoughts of the tU community on the topic. I think the recent rise of DSLs warrants more research in this area. Past work has been largely populated by debates on completeness, compiling vs. interpreting, efficiency, dynamic vs. static, typed vs. untyped, parallel vs. sequential, distribution, designer idiosyncrasies and, not to mention, elegant vs. ugly. While I don't deny the importance of the debates, the only one that comes anywhere near the territory of cognitive models is this notion of "elegance", but that's (as far as I know) never dealt with formally. I see a few areas of work here - (Maybe others strike you.) For an example of (1), Drescher's schema building mechanism seems a very interesting angle to building interfaces to the world of computation. (see Made-up Minds) .. and it does look like people are trying to apply that approach to special areas. Production rules (grammars) are another category. Of course, one can't forget Prolog. AppleScript and Hypercard are simple examples of (2), 'cos they were intended to be usable by non-computer science folk and yet are powerful enough scripting languages. Elements of the language such as "tell ...", and "it" exploit our ability to refer to "at hand" and relative entities without much effort. The Logo world and, particularly, Scratch must be mentioned too. I myself got interested in this topic after I worked on adding "the" and "it" to my own scheme toy and found some cognitive modeling results such as working memory size useful in determining usage boundaries. (3) is interesting as part of the design iteration loop. Thots? --- Link summary (extracted from posts) - While programming may be a mental exercise, it is rarely an exercise completed by individual programmers on any non-trivial project. More important, I suspect, is designing to integrate the efforts of, say, ten-thousand programmers working on hundreds of projects that integrate in ad-hoc manners. When dealing with large groups of programmers and large codebases, it shouldn't be an error to model individual programmers as having narrowly scoped goals, very limited foresight and knowledge of the codebase, and a severe distaste for reading or modifying existing code except as necessary to tweak it for their own work. What language features would be useful in that hugely scaled environment? That's the question I think we should be answering. Because, whether we or our languages admit to it or not, that's already the environment in which most of us are working. I'm laboring on my own answer to the idea of a language scalable to support tens of thousands of concurrent programmers with interdependent projects, and I won't go too much into it here (don't want to sound like a brochure), but I think language and development environment design would do well to learn from existing large-scale projects like Wikipedia. While programming may be a mental exercise, it is rarely an exercise completed by individual programmers on any non-trivial project This is most definitely false. Programming is often performed in small groups of one or a few people, e.g., they are writing entire compilers, kernels, games, and so on mostly by themselves. A lot of non-trivial programs and libraries out there were written by one or a few people. If you want evidence, just look at most successful OOS projects, before they were popular, one or two people were behind them. In this case, programming is the mental exercise that dominates, and process is to the side (though still important). What you are talking about is software engineering, which tries to scale programming to larger projects and larger groups of people. In this case, process dominates, and programming becomes less important. Of course, when less effort is devoted to programming, less gets done, but what else can you do on large projects? I would argue that MOST of the programming performed is done by very small groups (often just one person), and therefore, studying programming in isolation of larger-scale software engineering is useful. Of course, software engineering is also important and useful to study. But they are really different things... A lot of non-trivial programs and libraries out there were written by one or a few people.. When these libraries, operating systems, and standards are upgraded, it influences the projects that utilize them. When you're looking at programming in the large, it is almost never performed by individuals. Projects are interdependent even when individual programmers have narrowly scoped goals. Programming is often performed in small groups of one or a few people, e.g., they are writing entire compilers, kernels, games, and so on mostly by themselves. If you want evidence, just look at most successful OOS projects, before they were popular, one or two people were behind them. I agree that successful projects often begin their existence written by individuals. But you won't find many successful kernels or games that never have more than a few people laboring on all the different pieces of them. What you are talking about is software engineering, which tries to scale programming to larger projects and larger groups of people. Well... not really. I don't really believe software engineering is about scale so much as it is about achieving predictable results (in terms of completion, quality, budget, etc.). That concerns of scale get involved with software engineering at all is just a side-effect of realities surrounding all (or nearly all) non-trivial programming projects.. Sometimes the little things matter, such as: Is source code named in hierarchical niches, or is it in a flat namespace? How confident can you feel in someone else's work and can you easily fix or upgrade it if necessary? How are the risks of malicious code injection controlled (security, etc)? Can you trust the optimizer, or will you need to do xyzzy yourself to do it right? If someone else has done what you need, can it be slightly tweaked to make it do what you need with minimal invasive change to the code? How 'fragile' are the language components under refactoring, feature addition, and forward compatibility? The design decisions we make when designing a language can be targeted towards individuals or towards groups, and it is certainly possible to achieve a balance of the two. Heavy support for extending the language with EBNF macros, for example, is something that favors individuals in the small scale, but groups could take advantage of it by standardizing and agreeing upon a few DSLs for, say, describing interactive scenegraphs for an object browser (e.g. something akin to Inform language). I would argue that MOST of the programming performed is done by very small groups (often just one person), and therefore, studying programming in isolation of larger-scale software engineering is useful. I would argue that MOST of programming involves combining stuff written by other people and, therefore, studying programming with the idea of mashups and project composition firmly in mind is even more useful. I'm not talking about disabling the individual programmer. The sort of social engineering decisions above would effectively allow individual programmers to be highly productive in spite of having narrowly scoped goals, limited foresight and knowledge of the codebase, and a distaste for learning more. Indeed, such individuals may 'feel' they completed useful projects on their own... but that would require the (erroneous) perspective that the libraries, systems, standards, and protocols they utilized were given to them by mother nature. When these libraries, operating systems, and standards are upgraded, it influences the projects that utilize them. When you're looking at programming in the large, it is almost never performed by individuals. Projects are interdependent even when individual programmers have narrowly scoped goals. Most programming tasks aren't so glamorous. You produce something that someone will never reuse, just for some task at hand. When you look at programming in terms of population and tasks, I'm sure that more solitary programming dominates. Even when you look at most programs out there, they were written initially by one or two people: Linux, Emacs, OmniGraffle, compilers for Ruby, Python, even Javac was written by a small team. There are very few projects out there with more than 10 programmers (say Windows) and when projects beyond a couple of programmers grow process dominates, and actually most of the people involved in the project aren't contributing much code. I agree that successful projects often begin their existence written by individuals. But you won't find many successful kernels or games that never have more than a few people laboring on all the different pieces of them. Yes, plenty. World of Goo comes to mind as a game, OmniGraffle comes to mind as an office-style application, kernels are a bit more difficult if you include drivers, but if you are just talking about the core kernel, I don't think the team of direct contributors to Linux is very big. Anyways, go through the applications that you use daily and I'm sure you'll find lots of examples.. Fair enough. My counter-argument is that you might miss because the problems with most large-scale projects don't occur at the programming level, rather they suffer from problems in project management, design requirements, communication, integration, and so on...I don't see how you can shove those things in a programming language, but if you could, that would be great. I would argue that MOST of programming involves combining stuff written by other people and, therefore, studying programming with the idea of mashups and project composition firmly in mind is even more useful. Ah, we all agree reuse and components are good. But the problem you are talking about is much harder: how do you get multiple programmers to work closely together on a project. Its easy enough to produce a library when the line of communication, coordination, collaboration between the producer and user is almost nil: the library better be well designed or the user will just skip it. There isn't much of a social process there. Anyways, I see what you are saying and wish you luck in looking at this. I'm just arguing against your premises, half the battle in research is just figuring out what the problem really is. Most programming tasks aren't so glamorous. You produce something that someone will never reuse, just for some task at hand. Agreed. But it is exactly in those situations where 'you' become the person reusing other things in order to accomplish the task at hand. Integrating components written by other people is a non-trivial, and ultimately social, task. By no means was World of Goo developed by just three people... not when you include the components, documentation, service, integration, etc. associated with use of Simple DirectMedial Layer, Open Dynamics Engine, XML and bug trackers and version control, font generation, etc. problems with most large-scale projects don't occur at the programming level, rather they suffer from problems in project management, design requirements, communication, integration, and so on... Well, I wouldn't say that problems with large-scale projects don't occur at the programming level. And I'd certainly consider 'integration' to be a programming-level problem. But I readily agree that solving just programming level problems would be far from sufficient to solve all problems. For technology-based support of software engineering, I think the better approach is to focus on enhancing features of the integrated development environment (including source version control, bug-tracking, feature-requests/user-stories, configuration management, quality assurance and testing, etc.). The enhancements or properties needed often don't make sense in the language proper, excepting that it'd be nice if all the IDE features were available in libraries. In the broader sense, more than just project management could be managed by such IDEs. One could support an economic model with technology as well... e.g. allowing people to pool or auction rewards and incentives towards achieving new features or greater optimizations and integration of open source technologies, and offering clouds or grids in which one can run active services (e.g. video game servers) at competitive rates. But the problem you are talking about is much harder: how do you get multiple programmers to work closely together on a project. That's not the problem I'm concerned with. Small cliques of programmers will form naturally without any special language or IDE design efforts. Besides, if I wanted to 'force' people to 'work closely' with one another, I'd actually have a reverse policy... similar to how locking files in a version control system can 'force' you to go meet people you'd otherwise rarely go see, simply because they forgot to unlock a file. Rather, the important question is a slight (but significant) variation: how do I support integration and enhancement in a system where individuals and small cliques are mostly acting on their own individual interests? I.e. what I want is cooperation as an emergent behavior, not as a required one. I do have answers (maybe even correct ones) to this question, both for integrating and enhancing active services (which supports closed source services) and supporting cross-project integration, enhancement, and refactoring work in an open source arena. While I don't assume malice is common (I couldn't find answers for a largely byzantine environment) I also have answers for many relevant security, resource management, and privacy concerns. half the battle in research is just figuring out what the problem really is Indeed. I've been working on it for seven years now. I can't say with certainty I have the problem right, but I can say I've given it a lot of thought, observation, hypothesis and testing. I'm reasonably confident I have the problem right, and that the problem is not in any significant sense cognitive models in the small scale of individual programmers. "How well does the language support integrating stuff other people write?" is, I believe, a far more relevant question than "How well does the language support the individual mind?" Frameworks and libraries won't take you very far if it becomes a combinatorial hassle to put more than two of them together (e.g. due to mutex management, diverse memory management, safety issues, inability to tweak them a bit them prior to integration, etc.). what I want is cooperation as an emergent behavior It sounds like you're talking about cooperation in the positive sense - that people accommodate each other, work with each other, etc. It might be worth expanding that to *all* co-operation to include disagreements, fist fights, whatever. (a) "How well does the language support integrating stuff other people write?" is, I believe, a far more relevant question than (b) "How well does the language support the individual mind?" I've not thought much on this topic, but my gut feel is that the two aspects you mention are intertwined - in ways that we probably don't understand quite well yet. For example, it seems to make sense to ask the question "how does the language support *me* integrating stuff that I developed in the past?". Is that (a) or (b)? Design-wise, it probably has the same issues as (a), but cognition-wise it seems more like (b). It sounds like you're talking about cooperation in the positive sense - that people accommodate each other, work with each other, etc. It might be worth expanding that to *all* co-operation to include disagreements, fist fights, whatever. I would suggest that, as much as possible, the design of the language should be aimed towards positive cooperation and avoiding conflict. But I do agree that support for working in spite of disagreements and resolving disagreements should be included in the language and IDE design. the two aspects you mention are intertwined Likely, yes. But the degree to which two questions are intertwined or correlated is also the degree to which answering one question provides also an answer to the other. Thus, the more intertwined, the less any potential penalty for ignoring the other question.. If you integrate a library written by other people, your project has now been written by multiple people. If your project uses open standards and protocols designed by many people, your project has now been written by multiple people. and if I might add - you're probably using a programming language designed by other people :) And that language is also among those things that will change over time. To spoil an old joke, there's a great difference between "standing on the shoulders of giants" and "stepping on each others' toes". It seems that your discussion of "social modeling and engineering" is blurring the distinction between three modes of programming that I experience in different ways: 1) consumer - a "lone wolf" programmer who is (by definition) using languages, libraries, etc. created by others, but who is treating them as artifacts of nature simply to be used as they are, while she/he pursues a private agenda. The interaction pattern is read-only. The self-description might be, "If I find something useful, I'll use it; otherwise, I'll write it myself." 2) producer - a programmer (lone or otherwise) who is creating a language, library, etc. that will / may be used by others, but with an agenda not driven by their requirements/feedback. The interaction pattern is write-only. The self-description might be, "I'm writing this for my purposes. If someone else finds it useful, they're welcome to it; otherwise, they should look elsewhere." 3) collaborator - a programmer who is working concurrently and interactively with other programmers on a project shaped by their varying goals and contributions. The interaction pattern is iterative read/write. The self-description might be, "We're working together -- at least for the moment -- on something that won't happen without the accumulated contributions. We'll have to negotiate and compromise as we go." I'm not trying to propose a taxonomy, but looking to emphasize the difference between no-man-is-an-island generalities and "real" social and cooperative development, as a matter of the individual's orientation and attitude toward others. To switch metaphors, I may prepare my solitary breakfast (with the implicit recognition that other people existed, such as the farmer who grew the oats), but that's a radically different process from collectively preparing a family holiday dinner in real-time with a kitchen full of others. (And that, in turn, is different than operating a communal kitchen for a festival event with a population of thousands.) It would seem to me that there's an entire range of issues (packaging, portioning, utensil design, room layout, etc.) that will be different among these extremes. Are you suggesting that there are language design issues that benefit all of the cases of the "lone wolf" programmer, the small in-house development team, and the loosely-coupled open source project? language design issues that benefit all of the cases of the "lone wolf" programmer, the small in-house development team, and the loosely-coupled open source project? Well, every language design issue affects people driven by the various incentives you name, and given the range of language design decisions one should be extremely surprised if there weren't some language design decisions (and especially combinations thereof) that benefit all three. But we shouldn't restrict ourselves to design decisions that benefit all classes of work; it is more that we should find alternatives to combinations of design decisions for which there is justifiable reason to believe it might significantly hinder those operating under any particular incentive. Anyhow, consider a slight variation in the user stories: 1) consumer - a "lone wolf" programmer who is integrating frameworks, libraries, macro DSLs, etc. into a product (potentially intended to be a one-off product), and who is likely bumping into and resolving issues to make the integration possible. Sometimes, the lone wolf will discover it easier to fix issues in their source rather than work around them in his own (especially if said lone wolf bumps into the problems in more than one project), and so the lone wolf would often like the ability to commit framework/library tweaks (even for one-off products). For long term products, issues of maintenance further motivate the ability to push changes. This lone wolf also might have no particular concerns about sharing his/her product (i.e. it doesn't contain anything private) especially if it means (a) ability to work on it directly in a public wiki-style repository from any javascript-enabled browser from any network-enabled computer and if (b) there is a culture such that when other producers update the stuff they wrote (e.g. refactoring names, API, generalizing something, etc.) they'll fix the lone wolf's public code too. Pure self-interest motivates refactoring/tweaking/sharing. Language design decisions to aide the lone wolf includes especially support (a) for dependency injection, such that the lone wolf can modify a library to change an internal component based on an external provision, then set the default for said component to whatever the original value happened to be, (b) for injecting default parameters, such that the lone wolf can add a new parameter to a function without needing to modify other people's code. 2) producer - a programmer creates a library or framework for his own project, not particularly concerned about how others use, not particularly interested in reading or understanding or learning about existing projects that solve the same goal. Pattern is write-only, reinvention rather than reuse. We can presume the producer often doesn't care whether other people modify the product so long as said modifications don't cause runtime bloat, inefficiencies, or break anything in his own product. Producers concerned about forwards compatibility of their product among users benefit if they can make changes to, say, the API of their project then simply find all users in the public repository and push changes to them. This would be similar in concept to making a change to GNU Math and pushing the API update through to every user of GNU Math on all of SourceForge. Other people than the producer may also go through and fix such things (wiki-gnoming supported by unit tests?). Others will tweak for integration, modify, refactor away duplicated efforts (e.g. "yet another implementation of ackermann function" (as a highly contrived example)), etc. If concerned about toes being stepped upon, the producer may choose to keep a private version of the project in a private repository that inherits (in distributed version control fashion) from a public repository. With DVC this allows cherry-picking of changes made to his/her work, and allows pushing of updates he/she makes. If feeling lazy, the producer may simply allow others to pull from his private repository and cherry-pick/push changes to the public one themselves. Maintenance of a private repository is the common case today. The life of a producer is, thus, no worse than it is today, and is possibly much better... especially so if the library/framework/etc. utilizes other libraries, or if the producer isn't the sort of masochistic genius programmer who has and applies the foresight such that the resulting product is 'perfect'. As a producer, I would be more willing to have my code modified or references to external code added if the language provides whole-program and partial-evaluation optimizations such that tweaks like adding parameters to functions doesn't bloat the code for fixed parameters, and referencing other pages doesn't introduce need for more separately compiled components. (The benefits associated with separate compilation can readily be achieved by other vectors.) I'm also less likely to have problems if such changes can be guaranteed to not introduce concurrency (deadlock, safety) and security concerns. 3) collaborator - actively communicating programmers aiming to achieve a product that resolves cross-cutting concerns. Example products would be a robot command+control protocol, or a graphics library, or a common scene graph system for a virtual world interconnect. We can presume collaborators include consumers who each have motivations pushing for certain changes or additions, along with producers who actually know enough to really make the changes but lack the resources to try all of them. Distributed version control and public repositories help a great deal for collaborators that are willing to participate in it. All collaborators are aided if it is easy to branch the whole system, try a change, integrate it, and test the integration. and commit it back if it produces the desired effect and all the unit and integration tests pass. Consumer collaborators thus have an easier time operating as producers of the system, and producer collaborators have greater access to a testbed. If the public repository can include a class of 'tests' that are run every time dependencies change and alert the appropriate individuals of the failure, so much the better. Language design decisions that aid the collaborators include first-class support for service configurations, such that they can be abstracted, fired up and tested, instantiated with references too the real world to get real services running, etc. in addition to support for confinement so that such tests don't interact with the 'real' world, and support for overriding aspects of processes such that, for example, the state inside a process/actor can be replaced with a reference to a database allowing systematic observations and unit/integration testing. ------------- Of course, all this doesn't touch on other classes of users such as those with continuously running services, and those who wish to upgrade clients and services at runtime without touching the code with which said clients or services are written. There are language design decisions that help these guys a lot, too, including support for automatic distribution of code (so clients can put agents near services and vice versa), security, recognition of relative levels of distrust, and support for arbitrary distributed transactions (which allows ad-hoc composition of protocols and services without introducing race conditions). Here's where there is a lot of room for a curious researcher, in my opinion. You guys have a good back and forth about 'individuals', but wouldn't it be interesting to do a survey to see what sorts of social programming models prevail? You could look at how much code is written by how many people, and in groups, what the distribution is like. You could look at the influence (or rather, correlation) of languages on those numbers. On language scalability: I think the true measure of a language's "scalability" in most cases is the range it can handle, not the absolute high end. In other words, a language might be well suited to 10,000 person projects, but if it's no good for whipping up something quick, it has a limited range. I'd rather use a language that is good for a quick hack, and still performs ok at the huge project, even if not quite as well as the one that only works for huge projects. Good idea, but the caveat I would add is that looking at what large groups use is naturally going to select against obscure languages and models, even if they are perfectly well suited to large projects involving many developers. Similarly, PHP is a very popular language for large group projects, but I doubt it really has any real technical advantages in that setting... I was referring more to technical aspects rather than 'social' aspects such as how popular a language already is. Something like Java seems to be popular for large projects, and reasonably good at it, in that it enforces some barriers. It's not so good at smaller, nimbler things, and often requires more boilerplate just to get started doing something (at least that has been my experience). Something like Ruby, on the other hand, might be great for smaller projects, and still work ok for bigger ones, although of course if people start doing lots of "monkey patching" type activities, that could quickly sink a larger project in a hurry. When "whipping up something quick" or performing a "quick hack", is it not usually the case that you are, in actuality, composing and enhancing services built already by other people? If so, does that not require scalability of the language, such that hooking together services and frameworks and such to produce new ones can be performed without gotchas or considerable effort? If it takes a great deal of care or knowledge to combine services and frameworks safely, without deadlock, without error, and without sacrificing performance, then the language is not upwards scalable because composition of services will need to be "shallow" to be successful. Except in the case where one is building a new project using only the 'core' language features, "Quick hack" projects benefit primarily from the high-end form of scalability. And, while I do believe the ability to write up a quick functions and vocabulary from scratch is useful, I will happily sacrifice it in favor of shaping the language such that the path of least resistance encourages everyone to code in a manner that automatically supports safe, efficient, flexible, and comprehensible project composition. That said, I don't tolerate boiler-plate. The need for boiler-plate code greatly resists scalability. Definitely an interesting angle on the problem, though I wouldn't rule out the significance of individual programming effort as a "rare" thing. For one thing, I do a *lot* of "individual programming" :) .. but even there, my style and preferences have been recursively honed by my exposure to the work of the community. So, programmer development as a consequence of programmer-community interaction is probably the way to look at it. Vygotsky's social development theory is relevant I think. Saying you built your house all on your own doesn't give proper credit to those who paved the roads, built your truck, trimmed your lumber, and gave you some power tools. But, also relevantly, it doesn't give the necessary credit to how your needs, and those of others like you, shaped the very industry that gives you lumber and power tools. People who do "individual programming" are very, very rare. People who think they do "individual programming" are very, very common. What we call "individual" is usually a social dynamic of "implicit emergent cooperation". Distinguishing between these should be useful when making design decisions for IDEs and languages, especially with regards to sharing access to projects. Forgive my ignorance, but it seems this model relegates "individual programming" not to rarity but full extinction. Is there an example of someone, real or imaginary, who has constructed a program without the assistance of any human, that is, someone who is an "individual programmer" under the given model? Is there an example of someone, real or imaginary, who has constructed a program without the assistance of any human I'd include among such people those that built their own circuit boards. But one could also recognize degrees to which a project revolves around individual programmers in a non-binary sense. I would, to a lesser degree, include those that write assembler, write original drivers, certainly the dude who wrote Synthesis OS. To an even lesser degree, I would include those who use a 'pure' higher level language and compiler in a manner suitable for writing an OS from scratch (no libraries beyond the standard, no integration with an existing OS). This would also include many various 'trivial' projects of the sort you might see when learning Haskell, Scheme, or C in school, where use of libraries is often forbidden because you're learning how to write your own linked lists. this model relegates "individual programming" not to rarity but full extinction. The problem isn't with the definition, but with the fact that "individual programming" really is near full extinction, and has been moving steadily closer to it. If it survives today, it's in embedded systems and sometimes due to bad lessons taught to beginning students in programming about their role as programmers (sometimes they come out of school feeling they really need to write their own linked lists...). We should recognize this, call it a good thing, not elevate the status of the individual programmer based on illusion or egotistical desire. Right now, despite the fact that individually developed programs are rare for anything more than school exercises, (1) programmers are still treated by IDEs as gatekeepers, masters of a domain for individual projects, (2) language projects aren't designed to integrate naturally, makefiles are problematic, name conflicts abound if just tossing code together due to the heavy use of hierarchy, code is often copied from project to project. Our tools should treat the programmer and the code as they are: elements in an interactive and reactive society. This actually empowers 'individual' programmers by giving them more power to utilize, update, refactor, and document code written initially for projects other than their own. There is no cost in terms of IP when code needs to be protected... even within a company, one could inherit code from an OS arena using distributed version control then separately add and manage private code, making it easy for different project teams working on different projects to share and integrate (and even support pushing some enhancements back to the OS arena). Even without sharing one's own project, access to other projects, of recognition that code is a social effort that is mostly about integrating existing libraries, plus the language features necessary to make it practical (i.e. integration w/o makefiles and complicated build routines, ability to write libraries usable and optimized without boilerplate code, support for automatic and continuous unit testing, ability to be alerted of updates to certain pages, etc.) would offer considerable advantage. You can do "individual programming" by just thinking. Maybe you can use paper/pencil/whiteboard as the next step... ok maybe you use a word processor. Hmmm... why not an IDE then. .... but you're surely "running" your programs in your head, so you don't really need a computer, do you .... It is definitely individual cognition. Nevertheless, it has been shaped by interactions with the society as well. That's why I think both points of view have to be considered. It is not possible to isolate them or say one is more important than the other. Each is impossible without the other. People who do "individual programming" are very, very rare. People who think they do "individual programming" are very, very common. No way to verify such a statistic, but your statement surely implies the phenomenal success all programming languages to date have achieved w.r.t. collaboration :) What it explains today is DLL hell, the headaches we go through with frameworks and associated boilerplate code, serious challenges to share structured data between processes, deadlock concerns, the difficulty we experience when integrating shared libraries, etc. Because, with few exceptions, what we have today is minimal support for collaboration hacked in atop languages and IDEs and Operating Systems each designed with the idea of the individual programmer in mind. If you've not already come across it then the work of Chris Barker may be quite interesting to you. He has published several papers on the links between natural languages and formal languages. In particular he gave a keynote at POPL this year called Wild Control operators that seems to touch on points (2) and (3). I can't really offer you much detail to describe it, as it is somewhat outside of my area, but if you treat the semantics of natural languages as implementations of cognitive models then his work would be right in the middle of the area that you are asking about. There are several posters on Lambda who know his work far better than I do who could maybe give an explanation... Thanks. I didn't know about Chris Barker's work. I skimmed the wild control operators popl abstract and it seemed to be about probing the formalism of natural language. I was expecting the other direction - picking operators in natural language and bringing them over to formal languages ... which, however, begs the question, do end-user programming languages *have* to be formal? do end-user programming languages *have* to be formal? Well, something needs to interpret them, right? But perhaps one could focus on 'best guesses' and 'heuristic interpretations' and varying interpretations based on runtime observations (e.g. "kick the dog" would need to interpret "the dog" and "kick" appropriately based on whether the avatar is sitting, standing, where a dog is, whether you're more likely referencing the one in a woman's arms or the one on the ground (even if the one in the woman's arms is closer, etc.) I suspect an 'informal' language could be good for AI, describing scene-graphs or skits for 3D characters, scripted behaviors. However, even Inform language has a formal interpretation. Still, it's worth looking up. Thanks for the link to Inform. I understand what you mean. In fact, I'm finding it difficult to declare something as informal as long as it has a computer implementation :) You hit a nerve on the "varying interpretations based on runtime observations" point. We (as people) do that all the time, yet very few programming languages (if any) exploit that. I like Drescher's schema building approach for that reason. The axiom of formality for langauges: The degree to which a language is formal, is the degree to which the language and its semantics/results/side-effects/abstract-interpretation is: Put differently, IF you want your language's semantics to be well-defined and simple (from a reductionist perspective), THEN you will want your language to have an interpretation that can be formally treated. The difference between a programming langauge and a formal language: Programming languages have intrinsic resource-usage "semantics" (i.e. memory and time resources, and possibly other kinds of resources), while formal language EITHER don't, OR they run on machines that are abstract or do not have physical limitations. Isn't the definition of formality something like - "whose specification does not depend on anything outside the system."? That definition doesn't even make sense to me. I assume you know what symbol grounding is. Isn't it the role of all languages to ground some aspects of some external phenomena within a system of symbolic expressions which represent/denote those phenomena? No langauge is useful unless it is grounded, or applied (i.e. it is interpreted w.r.t a mapping from expressions to external phenomena). Once we ground a language, then it can be useful. From my experience, formality means (or implies?) that a language conforms, strictly, to a set of hard-and-fast rules. Of course, this definition is tentative. In retrospect, I have a hunch I've misunderstood what you mean. If this is correct, what do you mean by "outside the system"? that a language conforms, strictly, to a set of hard-and-fast rules That's in the spirit of what I wanted to say. A formal system can be specified purely mechanically, without any mention of "use" or "connection to the real world" or anything of that kind ... with almost an attitude of "if you find a use for it, that's your problem". That should resonate with how some mathematicians approach number theory, for instance. More formally (;-P) - a formal system is a set of postulates and a set of procedures or "rules" to derive "truths" from postulates and/or other "truths" of the formal system. You are forbidden from invoking any "rule" *outside* of the formal system in order to infer "truths". When applied to languages, I understand non-formality to mean that I can write expressions in the language that depend on the interpreter (the thing that connects the language to the world) for truth or falsehood - i.e. the set of postulates and rules I'm willing to write down for the symbols of the language are intentionally insufficient to express the kind of "truths" I'm interested in. Program-level integration These things all take the philosophy that the best way to make things reusable is by encapsulating their implementation behind a process wall, and by providing a standard system under which the processes can all be fully orchestrated. Another option: I'm surprised nobody's caught on to "Documentation--by-Contract"! Have you ever noticed how there is a rigid structure to typical API documentations (at least, the way Microsoft documents their APIs) that could be formalized?! Documentation specifies the semantics of: valid parameters, return values, invocation side-effects, etc. I'm sure there's something to be gained from this idea. Formal specifications are rigid, less ambiguous, and best of all, much briefer (not to mention their amenability to automated formal analysis). SOA, COM/DCOM, Unix Pipes and such only encapsulate part of the implementation. In particular, data representation, protocol, and contract cannot be encapsulated. To compose these systems easily requires a great deal of support for integrating at the communications boundaries, which often involves sharing source. As designs go, the SOA and dataflow approaches seem pretty solid... they still need a few enhancements to support security, secrecy, disruption tolerance, failover redundancy, graceful degradation, level of detail, ad-hoc cross-service transactions for service mashups, etc. Support for automatic distribution would allow parts of a composed service to automatically float over to wherever they need to be to optimize latencies and bandwidth. Just a few piddling trifles. ^_^ For source-layer and cross-process optimization, there are additional issues. By transporting messages in shared memory, one can avoid two payments for data translation. Given shared source (or high enough level bytecode), one can potentially inline the necessary aspects of the intermediate processes and services... and automatically duplicate the relevant bits when automatically distributing a multi-part service configuration. Due to the possible optimizations, users in SOA and Unix pipe systems, and to a lesser degree COM/DCOM systems, programmers are reasonably torn between reproducing efforts for efficiency and doing the simple thing. It is better if this pressure is avoided. Wherever possible, instead of encapsulating source and using separate compilation, share the source and support whole-system optimizations. This can be achieved with first-class dataflow pipes or process-calculi/actors-model based service configurations but not (in general) Unix pipes or SOA. Compile-time safety for data representation (plus possibly protocol and, stretching a bit, contract) would be icing on the multi-service cake. I'm surprised nobody's caught on to "Documentation--by-Contract"! Have you ever noticed how there is a rigid structure to typical API documentations (at least, the way Microsoft documents their APIs) that could be formalized?! More than a few people have noticed. I'm a believer in the idea that "anything that goes in a comment should really be automatically verified". However, in practice, there are limits to what we can check or test. In any case, I'd suggest having languages support a formal system of annotations and an extensible syntax to include said annotations. Then allow users to process the AST including these annotations using tools they build. The same system can be used to offer suggestions to the optimizer. You might be interested in Microsoft's CodeContracts being released for .NET 4.0. Thanks for the suggestion. Microsoft uses preconditions, postconditions, and invariants to aide with runtime debugging and manages partial static verification. Such an approach seems a good one for verifying certain classes of comments. Type and Category theory only takes you so far. You need to "skin" it. The future is tools and interactive systems. There's a gal at Sun that has talked about this (sorry can't find her writings). Would that be Cristina Cifuentes by any chance? It sounds like a quote from a talk on Parfait. I'm a psychology student at the University of Washington and the way in which programming languages influence the problem space in the mind of the programmer is one of my main interest areas (I'm also a professional programmer). I recently completed a paper exploring the idea a bit that folks may find interesting (or not :P). If nothing else, I believe it demonstrates a possible approach to the study of this matter on the scale of the individual (doesn't tie to the social issues people have surfaced here). It's at the undergrad level so there was no lit. review etc. I had to hash it out from conception to completion in less than a month, but it's a start. Semantic Organization of Programming Language Concepts To add my two cents to the individual versus social debate, a social context is in fact a collection of individual minds so in my opinion we would need to start there. However, there are emergent properties that arise from the interaction of the individuals, which are aspects not present at the individual scale. Those emergent properties need to be identified and addressed as well. Perhaps these are two reasonably separable topics. Setting aside all the usual critiques one might make (insufficient sample size, etc.) about your study, I want to zero in on the central premise: that the clustering of words elicited correlates to the semantic model of the domain. Rather than assume this, would it not be simpler to assume that different styles of programming have different communities with different associated jargons? For example, the jargon use of the word "prime" in your paper is idiosyncratic to the literature of psychology. I would predict that someone who was a psychologist and a mathematician who was "primed" with either psychology or math tasks would show different associations with the word "prime". I wouldn't expect this to tell me anything about how they actually think about either discipline. The concern regarding the assumption that the clustering of terms is related to how one would actually apply those concepts in a problem solving situation is certainly warranted. The key inference made with models like this is that related terms mentioned in response to a cue term are likely to be the ones the participants would also consider when working an actual problem, reasoning, drawing analogies, etc. This hits the classic problem of lab vs. nature and whether or not the findings are still valid outside the lab. However, there's a fair amount of literature on these kinds models with respect to novice vs expert comparisons and cognitive changes due to disease, etc. Setting aside all the usual critiques one might make (insufficient sample size, etc.) about your study, I want to zero in on the central premise: that the clustering of words elicited correlates to the semantic model of the domain. [Whoops, should've read the article first..] Got it right though: this is an assumption, mostly proven, which is used by most linguists. this is an assumption, mostly proven, which is used by most linguists. I can only humbly suggest that either you are over-simplifying or that you lack any familiarity with the field of linguistics as a whole. This technique is widely accepted as a basis for psychology and pycholinguistic (a specific sub-discipline of linguistics) experiments. However, to say that it is "mostly proven" is very arguable. I think it tends more to be a case of lack of better techniques for dealing with a tricky area. ... that I am laughing my head of, right now? Given what I know, his definition of a domain/semantic model is as good as any; and surely good enough for investigation. Do you believe the point you raised is that relevant? But, ok, if you are the expert, feel free to discuss. I liked what he did. You should really ask someone like Oleg to draw a domain model ;-). This site needs greater participation from people interested in more than programming languages themselves. I've been trying to get one of my best friends, a geologist and an avid R programmer, to consider participating occassionally, as I think a lot of people here would be interested to hear what he has to say. :-) I'm a bit skeptical of your methodology as well, but I think Marc's carping is somewhat unfair. My bigger complaint would be "just three programmers?!" Here is an anecdotal, though possibly useful insight into functional programmer psychology: I have to admit my first impression of pkhuong's code was the exact same as Qrczak's and Winheim's. And Winheim even had the benefit of seeing somebody else make the same mistake... so I suspect the code tricked a lot of functional programmers reading it, not just us three. I think that the monad do-notation might be a useful case study. I have an intuition to match a for-loop (in C, say) or recursion or pattern-matching or any number of constructs. But I am struggling to get one to handle do-notation. The problem is that each monad reduces to its own very special form. Consider this expression, which is close to something I came across on the web: do x := t u return (g x) -- (1) Define the ST type: type ST a = a -> (a,Int) Define return and bind for that type. Now, take (1), desugarise, replace bind and return, reduce and I get: \r -> (g (value (t r)), state (u (state (t r)))) --(2) where state and value extract the state from a pair and the value from a pair by state = snd and value = fst. Do the same process in the list monad, starting with a modified version because I prefer to call lists l and m: do x := l m return (g x) -- (1) and I get this: concat ( fmap (\x -> (concat ( fmap (\_ -> [g x]) m ) )) l) --(3) OK, so I see that there is an analogy here between 'list shape' and 'state transformer', and in each case the thing in question is being used to apply a basic function, g. There are still differences: the state transformer doesn't treat state separately from the value, the state interacts with generating the value. In the list shape, the shape introduced by m doesn't have the same interaction with the value. I suppose that that sort of interaction might be seen if the shape monad related to tensors,where there would be interaction between off-diagonal elements. But back to the notation: wherever I see an expression in do-notation or bind-notation, I can only, so far, understand it if I have first taken an example such as (1) and converted it into the equivalent of (2) or (3). This feels similar to interpreting obfuscated code, where the initial statement of the code cannot be understood until some transformations have been applied. do-notation and bind-notation emphasise sequence but there is much more to a monad that that. Monads, ignoring the IO monad as an exceptional case, are no less functional than any other part of haskell. In evidence of that, let me just observe that wherever there is a monad, there is also some function of the form extract :: Monad m => m a -> a. Part of the problem here is that monads abstract over a class of exactly such intuitions. So in some sense you'll never get "an intuition" for monads. That's the whole point! However, you can develop an intuition for exactly which intuitions are monadic. ;) In evidence of that, let me just observe that wherever there is a monad, there is also some function of the form extract :: Monad m => m a -> a In evidence of that, let me just observe that wherever there is a monad, there is also some function of the form extract :: Monad m => m a -> a Incidentally, this is not true. For a counter-example, consider the list monad mentioned in the parent. Also, the 'ST a' presented should I assume be Int -> (a, Int). Yeah, you need a generalisation to account for things like error monads where you genuinely might not have an answer. Not to mention IO-wrapper monads and the like. You can kinda cover the IO-wrapper case by saying the IO monad is the 'host' language rather than Haskell, though. ... on both counts. Matt and Phillipa also make good points here. Saying something is a monad really isn't saying much at all, so you usually can't get much of an intuition for what a bit of code does just by virtue of the fact it has a monadic interface. As for how to understand monads, it takes work, and time. My suggestion is simply to get familiar with *lots* of different examples of monads, preferably some advanced examples as well. I've been considering trying my hand at an advanced monad tutorial, that includes some of the most interesting (and in-depth) examples of monadic abstractions I'm aware of. Monads are useful as a standard kind of construct, that enables you to express a surprising variety of things. And since they can express almost anything, it's hardly surprising that they offer very little insight into anything in particular. The notation really does show you what's going on in general, though in a rather abstract way. Bind corresponds to a single-variable ML-style let, and do notation to a sequence of them ending in a result. What you don't have is a fixed evaluation order for it. In fact you don't even have guaranteed determinism for it - the list monad effectively gives this little language a non-deterministic interpretation. To simplify: monads are about binding. This includes binding and using other computations. See Wadler's comprehending monads for an alternative notation over monads based on list comprehensions so your examples would look something like [g x | x <- t, u] In Scala your examples look like for { x <- t _ <- u } yield g(x) And in C#'s LINQ from x in t from temp in u select g(x) Honestly I think these notations do a better job than "do" for guiding intuition on some kinds of monad but do significantly worse for most, especially for those that aren't particularly collection like. Thanks to everyone for these points. I hope to get a firmer grip on monads over time. I did raise the idea more on the basis that a cognitive model of 'do' might be a useful thing to have, rather than seeking advice on my own deficiencies, useful though that has been. Some of the responses suggest that 'do' might not be a good candidate for the question of such a model. Anyhow, thanks for the discussion.
http://lambda-the-ultimate.org/node/3229
CC-MAIN-2022-40
refinedweb
9,244
50.87
Django for Designers/Adding models Part 3: Models and our database Remember to make a new branch for section 3 based off the official branch! # in django-for-designers/myproject $ git branch my-branch-3 origin/pre-part-3 $ git checkout my-branch-3 Okay, being able to design your URLs however you want, without them having to correspond to your actual file structure, is pretty neat. But besides that, we haven't done anything yet that you couldn't do with just HTML, CSS, and JavaScript. Time to fix that. One key thing that separates web apps from web pages is that apps typically store data somewhere. The code that runs the app chooses what data seems most important to show at the moment. When writing an app using Django, we configure the storage through Django models. Every Django app comes with a models.py in which you list each kind of data you want to store. These are configured through Python classes (to name the kind of data) with a sequence of attributes (which control the pieces of data that make up the model). If you're familiar with, or interested in, SQL, these correspond to tables and columns respectively. The models that you define here are built on top of Django's object-relational mapper, or ORM. Because you define your models as Python objects, you can effectively write queries against a relational database by instead coding in Python with reference to your objects. Django then maps your Python code into relational database queries in SQL.By configuring your data access in Python, Django makes it easy to take advantage of your data layout in other places. For example, you'll see later how the ORM makes it easy to automatically generate forms that ask for exactly the information you need. It is also generally convenient to write your entire app in one language, rather than being required to switch to SQL to do queries. The ORM also handles "escaping," which makes your SQL queries handle Unicode and other strange characters properly. These conveniences let you avoid mojibake-style data corruption and SQL injection attacks effortlessly. Creating a basic model Let's make it so we can store some real live data in our application! In our simple bookmarking app, we’ll create two models: Bookmarks and Tags. What information do we need to store about these objects? A bookmark has: - A URL - A title (optionally) - A timestamp for when the bookmark was made A tag has: - The tag slug/name A tag also needs to know which bookmarks it applies to. Open up bookmarks/models.py in your editor. from django.db import models class Bookmark(models.Model): url = models.URLField() timestamp = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=200, blank=True, default="") - We've made a Bookmark class that inherits from Django's model class. - We gave it a url, which is a URLField (a field that expects a string that parses as a valid URL). - We gave it a timestamp, which is a DateTimeField (a field that expects a Python datetime object). auto_now_add means that the field will automatically set itself to the time when the model is created. - Finally, we gave it a title, which is a CharField (a field that expects a string of some length or less, in this case less than 200 characters). "blank=True" means that Django will permit this field to be blank. We also set a default of the empty string, so that if someone fails to specify a title we permit that. Now let's add a tag model! In the same file, below the Bookmark model: class Tag(models.Model): bookmarks = models.ManyToManyField(Bookmark) slug = models.CharField(max_length=50, unique=True) In relational databases, there are two basic types of relationships. In a ForeignKey relationship, one model relates to one and only one other model. You could imagine this like a Car model and a Wheel model. Each Wheel instance belongs to one and only one Car, so it would have a ForeignKey field for its car. The car, of course, can have multiple wheels. With a ManyToManyField, on the other hand, the relationship isn't exclusive for either of the models involved. For instance, you could imagine having a Pizza model and a Topping model. Each Pizza can have multiple Toppings, and each Topping can be on multiple Pizzas. (There are other variants of these fields, but this is the basic concept. See for more details for how these relationship fields work in Django.)In this case, each Bookmark can have multiple Tags, and each Tag can apply to multiple Bookmarks. So we use a ManyToManyField to store that information. Creating database tables for your app (carefully, with South) Now that we’ve made our first version of our models file, let’s set up our bookmarks app to work with South so that we can make migrations with it in the future! On the command line, write: # in django-for-designers/myproject $ python manage.py schemamigration bookmarks --initial As you can see, that’s created a migrations directory for us, and automatically made a new migration file inside it. # in django-for-designers/myproject $ ls bookmarks/migrations/ 0001_initial.py __init__.py All we need to do now is apply our new migration: # in django-for-designers/myproject $ python manage.py migrate bookmarks Great! Now our database file knows about bookmarks and its new models, and if we need to change our models, South is set up to handle those changes. We’ll come back to South later. python manage.py syncdb Add and commit all your work, including the migrations folder that South generated for you! Add some bookmarks via the command line Now, let’s hop into the interactive Python shell and play around with the free API ("Application programming interface" -- APIs aren't just data doodads that hip web startups provide for you, they're an important concept in software architecture.) that Django gives you. To invoke the Python shell, use this command: # in django-for-designers/myproject $ python manage.py shell - Making sure bookmarks (and any other apps you might have) are on the right path to be imported. - Setting the DJANGO_SETTINGS_MODULE environment variable, which gives Django the path to your settings.py file. Once you’re in the shell, let's explore the database API. Let's import the model classes we just wrote: >>> from bookmarks.models import Bookmark, Tag List all the current Bookmarks: >>> Bookmark.objects.all() [] How many bookmarks is this? Let's add a bookmark: >>> b = Bookmark(url="", title="Funny link") Try getting the ID number of our new bookmark 'b' by typing: >>> b.id Python has given you back your prompt because the value of b.id is None. Save your bookmark to the database. In Django, you have to call save() explicitly. >>> b.save() Now, try again to get the id of the Bookmark instance. >>> b.id 1 Access the database columns (Fields, in Django parlance) as Python attributes: >>> b.title "Funny link" >>> b.timestamp datetime.datetime(2011, 12, 1, 3, 3, 55, 841929) We can change the bookmark title by changing its title attribute, then calling save(). >>> b.>> b.save() >>> b.title "WHEEEE" If we now ask Django to show a list of all the Bookmark objects available, we can see it's no longer an empty list! >>> Bookmark.objects.all() [<Bookmark: Bookmark object>] Fix the hideous default model representation Use your text editor to open the bookmarks/models.py file and adding a __unicode__() method to both Bookmark and Tag: class Bookmark(models.Model): url = models.URLField() timestamp = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=200, blank=True, default="") def __unicode__(self): return self.url class Tag(models.Model): bookmark = models.ManyToManyField(Bookmark) slug = models.CharField(max_length=50, unique=True) def __unicode__(self): return self.slug Let's see our new shiny __unicode__ methods in action. Start a new Python interactive shell by running: # in django-for-designers/myproject $ python manage.py shell >>> from bookmarks.models import Bookmark, Tag >>> Bookmark.objects.all() [<Bookmark:>] Save and commit your changes. Adding more data via the shell >>> b = Bookmark(url="") >>> b.save() >>> b = Bookmark(url="", title="PyCon US website") >>> b.save() >>> b = Bookmark(url="") >>> b.save() We've created a bunch of bookmarks, but no tags! Let's change that. >>> b = Bookmark.objects.all()[0] >>> b <Bookmark:> >>> b.tag_set.create(slug="cats") <Tag: cats> >>> b.tag_set.create(slug="music") <Tag: music> >>> b.tag_set.create(slug="funny") <Tag: funny> >>> b.save() Slicing and dicing Django data There are many methods for searching across your Django models. We can filter our bookmarks, for instance for ones with a particular URL: >>> foo = Bookmark.objects.filter(url="") >>> foo [<Bookmark:>] Or for bookmarks which have titles: >>> titled_bookmarks = Bookmark.objects.exclude(title="") >>> titled_bookmarks [<Bookmark:>, <Bookmark:>] If you try to use filter to search for a bookmark that does not exist, filter will give you the empty list. >>> Bookmark.objects.filter(title="Who framed Roger Rabbit?") [] The get method, on the other hand, returns exactly one hit. If it finds zero matches, or more than one match, it will raise an exception. >>> Bookmark.objects.get(id=1) <Bookmark:> >>> Bookmark.objects.get(id=20) Traceback (most recent call last): ... DoesNotExist: Bookmark matching query does not exist. More information on making queries with Django's ORM can be found in the Django docs at. Part 3.5: Changing our mind and adding users I don't mean like the number of people using it--I mean a way to store different users' accounts and keep track of who owns which bookmarks. So let's change our app to include this feature.Lucky for us, Django comes with an app for user accounts and authentication from the get-go! In fact, it's already installed. If you look back at your settings.py file, you'll see that in INSTALLED_APPS, there is an entry for 'django.contrib.auth'.', 'bookmarks', ) That's our built-in authentication app! If it isn't already open, let's open the Django shell and play with this app a bit. # in django-for-designers/myproject $ python manage.py shell >>> from django.contrib.auth.models import User >>> User.objects.all() [<User: karen>] There's already a User here. How can that be? What is our user account's id number? >>> me = User.objects.all()[0] >>> me.id 1 Neato! Add user field to bookmark Now we need to create a relationship between the built-in User model and our Bookmark model. First, in our models.py file, we need to import django.contrib.auth's built-in User model so that we can refer to it in our models. from django.db import models from django.contrib.auth.models import User Now we need to think--what kind of relationship do users and bookmarks have? class Bookmark(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200, blank=True, default="") url = models.URLField() timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.url While we're at it, let's update the __unicode__ method too to let us know to whom a bookmark belongs to. class Bookmark(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=200, blank=True, default="") url = models.URLField() timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "%s by %s" % (self.url, self.author.username) Make a migration in South Now that we've added a field to our model, we are going to need to create a database migration. South can help us do this! To create our migration, run # in django-for-designers/myproject $ python manage.py schemamigration bookmarks --auto Eep! Before it will make our migration file, South wants some information from us: ? The field 'Bookmark.author' ? Please select a choice: 2 We could in theory modify our models to specify a default value for author, or make it optional. But neither of those sound like good options. So we'll choose 2, to set up a default value for our new author field just for the purposes of this migration. ? Please enter Python code for your one-off default value. ? The datetime module is available, so you can do e.g. datetime.date.today() >>> We then need to come up with a default value. Well, right now there's only one User in our system who the sample bookmarks we'd entered so far could belong to--our superuser account, which (if you don't remember) had an ID number of 1. ? Please enter Python code for your one-off default value. ? The datetime module is available, so you can do e.g. datetime.date.today() >>> 1 + Added field author on bookmarks.Bookmark Created 0002_auto__add_field_bookmark_author.py. You can now apply this migration with: ./manage.py migrate bookmarks Remember, the first step creates the migration, but doesn't run it. So let's do what South says and run a command to apply our migration! # in django-for-designers/myproject $ python manage.py migrate bookmarks Running migrations for bookmarks: - Migrating forwards to 0002_auto__add_field_bookmark_author. > bookmarks:0002_auto__add_field_bookmark_author - Loading initial data for bookmarks. Installed 0 object(s) from 0 fixture(s) Save and commit your work to add users to your bookmarks app! Templates and links for login/logout/etc Django's auth app comes with built-in views, which we can use to handle login and logout functionality for our users. Once we point some URLs at them, that is. First, let's edit urls.py: urlpatterns = patterns('', url(r'^$', 'bookmarks.views.index', name='home'), url(r'^bookmarks/$', 'bookmarks.views.index', name='bookmarks_view'), url(r'^tags/(\w+)/$', 'bookmarks.views.tag'), url(r'^login/$', 'django.contrib.auth.views.login'), ) Now if anyone goes to localhost:8000/login/, the built-in login view will get triggered. Run your dev server and try that. What error do you see? While there is a built-in login view, there is no built-in login template. We need to build one for it. While we could put it anywhere and tell login explicitly where to look, by default the login view expects the template to reside at templates/registration/login.html. So we may as well put it there. # in django-for-designers/myproject $ mkdir bookmarks/templates/registration Create a new file within the new registration directory called login.html, and put this inside: {% extends "base.html" %} {% block subheader %}Login{% endblock %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {%="/" /> </form> {% endblock %} We need to add a logout view too! Let's do that. Back in urls.py: url(r'^login/$', 'django.contrib.auth.views.login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}) Now we need to add a login/logout link to our site so people can actually use these views! We want this link to be at the top of every page, so we'll edit our base template: <body> <div id="container"> <div id="header"> {% block bookmark_widget %} {% endblock %} <div id="authentication"> {% if user.is_authenticated %} Hi {{user}}! <a href="{% url 'django.contrib.auth.views.logout' %}">Logout</a> {% else %} <a href="{% url 'django.contrib.auth.views.login' %}">Login</a> {% endif %} </div> <h1><a href="/">My bookmarking app</a></h1> </div> [ ... ] Check and try logging in with the superadmin username and password you created before! It should work. :) The answer is in the function we are using to render our templates, render(). render() automatically uses the request we sent it to create a Django RequestContext, which contains a bunch of extra context variables that get sent along to every view that uses a RequestContext. The Django auth app adds the current user to the RequestContext automatically. This is handy, since you don't want to have to look up the current user to every single view you ever write separately, just so the nav section on your website will work everywhere!There are other functions that return an HTMLResponse, like render(), but don't include a RequestContext. render_to_response() is one common shortcut function that doesn't include it by default; another was the HttpResponse() function we used earlier! Just something to remember--if you're trying to send a piece of data to almost every page in your web app, 1.) you probably want to use render() in your views, and 2.) you want to find a way to add your data to your app's RequestContext. ( says more about this!) Save and commit your changes in adding login/logout functionality. Part 3.75: Modify views and templates to use model data Let's edit our views and templates so they use real bookmark data from our database! Add more data First, let's add a bit more bookmark and tag data to our database. We'll use a Python loop to add a lot of bookmarks at once. # in django-for-designers/myproject $ python manage.py shell That will bring us to the Django management shell. Within that special Python prompt, type the following: (Remember, any time you see ">>>", you don't have to type those characters.) >>> from django.contrib.auth.models import User >>> me = User.objects.all()[0] This tells Python we'll be accessing the user model, and then grabs the first user, storing it in a variable called me. Keeping that Python prompt open, run the following commands: >>> from bookmarks.models import Bookmark, Tag >>> import random >>> tag_names = ['kids', 'read_on_plane', 'send_to_dad'] >>> # Create the Tag objects >>> for tag_name in tag_names: ... tag = Tag(slug=tag_name) ... tag.save() ... >>> kids_urls = ['', '', '', '', '', '', '', '', '', ''] >>> for kids_url in kids_urls: ... b = Bookmark(author=me, url=kids_url) ... b.save() ... how_many_tags = random.randrange(len(tag_names)) ... for tag_name in random.sample(tag_names, how_many_tags): ... b.tag_set.add(Tag.objects.get(slug=tag_name)) ... >>> b = Bookmark.objects.get(url='') >>> b.>> b.save() This creates a number of bookmarks, tagged appropriately! You can exit the shell by typing: >>> exit() Get views.py to talk to our models Then, we'll need to have our views.py file import the bookmark model and send data to the index view. We'll add an import statement: from bookmarks.models import Bookmark And we'll edit index(request): def index(request): bookmarks = Bookmark.objects.all() context = { 'bookmarks': bookmarks } return render(request, 'index.html', context) Wait! We don't actually want to load every bookmark in our database when we go to the front page. Instead, let's show the 10 most recent bookmarks: def index(request): bookmarks = Bookmark.objects.all().order_by('-timestamp')[:10] context = { 'bookmarks': bookmarks } return render(request, 'index.html', context) We also want our tag view to show real bookmarks. We only want to show bookmarks that have been tagged with the given tag. So we'll edit the import statement we just added: from bookmarks.models import Bookmark, Tag And alter the tag() definition as well: def tag(request, tag_name): tag = Tag.objects.get(slug=tag_name) bookmarks = tag.bookmarks.all() context = { 'tag': tag, 'bookmarks': bookmarks, } return render(request, 'tag.html', context) Change templates to handle bookmark data Now, let's modify our templates to use this data. In index.html, update just block content per the following. Make sure to keep the extends directive and the block subheader directive. {% block content %} <ul class="bookmarks"> {% for bookmark in bookmarks %} <li> <a class="bookmark-link" href="">{{ bookmark }}</a> <div class="metadata"><span class="author">Posted by Jane Smith</span> | <span class="timestamp">2012-2-29</span> | <span class="tags"><a href="">funny</a> <a href="">haha</a></span></div> </li> {% endfor %} </ul> {% endblock %} Start your development server and look at now. You'll see that instead of the fake HTML we had before, each link's text is the unicode representation of each bookmark in your database. Cool, huh? That's okay, but the programmer-friendly unicode representation isn't really what we want to go there. Let's fix that: # in index.html <a class="bookmark-link" href="{{ bookmark.url }}"> {% if bookmark.title %}{{ bookmark.title }}{% else %}{{ bookmark.url }}{% endif %} </a> If the bookmark has a title, we'll make the title the link. Otherwise we'll show the URL. We also fill in the URL on the <a> tag, to make the link work. We also want to fill in the other metadata, like tags and author info. To do that: # in index.html <div class="metadata"><span class="author">Posted by {{ bookmark.author }}</span> | <span class="timestamp">{{ bookmark.timestamp }}</span> {% if bookmark.tag_set.all %}| <span class="tags"> {% for tag in bookmark.tag_set.all %} <a href="{% url 'bookmarks.views.tag' tag.slug %}">{{ tag.slug }}</a></span> {% endfor %} {% endif %} </div> We check if there are any tags for the bookmark, and if so loop over the tags to put each of them in. Additionally, we use Django's {% url %} tag to generate the URL for our tag's link. Run # in django-for-designers/myproject $ python manage.py runserver and confirm that your tag links working and our other changes are visible. It's easy to typo or make a mistake with {% url %} tags, so we want to make sure everything is working. The default timestamp formatting that Django gave us is pretty neat, but in our original mockup we just used the date--not this long timestamp. Fortunately, Django's built-in filters make it easy to format a date or time any way we want! Since we just want to show the date, we'll use the date filter: <span class="timestamp">{{ bookmark.timestamp|date:"Y-m-d" }}</span> Spin up your dev server, if you haven't got it running already, and check out your changes! Then save and commit your precious work. Updating the tag template, and dealing with errors Let's update our tag.html template to use the same formatting as index.html. Since we're using the same formatting for the list of bookmarks, and there aren't any other content block differences between index.html and tag.html, we can simply modify our tag template to inherit from index.html. Edit tag.html to have only the following contents. (That means you can remove the mockup "block content" section in tags.html. Yay!) {% extends 'index.html' %} {% block subheader %}Bookmarks tagged {{ tag.slug }}{% endblock %} Now we can go to and see a nicely styled list of bookmarks tagged with that tag! What happens if we go to ? Our application is erroring on one of our view lines: tag = Tag.objects.get(slug=tag_name) Fortunately, Django has a shortcut function that can help us -- get_object_or_404(). from django.shortcuts import render, get_object_or_404 from bookmarks.models import Bookmark, Tag [...] def tag(request, tag_name): tag = get_object_or_404(Tag, slug=tag_name) bookmarks = tag.bookmarks.all() context = { 'tag': tag, 'bookmarks': bookmarks, } return render(request, 'tag.html', context) Now will throw a nicer 404 error. We could even make a pretty 404.html template to handle such errors! Save and commit your error-catching work.
https://wiki.openhatch.org/w/index.php?title=Django_for_Designers/Adding_models&mobileaction=toggle_view_mobile
CC-MAIN-2021-17
refinedweb
3,813
60.21
Answered by: Exception: "has no supported translation to SQL" Hello, I am using LINQ to get my products out of my database. The products table has a column called "offerCount" of type int. I have extended the product class, which was generated by Linq to SQL, with a method to check its validity:Code Block partial class product { public bool IsValid() { return offerCount > 0; } } But when I try to access the data via Linq expression:Code Block var v = from a in dbContext.products where a.IsValid() == true select a; I am getting this ExceptionCode BlockMethod 'Boolean IsValid()' has no supported translation to SQL. I do not understand what happens here. I thought I could extend the classes with own methods and use them in the linq expressions. I also get the method "IsValid()" proposed by Intellisense when typing the "where a." Am I on a completly wrong way? How would you solve the problem? Thanks Hannes.Monday, December 17, 2007 4:50 PM Question Answers All replies According to this article: "Method" in the entity class cooresponds to a "Stored Procedure or Function" on the database side. The first step to turning this around is to make IsValid into a property.Monday, December 17, 2007 5:19 PM - HI David, thanks for your awnser. I changed "IsValid()" into a property "IsValid", but it didn't help. Also with a property, I get the Exception "IsValid has no supported translation to SQL".Monday, December 17, 2007 8:28 PM You are not adding any attributes around your property or method that map back to SQL? PetarTuesday, December 18, 2007 12:21 AM Now that I have access to my LINQ environment, I have figured out how to accomplish your goal. LinqToSql won't translate just any old method (or property, which is just a fancy method). LinqToSql won't even translate any Func. LinqToSql translates expressions. Specifically: System.Linq.Expressions.Expression<Func<T, bool>>Code Block {//not gonna work public static Func<TestTable, bool> IsValid(int i) {return new Func<TestTable, bool>(myTable => myTable.TheKey > i); }//works!!! public static System.Linq.Expressions.Expression<Func<TestTable, bool>> IsValidExpr(int i) {return (myTable => myTable.TheKey > i); } } Here's how-to call it (along with 2 examples of how-not-to call it:Code Block {DataClasses1DataContext myDC = new DataClasses1DataContext(); //Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL. //var q = // from t in myDC.TestTables // where TestTable.IsValid(1)(t) // select t; //Compile error: MethodName expected//var q = from t in myDC.TestTables // where TestTable.IsValidExpr(1)(t) // select t; IQueryable<TestTable> q = myDC.TestTables .AsQueryable<TestTable>() .Where<TestTable>(TestTable.IsValidExpr(1)); Console.WriteLine(myDC.GetCommand(q).CommandText); foreach (var item in q) { Console.WriteLine(item.Name); } } Note the need to call AsQueryable, if you don't, you'll invoke the Where method in System.Linq.Enumerable... when you really want the Where method in System.Linq.Queryable .Tuesday, December 18, 2007 4:00 AM Thank you, thank you, thank you for this post. There's so much to learn about LINQ.Thursday, May 15, 2008 7:18 PM No problem. Glad I could help.Friday, May 16, 2008 3:41 PM - Using your method I get the following run time error "System.NotSupportedException: Unsupported overload used for query operator 'Where'." Does your code actually execute?Thursday, September 25, 2008 10:11 PM - Thanks for the clarification, Dave! I wanted to print it, but MSDN forums are extremely hard to print. IE7 print one good page, but 7 blanks. Is there a special technique developers use to print any posting that I am not aware of? Fakher HalimFriday, March 13, 2009 4:41 PM David, Awesome reply!! it can be further simplified as follows public class TestTableExt { public static System.Linq.Expressions.Expression<Func<TestTable, bool>> IsValid(int i) { return (a => a.Count > i); } } void Main() { var q = TestTable.Where(TestTableExt.IsValid(1)); }Tuesday, July 26, 2011 9:32 PM
http://social.msdn.microsoft.com/Forums/en-US/ce3e3721-ded0-4dc6-a40a-ddeb981c2ebe/exception-has-no-supported-translation-to-sql?forum=linqprojectgeneral
CC-MAIN-2014-41
refinedweb
660
59.9
GraphQL Tutorial with Angular 7/8 and Apollo Example In this tutorial, we'll teach you about the fundamental GraphQL concepts starting with an introduction and then explaining the building blocks for a GraphQL API. Next, we'll see how to build an example Angular 7/8 app that consumes a GraphQL API from scratch using Apollo client. We'll be consuming a GraphQL API built with Node.JS and Express. In a nutshell, you'll understand: - What is GraphQL and why using it to build web APIs instead of REST, - What is the difference between a Schema-first-approach vs. a Code-first-approach, - What is a Schema and how to use it to define the structure of the data in your API, - What's a Schema Definition Language (SDL) and how can be used to define a Schema, - What's a builtin scalar type and how to use it to create object types, - What are object types and how they are used to define a Schema, - Root types such as queries, mutations, and subscriptions, - What's a resolver function, - How to map resolvers to fields in the root types of a Schema, - How to make executable Schemas to actually create a GraphQL API. For the practical example, we'll learn how to: - Install Angular CLI 8 - Create an Angular 8 app - Creating an Angular component for displaying consumed GraphQL API data - Install and set up Angular Apollo using the ng addcommand - Connect Angular Apollo to our GraphQL API server built with Node.JS and Express - Consume the GraphQL API from our Angular component using Angular Apollo service Do You Need to Learn how to Build a GraphQL API? As far as Angular is concerned, you only need to know how to consume a GraphQL API not how to build it, but if you want to take it further, you can learn how to use Node.js to build a web API with our easy-to-follow tutorial. Angular is not a server-side framework, so it can't be used to build web APIs with GraphQL but as an Angular developer, most often than not, you would need to consume an API which may be, very well, written in GraphQL as the technology became very popular in the recent years. As a frontend developer, you are not required to know about server-side technologies like GraphQL but will definitively help you to better communicate with the backend team/developer if you know the fundamental concepts of GraphQL. Note: GraphQL has been open-sourced and released as an open-source specification, so the GraphQL API server can be developed in any server-side programming language that you know including TypeScript (On top of Node.js). What is GraphQL? GraphQL stands for Graph Query Language. The official website defines GraphQL. So, GraphQL is a query language (In the same sense as SQL is a query language) but not for databases, instead it's designed for querying data over the HTTP protocol and creating an API in the same way REST is used but with more advantages. It's also a runtime that provides the actual mechanisms for processing the API queries and returning data and responses. GraphQL allows you to provide a complete description of the data used in your application. As a result, clients will be able to query for the exact data that they need no less, no more. If you used REST before, you can imagine how powerful the GraphQL approach is. GraphQL was originally created by Facebook and later open-sourced. Nowadays, more companies are using it ranging from IBM and GitHub to Twitter and PayPal. Advantages of GraphQL According to the official website, these are the advantages of GraphQL: - Ask for what you need, get exactly that. - Get many resources in a single request. - Describe what’s possible with a type system. - Move faster with powerful developer tools like GraphiQL. Since you can describe the exact data that you need to fetch from your API server, you can send only a single HTTP request for multiple resources instead of many requests in the case of REST. This means you'll have less network overhead and more performance. When using REST, things may become tedious and error-prone for complex data requirements but with GraphQL, you can have nested queries which make it easy to get related data without trying to figure out how much requests you need to send and in what order. You may even end up failing to get the desired data if a proper endpoint is not present in the backend in the case of REST but not with GraphQL. What is a GraphQL Schema? A GraphQL schema is a fundamental concept around which you can build your API. The first step of building a GraphQL API is the definition of the schema. You can consider a schema as a blueprint for all of the data that you can return in your API. The schema describes the data types and the relationships between them. It also defines the possible queries that can be used to fetch data and what mutations can be used to create and update data. A schema may contain types and their fields, queries, mutations, and subscriptions. a type can be either an object type or builtin scalar. Additional information can be added as custom directives. You need to include at most one schema definition when using the type system definition language. In this example, a GraphQL schema is defined with both query and mutation root types: schema { query: QueryRootType mutation: MutationRootType } What is an SDL? GraphQL provides its own Schema Definition Language or SDL which provides an agnostic way to define a GraphQL schema no matter what programming language is used. Schema-first-approach vs. Code-first-approach You can write a GraphQL API in one of two approaches, a schema first approach or code first approach. The latter approach is more tied to a specific implementation provided by a programming language since you need to use code to define your GraphQL schema. In a schema-first approach, we write our schema in the GraphQL SDL language and we call some methods to execute it. We then need to map resolvers (the methods that actually implement the queries and mutations) to fields. This is the leading approach in the GraphQL community. In a schema-first approach, you write your data types, queries and mutations in the schema first then you add the implementation using resolvers. This offers many benefits, for example, it allows frontend developers to start building the UI based on the schema before it's implemented by backend developers. GraphQL Scalar and Object Types In GraphQL, types are en essential concept. In fact, everything in the schema is a type even queries and mutations. Queries, mutations, and subscriptions are called root types. The basic elements of a GraphQL schema are object types, which define a type of object you can fetch from your API, and what fields it has. We create the object types out of the builtin scalar types. GraphQL provides various built-in scalar types defined by the specification such as: - ID, - String, - Int, - Float, - Boolean It also allows you to create object types for describing the structure of your data. You can define a type using the type keyword: type Employee { id: ID! name: String phone: String address: String emails: [String] } Employee is an object type, created using the builtin scalar types. It doesn’t provide any functionality except defining the structure or shape of our employee model in the application/database. It's composed of fields. A field has a name and a type: name: String Note: In addition to scalar types, a field can use any other type defined in the schema definition. You can make the field non-nullable by adding an exclamation mark, as follows: id: ID! You can define list fields using square brackets around the type: To implement the API, you will need to add fields to the root types (Queries, Mutations, and Subscriptions) of the GraphQL schema. These types define the entry points for the GraphQL API. GraphQL Enums An enum allows you to define a type that has a predefined set of possible values. For example: enum Category { CAT1 CAT2 } GraphQL Interfaces An interface is comprised of a list of fields and can be implemented by a GraphQL type which must have the same fields as the implemented interface: interface Person { name: String! } You can use the implements keyword to implement the interface: type Employee implements Person { } What is a GraphQL Query Type? A GraphQL query is a root type that defines the shape of the queries that can be accepted by the API server. For example: type Query { empolyee(id: ID!): Employee } This root type exposes an employee field that takes an ID and returns an Employee. Note: The root types of a schema define the shape of the queries and mutations that will be permitted by the API server. This enables GraphQL to provide a concise contract for client-server communication. What is a GraphQL Mutation Type? Mutations are root types that are used to create, update or delete data. They are similar to the PUT, PATCH and DELETE operations in REST APIs. We use the Query root type to define the entry-points for operations used to fetch data and the Mutation root type to add the entry points for the operations to create, update and delete data. For example: type Mutation { addEmployee(name: String, phone: String, emails: String[], address: String): Employee } Here we add a single addEmployee mutation which accepts the name, phone, address arguments (also called input types) and returns the created Employee object. What is a GraphQL Resolver? When you build GraphQL APIs, the process is centered around the schema. The process is generally as follows: - You create the schema definition, - And you implement the actual operations using the resolver functions. GraphQL makes a separation between the structure and behaviour. The structure is defined with the schema. You then need to write an implementation that provides the behavior of the fields in the root types. This is done with what's called a resolver function which needs to be provided for each field in the root types. A question that arises is how to map the resolver functions to the fields? This can be done in many approaches. In the code-first approach, you have objects that you can use to define fields and resolvers in the same place. See graphene-js or express-graphql for JavaScript. In the schema first approach, you can't add resolvers directly in the schema, but you have various APIs (available from different packages such as GraphQL.js and graph-tools) to map the resolvers after defining your schema such as: - Using the buildSchema()method which is available from the GraphQL.js package, - Using the makeExecutableSchema()method of the graphql-toolspackage. Consuming a Node.js GraphQL API with Angular 8 and Apollo Let's now see how to consume a Node.js GraphQL API built in this tutorial using Angular 8 and Apollo. Installing Angular CLI 8 Before we can initialize our Angular project, we need to install Angular CLI. Make sure you have Node.JS and NPM installed on your development machine and open a new terminal then run the following command: $ npm install -g @angular/cli That's it, we are ready to create our Angular project and consume a GraphQL API. Creating an Angular 8 App Let's start by generating our Angular 8 application. Open a new terminal and run the following command: $ ng new angular-graphql-example You'll be prompted if you would like to add routing to your project and which stylesheets format would you like to use. You can answer yes for routing and CSS for stylesheets. Next, navigate to your project's folder and serve your app using the following commands: $ cd angular-graphql-example $ ng serve Your application will be available from. Creating an Angular Component for Displaying GraphQL API Data We'll be consuming a Node.js GraphQL API for an employees database, so we don't need many components in our application. We already have the App component which we can use for displaying our GraphQL API data, but let's create a component and add a route for it in the router configuration for best practices. Open a new terminal anf run the following commands: $ cd angular-graphql-example $ ng generate component employees Next, open the src/app/app-routing.module.ts file and add a route for the employees component to the router configuration: import { EmployeesComponent } from './employees/employees.component'; const routes: Routes = [ { path: 'employees', component: EmployeesComponent } ] We can now access the component from the path. Installing Apollo for Angular 8 We'll be making use of Apollo with Angular 8 to consume the GraphQL API, so we'll need to run the following command for setting up Apollo in our project: $ ng add apollo-angular apollo-angular enables you to fetch data from your GraphQL server and use it for building complex and reactive UIs using the Angular framework. Apollo Angular may be used in any context that Angular may be used. Connecting Angular Apollo to our GraphQL API server Now, we can connect our Angular components with the GraphQL server for consuming data. Open the src/app/graphql.module.ts file and update the uri variable with your GraphQL URL as follows: const uri = ''; // <-- add the URL of the GraphQL server here That's all what we need to connect our Angular 8 application with our Node.js GraphQL server. Consuming GraphQL APIs with Angular Apollo Service Let's proceed to consuming the GraphQL API using the Apollo service. Open the src/app/employees/employees.component.ts file and add the following imports: import { Apollo, QueryRef } from 'apollo-angular'; import gql from 'graphql-tag'; Next, before the component definition, add the following GraphQL query: const EMPLOYEES_QUERY = gql` query { employees { id, name, email, phone, address } } `; The gql tag allows you to create a GraphQL query object from a template string. Next, update the component as follows to send a GraphQL query when the component is initialized: @Component({ selector: 'app-employees', templateUrl: './employees.component.html', styleUrls: ['./employees.component.css'] }) export class EmployeesComponent implements OnInit { employees: any[] = []; private query: QueryRef<any>; constructor(private apollo: Apollo) {} ngOnInit() { this.query = this.apollo.watchQuery({ query: EMPLOYEES_QUERY, variables: {} }); this.query.valueChanges.subscribe(result => { this.employees = result.data && result.data.employees; }); } } In the ngOnInit() method we call the apollo.watchQuery() method to initialize data fetching. Next, we subscribe to any data changes using the valueChanges.subscribe() method and we set the employees array with the data consumed from the GraphQL server. Conclusion In this tutorial, we've introduced you to the fundamental GraphQL concepts such as: - Schemas, - Scalar and object types, - Queries, mutations, and subscriptions, - Resolvers. We have seen the difference between the schema first approach and code first approach for creating GraphQL APIs. How you can make an executable schema using methods like buildSchema() and makeExecutableSchema() from the GraphQL.js and graph-tools packages. Next, we have created a GraphQL client application with Angular 8 and Apollo for consuming a GraphQL API server built with Node.JS and Express.
https://www.techiediaries.com/graphql-tutorial/
CC-MAIN-2021-39
refinedweb
2,555
60.85
Stores status of the currently executed statement. More... #include <sql_error.h> Stores status of the currently executed statement. Cleared at the beginning of the statement, and then can hold either OK, ERROR, or EOF status. Can not be assigned twice per statement. Const iterator used to iterate through the condition list. The type of the counted and doubly linked list of conditions. The number of conditions (errors, warnings and notes) in the list. Copy SQL-conditions that have been added since mark_preexisting_sql_conditions() was called. Copy Sql_conditions that are not SL_ERROR from the source Diagnostics Area to the current Diagnostics Area. Copy all SQL-conditions from src_da to this DA. Return the current counter value. Return the number of conditions raised by the current statement. Mark the Diagnostics Area as 'DISABLED'. This is used in rare cases when the COM_ command at hand sends a response in a custom format. One example is COM_STMT_PREPARE. The number of errors, or number of rows returned by SHOW ERRORS, also the value of session variable @error_count. Checks if the condition list contains SQL-condition with the given message. Checks if the condition list contains SQL-condition with the given error code. Increment the current row counter to point at the next row. Mark current SQL-conditions so that we can later know which SQL-conditions have been added. Pop "this" off the Diagnostics Area stack. Push the given Diagnostics Area on top of the stack. "This" will then become the stacked Diagnostics Area. Conditions present in the new stacked Diagnostics Area will be copied to the new top Diagnostics Area. Add a new SQL-condition to the current list and increment the respective counters. Add a new SQL-condition to the current list and increment the respective counters. Make sure there is room for the given number of conditions. Reset the current condition information stored in the Diagnostics Area. Clear all conditions, the number of conditions, reset current row counter to point to the first row. Reset the current row counter. Start counting from 1. Clear this Diagnostics Area. Normally called at the end of a statement. Reset between two COM_ commands. Conditions are preserved between commands, but m_current_statement_cond_count indicates the number of conditions of this particular statement only. Set the current row counter to point to the given row number.. Returns the Diagnostics Area below the current diagnostics area on the stack. Used for @warning_count system variable, which prints the number of rows returned by SHOW WARNINGS. The number of rows affected by the last statement. This is semantically close to thd->row_count_func, but has a different life cycle. thd->row_count_func stores the value returned by function ROW_COUNT() and is cleared only by statements that update its value, such as INSERT, UPDATE, DELETE and few others. This member is cleared at the beginning of the next statement. We could possibly merge the two, but life cycle of thd->row_count_func can not be changed. Indicates if push_warning() allows unlimited number of conditions. Set to make set_error_status after set_{ok,eof}_status possible. A memory root to allocate conditions. List of conditions of all severities. Row counter, to print in errors and warnings. Not increased in create_sort_index(); may differ from examined_row_count. The number of conditions of the current statement. m_conditions_list life cycle differs from statement life cycle – it may span multiple statements. In that case we get m_current_statement_cond_count 0, whereas m_conditions_list is not empty. A break down of the number of conditions per severity (level). True if status information is sent to the client. Similarly to the previous member, this is a replacement of thd->first_successful_insert_id_in_prev_stmt, which is used to implement LAST_INSERT_ID(). Number of conditions of this last statement. May differ from the number of conditions returned by SHOW WARNINGS e.g. in case the statement doesn't clear the conditions, and doesn't generate them. Message buffer. It is used only when DA is in OK or ERROR status. If DA status is ERROR, it's the MESSAGE_TEXT attribute of SQL-condition. If DA status is OK, it's the OK-message to be sent. SQL error number. One of ER_ codes from share/errmsg.txt. Set by set_error_status. List of conditions present in DA at handler activation. SQL RETURNED_SQLSTATE condition item. This member is always NUL terminated. Save @error_count before pre-clearing the DA. Save @warning_count before pre-clearing the DA. Pointer to the Diagnostics Area below on the stack.
https://dev.mysql.com/doc/dev/mysql-server/latest/classDiagnostics__area.html
CC-MAIN-2019-22
refinedweb
737
61.22
The following forum message was posted by rsflux at: PyDev appears to be incorrectly parsing a file (with Grammar Version set to 3.0) with the 2.* rules for local imports. I'm posting here to make sure this isn't a known issue; if I get the OK, I'll post an issue in the bug tracker. To reproduce, set up a project with this relationship: main.py pkg (folder) -> __init__.py -> foo.py (Contains: import math print(math.pi) ) -> math.py (empty file) If foo.py attempts to "import math", PyDev thinks that the interpreter is going to import pkg.math, instead of the built in math module. This is correct in Python 2.*, but is no longer the case in 3.* (see PEP 328 here). Because of this error, any uses of the math symbol within foo.py, such getting the .pi attribute, gets tagged with an "Undefined variable from import" error. Auto-completion and go to definition functionality is also broken. As a fix, when a PyDev project is in 3.0 Grammar mode, it should always use absolute paths in imports except when using the dot syntax (from .math import something). Thoughts? -Ryan The following forum message was posted by fabioz at: Yeap, seems like a bug to me. Please report it in the bugtracker (you can reference this thread if you want). Cheers, Fabio The following forum message was posted by mkearney at: I just encountered this apparently as a consequence of updating to pydev version 2.2.2.2011082312. I have been using Version 2.2.0.2011062419 for a few months without trouble. It has been good enough for my purposes. I have been searching for an archive site so I could download/update the version that works for well enough for me. I haven't found one yet. Is there such a site? The following forum message was posted by fabioz at: The update site () has archives (in the install dialog you have an option to show old versions). Cheers, Fabio The following forum message was posted by mkearney at: I never had to use the archives before now, which says a lot. Thanks, -m The following forum message was posted by fabioz at: Just to note, I'm working on this issue now, so, if you wait until tomorrow, there should be a nightly build with this fixed. Cheers, Fabio
http://sourceforge.net/p/pydev/mailman/pydev-users/thread/forum-293649-10600828@sourceforge.net/
CC-MAIN-2015-48
refinedweb
400
76.42
Apache 2 and PHP Installation The. - Download/unpack Apache2 source from the Apache httpd server website, - In the Apache 2 source directory, create a Makefile by typing: - Make Apache from the just-created Makefile: - If make is successful, install Apache as root: - Download/unpack PHP source from the PHP website, Pick the latest from the 4.x series or 5.x series. - In the PHP source directory, create a Makefile by typing: - Make PHP from the just-created Makefile: - If make is successful, type this as root to install PHP: - If file /usr/local/apache/modules/libphp5.so does not exist or is an older version, type this (change this to libphp4.so for PHP 4): - Install the php.ini file: - Add these directives are in /usr/local/apache/conf/httpd.conf (if already there, verify they are correct):: - You're now ready to try it out. Start Apache (httpd) as root: - Perform these sanity checks to verify your install went OK: Note: on BSD-based UNIX systems, you need to use "ps -aux" instead of "ps -ef". - Access your webserver with telnet. Type HEAD / HTTP/1.0 followed by a blank line: - Access your webserver with your favorite browser. The following is a good test page to use for PHP. You only need the one line in bold is needed to display PHP configuration information. Name the file anything you want, but it must end with .php, such as phpinfo.php, and move the file to your web server content directory (for me /usr/local/apache/htdocs), with read permission set: Tips and Notes • Disabling Existing Apache Software If Apache is already installed with your Linux distribution you have to disable it before installing your own custom version. To do this, type the following under RedHat Linux: • Automatic Startup of Apache To start Apache automatically, follow these steps: - Copy Apache startup file to the startup directory: - Edit /etc/init.d/apachectl by inserting these 2 lines in bold: - Enable httpd to startup automatically: update-rc.d apachectl defaults For other distributions, make appropriate softlinks to directories /etc/rc*.d/ - Reboot Linux to verify Apache starts [Thanks to Beriah Dutcher and others] • Make doesn't make dynamic library libphp5.so, just static library libphp5.a First make sure libphp5.so isn't there. It's usually in the libs or .libs subdirectory. Run find from the PHP source directory root: find . -name libphp5.soIf that doesn't work, make sure you use the --with-apxs2 option with the correct directory in ./configure. For example: ./configure --with-mysql --with-apxs2=/path/to/apache/apxs When re-running ./configure always start with a fresh, clean source directory (no object). (For PHP 4, substitute libphp4.so and libphp4.a for libphp5.so and libphp5.a, respectively.) • PHP 5: My PHP scripts that worked with PHP 4 now ignores input variables If you have old PHP 4 scripts you don't want to convert to PHP 5, change this line in your php.ini file: For the long term, you may want to upgrade your PHP software or convert the PHP source code to use new-style variables. E.g., use $_REQUEST[i] instead of $i • PHP 5.2.0 Upgrade from 5.1.x (November 2006)I had one problem with upgrading from PHP 5.1.x to 5.2.0. The Phorum 3 software I use has a function date_format that now conflicts with a new PHP 5.2 internal function, also called date_format. This new function is used for PHP 5.2.x's new "datetime support". I fixed this by renaming Phorum's date_formatfunction to not conflict with PHP's function. See also PHP 5.2 Update Info for more PHP 5.2 upgrade information. • PHP 5.x: you may need to upgrade libxml2 to use XML To use PHP 5 and XML (--with-xml), you need the libxml2 library version 2.6.0 or greater. You may need to upgrade if you have an older Linux distribution. Check with rpm -q libxml2 If it's not installed, check your installation disks for the libxml2 package. If it's too old, you can get the library from XMLSoft.org. You will probably need to compile and install it yourself. • PHP 4.3.5 / 4.3.6 / 5.0RC1 PCRE Regression (March 2004) If you use PHP 4.3.5, 4.3.6, or PHP 5.0 RC1 with PCRE (Perl Regular Expressions, the default), you get a core dump when you try and restart (SIGHUP) Apache (at least with Apache 2.0.49). The cause is from adding a new version of PCRE, 4.5, in PHP. This is fixed in PHP 4.3.7 and 5.0. The symptom are these messages in error_log (which is also a symptom for lots of other memory-type bugs in Apache): To fix, upgrade to PHP 4.3.7 or higher, which fixes it (PHP 5.0 or higher also fixes the bug). A workaround is to stop/start Apache, instead of restarting Apache. For details, see PHP bug 27810. • ServerRoot Installation Directory By default, Apache is installed in ServerRoot, as specified in httpd.conf or the httpd -d option: ServerRoot "/usr/local/apache" Some packagers and distributions move the location to /usr/local/httpd or /usr/local/apache2 so check that Apache is installed where you say it is, and check that you don't have two separate Apache installations by mistake. • PHP-required Apache files must be present PHP expects certain files to be present. They may be missing for some Linux distributions, which tend to separate files among the /var, /etc, and other directories. The apxs program expects to find httpd under the bin directory where apache is installed (by default /usr/local/apache/bin). PHP expects to find the os.h and unixd.h header files under the include directory where apache is installed (by default /usr/local/apache/include). • MySQL Use the --with-mysql configure option to build PHP with PHP's version of MySql. If you want the system's MySQL, or are also using MySql with another apache module (e.g., mod_perl), use this: with-mysql=/usr Make sure the MySQL developent headers are installed. This is usually package mysql-devel (thanks to Dev for the tip) • Custom OpenSSL and SSL When using "--enable-ssl" (i.e, build with OpenSSL), the configure script will try to guess the location of OpenSSL. If you're using your own custom SSL, you must specify the location. For example, "--with-ssl=/usr/local/ssl" (of course, you can use the SSL and PHP that comes with Redhat 9 and other distributions). Please note that mod_ssl is only for Apache 1.x. Apache 2.x does not use mod_ssl—SSL is built into Apache 2.x. Jason reports that with RedHat 9 on his system, the make failed at mod_ssl. It needed a missing krb5.h header file. The fix is to Add an environment variable, $CFLAGS, before making PHP. That is: "-I/usr/kerberos/include/ -L/usr/kerberos/lib" • gdbm If you get this error when using "--with-gdbm": configure: error: DBA: Could not find necessary header file(s). then you are probably missing the gdbm-devel rpm package. • Apache 1.x and Apache 2 Configuration Directives The "AddModule," "AgentLog," "ReferrerLog," "RefererIgnore," "BindAddress," "ClearModuleList," "Port," "FancyIndexing," "ServerType," "AccessConfig," and "ResourceConfig" directives in Apache 1.x no longer exist in Apache 2. Also, "HAVE_*" httpd.conf definitions no longer exist. Comment them out of your httpd.conf for Apache 2. Most of these directives have been replaced by other directive(s). • Error after glibc library upgrade Apache should still work after upgrading glibc with security and bug fixes for the same release. If you use another architecture (say from or to i386/i686), you need to recompile. One symptom is an error like this in your Apache error_log: [error] (38)Function not implemented: • make clean Kåre Olaussen adds this note: If you're compiling php4 for both Apache 1.3 and Apache 2, use a separate php source directory for each version of Apache. "The module wouldn't load into Apache 2, because I had forgotten to run make clean in between." [Ed. note: I recommend untaring the source from scratch in another directory, that way you are sure no old state information is left behind from previous makes. Do this for any configuration or version changes.] • Enabling register_globals for Apache 2 From Duke: For those of you that are desperately trying to enable register_globals on a per-directory basis using Apache 2 with PHP 4 [or PHP 5] using.htaccess files, the syntax is different from Apache 1.x. In the directory you want to enable register_globals (or pretty much any other on/off setting), add an .htaccess file containing: [Editor's note: To enable globally, add register_globals=off to your php.ini file.] To enable register_globals on a per-directory basis, you can add to a <Directory> stanza or create a .htaccess configuration file in the directory. To use.htaccess, you must first enable it by adding AllowOverride All (or some combination of AllowOverride options within the correct <Directory> stanza. Also newer PHP software, such as SquirrelMail, no longer require register_globals to be enabled. Keeping register_globals disalbed makes the system much more secure (as it's harder to set internal php variables through submitting html forms). ] • Multi-Processing Module (MPM): don't use multi-threading MPMs MPMs is how Apache 2 handles multiple web server requests. That is, with multiple processes or multiple threads or some combination. For now, on Linux (and even UNIX) you should only use the (default) prefork module with PHP. This is specified at compile time. Other MPM modules (any involving threads) break PHP. This is partly because PHP uses a great number of external libraries, and many or most of them are not thread-safe or thread-aware. In any case, Linux 2.4 doesn't handle threads efficiently yet—multiple processes are better (this changes with Linux 2.6, or RedHat 9 with 2.6 threads backported to Linux 2.4). • API module structure `php5_module' in file . . . is garbledIf you get a message like this: • PATH_INFO Dan Fitzpatrick notes that he uses PATH_INFO for many PHP scripts like /index.php/go/do/something (where parameters are passed to PHP as "fake" subdirectories). He received a 404 Not Found errors with Apache 2 but not Apache 1.3.27. He had to add "AcceptPathInfo On" to file httpd.conf. For details, see • Using <? ?> style tags in addition to <?php ?> style tags If you want to also use the old-style (or MS ASP-like) tags <? and ?> then add this line to your php.ini file. This is the default starting with PHP 5: • GD library now built-in PHP PHP 4.3.0 has gd built-in, just pass --with-gd to PHP configure. • --with-apache If you don't have Apache source at the default directory at /usr/local/apache, then use --with-apache=DIR with PHP configure, where DIR is the root source directory, This tells PHP where to look for the Apache source. • Redhat 9 Apache 2 and PHP is built-in RedHat 9 (packages httpd 2.0.40, and php 4.2.2). Apache is mostly under /usr/lib/httpd and /usr/sbin/httpd. PHP is at/usr/lib/httpd/modules/libphp4.so For a complete file listing, type: rpm -ql httpd php For RedHat 9, PHP 4.3.1 gives a compiler errors with RedHat 9 similar to: my_malloc.c:24: undefined reference to `errno' The problem is with mysql and will have to wait for a fix from them. Until then, add this line: #include <errno.h> to the beginning of file ./ext/mysql/libmysql/mysql.h in your PHP source and remake PHP (from scratch). • Notes about Gentoo Linux and Apache2 with PHP LoadModule php5_module modules/libphp5.so becomes: LoadModule php5_module /usr/lib/apache2-extramodules/libphp5.so To start automatically under Gentoo: rc-update add apache2 default (change php5 to php4 for PHP 4) [Thanks to Phillip Temple]
https://blog.csdn.net/buutterfly/article/details/5630192
CC-MAIN-2019-04
refinedweb
2,023
67.45
In the last part, we left GildedRose in a very awkward position. - It is not a huge mess anymore (Good!) - It is not a huge conditional mess anymore (Even better!) - It is not a huge procedural conditional mess anymore... ... or is it? It looks more OO, but in reality, is a mimicry: I just camouflaged bits of procedural code in objects. Unfortunately, in my real life: - lots of the OO code I see looks like what we had in part 1; - most of the OO code I see looks like what we first created with smaller methods in part 2; - some well-behaved kids try OO and get to those small objects we created in part 3; - ... and we are still in the middle of Faux-O. Oh, we did a HUGE step forward, it is just that we are not there yet. But before continuing our Journey, a quite unrelated side-step, for you to understand why I did a part of what you will see in future code samples. Good OO looks like Functional Programming This is a little exaggerated, but not by much. Chaining messages, when done properly, can feel like composing functions. You may have been told rules like "No more than 2 dots on a line". I feel this rule stupid. The functional developper inside of my stomach shifts uneasily when hearing such sayings. The heart is at the right place, I understand what the people mean, but I am not sure it means the same thing for them as it does for me. When the returned object of each message is different, we should not go above 2. It would mean that we send messages to objects we should not be aware of in the first place. But what about something like: str = "a STRING is like a spring!" str.downcase .gsub(/(s.ring)/, 'beautiful \1') .capitalize # => A beautiful string is like a beautiful spring! Each method is called on the same object; it does not count as "three dots"! I want all my classes to behave like String and allow me to chain calls as I see fit. To that avail, a simple rule: "A public method which does not return a meaningful result should return self" So you will see some self coming in the mix soon enough 😊 But let us go back to our main subject. What does GildedRose? It responds to 1 message, and that is it. def update_quality @items.each do |item| case item.name when "Aged Brie" AgedBrie.new(item).update when "Backstage passes to a TAFKAL80ETC concert" Backstage.new(item).update when "Sulfuras, Hand of Ragnaros" Sulfuras.new(item).update else CommonItem.new(item).update end end self end Let us see it from another angle: GildedRose creates some classes and propagates a message to those classes. Oh. God. I fear GildedRose is in reality... a kind of Factory. No, not the gross factories from the Java world: The pure, aesthetic factories promoted by Object Oriented Programming. Now that we considered GildedRose that way, impossible to go back: we need to refine it and shape it like the factory it is. From a standard class to a factory @items is an Array of Item instances. I would prefer it to be an Array of CommonItem. My problem is: which child of CommonItem? Well, it depends on the item name. Let just code some helper for that! (In reality, the code is already there, can you see it?) private def class_from(name:) case name when "Aged Brie" AgedBrie when "Backstage passes to a TAFKAL80ETC concert" Backstage when "Sulfuras, Hand of Ragnaros" Sulfuras else CommonItem end end Given an Item, I can now instantiate the right object with a simple class_from(name: item.name).new! We just can now refactor our code around this idea. class GildedRose def initialize(items) # I do not store Item instances anymore, but instances of CommonItem @items = items.map { |item| class_from(name: item.name).new(item) } end def update_quality # item is now an instance of CommonItem. # it can just be sent the "update" message! @items.each { |item| item.update } self end private def class_from(name:) case name when "Aged Brie" AgedBrie when "Backstage passes to a TAFKAL80ETC concert" Backstage when "Sulfuras, Hand of Ragnaros" Sulfuras else CommonItem end end end I do not know for you, but for me, it starts to look really elegant. And simple. But let us go a little further. The content of #class_from is a real pain. Come on, you know me by now: it is a dreaded conditional! Even worse: it's a configuration conditional 🤢 Luckily for us, we know perfectly well a data structure that can handle a simple key/value configuration: we shall use an Hash. And here is what the (final?) code looks like: class CommonItem attr_reader :item def initialize(item) @item = item end def update item.sell_in -= 1 item.quality -= 1 item.quality -= 1 if item.sell_in < 0 limit_quality self end private def limit_quality return item.quality = 0 if item.quality < 0 item.quality = 50 if item.quality > 50 end end class AgedBrie < CommonItem def update item.sell_in -= 1 item.quality +=1 item.quality +=1 if item.sell_in < 0 limit_quality self end end class Backstage < CommonItem def update item.sell_in -= 1 item.quality = 0 and return self if item.sell_in < 0 item.quality += 1 item.quality += 1 if item.sell_in < 10 item.quality += 1 if item.sell_in < 5 limit_quality self end end class Sulfuras < CommonItem def update self end end:) ITEM_CLASSES[name] || CommonItem end end class Item attr_accessor :name, :sell_in, :quality def initialize(name, sell_in, quality) @name = name @sell_in = sell_in @quality = quality end def to_s() "#{@name}, #{@sell_in}, #{@quality}" end end Technically speaking, the refactoring is now finished. - We have a very lean class - Its responsibility is well defined - We can add a functionality very easily The last part will deal with this new functionality, and a sprinkle of refactoring: this time, we will try to accommodate my tiny brain with quality of life changes. Bye for now :) Discussion (0)
https://dev.to/lomig/a-walk-through-the-gilded-rose-kata-pt-4-discovering-what-gildedrose-really-is-41d
CC-MAIN-2021-31
refinedweb
1,005
76.22
nsICryptoHMAC This interface provides HMAC signature algorithms. More... import "nsICryptoHMAC.idl"; nsICryptoHMAC This interface provides HMAC signature algorithms. Completes this HMAC object and produces the actual HMAC diegest data. NOTE: This method may be called any time after |init| is called. This call resets the object to its pre-init state. Initialize the hashing object. This method may be called multiple times with different algorithm types. WARNING: This approach is not FIPS compliant. NOTE: This method must be called before any other method on this interface is called. Reinitialize HMAC context to be reused with the same settings (the key and hash algorithm) but on different set of data. Calculates and updates a new hash based on a given data stream. Hashing Algorithms. These values are to be used by the |init| method to indicate which hashing function to use. These values map onto the values defined in mozilla/security/nss/lib/softoken/pkcs11t.h and are switched to CKM_*_HMAC constant.
http://doxygen.db48x.net/comm-central/html/interfacensICryptoHMAC.html
CC-MAIN-2019-09
refinedweb
162
68.87
Welcome to Part. Creating Apps With Android Studio Overview This is a predominantly demo-based module. Larry explains the core features of the Android Studio development suite including: - Creating an activity-based project - The basic layout and usage of Android Studio UI - Adding and working with Java files - Adding and working with XML files - Helpful features and built-in Creating a New Activity Project In this lesson Larry shows us how to make a simple action bar based activity with fragments. I am trying out the advice on the very latest (as at 11th June) Android Studio 2.2 preview 3 release so that I can point out any differences to you… To start, click New Project and fill in these details: - Application name: ServiceInfoViewer - Module name: app - Package name: com.pluralsight.serviceinforviewer - Project location: C:\Dev_work\samples\ServiceInfoViewer (or wherever you like) - Minimum required SDK: API 15 (IceCreamSandwich) - Target SDK: API 19 Android 4.4 (KitKat) - Compile with: API 19 Android 4.4 (KitKat) We see the starter templates. Larry says new templates are being added all the time. He describes and briefly demos these ones: - Blank activity - Fullscreen activity - Master/Detail flow For more information on Fragments, Larry recommends Jim Wilson’s course Improving UI design with Android Fragments We choose Blank activity and use these default details on the next screen: - Activity name: MainActivity - Layout name: activity_main - Fragment Layout Name: fragment_main Larry explains each of the Additional Features options. We use “Include Blank Fragment”, and Android Studio creates all of our starter files for us in a new project. Android Studio UI Overview Larry highlights and explains each of the main UI elements in Android Studio: - Project View - Package View - Collapse Package Tree - Flatten Packages - Compact Empty Middle Packages - Toggle Border controls - Structure pane - TODO pane - Android pane - Event log pane - Gradle pane - Gradle console pane - Maven pane - Menu bar Creating UI Layouts Larry describes fragment_main.xml which is in app/src/res/layout, and the preview pane which shows roughly what the layout will render. We can select different device definitions, orientations and themes. Larry points out there are two tabs Text and Design and clicks on Design taking us to a Graphical design for the layouts. Larry says the LinearLayout performs better at runtime than a RelativeLayout. We see the error: Rendering Problems Except raised during rendering: Binary XML file line #-1: No start tag found! This means the designer hasn’t found a root layout. Larry says we can ignore this, but we’re about to change it. We drag the LinerLayout (vertical) onto fragment_main.xml and change the layout:height property to “wrap_content”. Then we add a ListView. This is found in the Containers directory. We see a sample view with a list of items with sub-item text. Next we give it an id of @+id/service_list We also add a Large Text widget. Because the screen is getting quite busy, drag this over to the Component Tree instead. When we scroll down to the text property, we see a yellow lightbulb on the left of it. This gives us the option of creating a string resource. Another way is to click the button to the right of the edit text field which has an ellipses in it. Larry also explains how to change the textStyle property to bold. Next we add a service detail fragment. File name: frag_srv_detail Root element: TableLayout For our details screen, we want to display rows of data for the service, and each row will have two columns: the name of the data, and the data itself. For the purposes of reuse, we create another layout which has just a table row in it. File name: item_srv_detail_row Root element: TableRow The last part of this lesson covers the XML we need to type in for both of these layouts. Writing Java Code In this lesson we add the plumbing for showing the details in MainActivity.java, beginning with the PlaceholderFragment method. We create a RunningServiceWrapper, and add code into onCreateView, onItemClick and onResume. Next we create a new Fragment called ServiceDetailFragment. We get errors due to the importing an invalid namespace android.support.v4.app.Fragment, and change this to andoird.app.Fragment. Larry explains all the code we need to add into the onCreateView method for this fragment.
https://zombiecodekill.com/2016/05/30/creating-apps-with-android-studio/
CC-MAIN-2017-43
refinedweb
722
54.32
10774/hyperledger-sendpeersproposal-promise-rejected-connect I am getting the following error when I am trying to install hyperledger and run chaincode. I am following the steps from here. error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Connect Failed error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: Connect Failed while running the query.js. I have following active docker running The problem is with the connection. First, find out the IP address of the system: $ ifconfig Then replace localhosts in query.js with IP that you found with the previous command Example: @@ -12,7 +12,7 @@ var options = { user_id: 'PeerAdmin', channel_id: 'mychannel', chaincode_id: 'fabcar', network_url: 'grpc://<IP address>:7051', }; Hi. I am new to Linux and when I run ifconfig, I am getting 2 IP address, which should I use? I think I have 2 interfaces. One is named lo and the other is named eth0. Which should I use? lo is a loopback address and eth0 is ethernet. Use the IP address for the interface eth0. Try to install nom first and then run node query.js. $ npm install When I run this, I am getting the following error: warning :npm WARN fabcar@1.0.0 No repository field. Open the datasources.json file and replace the grpcs:// with grpc://. This solution worked for me. This error happens because basic-network/docker-compose.yaml has CA ...READ MORE You could simply replace --net=bridge with --net=artifacts_default in your DockerFile. I used ...READ MORE This config worked for me: { "network-config": { ...READ MORE You can extend your /etc/hosts file and make orderer.example.com domain name ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE This was a bug. They've fixed it. ...READ MORE Not sure if you are still looking ...READ MORE The sample config files in the Hyperledger Fabric main ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/10774/hyperledger-sendpeersproposal-promise-rejected-connect?show=44810
CC-MAIN-2020-10
refinedweb
334
62.34
" and not "8 - 2 == 6".. goto last next redo dump left , => nonassoc list operators (rightward) right not left and left or xor In the following sections, these operators are covered in precedence order. Many operators can be overloaded for objects. See overload.. The parentheses enclose the argument list for "print" which is evaluated (printing the result of "$foo & 255"). Then one is added to the return value of "print" (usually 1). The result is something like. $i = 0; $j = 0; print $i++; # prints 0 print ++$j; # prints" is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than "undef"). The auto-decrement operator is not magical. Note that certain exponentiation expressions are ill-defined: these include "0**0", "1**Inf", and "Inf**0". Do not expect any particular results from these special cases, the results are platform-dependent.'' isn't numeric in negation (-) at .... Unary "~" performs bitwise negation, that is, 1's complement. For example, "0666 & ~027". When complementing strings, if all characters have ordinal values under 256, then their complements will, also. But if they do not, all characters will be in either 32- or 64-bit complements, depending on your architecture. So for example, "~"\x{3B1}"" is "\x{FFFF_FC4E}" on 32-bit machines and "\x{FFFF_FFFF_FFFF_FC4E}" on 64-bit machines. If the experimental ``bitwise'' feature is enabled via "use feature 'bitwise'", then unary "~" always treats its argument as a number, and an alternate form of the operator, "~.", always treats its argument as a string. So "~0" and "~"0"" will both give 2**32-1 on 32-bit platforms, whereas "~.0" and "~."0"" will both yield "\xff". This feature produces a warning unless you use "no warnings 'experimental::bitwise'".. Binary "!~" with a non-destructive substitution ("s///r") or transliteration ("y///r") is a syntax error. Binary "/" divides two numbers.). (raising a warning''.)".)match between its arguments. Smart matching is described in the next section. comparisions, look at the ``fc'' in perlfunc case-folding function, available in Perl v5.16 or later: if ( fc($x) eq fc($y) ) { ... }.. Smartmatching of Objects. Note that "&" has lower priority than relational operators, so for example the parentheses are essential in a test like print "Even\n" if ($x & 1) == 0; If the experimental ``bitwise'' feature is enabled via "use feature 'bitwise'", then this operator always treats its operand as numbers. This feature produces a warning unless you also use "no warnings 'experimental::bitwise'". isn} ])+/"). Because each operand is evaluated in integer form, "2.18 .. 3.14" will return two elements in list context. @list = (2.18 .. 3.14); # same as @list = (2 .. 3); printf "I have %d dog%s.\n", $n, ($n == 1) ? "" : "s"; Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected. and experimental. See ``Bitwise String Operators''. In list context, it's just the list argument separator, and inserts both its arguments into the list. These arguments are also evaluated from left to right. The "=>" operator (sometimes pronounced ``fat comma'') is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores. This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behavior,. open HANDLE, "< :utf8", "filename" or die "Can't open: $!\n"; However, some people find that code harder to read than writing it with parentheses: open(HANDLE, "< :utf8", "filename") or die "Can't open: $!\n"; in which case you might as well just use the more customary "||" operator: open(HANDLE, "< :utf8", "filename") || die "Can't open: $!\n"; See also discussion of list operators in ``Terms and List Operators (Leftward)''. print FH $data or die "Can't write to FH: $!"; This means that it short-circuits:) from the next line. This allows you to write: s {foo} # Replace foo {bar} # with bar. The following escape sequences are available in constructs that interpolate, and in transliterations: Sequence Note Description \t tab (HT, TAB) \n newline (NL) \r return (CR) \f form feed (FF) \b backspace (BS) \a alarm (bell) (BEL) \e escape (ESC) \x{263A} [1,8] hex char (example:. There are a couple of exceptions to the above rule. "\N{U+hex number}" is always interpreted as a Unicode code point, so that "\N{U+0050}" is "P" even on EBCDIC platforms. And if "use encoding" is in effect, the number is considered to be in that encoding, and is translated from that into the platform's native encoding if there is a corresponding native character; otherwise to Unicode... For example, $rex = qr/my.STRING/is; print $rex; # prints (?si-xm:my.STRING). p When matching preserve a copy of the matched string so that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined (ignored starting in v5.20) as these are always defined starting in that relese o Compile pattern only once. a ASCII-restrict: Use ASCII for \d, \s, \w; specifying two a's further restricts things to that last four modifiers listed above, (for example, "m//gc"). Modifying the target string also resets the search position. # a very old . If no string is specified via the "=~" or "!~" operator, the $_ variable is searched and modified. Unless the "/r" option is used, the string specified must be a scalar variable, an array element, a hash element, or an assignment to one of those; that is, some sort of scal. "eval"ed before being run as a Perl expression. Note the use of "$" instead of "\" in the last example. Unlike sed, we use the \<digit> form only in the left hand side. Anywhere else it's $<digit>.; $foo = q!I said, "You said, 'She said it.'"!; $bar = q('This is it.'); $baz = '\n'; # a two-character string $_ .= qq (*** The previous line contains the naughty word "$1".\n) if /\b(tcl|java|python)\b/i; # :-) $baz = "\n"; # a one-character string (for example, ";" on many Unix shells and "&" on the Windows NT "cmd" shell)..; } See ``I/O Operators'' for more discussion. split(" ", q/STRING/); the differences being that it,; for example, "tr[aeiouy][yuoiea]" or "tr(+\-*/)/ABCD/". Characters may be literals or any of the escape sequences accepted in double-quoted strings. But there is no interpolation, so "$" and "@" are treated as literals. A hyphen at the beginning or end, or preceded by a backslash is considered a literal. Escape sequence details are in the table near the beginning of this section. Note that "tr" does not do regular expression character classes such as "\d" or "\pL". The "tr" operator is not equivalent to the tr(1) utility. If you want to map strings between lower/upper cases, see ``lc'' in perlfunc and ``uc'' in perlfunc, and in general consider using the "s" operator if you need regular expressions. The "\U", "\u", "\L", and "\l" string-interpolation escapes on the right side of a substitution operator will perform correct case-mappings, but "tr[a-z][A-Z]" will not (except sometimes on legacy 7-bit data).. It turns out that in this example, these are the ASCII printable characters. So after this is run, $string has only controls and characters which have no ASCII equivalents. But, even for portable ranges, it is not generally obvious what is included without having to look things up. A sound principle is to use only ranges that. s Squash duplicate replaced characters. r Return the modified string and leave the original string untouched.. $ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case ASCII $cnt = tr/*/*/; # count the stars in $_ $cnt = $sky =~ tr/*/*/; # count the stars in $sky $cnt = tr/0-9//; # count the digits in $_ tr/a-zA-Z//s; # bookkeeper -> bokeper ( If multiple transliterations are given for a character, only the first one is used: tr/AAA/XYZ/ will transliterate any A to X. $@; The terminating string may be either an identifier (a word), or some quoted text. An unquoted identifier works like double quotes. There may not be a space between the "<<" and the identifier, unless the identifier is explicitly quoted. (If you put a space it will be treated as a null identifier, which is valid, and matches the first empty line.) The terminating string must appear by itself (unquoted and with no surrounding whitespace) on the terminating line. If the terminating string is quoted, the type of quotes used determine the treatment of the text. print <<EOF; The price is $Price. EOF print << "EOF"; # same as above The price is $Price. EOF. print << `EOC`; # execute command and get results echo hi there EOC It is possible to stack multiple here-docs in a row: print <<"foo", <<"bar"; # you can stack them I said foo. foo I said bar. bar myfunc(<< "THIS", 23, <<'THAT'); Here's a line or two. THIS and here's another. THAT Just don't forget that you have to put a semicolon on the end to finish the statement, as Perl doesn't know you're not going to try to do this: print <<ABC 179231 ABC + 20; If you want to remove the line terminator from your here-docs, use "chomp()". chomp($string = <<'END'); This is a string. END If you want your here-docs to be indented with the rest of the code, you'll need to remove leading whitespace from each line manually: ($quote = <<'FINIS') =~ s/^\s+//gm;.. Note also that the interpolation code needs to make a decision on where the interpolated scalar ends. For instance, whether "a $x -> {c}" really means: "a " . $x . " -> . It is at this stage that "split()" silently optimizes "/^/" to mean "/^/m"." at end-of-file or on error. When $/ is set to "undef" (sometimes known as file-slurp mode) and the file is empty, it returns '' the first time, followed by "undef" subsequently. Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a "while" read input from STDIN. If what the angle brackets contain is a simple scalar variable (for example, . Even "<$x >" (note the extra space) is treated as "glob("$x ")", not "readline($x)"." extension. Of course, the shortest way to do the above is: chmod 0644, <*.c>; A (file)glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it will start over. In list context, this isn't important because you automatically get them all anyway. However, in scalar context the operator returns the next value each time it's called, or "undef" when the list has run out. As with filehandle reads, an automatic "defined" is generated when the glob occurs in the test part of a "while", because legal glob returns (for example,. If precomputes the number which that expression represents so that the interpreter won't have to. 1 while foo(); This somewhat unpredictable behavior can be avoided with the experimental ``bitwise'' feature, new in Perl 5.22. You can enable it via "use feature 'bitwise'". By default, it will warn unless the "experimental::bitwise" warnings category has been disabled. ("use experimental 'bitwise'" will enable the feature and disable the warning.) Under this feature, the four standard bitwise operators ("~ | & ^") are always numeric. Adding a dot after each operator ("~. |. &. ^.") forces it to treat its operands as strings: use experimental . The behavior of these operators is problematic (and subject to change) if either or both of the strings are encoded in UTF-8 (see ``Byte and Character Semantics'' in perlunicode. See ``vec'' in perlfunc for information on how to manipulate individual bits in a bit vector..
http://linuxhowtos.org/manpages/1/perlop.htm
CC-MAIN-2020-10
refinedweb
1,972
65.52
On 01/11/2012 08:27 PM, Peter Rosin wrote: > Stefano Lattarini skrev 2012-01-11 18:31: >> Hi Peter, sorry for the delay. > > No rush! > >>>>>> We could enhance your original workaround like this: >>>>>> >>>>>> am__remove_distdir = \ >>>>>> { test ! -d "$(distdir)" \ >>>>>> || { find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ >>>>>> - && rm -fr "$(distdir)"; }; } >>>>>> + && if rm -fr "$(distdir)"; then :; else \ >>>>>> +## On MSYS (1.0.17) it is not possible to remove a directory that is >>>>>> +## in use; so, if the first rm fails, we sleep some seconds and retry, >>>>>> +## to give pending processes some time to exit and "release" the >>>>>> +## directory before we removed. See automake bug#10470. >>>>>> + sleep 5 && rm -fr "$(distdir)"; fi; }; } >>>>>> am__post_remove_distdir = $(am__remove_distdir) >>>>>> endif %?TOPDIR_P% >>>> >>>>> This works, best so far! Committable, if you ask me. >>>>> >>> >> Could you try the attached test case to see if it can reliably expose the >> problem on MSYS/MinGW? If yes, I'll prepare a patch shortly. > > If I (try to) mend the race (the "rm -rf foo.d" reliably beats the "cd foo.d" > in the subshell) by adding a "sleep 1" before the "rm -rf foo.d" > Thanks for the info, I've amend the test accordingly. > So, I guess no, the probelm is not exposed by the test. > > Did you mean "$my_sleep &" in the foo.test script? > Yes, I did; sorry for the sloppiness. > If add that &, the test fails in much the same way as we've seen previously > in this bug report. > Good! Attached is the proposed patch series: the first patch should expose the bug, the second patch should fix it. I will apply them once I have confirmation the bug is correctly exposed and fixed. Thanks, Stefano. 0001-coverage-expose-automake-bug-10470-distcheck-related.patch Description: Text Data 0002-dist-avoid-distdir-removal-failure-on-MSYS-MinGW.patch Description: Text Data
http://lists.gnu.org/archive/html/bug-automake/2012-01/msg00121.html
CC-MAIN-2016-26
refinedweb
304
76.52
Linux 4.1 has arrived with a new feature for its popular ext4 filesystem: filesystem-level encryption! This feature appears to have been implemented by Google since they plan to use it for future versions of Android and Chrome OS. Android filesystem encryption currently relies on dm-crypt. Google's motivations for pushing encryption to ext4 seem: - To avoid using a stacked filesystem design (for better performance?). - To encrypt data with integrity. - To allow multiple users to encrypt their files with different keys on the same filesystem. I decided to write a userspace tool to use this new feature: ext4-crypt. At the time of writing, my personal opinion is the current kernel implementation is really shaky and unstable and should not be used. Although future kernel versions will certainly come with enhancements, I think this is far from being production-ready and has been pushed prematurely into the kernel (I encountered kernel crashes by merely testing it as a simple user). Let's move on and take a peek at the implementation. Cryptographic implementation This section describes the implementation as of Linux 4.1.3. ext4 encryption works on a per-directory basis. An encryption policy is at first applied to an empty directory. The policy specifies basic information like: - Versioning information. - The cipher used for encrypting filenames. - The cipher used for encrypting file contents. - The length of padding for filenames (4, 8, 16 or 32). - An 8 bytes descriptor used to locate the master key in the user keyring. On the disk structure, an encryption context is associated with the inode and stored in an extended attribute. The type of xattr used does not belong to any namespace, and you won't be able see it with a userspace tool like getfattr. The encryption context contains the same information as the encryption policy, along with a random nonce of 16 bytes that is used to derive the encryption key. Each inode has its own random nonce, so as a result each file in the directory is encrypted with a different key. Every time a new inode is created inside that directory, the encryption context will be inherited from the parent directory. The encryption process is only applied to three kind of files: directories, regular files and symbolic links. For now, it is not possible to choose the cryptographic ciphers: - File contents will be encrypted with aes256-xts. - Filenames will be encrypted with aes256-cbc-cts (IV = 0) and encoded with an algorithm similar to base64. No data integrity is implemented yet. However more cipher modes will be available in the next kernel versions, including aes256-gcm. When an encrypted inode is accessed, the master key associated with its policy descriptor is requested from the user keyring. The key type must be logon (i.e. readable only by kernel) and the key descriptor be formatted as ext4:<policy descriptor in hexa>. If the master key is not found, opening the file will return an access denied error. Otherwise, the encryption key is derived from the master key and the nonce using aes128-ecb. Surprisingly, there is no verification that the provided master key is actually the one that was used to encrypt the file contents in the first place. This is an overview of the encryption process: AES256-CBC-CTS +--------------------+ & encode +------------------+ |ext4 dentry +--------+-------->ENCRYPTED FILENAME| | | | | | +---------^----------+ | +------------------+ | | | | +---------v----------+ AES256-XTS +------------------+ |ext4 inode +--------+-------->ENCRYPTED CONTENTS| | | | | | +--------------------+ | +------------------+ |encryption xattr | | | +------------------------+ policy desc +---------v----------+ | | USER SESSION KEYRING <-----------------+ crypto context | | | | | | | | +-------------------+ +-----------------> - policy descriptor| | | | ext4 policy: key | | master key | - random nonce | | | +-------------------+ | | | | +------------------------+ +---------+----------+ | | | AES128-ECB(master_key, nonce)| | | | +---------v----------+ | | ENCRYPTION KEY +--------+ +--------------------+ Usage from userspace To use ext4 encryption, one first needs to have a Linux 4.1+ kernel compiled with CONFIG_EXT4_ENCRYPTION. The process of encrypting a directory is quite simple and does not require any particular privilege other than owning the directory: - First ensure the directory is empty. - Open the directory and send an ioctl to assign it an encryption policy. - Insert the master key into the user session keyring. The key must be of logon type. That's it. Now, every file you write inside that directory will be transparently encrypted on disk. I wrote a userspace tool to create encrypted ext4 directories. You can download it from github. To create an encrypted directory, simply do: $ mkdir vault $ ext4-crypt create vault Enter passphrase: Confirm passphrase: vault: Encryption policy is now set. $ ext4-crypt status vault vault/: Encrypted directory Policy version: 0 Filename cipher: aes-256-cts Contents cipher: aes-256-xts Filename padding: 4 Key descriptor: lkVZDRI6 Key serial: 524153968 You can then check the master key is properly assigned to your keyring and is not readable: $ keyctl show Session Keyring 813374732 --alswrv 1000 65534 keyring: _uid_ses.1000 758072319 --alswrv 1000 65534 \_ keyring: _uid.1000 524153968 --alsw-v 1000 1000 \_ logon: ext4:6c6b565a44524936 When the ext4 volume is mounted and no key is provided, filenames will appear as encrypted and reading or writing to files will be denied. You can access the directory contents by inserting the master key again into the keyring: $ ls vault ,nCGhbNxWfdBfzffulophA 74XmRzli9dITlYBWLbpkTD CdJOUkfjKxzOd+0zYaO0GC $ ext-crypt attach vault Enter passphrase: $ ls vault Documents Downloads Music Remarks The current implementation of ext4 encryption has a number of problems compared to the existing alternatives for disk encryption. The biggest of them in my opinion is the lack of key verification on the kernel side. Any key you insert into the user keyring will be blindly accepted by the kernel and used for all kind of file operations. As a consequence you can read and write to files with the wrong encryption key, resulting in data corruption or just reading junk data. This can lead to even stranger situations because filenames decrypted with the wrong key can contain slashes and null bytes, which are forbidden characters for the filesystem. Decrypted filenames can contain "/" or "/../", and you can't open them. I'm not even sure what are the actual implications of this, but that probably should never happen. Some parts of the code also indicates a lack of testing. From fs/ext4/crypto_key.c in Linux 4.1.3: ukp = ((struct user_key_payload *)keyring_key->payload.data); if (ukp->datalen != sizeof(struct ext4_encryption_key)) { res = -EINVAL; goto out; } master_key = (struct ext4_encryption_key *)ukp->data; BUILD_BUG_ON(EXT4_AES_128_ECB_KEY_SIZE != EXT4_KEY_DERIVATION_NONCE_SIZE); BUG_ON(master_key->size != EXT4_AES_256_XTS_KEY_SIZE); // <--- ??? Why return an error code on user-supplied data when you can just oops the kernel? Other issues include the filesystem cache that is not invalidated when the key is unlinked and still lets you see the plaintext filenames. An encrypted directory is also left in a inconsistent state if a policy is applied and no inode is created before the device is unmounted. I encountered some kernels crashes during the development of the tool with some basic file/key manipulations. I am really surprised since I would have expected a very thorough code review and a lot of testing for a major filesystem like ext4. It is probably wise to wait for the next kernel versions before using this feature. Some of these problems will hopefully be fixed by then and new features like data integrity should be added in the future.
https://blog.quarkslab.com/a-glimpse-of-ext4-filesystem-level-encryption.html
CC-MAIN-2021-39
refinedweb
1,184
54.32
Disclaimer: This article is not about which components are better, but more of a discussion on the differences. When I started learning React with my bootcamp, we mainly focused on using class components -- if there is initial state, and presentational components if we are just grabbing props. I heard of functional components, but never felt comfortable using it until I started learning Hooks (Remember you can only use Hooks in functional components, not class components). Let's break down the syntax difference in each of these components! Difference 1: Rendering JSX 🕹 Syntax 🕹 Class Component (without ES6 destructuring) import React from 'react'; class App extends React.Component { render() { return <h1>Hello, World!</h1>; } } Functional Component import React from 'react'; function App() { return <h1>Hello, World!</h1>; } 🍳 Breakdown 🍳 As you can see above, there are a couple obvious differences in functional component: - We don't need to extend a component - We also don't need to use the renderkeyword. Q: Why do we need to extend the React.Component class in class component? A: In React, by extending the React.Component class, it allows us to pass props to a user defined class/component and inherit methods from React.Component class, like the lifecycle methods ( componentDidMount, componentDidUpdate, componentWillUnmount, render) and setState. 📝 Note 📝 In case you don't know, render is one of the lifecycle methods and the only required method in a class component. It would examine this.props and this.state and return types like React elements (JSX), array and fragments, etc. Do not expect it will modify component state! The React documentation has a very precise and clear explanation on the render method, as well as the rest of the lifecycle methods. here ⭐️ Additional Note ⭐️ Here's a rule of thumb 👍🏻: If you only have the render method in your class component, use functional component (which is referred as stateless component sometimes) instead. In functional component, everything defined in the function's body is the render function which returns JSX in the end. That's how Hooks comes in place as well. In case you want to make a state change in that functional component, you can easily add it without changing to class component by using useState and useEffect for lifecycle methods (will cover that in a bit!). Resources - Extending React (JavaScript January) - Why we do extends React.Component when creating the class component in React? (Stack Overflow) Difference 2: Passing Props 🕹 Syntax 🕹 Let's say we have a props name from this Component: <ExampleComponent name="Megan" /> Class Component class ExampleComponent extends React.Component { render() { const { name } = this.props; return <h1>Hello, { name }!</h1> // or without destructuring, it will look like this: // return <h1>Hello, { this.props.name }!</h1> } } Functional Component // with destructuring const ExampleComponent = ({ name }) => { return <h1>Hello, { name }!</h1> } // without destructuring const ExampleComponent = (props) => { return <h1>Hello, { props.name }!</h1> } 🍳 Breakdown 🍳 In class component, since it is a class, we have to use this to refer to the props, or we can destructure it to get name inside props. Or if we have multiple props, we can do that too: class ExampleComponent extends React.Component { render() { const { name, age, occupation } = this.props; return ( <div> <h1>Hello, { name }!</h1> <p>I am { age } yo and I work as a { occupation }.</p> </div> ) } As for functional components, we are passing props as an argument of the function. Same as above, if we have mutliple props, we can do this: // with destructuring const ExampleComponent = ({ name, age, occupation }) => { return ( <div> <h1>Hello, { name }!</h1> <p>I am { age } yo and I work as a { occupation }.</p> </div> ) } // without destructuring const ExampleComponent = (props) => { return return ( <div> <h1>Hello, { props.name }!</h1> <p>I am { props.age } yo and I work as a { props.occupation }.</p> </div> ) } Difference 3: Handling and Updating state Before React 16.8 (released in Feb 2019), class component was the only component that can handle state. With the introduction of Hooks and its useState in React 16.8, we can handle state in functional component! yay! In case you are not familiar with Hooks and wondering what so special about this Hooks thing, this Intro to Hook from React documentation explains pretty thoroughly. (Off topic: I personally enjoy reading the React documentation because they are able to explain the most technical concepts in a not so robotic and boring tone, really unlike a lot of the documentations I have read. I highly recommend you to spend some time reading the doc!) 🕹 Syntax 🕹 Class Component class ExampleComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0, name: "Megan" }; } // or you can write this without constructor(): // state = { // count: 0, // name: "Megan" // }; render() { return ( <div> <h1>Hello, {this.state.name}</h1> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click to add 1 </button> </div> ) } } Alternatively, you can write the function inside onClick event before render(): class ExampleComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0, name: "Megan" }; } // or you can write this without constructor(): // state = { // count: 0, // name: "Megan" // }; handleClick = () => { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> <h1>Hello, {this.state.name}</h1> <button onClick={this.handleClick}> // or <button onClick={() => this.handleClick()}> Click to add 1 </button> </div> ) } } Functional Component // by the way, I don't want to continue this without explanation // This is the arrow function, in case you are not familiar // Alternatively, you can also write // function ExampleComponent() // They are basically the same thing. import React, { useState } from 'react'; // ES6 destructure ^ const ExampleComponent = () => { const [count, setCount] = useState(0); // or without destructuring, this will be React.useState(0) return ( <div> <h1>Hello, {this.state.name}</h1> <button onClick={this.handleClick}> // or <button onClick={() => setCount(count + 1)}> Click to add 1 </button> </div> ) } 🍳 Breakdown 🍳 In class component, we can access the value of the state by using this.state inside JSX and we would use setState to update the value of the state. You can set the function inside the event or outside of the render() method -- for readability. In functional component, we would use useState to assign initial state and we would use setCount (in our example) to update the state. If we want to access the value of the state, we can omit this.state and call the name of the state instead, in our case, it would just be count. Q: What's with the square bracket, like [count, setCount]? A: The [count, setCount] syntax is called "array destructuring"!! We are basically making two new variables, in other words, let countVariable = useState(0); let count = countVariable[0]; let setCount = countVariable[1]; This can be quite confusing by accessing with 0 and 1 as they have a specific meaning, so React use the "array destructuring" instead. This is simply the highlight I got from the React documentation, here's the section where you can read in details! Last but not least... Difference 4: Lifecycle Methods useEffect is the combination of componentDidMount, componentDidUpdate and componentWillUnmount. componentDidMount It is invoked immediately after a component is mounted (Mounting means when an instance of a component is being created and inserted into the DOM -- React Doc). 🕹 Syntax 🕹 Class Component class ExampleComponent extends React.Component { this.state = { data: [] } componentDidMount() { fetch(someUrlHere) .then(res => res.json()) .then(data => this.setState(data)) } render() { ... } } Functional Component const ExampleComponent = () => { const [data, setData] = useState([]); useEffect(() => { fetch(someUrlHere) .then(res => res.json()) .then(data => setData(data)) }, []); return ( ... ) } 🍳 Breakdown 🍳 In class component, componentDidMount is only called once after the first render. In functional component, we replace componentDidMount with useEffect. As we can see there's a [] in the second argument, we usually would put some state we like to update/change, let's say you want to restart a quiz app. useEffect will only be called if there's any selected changes. In our case right now, since it is an empty array, useEffect will be called once on mounting, similar to componentDidMount. As you can see in both components, we can set state inside the methods. Further Reading - If you are interested in seeing how useEffect works with fetching data using async/await and axios, here's a great article 👩🏻💻Author's Note: I am not so sure how to demonstrate the componentDidUpdate() and useEffect(). If you are interested, I am attaching this link from React Doc, this Stack Overflow post and How to mimic componentDidUpdate() with React Hooks from another dev.to writer. Based on my quick research, it looks like we may need useRef() and custom hook, which currently is out of my knowledge range at the moment.👩🏻💻 componentWillUnmount It is invoked immediately before a component is unmounted and destroyed. It is usually used for performing any necessary cleanups. One of the most straightforward examples is clear an interval ( clearInterval duh). 🕹 Syntax 🕹 (Code reference from this Stack Overflow post) Class Component class ExampleComponent extends React.Component { this.state = { data: [] } // say we have a mounted function that returns a boolean mounted = () => { ... } componentDidMount() { this.mounted = true; fetch(someUrlHere) .then(res => res.json()) .then(data => { if (this.mounted)) { this.setState(data) } }) } componentWillUnmount() { this.mounted = false; } render() { ... } } Functional Component const ExampleComponent = () => { const [data, setData] = useState([]); useEffect(() => { let isMounted = true; request.get(url) .then(result => { if (isMounted) { setData(result); } }); return () => { isMounted = false; }; }, []); return ( ... ) } 🍳 Breakdown 🍳 Not so much of a breakdown, but as you can see: Cool thing about useEffect is that you can write functions for both mounting and unmounting in the same place. componentWillUnmount is useful when doing cleanups as mentioned above, without that, it can cause severe memory leaks on a bigger project. Conclusion As this article is getting longer, I promise I will keep this conclusion section short but short enough to give you room to think about. React Hooks are taking over in modern React, as it is created to be more relevant and timeless (according to the React doc). From the comparisons above, we can see how functional components are written shorter and simpler, which makes it easier to read, write and test -- because they are just plain JS functions. However, the rendering time and performance in either components do not make a lot of differences. I do not necessarily think one is better than the other. A functional programmer may find easier to use functional components, while that applies the same to an object oriented programmer may find easier to use class components. As I mentioned in the introduction, I started with class components and I am currently in the transition of using functional components, as I like React Hooks a lot and I feel like I can do a lot more with it, but I still feel more comfortable to use the lifecycle methods in class component. There are a lot of discussions out there which one is better than which and why one prefer over the other. Let me know what you think and let's start a discussion down below! Further Readings - Container vs Presentational Components in React - Functional Components Vs. Class Components In React.Js 👉🏻 They got more in-depth with the analysis and did some performance test - Understanding Functional Components vs. Class Components in React 👉🏻 Codepen examples - Introducing Hooks (React Documentation) 👉🏻 As you may have noticed, I have quoted from React documentation so many times in this article. I promise you you will find the documentation super helpful and also since React is a front-end framework, let's all agree that the design of the documentation makes it more fun to read 🙌🏻 - React Class Components vs Functional Components with Hooks: A Never Ending Story by my developer friend, Andrej. As there are discussions around using Hooks or not, Andrej talked about the pros and cons about React Hooks and why it is better with Hooks. Go check it out if you are interested! If you are looking for more articles/resources to read, I recommend to look for articles that are written after Feb 2019, as it is more relevant to the current React version. Discussion (9) So basic rules for useEffect: useEffect(() => { // some logic }, []); useEffect(() => { // some logic }); useEffect(() => { // some logic }),[ param1, param2 ]; useEffect(() => { // some logic return () => { // some umount logic } }); thank you for commenting this!!! this is super helpful! Functional components are much much easier than class ones. Once I rewrote an app to functional components and never regret of this. Yet, writing custom hooks is much easier than writing higher order components. I am still learning about custom hooks atm! Would you mind elaborating more on that and how it is easier than writing HOC for readers who just started exposing to functional components? thanks! I'm not sure I can explain this in couple of words 🙂 In general, HOCs require you to combine and destructure passed props which is always cumbersome. Implementing some logic atop of it adds more complexity. Perhaps you find interesting my post on creating no-lib global store. I implement it with hooks, and that's trivial; then reimplement the same with HOCs, and that looks very convoluted. Thank you for creating this post, i am also trying to learn how to code with functional component. Nice explanation! Nice breakdown and analysis. Personally I'm a much bigger fan of Hooks/ functional components. It's interesting to see them compared. After using Hooks on one of my projects and spending a lot more time on Hooks documentation, I am convinced to use Hooks more often and definitely see a lot more benefits from that 🙌🏻
https://dev.to/mehmehmehlol/class-components-vs-functional-components-in-react-4hd3
CC-MAIN-2022-33
refinedweb
2,229
55.95
* A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Java » Game Development Author Java Intersects Mohammed Uddin Ranch Hand Joined: Mar 04, 2012 Posts: 31 posted Mar 04, 2012 12:29:01 0 Hi, This is my very first post and I am new to this forum. I wish to both benefit and contribute to this forum with regards to Java Programming. Anyway, I not new to Java but new to Java Game Development. I am making a very basic version of break out. To briefly describe what breakout is: It is a simple game where the players paddle is located on the bottom of the screen with a ball bouncing around the screen. The player must move the paddle (located on the bottom of the screen) left or right and prevent the ball from hitting the south side of the screen. On the top of the screen are where all the bricks are positioned. When the ball hits the players paddle and bounces back up it hits one of the bricks. At this point the brick hit disappears and the ball then bounces back down towards the player's paddle. This is the basic principle of breakout. The problem I am having is this. I am using intersects to detect the collision between the ball on the screen as it bounces about with both the player's paddle and the bricks. The collision works but to a certain extent. When using intersects, when the ball say moves towards the north side of the paddle, the ball hits the paddle and collision works fine. If the ball however moves towards the paddle from the south side of the paddle, the ball travels through the paddle and when it hits the north side it then reacts as per collision design. In essence, collision (intersects) works only when the ball hits either the paddle or a brick if it hits the object from a certain side. Otherwise it travels through the object and once it hits the other side, it then reacts to collision (e.g. brick disappears, ball bounces etc). As I am new to intersects I am not sure why this is happening. I have given the collision code below. public void paddleCollision() { if (ball.intersects(paddle.paddle)){ this.setYDirection(-1); } } public void brickCollision() { for (int i = 0; i < rowAmount; i++) { if (ball.intersects(bricks[i].brick)) { bricks[i].brick.setLocation(-100, -100); this.setYDirection(-1); } } } Thanks in advance for any help provided. Also, sorry for the long post. This is my first post and was not entirely sure how much info to provide. Caleb Kemper Greenhorn Joined: Feb 08, 2012 Posts: 27 I like... posted Mar 05, 2012 06:05:20 0 It may be an issue with your setYDirection() method. Could you post that? Also, the instance data for the ball class would be helpful. And how are you going about dealing with motion? Do you have velocity variables and a tick? or are you doing position with logic? Thanks, Caleb Mohammed Uddin Ranch Hand Joined: Mar 04, 2012 Posts: 31 posted Mar 05, 2012 11:41:26 0 Here is the code for the ball: import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.util.Random; public class Ball implements Runnable { int x, y, xDirection, yDirection; Rectangle ball; static Paddle paddle; static Bricks[] bricks = new Bricks[12]; static final int rowAmount = 12; Ball(int x, int y) { this.x = x; this.y = y; int r = (int)Math.random() * 1; int xrDir = r; if (xrDir == 0) xrDir--; setXDirection(xrDir); int yrDir = r; if (yrDir == 0) yrDir--; setYDirection(yrDir); ball = new Rectangle(this.x, this.y, 10, 10); paddle = new Paddle(200, 450); for (int i = 0; i < rowAmount; i++) { bricks[i] = new Bricks(50 + (i * 35), 100); } } public void setXDirection(int x) { this.xDirection = x; } public void setYDirection(int y) { this.yDirection = y; } public void draw(Graphics g) { g.setColor(Color.GREEN); g.fillRect(ball.x, ball.y, ball.width, ball.height); } public void paddleCollision() { if (ball.intersects(paddle.paddle)){ this.setYDirection(-1); } } public void brickCollision() { for (int i = 0; i < rowAmount; i++) { if (ball.intersects(bricks[i].brick)) { bricks[i].brick.setLocation(-100, -100); this.setYDirection(-1); } } } public void move() { this.paddleCollision(); this.brickCollision(); ball.x += this.xDirection; ball.y += this.yDirection; if(ball.x <= 0) { setXDirection(+1); } if (ball.x >= 490) { setXDirection(-1); } if(ball.y <= 15) { setYDirection(+1); } if (ball.y >= 490) { setYDirection(-1); } } public void run() { try { while (true) { move(); Thread.sleep(10); } } catch (Exception e) {} } } The ball is a thread object where at each interval of Thread.sleep the move command is called. This makes the ball moves (the players paddle is similar to this). There really isnt a velocity per say. As reuqested the setYDirection is also present in the code. The code provided is the entirty of the ball class. Once again, any help would be welcome. Thanks Caleb Kemper Greenhorn Joined: Feb 08, 2012 Posts: 27 I like... posted Mar 05, 2012 19:55:55 0 Alright, I'm not ENTIRELY sure, as my set-up when I do something like this is a bit different. I believe the problem is with your setX/YDirection methods. Instead of only negating that variable when intersects occurs, you want to toggle it. I would probably write it something like this... public void setXDirection() { this.xDirection *= -1; } public void setYDirection() { this.yDirection *= -1; } This way, if the variable is positive, it'll become negative, and vice versa. Your setup before only allowed the intersects to work from one direction, because if the variable was already negative, then nothing would really occur, and it would go right through. When I work with my movement, I have a velocity variable which does the same thing--toggles when necessary. Hope this helps, Caleb Mohammed Uddin Ranch Hand Joined: Mar 04, 2012 Posts: 31 posted Mar 06, 2012 12:29:36 1 Hi, Thanks a lot buddy. You really helped me out here. I wasn't event aware of the fact that a negative number would remain negative. Yes, your idea worked perfectly for me. Thanks, Mohammed I agree. Here's the link: subject: Java Intersects Similar Threads Screen Flashes BreakOut Java Bug can not move the paddle in this program Timely response to user input The game "Breakout", stuck with collision checking All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/569325/Game-Development/java/Java-Intersects
CC-MAIN-2014-35
refinedweb
1,094
66.74
Cheat Sheet Beginning C Programming For Dummies The best way to learn programming is to start with a fundamental language like C. Nearly every other popular language today borrows from C. Whether you’re curious about programming, need to pass a college course, or want to start your own app business, learning C is the right place to begin. Understanding the C Language Skeleton Most coding starts with a C language structure. This skeleton includes the basic bones upon which most programs are written. Use this simple skeleton to get started: #include <stdio.h> int main() { return(0); } Traditionally, the program begins with preprocessor directives plus prototypes. The #include statements bring in header files, such as stdio.h, the standard input/output header file. The primary function in all C code is main(), which is the first function that's run when the program starts. The main() function is an int function, so it must return an integer value. All the function's statements are enclosed in curly brackets, or braces. C Language Keywords. C Language Variable Types. Common C Escape Sequences. Common C Conversion Characters The printf() and scanf() functions use conversion characters as placeholders for various values. Conversion characters are used to indicate a value when the function runs in the final program. The Order of Precedence in C.
http://www.dummies.com/how-to/content/beginning-c-programming-for-dummies-cheat-sheet.html
CC-MAIN-2016-07
refinedweb
221
67.86
369/list-elements-that-with-particular-string-using-selenium-ruby Below is a method to check if the panel is displayed or not. def verifyNav(section) wait = Selenium::WebDriver::Wait.new(:timeout => 10) wait.until { @driver.find_element(:id => section + '-panel').displayed? == true } end I want to add code, which says that all other elements that have an id that ends in '-panel' should not be displayed. I found that I can use the end_with method in which there is a find_elements method that returns a list of matching elements. a = 'radio-panel' a.end_with?('-panel') returns true.. but if I try to call @driver.find_elements(:id => end_with?('-panel')) I get an error saying that end_with is an undefined method. Any ideas on what I can do? The problem is that, the end_with method is not defined anywhere. Try using a CSS selector: @driver.find_elements(:css => '[id$="-panel"]') Hopefully this should work. @Rajni, following test case is somewhat similar ...READ MORE Hey Paula, to get the tagname of ...READ MORE Hey Fawad, you can use this piece ...READ MORE Hi Sunita, you can use following code .. @Beforesuite annotated method runs before the testNG.XML ...READ MORE Hey, try using following code command to ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/369/list-elements-that-with-particular-string-using-selenium-ruby
CC-MAIN-2020-05
refinedweb
211
71.1
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives I was thinking about this yesterday. If the point of functional code is that it is easier to reason about, should we like Monads? Consider we have an interpreter, and that we construct a sequence of commands in the free monad. Given a program like this: f = do s <- newRef writeRef s 23 writeRef s 42 readRef s Now I have deliberately not specified the implementation of the interpreter, it could be pure using threading, it could be impure using IORef, or it could be any other valid implementation in Haskell except we won't allow "unsafe" code. The question is, just looking at the above code, it looks like "s" is mutated. Yes the implementation in the monad could be pure and use state threading, but how does that help us reason about the above imperative program? How is the above program any better than the following JavaScript program: function f() { var s s = 23 s = 42 return s } Ignoring syntax differences (because we can trivially translate from one syntax to the other) surely we can make any argument about implementation in the free monad with an interpreter about this code that we can about the first example? Surely this means that this second imperative program is no easier or harder to reason about than the first? Hence my deliberately controversial title, why write an imperative program in a monad? Either we should actually write code in a visibly referentially transparent way like this: f = let s1 = 23 in let s2 = 42 in s2 Or we may as well just use an impure language to start with. (I am deliberately ignoring the fact that parts of a program could be pure in Haskell). The second second part of this question is, if making a program look as if it had state is as bad as having state from an analysis point of view, how could we prevent this in the type system? What loophole is allowing 's' to behave as if it had state, and how can that be closed? Some answers that occur to me, for discussion are, that the first example really is no better than the second. We have in effect implemented an impure imperative language and embedded it in our pure functional language. This is always going to be possible because our pure functional language is turing-complete and if we have the ability to write a program that interprets a different impure imperative language in a file or string, and we have the ability within the pure functional language to compose fragments that represent parts of this impure imperative languages abstract syntax, you can't stop programmers doing this kind of embedding. The final part of my answer would have to be with my current thinking that even though you can do this, it is not a good idea, as you may as well program in an existing impure imperative language, just like it is not a good idea to shoot yourself in the foot, although you can. Edit: Another way to look at this is we could create an embedding for BASIC into our pure functional language, but this does not make BASIC a better language to program in. Does an embedding of a BASIC interpreter into a pure functional language make it any easier to reason about BASIC programs? JavaScript is a mess with its truthiness, implicit conversions, dubious semicolon insertion, second class references, automatic variable declarations, weird scoping, etc.. You'd need to try harder to make the Haskell imperative monad just as bad as JavaScript. Writing a JavaScript interpreter would do it, though. I agree with one of your general hypotheses, that reasoning within the embedded language isn't easier than implied by the features of said language. We do gain some benefits though. Like, JavaScript needs specific language constructs for looping. But with monadic languages, we can use generic loop and control abstractions. And there's also abstraction of the monad type itself, e.g. use of "writeRef" and "readRef" could be abstracted under a typeclass (e.g. using type family for reference type), allowing this little program fragment to be reused for many language feature sets. I won't posit that monads are the best option. Monadic behavior is an especially awkward fit for concurrency. We could try process networks as an alternative to monadic effects models. In retrospect, I think monads did not waste my time because it allowed me to think about my effects models and explore various alternatives in ways that working in concrete languages never did. This is liberating. When my entire programming experience was in imperative languages, I had little cause to even begin thinking about other ways of doing things, and when I did explore the language's pervasive features would fight me. Like, what if we take an imperative language but remove only "new" from "newRef" etc.. Instead a space of references will be provided to the program and accessed by URL-like values. This makes saving program state, backtracking, inspecting and rendering state, pausing and resuming or continuously updating and compiling the program, etc.. much easier. I wouldn't easily think about this in languages where fresh variables are cheap and pervasive. Following Betteridge's law of headlines... I don't think Monads, as an abstract algebraic concepts are a waste of time. My thinking was more along the lines of unintended consequences. We take something that seems harmless (turing-completeness and the ability to write interpreters) and something else harmless (the free monad) and put them together to create something that appears to break referential transparency. I know it does not technically break referential transparency because of state threading, but when you read that embedded program it looks like it does, and I don't think it helps make that embedded program any more analysable. It's a loophole that lets us have stateful objects. Now if we admit we want stateful objects, isn't all this linguistic boilerplate and complexity a problem and not a solution. We may as well build stateful objects into the language directly and design a type system that deals with it nicely. Even if we want stateful objects, I might not want the design that you're thinking about. There are a lot of approaches to state (and objects) based on whether we want global features like undo, replay, transactions, publish-subscribe, iteration over objects, choice of concurrency model, etc.. You dismiss monads as just "a loophole that lets us have stateful objects." But I think of them more as "a substrate for a sequential DSL" which might not have arbitrary state (e.g. parser combinators, or restricting shared state to CRDTs) or might have non-conventional ideas about state (e.g. STM, ST, or adding logical timestamps to states and aggregating events to compute the next state, etc..). Of course we can model languages that are difficult to reason about. But we can also model languages that are relatively easier to reason about, where some equational reasoning might still hold. That flexibility has been useful to me. Algebraic effects seem to be able to do all the things you list as important, without needing a monad as an explicit construct. You could use the argument that Monads are algebraic properties, so something that has the correct properties is still a monad whether you explicitly declare it as such or not (and I myself have made that argument in the past), but it does not require the programmer to understand Monads. The interesting question for me here is, if you have algebraic effects, what else do you need to have a concise self-consistent language. Do you need constructor classes? Do you need higher kinded types? Algebraic effects are useful. If you use the operational monad together with some row polymorphic variants (cf. the "freer" monad of Oleg Kiselyov's "Free and Freer Monads") you'll essentially get algebraic effects. Any monad can be implemented this way. However, not all DSLs are sequential. For example, some represent process networks. In these cases, monads may be an awkward fit, as would be a PL that pervasively assumes sequential effects. Instead we might want arrows or applicatives or bifunctors or something else. An advantage of modeling monads explicitly is that you can simply avoid the concept when you don't want it. You could do the same for algebraic effects by marking lots of components pure, which isn't a huge issue but doesn't really leverage the language features. So you're still making a design choice with baking in algebraic effects. It isn't a bad choice, though. Increasing performance at cost of awkward expression for some niche use cases might be a worthwhile trade. I cannot answer your interesting question. Concise language is a verbose topic. Who would have guessed.. "I am shocked — shocked — to find that gambling is going on in here!" — Captain Renault, Casablanca, 1942. ... the world's finest imperative programming language. Okay, the preceding was too snarky but Keean you're discussing common knowledge here. This has been discussed before at length here on LtU with people ascribing to various views. Sure, a monad over a state means you'll end up with stateful reasoning to prove properties correct. That's just a no-brainer. There are some merits, like proper encapsulation of state, and some disadvantages, like poor composability of monads and the fact that this just isn't what pure functional programming set out to be. About the latter, the hope was that functional programming would lead to a style with trivial correctness through mostly equational reasoning for instance. Monads completely shattered that dream. Now functional programmers are writing imperative programs in a bad manner. That wasn't the aim, far from it. Written in monadic style f is a value that can be introspected and manipulated like any other value. You can write a static analysis function to ensure the value satisfies whatever properties you want without having to rewrite or extend the actual underlying compiler. Also the value is built with a fixed set of primitives, you can easily know what all the possible effects are (e.g. you don't need to worry about exceptions if the EDSL doesn't have them). f The JavaScript program is a black box* you can't do much with it other than running it to see what it does. You can arguably extend the compiler to do any analysis you want or write extra tools, but you're always have to be wary of the full language semantics and possible effects. * Well actually you can use f.toString() to get the source, but then you need a JavaScript parser and now you have Yak herd to shave before you can properly analyse the program. f.toString() I don't think the important concept is `monad'. It's having a pure semantics for whatever impure constructs your language provides. To me it's clear that this is a good idea. Advantages are simpler core semantics, type system support for tracking which imperative features are used where, ability to reinterpret or add new impure constructs. (Though just using monadic style doesn't afford much introspection because continuations are opaque.) Then don't compare to Javascript but an OO language which neatly encapsulates state too. Tracking what goes on isn't much more difficult than observing the member variables. You're thinking of Haskell when you propose that f can be introspected and manipulated like any other value. You can design OO languages that way too if you feel like. And you probably shouldn't because of performance reasons. Haskell can get away with a lot of things because at heart it is a glorified expression evaluator. So far, they get reasonable performance but I wouldn't compare it to C. Stated differently, you seem to want to reason over and compose 'f', sure that's academically nice but comes at a performance cost people aren't willing to pay. Monads, as used by most Haskell programmers, were just a complete capitulation that imperative programming, one might even say OO, is simply more productive, or even 'better'. And these programmers don't think about composability of 'f'. One can write in a monadic style* in any language, Haskell just has a nicer syntax, but one could reasonably add a nicer syntax layer in a Lisp or any language with macros. The syntax, though, isn't the important part, the ability to compose programs as values is. Usually in FPLs, Haskell particularly, people tend to use this style much more because the language provides simple data definitions, pattern matching, etc., which help write these EDSLs. I wrote such programs in Smalltalk and Java (e.g. monadic parser combinators) too, but that's not the usual style in those languages. WRT to performance there are many reasons why a free monad interpretation of state in Haskell would have poor performance when compared to the same code written in C, not just because "imperative programming is more productive and/or has better performance". If a C programmer writes a naive FP interpreter on C it would perform much worse than the same program written directly in Haskell, it doesn't mean Haskell is inherently better than C, but that the usual Haskell compilers have much more engineering effort in it than whatever hours the C programmer put in his interpreter, ditto for a free monad interpretation of state in Haskell vs C. As to monads being a "complete capitulation that imperative program is more productive", it's complete nonsense when you look at actual Haskell programs written on the wild. Yes, they include sections written in an imperative style, but most of the code isn't in monadic style and even the parts written in monadic style aren't imperative programs in disguise. It's a stretch to call a parser defined using monadic parser combinators as an imperative program (the imperative version wouldn't be syntactically near the version written in Haskell) and yet it uses monads. Any decently sized real world program has multiple styles of programming in it, not because the main style "capituled" that the other styles are more productive for all purposes, but because there is value in specialization. Using SQL for querying instead of the imperative equivalent of walking through the B-trees and indices is more productive, yet that says nothing about the productivity of the programs that use such SQL statements, ditto for regular expressions, neural networks, and such. I disagree with your observations which of course may differ from my random observations. Imperative Haskell programs seem to be the norm. It was promised to me I would be liberated from the Von Neumann style of programming. That didn't pan out. That's why I call it a complete capitulation. You claim that capitulation implies imperative is "more productive, or even 'better'". But as far as I can tell, it's only a capitulation that imperative is the best way to integrate with imperative OS system call and foreign function APIs. A model of interaction is imposed by the environment. Trying anything else will introduce presumptuous layers of abstraction and overhead. Best leave those layers to the programmers, right? Right. I wouldn't assume the dominance of imperative is due to intrinsic qualities or alleged benefits of said paradigm. Path dependence and inertia are a sufficient explanation. There are two factors that distinguish impure imperative languages: IO requires sequencing by definition, therefore language that respects the order of effects is necessary; IO objects have identity and state (read the file from the USB stick in slot 1). Without both identity/state and effect order you could not store data to a particular object and then remove the object knowing the data is on it. We don't need identity, and state does not imply identity. We could use external wiring of processes like flow-based programming or Kahn process networks. We could use topic-based publish-subscribe. We could model a blackboard system. We can have pools of threads that in each step simply propose, receive, or suppress events, like behavioral programming. We can have content addressed memory and networks, or scoped broadcasts. There are many ways to approach IO that don't require a concept of identity. So how do I know which USB device I have saved my file to? How do you know what "USB slot 1" means to you and your system? If you want to save a file to detachable storage device and you have more than one option, you'll probably examine the data already on that device in order to identify your target. Or perhaps you'll choose the most recently added device. I think you assume we'll indirect through an address such as "USB slot 1", and that's not a bad idea for efficiency reasons. But there is nothing to fundamentally prevent us from representing events of the form "save the file foo.txt to every connected storage device that already has bar.txt". Urbit essentially uses this with its network, broadcasting to all nodes that have a specific public key. Similarly, if we were focused on external wiring like flow-based-programming, we might instead prefer to externally wire a process's output stream to a USB file. Like use of `myProc > /mnt/usb1/foo.txt` in a shell. Naturally, the human would still need to establish what "usb1" means in context. But `myProc` doesn't need to care or deal with object identity. Local ports/channels like `stdout` are sufficient. How would you write the operating system that connects the streams to files? Just pushing the problem outside the box seems a poor solution to me. I agree that channels are sufficient for all IO, but you need to run a protocol over the channel which means a state machine at each end. I seem to remember a previous discussion where we disagreed about the nature of a state machine. The summary of that discussion is that you can view the 'plan' of a statemachine as declarative data, but you still need to respect the order in which events (messages over your channel protocols) arrive. You can describe state machines purely by pure functional transition functions, and infer the state storage, but such storage must still exist, you still need the states to implement your statemachine plan. These transition functions require naming all the states, which means in a sequential protocol you will have many states A, B, C, D... etc, and transitions A -> B, B -> C, C -> D etc. This seems a lot like boilerplate and we could use a monad to sequence this resulting in expressing the protocol in a imperative form. Imperative form seems optimal when linear sequences dominate the state machines state diagram, but an arrow notation seems better when there is a high branching factor from every state. I think the Imperative style developed and dominates because these state machines in general have low branching factors and tend towards linear sequences. From above we could simply view the imperative form as a simpler and more convenient notation where we allow the compiler to infer the state names. To put it another way, we can view every JavaScript program as being in the IO monad, but there is no need to actually compile it that way when implementing on stateful hardware. There is no benefit to rewriting this program into the Haskell IO monad if we don't take advantage of the pure parts of the language, and adding pure functions to JavaScript would be a viable alternative (ignoring all the problems with the actual JS language which are not relevant to this thought experiment). In the end I come back to Turing, and Stepanov. State is a wonderful thing that Turing introduced to mathematics. It expanded what mathematics could model. We do not want to go backwards, we should embrace state and strive to further improve the mathematical tools for dealing with it. I did not say we don't need state. I very specifically said we don't need identity. I'm not sure why your counterargument only mentions state and not once mentions identity? These two concepts are not equivalent and should not be conflated. State is essential complexity. Identity can be avoided. To avoid equivocation, I'm more specifically referring to the sort of "object identity" common to imperative or OO code, observed through aliasing. I believe this is the identity you intended. Linear objects do not have observable object identity. Because no aliasing. Values do not have object identity. Floaters in cellular automata do not have object identity. Of course, purely functional systems can indirectly model object identity, e.g. by treating table keys as object references in a monadic context. And identity might even be useful or efficient. I'm not claiming that we should avoid identity at all costs. (It's "new" identities - as in `new Object()` or `newIORef` - that I find troublesome. I frequently use filesystem or URL paths.) But unlike a model of state, we don't "need" a model of identity within our software systems. There exist ways to do without. Some of those ways: Make all objects linear, and model references/addresses explicitly if needed (like concept-oriented programming). Instead of addressable objects, favor mobile object concepts and locality-relative communication models (e.g. rendezvous, or broadcast to neighbors). Use "content addressed" storage, registry, discovery, and network models, i.e. moving based on intrinsic properties of things (types, data) instead of extrinsic namespace management. Record anonymous data entries, like datalog tuples or topic based publish subscribe. Even filesystems could be replaced to avoid the object identity of filenames, if you insist on begging the question. Does relational algebra offer a replacement for filesystems that does not have identity? Table rows are just tuples of values? You could certainly take inspiration from a relational algebra. But by itself I imagine it would be awkward and rigid. If that's a direction you choose, I would suggest pursuing something closer in nature to Clojure's Datomic or the Bloom programming language. If you haven't already read Brian Cantwell-Smith's book "On the Origin of Objects", I think you might enjoy it. A large part of it is about the probematicness of objecthood and identity. What does identity look like syntactically: s.update(43) Contrast this with no identity: s2 = s1.update(43) Here you can see that identity and mutable state are conflated. In fact I don't see how you can separate them. Values are immutable and have no identity (every 2 is the same so 1 + 1 == 3 - 1) however as soon as you have something mutable (it is stateful) you need to know which one you are manipulating. A = 1, B = 3, A += 1, B -= 1, A != B (the value of A may equal the value of B but they are not the same object, their identity is different). How can you separate state from identity? How can we have multiple mutable state containers (objects) without knowing which one we are mutating? I have read about a functional programming language extended with object-oriented concepts. In this language, the syntax `s.update(43)` was logically a linear replacement (or shadowing) of `s` in the environment. By convention, when using this syntax we'd want function `update` to return an object of the same or similar type. We also need a form `result <- s.update(43)` wherein `update` must return a pair. This language in question was briefly developed to describe a bridge between FP and OOP - mutable references were introduced in the next chapter. But it left an impression on me. We can develop reasonable OOP systems based on mobile linear values/objects that communicate through local rendezvous or through a medium of shared environments. Arguably, this would not be too different from how physical objects interact with their physical environments IRL. Physical objects can be understood as linear structures interacting in physical media or manipulated by pervasive physics rules. Modeling conventional OOP systems above linear ones is also not difficult: it simply involves explicitly creating a relatively stable addressing and routing model for the objects, a lot like homes or mailboxes for humans, where our objects reside permanently or perhaps occasionally visit. The stable address then serves as a form of object identity. But this identity is not pervasively conflated with object state: we aren't forced to use this addressing model everywhere. Given how identity and even objecthood is a rather dubious concept (in philosophy), this separation appeals to me. Well, I also appreciate it because it works nicely with linear objects/values, which in turn work nicely with purely functional programming and term-rewriting and various other models. Consider a functional programming language with a concatenative syntax (such as Joy, Cat, Kitten). In these languages, linearity is an easy fit because `copy` becomes an explicit function, clearly distinct from move-operations like `swap` or `roll`. The environment - the stack - itself is also a linear object. Your two examples would correspond to `s 43 update` versus `s copy 43 update`, the latter results in having two versions of `s` in the linear environment. IMO, functional programming using concatenative combinators does a lot to make these mechanical and linear aspects more obvious. OTOH, it's trivial to desugar lambdas into a concatenative syntax. Assuming: [B][A]a == A[B] (apply) [B][A]b == [[B]A] (bind) [A]c == [A][A] (copy) [A]d == (drop) Defining T(X,E) such that: X T(X,E) == E for value type X T(X,E) if E does not contain X == d E T(X,X) == T(X,[E]) == [T(X,E)] b T(X,F G) if only F contains X == T(X,F) G if only G contains X == [F] a T(X,G) if both contain X == c [T(X,F)] a T(X,G) Assuming linearity with your latter example involving A and B variables, you'll find that A does indeed equal B. Assume a desugaring like the above, such that `-> Var;` effectively pops data from a stack into a local variable, with sensible shadowing. (Kitten uses this syntax, although it isn't currently implemented by desugaring.) You might express this as: 1 -> A; 3 -> B; A 1 + -> A; B 1 - -> B; A B = This subprogram should desugar without use of the copy operator, and would evaluate to `2 2 =` by the last line. Our stack value at `=` might be represented more conventionally as a tuple `((S,2),2)` (where S is the remainder of the stack). Although the two numbers have clearly different locations (space is indeed an essential concept!), and even different histories/origins (which seems essential to how we think about objecthood and state), the objects themselves (2 and 2) do not have distinct identity. Local stack or parameter or tuple position doesn't strongly correspond to the sort of imperative mutable shared state or object identity you're arguing for in your examples. Ultimately, it is the implicit, pervasive aliasing of state - such that we have an ad-hoc global address and shared state access model and no easy way to escape it - that conflates state and identity in conventional imperative languages. If we're given freedom in our language about whether, where, and how we model addressing, we can cleanly separate the concepts of state and identity. How can we have multiple mutable state containers (objects) without knowing which one we are mutating? Functions on linear objects can take a local view: they manipulate the objects they're given, and may return composed, decomposed, or modified objects. Objects or agents that we model as communicating through shared mediums (e.g. pubsub, tuple spaces, blackboard systems, behavioral programming) or external wiring (e.g. flow-based programming, Kahn process networks, functional-reactive behaviors) don't need any reference to or knowledge of which objects and media they're interacting with (beyond compatible IO types). Term rewrite rules, cellular automata, temporal logics (cf. Dedalus), etc. can apply physics-like rules to manipulate whole sets of values/structures without any concept of referencing or identifying them. I'm sure there are several more ways to answer your question. I feel you just need to be a bit more creative, more accepting, perhaps more knowledgeable of paradigms outside the few you normally use to think about these subjects. Imperative is not fundamental to physics or philosophy; it's just your favorite paradigm. We did something similar, developing a bridge between OO and functional in the OOHaskell paper I worked on with Oleg and Ralf. I of course see how linear types and shadowing can apply to "s.update(43)" and I have already discussed this elsewhere in the thread. Assuming linearity with your latter example involving A and B variables, you'll find that A does indeed equal B. That would in my opinion be an error, because A is not B, they may contain equal values, but they are different objects. If I am 30 years old and Bill is 30 years old, we both have the same age, but we are not the same person. In the A/B example A and B only have one (default) property, but they are still containers not values. I think you are making an assumption when you say that imperative objects are my favourite paradigm, I am more like a disillusioned logic and functional programmer who finds the simplicity of objects enviable and practical. I wonder if all the time spent on complex type systems and functional modelling of state is useful in the end. It doesn't help me get my day job done, what does is the study and creation of algorithms, and the simpler and more efficient the algorithm the better. If I can express the algorithm most simply and efficiently using a mutable dictionary, then that is likely to result in the easiest implementation to understand and debug. I agree with you that control of aliasing is important. That would in my opinion be an error, because A is not B, they may contain equal values, but they are different objects. I had specified a linear context. Thinking of mutable variables as separate "containers" is useful to understand manipulations through an alias: the different variables may in the future contain different values due to external manipulations, and so value and variable should be distinguished. But there is no aliasing if linear. In general, linear objects are indistinguishable from their values. And hence linear objects have no more object identity than values. Regarding your "different people, same age" scenario, that's analogous to how we can distinguish a tuple value (30,1) from (30,2), even though both have the same first value. No need to introduce object identity or state. simplicity of objects enviable and practical I can agree with your sentiment favoring ease of expression and performance. But I think simplicity is something deeper. For example, most languages make floating point numbers easy to use, which also enables leveraging high performance floating point hardware units. But it isn't very easy to reason about how these floating point representations lose information and accumulate error. In many cases, what appears simple is deceptive. I think the apparent simplicity of imperative or OOP shared state is also deceptive. I think linear types probably are the best compromise we have right now. However having programmed in Rust I can say that they do not reach the level of simplicity I was hoping for. Is Rust doing it wrong? Can we have linear types without having to worry about lifetimes (surely if we have GC we can avoid this and leave it to the compiler)? Can we solve splitting containers in a simple and elegant (and preferably transparent way). Can we make it look like a simple OO language but have it catch the problems that you think make OO complex? As a another opinion, I don't like substructural types. Substructural types describe how you arrived at a value rather than the value itself and I want a focus on values. But I do agree that controlling aliasing is important to having a simple semantics. Surely databases have all these exact problems, with 1000s of operations from different origins all trying to operate on a single shared data instance. Perhaps trying to understand what existing solutions offer and categorising them against the ACID guarantees would help understand the compromises involved with different solutions. One solution that occurs to me is to return somewhat to the SmallTalk semantic model, and consider each object its own (green) thread, and that all method calls are messages, so that all operations on an object are serialised (one of the strongest transaction guarantees). We could then improve on this by making the object a state machine by insisting the transition functions are pure. consider each object its own (green) thread, and that all method calls are messages, so that all operations on an object are serialised (one of the strongest transaction guarantees) That's essentially Actors model. But it isn't truly transactional. Transaction literally means "across actions". True transactions require the ability to send multiple messages to an actor, and even receive responses from those remote actors to decide messages within the transaction. This quickly becomes a very nasty distributed transaction problem! This quickly becomes a very nasty distributed transaction problem! It is only a distributed problem if we break certain assumptions. If we have a bank account and a wallet object and we want to ensure transactional integrity of moving between, we need to have a 'transfer' object via which all requests to transfer between the bank account and the wallet have to go. Using modularity we can package the bank account and wallet as private objects inside a module which only exports the transfer object as its API. Edit: This approach seems to work well for Erlang. It's feasible to work around specific problems, of course. Assuming you're willing to do a fair bit of concurrency management work for every specific problem, on top of solving said problem. Distributed transactions are effectively a 'generalized' solution. You asked about actors a few years ago. My reply from then: Actors model criticism. In any case, actors won't solve problems related to shared state. You would replace shared state with message passing, like in Erlang which seems to work well. Of course shared state does require identity, so are you not countering your own argument about alternatives to the stateful identity model? Message passing to shared stateful objects/actors/processes is still a form of shared state. You cannot "replace shared state with message passing". You're only moving shared state around, distributing it, not replacing it. See also: Erlang style actors are all about shared state. This was in my criticisms list. shared state does require identity Shared state doesn't require identity. There are models involving shared state that do not use or depend upon a concept of identity. I've mentioned several such models this thread: publish-subscribe, blackboard systems, term rewrite systems, temporal logics like Dedalus, etc.. In these cases, anonymous objects/agents/rules interact indirectly through implicit, anonymous, shared, stateful environments. The components do not need identity to interact. But just now, we were discussing shared objects or actors. Those models do heavily use identity. Are you really suggesting those as practical alternatives for programming? Prolog is a kind of term rewriting system, and I really like Prolog, but it has performance problems, so you end up introducing cuts, and it all gets messy and dependent on the particular implementation of resolution. I am not convinced you could use these kind of solutions for efficient general purpose solutions. I am also not sure they are 'human friendly' solutions. We need programming languages that humans can easily understand and that is normally the simple and obvious model. Those techniques are indeed practical and have been used for real-world systems. Communications or interactions involving use of 'identity' fundamentally has a few problematic characteristics: components cannot interact without introduction, components cannot easily observe or enhance existing interactions, and dangling references for transient components. Systems based on this are thus difficult to extend, control, or upgrade at runtime (by updating software of specific components). They also introduce awkward life-cycle management concerns. It turns out that techniques avoiding identity, such as publish-subscribe and blackboard systems, can be very human friendly and practical.. The cost of these techniques is usually a moderate performance hit because we cannot optimize for point-to-point communications. But it's a predictable hit, so we can still have real-time systems if we control the set of extensions. In the real world, I've encountered use of a tuple-space like blackboard system for an unmanned helicopter that had flown over 35 unmanned missions. At the time, they had seven different agents contributing to the blackboard - handling different tasks like high level mission control, obstacle recognition, emergency obstacle avoidance, short-term tactical planning. This was discussed over powerpoint at a conference. The authors describing the system were enthusiastic about how easy the blackboard system architecture made it to extend the system, experiment, debug, upgrade software in real-time, test software changes against recorded or simulated inputs, etc.. I've personally made heavy use of topic-based publish-subscribe systems. They proved very flexible, adaptable, plug-in extensible, and debuggable compared to the old object-oriented systems they were replacing for unmanned systems control. Specifically, we used the DDS model for publish-subscribe not too long after it was standardized by the object management group. Term rewrite systems and temporal logics I've seen less frequently. I once read a 1980s paper involving a Datalog-based temporal logic used for hard real-time mission critical systems - specifically, fly-by-wire. The Bloom and Eve programming languages could be taken as more modern approaches in this vein. Eve is especially designed around the concern of human friendliness, while Bloom is designed more around the concern of scalability. Like blackboard systems, these techniques are readily extensible and accessible. But we may need to be careful to ensure real-time properties in some contexts. When you say "the simple and obvious model", I suspect you mean "the model I'm familiar and experienced with". Nothing against you particularly: I suspect similar from anyone who uses either of those two words "simple" or "obvious". It's usually a valid suspicion. Evaluating models isn't easy when we try to be objective and unbiased about it (a rubric of -ilities, cognitive dimensions of notation, complexity metrics, and so on). People rarely think deeply about what they consider simple. People cannot effectively compare what they know with ideas unknown to them. And, frankly, it seems no model is obvious to someone who isn't experienced with it. In any case, I didn't mention these models to convince you of their virtues. How much you value extensibility and other features depends a lot on your problem domain. I mention the models because you repeatedly conflate identity and state, while I believe it's valuable to distinguish those concepts. Does this mean that we agree that monads are a waste of time, because they embed state with identity into a functional language, and we could either just use a stateful language as the monadic embedding doesn't really help reasoning about the stateful imperative code, or we should be looking at some of the methods that do not have identity that you posted? monads are a waste of time, because they embed state with identity into a functional language Well, the ST and IO types are monadic and certainly model state with identity (e.g. via STRef and IORef). But #NotAllMonads. Monads have a great deal of freedom about which features they provide. For example, some monads, such as State and Writer, already support state without a concept/abstraction for identity. Other monads might support backtracking or probabilistic programming or exceptions without any state concept. Two features with real value include embedding for DSLs and generalizing algorithms across similar DSLs. You could achieve this without an explicit monadic abstraction, e.g. by use of algebraic effects. But if you use a first-class data type to model sequential DSLs, you'll eventually discover some value in generalizing that "sequential" adjective, and thereby reinvent the monad. IMO, the main issue isn't the monad abstraction per se, but rather how the Haskell language and conventions surrounding it tend to force users to confront high level abstractions before they're ready. FP drill instructor: "The Monad! You can't handle the Monad, worm! Write out the while loop for five different DSLs first, refactor, then you'll be prepared to understand and appreciate the Monad!" This isn't an issue specifically for monads, however. For example, Arrows or Applicatives or Contravariant functors or Fixpoint or high-level zipper/iterator or or or ... abstractions likely wouldn't do any better. It's just that Monad is the first, biggest hurdle that a new Haskell programmer encounters - starting at `main :: IO()` and the explanation of do-notation. I remember when I first tried Haskell in University, circa 2003. I hadn't yet learned any real FP, only the fake first class procedural programming from Scheme and Lisp. At that time, the Monad was a daunting concept, like diving into the deep end of a pool before learning to swim. I only got past it by telling myself to ignore the abstraction, just do a bunch of concrete work in IO and eventually other concrete monads as needed (such as parser combinators). It was only much later that I had my eureka moment and grasped monads. So I wouldn't say that monads are a waste of time so much as an undesirable hurdle if encountered too early in a language's programmer experience. And this is a consideration for any abstraction. If we can redesign languages (or IDEs) so programmers can first express themselves concretely then later generalize algorithms automatically, that might be a more human-friendly approach. I think I was working on the HList paper with Oleg and Ralf around that time. Back then I was totally convinced that Haskell was the future of programming. Monad Transformers are where it all starts to go wrong. This is what makes me think that Monads, or at least how they are used are the wrong abstraction. Algebraic Effects can be expressed as a row-polymorphic monad (where the constructor is the row), and this has been done in PureScript. But if algebraic effects provide a way to define DSLs then why double up with Monads. I'm not saying it should be impossible to define a monad, but I think Monads should be a speciality topic, rarely used, and when they are used it would be specifically for their property of non-composition. I like the approach to algebraic effects in this paper where they separate the world into computations and values: An Introduction to Algebraic Effects and Handlers I've already mentioned (here) Oleg Kiselyov's Free and Freer Monads. That paper essentially argues for one concrete Monad to rule them all - the operational monad (called Freer), modeling algebraic effects via row polymorphic types (in the manner of HList). Assuming you've selected this concrete monad, you don't really need the `typeclass Monad` abstraction anymore. You don't need to inform your programmers that they're using a monad. Instead, you teach them about algebraic effects and how to define their own effects handlers. I can agree with that position. Obviously many others do as well. PureScript, Kitten, Koka, Idris, Eff, etc.. Also, due to their concrete nature, operational monad and algebraic effects are a lot more convenient to model from dynamically typed languages or where typeclasses might be awkward. My only issue with it: I have some doubts about monadic effects models in general. They're a little too sequential for a lot of use cases - a bottleneck for parallelism, awkward for composing concurrent computations, difficult to use for distributed stream processing. These aren't problems that algebraic effects will fix! This is why I'm experimenting with alternatives such as KPNs. I wonder whether baking algebraic effects into a PL syntax and semantics will prove a premature commitment to sequential effects models. Frank (on arXiv, on LtU) elegantly supports handling several arguments at once, which would let you model parallelism (you can write a program waiting on several outputs at once, and an extension with parallelism would also let you wait for "at least one output", parallel-or style). See "2.7: Handling on multiple ports" in the paper. (Of course, as I believe Matt M pointed out, this can also be seen as a restricted form of (effect-typed) process calculus, specialized to the "only one output" flavor of the lambda-calculus. Working with effect-typed process calculi may be equally or more convenient, but the syntax wouldn't be as familiar.) This is a slight aside, but as Monads are about sequencing, it's not totally irrelevant. Threads are problematic because shared state needs locks. This amplifies all the problems with impure imperative programming. Implicit parallelism doesn't really work - speculative out of order execution in the CPU already exploits the available implicit parallelism in programs more efficiently than a compiler can due to the ability to schedule based on actual execution time and available resources on any given machine. The best approach I have encountered is "algorithmic parallelism" which is where the algorithm itself is expressed generalised over a number of "tasks", sort of like a template. This is how GPU programming is done. In other words we don't want to try and parallelise sequential code, but we do write the kernels in a sequential way (as all compute elements execute sequential code, even in highly parallel architectures like a GPU) over a generalised resource model. Something like a generalised abstract model of OpenCL. Any suggestions on papers/work relevant to this kind of approach? Thinking about the OpenCL model for GPU and multiple CPU programming, doesn't the actor model fit well hare? You have some local state storage on each compute element, which would be the local variables in the actor, and we have data streamed through the actor from various sources. We also can allow addressing external resources which would be done via message passing to another actor. It turns out that techniques avoiding identity, such as publish-subscribe and blackboard systems, can be very human friendly and practical. Only for summary information. It's a catastrophe inside the big O.. Very true, but that works well with summary events, and not anything with transactional frequency or higher. The cost of these techniques is usually a moderate performance hit because we cannot optimize for point-to-point communications. In effect, they are heavily tailored systems, and not loosely coupled. The cost of building a truly loosely coupled, event-driven system is near-infinite in terms of development and operational capacity. For example I saw a "blackboard system" 15 years ago that consumed two servers each with 16 CPUs and 128 GB of RAM, and still managed to run like the rotting carcass of a hippo. We replaced it with a few commodity blades, and improved both the throughput and the uptime by a few orders of magnitude. (At the time, the solution that went to production handled over 20% of the world's foreign exchange transactions.) Again, to be clear, it's not the choice of the blackboard that makes the system suck. It's the religious adherence to the least common denominator, i.e. publishing data with sufficient level of detail required by any conceivable consumer, instead of using domain knowledge to craft the appropriate granularity and/or rate of publishing. Tuple space solutions work well for a vanishingly small number of problems. I've yet to find many problems that call for such a solution, despite the fact that I love the abstraction. I can't see anything using global broadcasts being remotely efficient. Yes you can optimise the messages behind the scenes, but how do you write that optimisation if the PL only supports the identity-less model of state? It seems to me that you would end up having to build an identity-less DSL in a language that supports identity, so you can optimise it for each specific application. To me this seems similar to Prolog and logic languages (which I really like) in that it seems very promising, looks elegant, but has all sorts of practical problems that stop widespread adoption. Yes you can optimise the messages behind the scenes, but how do you write that optimisation if the PL only supports the identity-less model of state? There is no such thing as a Turing-complete programming language that only supports identity-less models of state. For example, even in a purely functional language, you can still model addressable IntMaps of stateful 'objects' that address each other using integers. You can even leverage the column-like layout from entity-component-system to model extended attributes. But such models will be explicit! The better question is whether a language has some pervasive or implicit model of identity, beyond control of type systems or APIs. Further, what matters isn't how you implement the optimizations, but rather how effectively you can locally reason about costs/performance while extending or modifying programs that aren't deeply understood by you. I grant that logic programming doesn't make performance reasoning easy (because simple extensions can incur combinatorial costs). But I feel you make an error when trying to generalize identity-less state models from your experiences with Prolog. I feel that you're assuming naive implementations. Real-time publish-subscribe systems such as DDS support multiple quality-of-service control options for both publishing and subscribing, e.g. so we can match on metadata about where it's acceptable to lose intermediate states, desired and available frequencies, how late the data may be. Subscriptions to topics can also support queries that refine them further. And we can "publish" the metadata about subscriptions, such that publishers subscribe to the subset of relevant subscriptions and avoid publishing if unnecessary. Publishers can precisely compute and publish just the topics of interest to at least one observer, rather than publishing all things at all times. Ultimately, physical network communications can be reasonably close to point-to-point if there are only a few interested observers. There is some extra setup overhead, registering interests or available topics. But the right performance analogy is closer to "global search" or matchmaking in a shared index/registry rather than "global broadcast". For blackboard systems, we also have a lot of freedom about the 'patterns' we support. We can take inspirations from various forums, work-order, inventory models, and CSCW patterns for example. Rather than publishing all data at all times, we can publish when some other tuple indicates a requirement. Resources and requests can be modeled explicitly. And of course there are plenty of intermediate models, that only weakly use identity. For example, consider a MOO or MUD. These partition an environment model into multiple "rooms" that then receive local attention. Linear objects can navigate these rooms, and only communicate by altering the state of the room, its neighbors (e.g. by shouting or shooting or moving), and themselves. They do not communicate with each other by identity, and don't even need to hold a reference the room they're in. But the concept of rooms would naturally require some form of identity due to aliasing in navigation (that is, we can reach the "same" room from multiple paths like north vs. west-north-east). Mobile linear objects navigating a Cartesian coordinate system would operate similarly, with Cartesian coordinates becoming identity and interacting only with "nearby" objects. Intriguingly, a tree-structured world would have no aliasing and could avoid the concept of identity even for rooms. Identity is 'weak' in this design insofar as it depends on the topology of the implicit environment model. For example I saw a "blackboard system" 15 years ago that consumed two servers each with 16 CPUs and 128 GB of RAM, and still managed to run like the rotting carcass of a hippo. I've encountered OOP systems that have similar characteristics. :D For controlling performance, the patterns we use ultimately matter a lot more than the paradigm. But the paradigm does affect which patterns are easy to use. Compared to logic or constraint programming, imperative and FP do have an advantage of keeping the performance for 'primitive' small-step operations and compositions down to O(1). But this doesn't generalize to higher level abstractions - collections-oriented patterns like visitor pattern, observer patterns, entity-component-system, etc.. Substructural types describe how you arrived at a value rather than the value itself and I want a focus on values. Substructural types do describe values. Specifically, they describe functions, and how those functions may arrive at values. But functions are values, too. :D Substructural types are convenient for describing some "correctness" constraints on functions. Opportunities vs. obligations correspond roughly to affine vs. relevant types. Handshakes and protocols between agents can often be conveniently modeled using token values with substructural types. However, for the general use case, substructural types should be scoped to subprogram computations, e.g. attached to parameters of a function rather than directly to values. Basically, if a non-linear function with non-linear arguments can return a linear result, something is wrong. Substructural types describe how a function was constructed, not what it does (as a map from inputs to outputs). I'm probably being overly pedantic in this context, though, because I'm ok with linear type systems in a practical sense, but just think they should be recast as structural type systems. When you say "describe how a function was constructed, not what it does", it seems you assume it's infeasible to describe or constrain what a function does in terms of its construction. But it isn't difficult at all. I'm unclear on what you envision with "recast as structural type systems". Substructural types can certainly constrain what a function does but they also distinguish between functions that I would want to call extensionally equal. If you work with values that are descriptors of the functions, then the violations of linearity (or whatever) become observable / structural. "values that are descriptors of the functions" Do you mean something like a DSL or GADT that we can inspect, interpret, or compile? Edit: I think I see how that would be possible, but the way I imagine it would also be awkward. And I'd want dependent types to statically enforce constraints when composing such functions. I was thinking more of using them during representation selection. Linear types would be useful for extracting an efficient representation. The representations are the "descriptors". I've mentioned my ideas of rep selection before, but still haven't fleshed them out. It's basically just a way of exposing the compilation process to the programmer. I can appreciate controlling representations through some programmer-controllable model. But substructural types aren't just about performance. As I mentioned, they're useful to model obligations or opportunities. Obligations such as: close the file handle after you've opened it (via linear token for file). Or opportunities like: you only get three chances to guess the number (via an affine lockbox object). This is why I say substructural types describe functions - requirements, not mere performance considerations. I do believe it useful to distinguish selection of unique representations (to allow efficient in-place updates) vs. substructural types (to express protocol requirements). With effects modeled at the value level (monads, algebraic effects, your Kann network idea, etc.), obligations and opportunities are already structural. I think modeling effects with values is a good idea, partly because it means they can be modeled with structural types, but for other reasons, like being able to write handlers. Can you elaborate on what you mean by effects as values? Computations have effects, values are data. I actually disagree that functions are values (at least referentially transparent values), functions take time to execute and may not terminate. I mean that instead of having effects that happen as a side-effect of evaluation, you have evaluation produce effect descriptors that are values that the run-time interprets to produce effects. I prefer considering non-termination to be a bottom value, rather than effect. If your program that was supposed to produce an Integer diverges instead, then it's errant. So this is basically composing an abstract syntax for the language, that composes functionally, and is then fed into an interpreter, where the side-effects happen? An interesting question is what happens if we make the abstract syntax co-data, so the interpreter can stream the values? All this is sounding a bit similar to the handling of side-effects in vau-calculi (reasonably accessible blog post, but not going into detail on the more interestingly side-effect-ish and difficult state calculus, yonder; more complete but daunting would be my dissertation). In a monadic style, each effect descriptor typically has a continuation that is invoked with whatever return value the effect has. So every step is under a function call. It's basically codata already. I suppose it is in a lazy language like Haskell. Even in a strict language, you can model a stream as: data S a = S a (() -> S a) Dup. I'm all in favor of representing intended effects as values. But it isn't clear to me how to represent obligations in an algebraic effects model. Nor how to represent ad-hoc resource-limited opportunities that affine types can easily model. If you can offer some insight on this, I'd appreciate it. This is probably too abstract to be useful, but if you have a type discipline that you like (offers good power/pain ratio), you should be able to keep it. You just reframe it as being about effect usage rather than arbitrary value usage. Because effects are values, this will convert it to a structural type system. The call-stack is the most efficient automatic GC region. But knowing what we can allocate on the stack is somewhat complicated, especially in context of first-class functions, and even more so if the functions might remember their arguments like stateful object methods. Rust's borrow model essentially makes this concern visible in the type system. White-box compiler optimization is probably less than half as effective. A moderate hit to ease-of-expression for tricky borrow cases seems a reasonable tradeoff in context of Rust's performance goals. It is true that GC could avoid the issue, but you'd certainly pay for it with performance - conservatively allocating a lot more on the heap. Rust does have some difficulty with borrowing array slices, but apparently some people have addressed this by dropping into unsafe code to implement a split function. See Borrow Splitting. That page should solve your immediate hangups with Rust's linear types, or at least the ones you've mentioned to me. A borrow model isn't without some benefits. It implicitly releases borrowed fragments when we're done with them, eliminating need to explicitly glue fragments back together. Without this, we instead need to track phantom types regarding adjacency so we know we can safely use the O(1) `append_adjacent` instead of the O(N) `append`. And then we'd actually need to call `append_adjacent` to rebuild our array from the slices. I really don't like having to do this. I have stopped doing so much with Rust because I had to use so much unsafe code to do reasonable things. For me there is something wrong with Rust's type system, the ad-hoc borrow checker being one of the most obvious ones. Using `unsafe` to express safe things that the type system doesn't know how to handle is exactly what it's for. Essentially, it's a way to add new built-in functions to a language. If you choose to develop a new programming language instead, you'd only be fooling yourself if you imagine adding new built-ins is much safer than permitting `unsafe`. If you're pushing the bleeding edge of what's possible and efficient in a language, you should expect to see `unsafe` on occasion. I've certainly used the equivalents in Haskell and F#, to implement features such as distributed virtual memory and structure sharing for larger-than-memory values via secure hash binary references, and transactional database interfaces that use these values. I haven't used Rust enough to speak good or ill of its borrow checker's subtle caveats, especially not in a more specific context of Rust's standard libraries. In general, borrow seems not a bad approach. Just, the developers perhaps overlooked the importance of splitting collections for various divide-and-conquer strategies. Unfortunately Rust hides unsafe, which is "unsafe", really any code that calls an unsafe function should be unsafe, which in effect means all Rust code is unsafe. Haskell does not need "unsafe" code to do the same things, you never need to use unsafePerformIO. I agree that pass-by-reference (which is what a Rust borrow is) is a good way to efficiently pass data to sub-functions. Haskell uses unsafePerformIO more than a little bit. Under the hood of Data.ByteString, as one common example. A lot of FFI marshalling integration as another (not all FFI is for impure functions). It's true you don't "need" to use it. Unless you need performance or FFI. I disagree, you can put those external functions into the IO monad with no loss in performance. The only case where I have ever used unsafePerformIO was to add debug logging to a pure part of a program, because to refactor a whole chunk of code into the IO monad, when the logging would not be in production seems a waste of time. Haskell has unsafe operations other than `unsafePerformIO`. Such as, when marshalling, we have `peek` and `poke` that operate at byte offsets. It isn't difficult to peek or poke beyond the end of an allocated array. Putting all ByteString accessors and constructors into IO would also make them unusable in practice, e.g. cannot use ByteString keys in a Map, cannot replace inefficient String type by utf-8 encoded ByteString, etc.. In any case, unsafe operations are probably used more than you imagine in Haskell, even if you're not the one writing them. But mostly for edge cases, which is how it should be. I suspect the reasons for any unsafe operations are historic and not fundamental. There is no reason you cannot have a pure immutable byte-string, and a mutable byte string would need to be a monad. You do not want a mutable byte-string as a hash key, as you can easily mutate it without updating its hash index position (it's definitely unsafe). You should 'freeze' it into an immutable byte-string before using as a key. This can be done efficiently, in fact there is no reason it cannot be the same underlying buffer providing we know there are no other references to it. I find it odd that you are arguing in favour of identity less implementations of state, and them pointing out flaws in existing languages where people have used such representations as if they are some fundamental problem. I agree that inertia and path-dependence have a lot to do with things. As I mentioned, unsafe code is basically how we introduce new "built-ins" to a language without waiting on the language designers. The immutable ByteString wasn't a built-in, so we use unsafe code to implement it. Similarly, the accelerate libraries to support high-performance linear algebra on the GPGPU will hide its use of IO because basic math isn't really effectful and the GPGPU is conceptually an implementation detail. Or alternatively, we might want to use LAPACK or BLAS. There's a lot of history. So, naturally, we end up using a lot of unsafe operations. D: I find it odd that you are arguing in favour of identity less implementations of state Arguing "shared-state doesn't require identity" is not the same as "you should avoid identity when modeling shared-state". Much like "people pick their noses" is not the same as "you should pick your nose". So far, I haven't said much at all about what I favor or disfavor. State and identity are separate concepts that should not be conflated. Keeping these concepts separate in my mind and heart is useful for understanding non-conventional paradigms, useful for thinking about alternative ways to model software systems. Especially at larger scales. I do disfavor software that internally creates/allocates "new" identities rather than computes/discovers existing identities. The latter is vastly more convenient in context of job control and software system management, transparent durability, caching or mirroring, distribution and sharding, continuous deployment, debugging, etc.. That is, I favor a relatively RESTful approach to associating state with identity, not avoiding identity entirely. Edit: obviously, conventional OOP systems do the opposite of my preferred use of identity. But it is feasible to model OOP software systems that avoid allocating identities (e.g. concept-oriented programming seems relevant). Dup Let's take this one step further, what if we create an interpreter for JavaScript in Haskell, and then embed this in the free monad. How is programming JavaScript embedded in Haskell any better than just programming JavaScript? It's the same language so any analysis would be just as difficult. If you put your whole program as a giant JavaScript fragment embedded in Haskell then that's pretty clearly worse to me than just doing it in JavaScript. The tooling is worse, etc. and everything has an added layer of complexity. But that seems like a straw man. Who's proposing that style of programming? As Daniel Yokomizo said, the important thing is that your imperative program is now a first class value with all the properties that entails. This is a clear advantage over JavaScript. If you are posting code snippets of Haskell and JavaScript and pointing out how similar they look then you've completely missed the point, because regardless of the syntax, JavaScript does not make those computations in to values, which is the important part. Sure, it would be nice to have another paradigm besides imperative programming with better properties. And there are people working on those things. Those new paradigms may or may not make use of similar algebraic structures. I think it's a little weird that there are so many people who are triggered by the word "monad", and spend so much time trying to debunk the concept. It's just one algebraic structure among many, but for whatever reason it has become a strangely political topic among many developers. "This is a clear advantage over JavaScript." No idea why you think so. For an interpreter or compiler, if that would be the general behavior, that's just wasting cycles on something which may be academically neat but isn't an interesting property. For the programmer, if he wants that kind of compositionality, he can just abstract into functions in most languages. I'm not sure what "abstract in to functions" means. The point is to capture a computation as a value. You can indeed do that in most languages, Haskell is not special besides providing some syntactic sugar and static analysis (e.g. for dispatch on the return type of `return`). As to why making things values is a good idea in the first place, you might enjoy Rich Hickey's talk, The Value of Values. It's not academic at all, it's extremely pragmatic and is relevant to all developers. "Wasting cycles" is the sort of argument people used to oppose C when it first came out so I'm totally unconvinced by that. No, you can do it if you want to. But there are trade-offs. Lisp, of course, has had this for ages. Does that make Lisp better than C, or C better than Lisp? Neither, you make a list of pros and cons for both languages and choose one. If C never adopts the idea that data and computations are interchangeable, I just would be fine with that. Even if there are languages where it does make sense. It just depends how high on the abstraction stack you want to go, and what you're willing to pay for that. I glanced at the talk. Yeah, neat. But it is also a prime example of how deceivingly simple ideas can be wrong. Sure, it would be nice if referentially transparent programming would pan out. So far it hasn't. And apart from that, any OO guru can give a similar deceptively convincing talk that it's normal for objects to have state and that that should be encapsulated. Or are you the same person now as you were yesterday? Bank accounts change, there's merit to encapsulated state, it's how we see the world. Neither talk would be correct. It's never that easy. If you glanced at the talk then you admit you didn't really grok it. He addresses the things you mentioned. Sure, it would be nice if referentially transparent programming would pan out. So far it hasn't. Of course it has. Bank accounts change The bank account's value yesterday and today are two different values. This is a really simple example that is addressed in the talk. You don't need or want mutable state to model this situation. This sort of false temperance in PLT is kind of frustrating. "Well, these people over here say this thing, and these other people say this other thing, so the truth must be in the middle." If we want to be able to make progress, we have to be able to say that some things are just bad. You don't see nearly as much equivocation over, say, `goto`. We've accepted that it's rarely what you want. In the same way, this value oriented movement is making the case that, no, it's not about your perspective, or about trade-offs, but it really is the case that you want to be programming with values >90% of the time. Well, if we are going to say that some things are bad then it is referential transparency. The computer is way more amenable to OO, it leads to better shorter code, you don't need half a PhD, programs are more readable, it easily satisfies most engineering needs, domain modeling is a breeze, tons of efficient algorithms can be easily implemented, and referentially transparent languages even capitulate into that direction. Have it your way. If some state has different values over time, it is mutable, even if it is time indexed, represented as a new world replacing an old one, or whatever alternative representation you can think of. What FP people rail against is implicit mutation and stateful effects, not explicit mutation and stateful effects. And of course, if they want to do deal with a changing world, they have to model non-values (call them objects or entities or whatever synonym of object you can come up with) that have state that is changing, unless you are happy with 1970-era interfaces and the like. The nature of identity and naming seems something fundamental to programming. I like the terms object and value for the two kinds of things. The real world seems to be made of objects, but objects are also values (as in my grandfather's broom). There is some kind of duality here. The components of a collection (the parts of the broom) appear to behave as values, yet if I carve my name on the head of the broom, this maintains state, so it is also an object. To me it seems that concrete things are objects, anything physical in the real world. It seems that values only exist in the abstract (I have three oranges, I could swap a orange with someone else and I would still have three oranges). Likewise in a computer memory locations are like objects. The problem in a computer is that instead of the contents of a location being an object, like in the real world, it's an abstract value. Personally I think a language needs to put objects and values on an equal footing. The separation into pure and impure in Haskell, where once something is impure it cannot be used in pure computations seems unhelpful to me. Purity seems to be a property of abstraction, so when I say I have three oranges, I abstract away the individuality of the oranges. I guess the other interesting thing is that objects can be serialised into values, and values deserialised into objects. This all relates to how things are referenced and copied. Whether something is an object or a value looks more and more like a property of the observer not the thing itself. (Fermions would be objects, I suppose.) I've long suspected that our programming languages at scale become so dependent on names that it becomes a liability. And yet, the point of the exercise seems to be explaining programs to sapient minds, for which language is the natural communication medium... It depends on how you define things. A value is a point, an object is a speeding bullet, its position is mutable in what point it is at. Defining values as immutable atoms allows us to define mutable properties as being assigned to different values over time. A GUID is a value also, of course, but with it you can form an arbitrary object. All you need is a dictionary, even an immutable one, which you can see as a value also. Now throw in some points in time (also values) that can index some more immutable dictionaries, and you easily have objects with mutable properties, Objects are simply higher-level constructs that can be made up of value constructions, conflating values and objects takes away that nice layering. My suggestion was that objects are actually lower level, and values are the higher-level constructs. The fundamental building blocks of matter have identity (and location). An electron has spin state, and is a unique object. Values only exist in the human mind as a way of categorising and abstracting the real world. I thought that at the lowest levels, quantum entangled particles don't really have individual identity. Depends what you mean by identity. Particles are of two kinds, fermions and bosons. The difference is that no two fermions can occupy the same quantum state at the same time (the Pauli exclusion principle, which is why you can only have so many electrons in each orbit in an atom), whereas two bosons can occupy the same state (e.g., photons). You can always think like that, sure. But when you are implementing a programming language system, it is nice to have values as the foundation to stateful objects, rather than the other way around. I don't object to objects based on values, although I don't see it as necessary. I am happy to have two classes of thing, objects and values on equal footing. What I do think is important is the ability to abstract pure value-oriented interface from impure object-oriented code. Haskell only permits the reverse, I think you need both. To truly encapsulate state and tame the combinatorial explosion of complexity, being able to define a pure (message passing) API to a module is important. I want module implementations to be written in simple efficient imperative code, but I want the module interfaces to compose easily and encapsulate that implementation. The properties that electrons have, like charge and spin, have values, like +1 or -1, +1/2 or -1/2. "Value" is the label we give them, but the values themselves can be measured empirically. As such, they don't only exist in the human mind. (Although you may believe otherwise if you're an anti-realist.) You can describe a particle by a collection of such properties and their values, much as you do with an object in a programming language. However, the values associated with a fundamental particle don't change without some sort of external interaction. Particle "identity" can only survive such interactions in some cases, and then only if we choose to impose it. (This becomes even clearer when you consider that even particles aren't fundamental, since there's good evidence that quantum fields are more fundamental, and particles are emergent phenomena arising from the behavior of fields. Assigning identity to a wave packet in a field is an arbitrary operation that depends on choices we make.) In other words, identity for particles is a property that only exists in the human mind. We construct that identity by assigning it to a series of particles related by interactions over time. We do the same basic thing with "mutable" objects in functional programming, and indeed with all objects in the physical world that we consider to have identity. It seems clear that at the lowest levels, "values" are in fact fundamental, as far as we know. They can't be decomposed, whereas particles - or wave packets, or fields - can be described by a set of properties and associated values. Of course as you go higher up the stack of abstractions, the concept of a "value" can be used at any level, and such values can be composite and thus non-fundamental. But in both programming languages and physics, at the bottom of the abstraction stack, values must ultimately be fundamental, since they can't be decomposed, and objects have to be described by or constructed from them. I am not sure I agree with your interpretation. If we take a bunch of particles which can have spin state, and compose them into a group that can have an exponential number spin states, and set it into a superposition, you cannot copy of that superposition, so they do not behave like values. It appears to me that quantum cryptography also relies on the object nature of photons. If photons behaved like values then only normal mathematical cryptography would be possible. I think it's a little weird that there are so many people who are triggered by the word "monad", and spend so much time trying to debunk the concept. Not so sure people are "triggered" by the word "monad". Granted people sometimes debunk the concept, but imho that seems like a natural reaction to other people pushing the concept. I'm just confused as to why people have such a strong reaction to an algebraic structure that can be expressed in perhaps >95% of languages in common use. It's a very strange thing to put on a pedestal, to me. Tell that to Wadler. Maybe he will stop popularizing trivial notions. The free monad is trivial in this case, it's basically just a fancy list constructor, we could write "run [Store 23, Store 42, Get]" instead. It is the embedding of an impure imperative program into a pure functional program that I am trying to discuss here. Although the free Monads role in embedding is interesting. ... between purity and impurity in a programming language. In particular, the Steelman requirements, which dictated what the language later called Ada had to look like, include this one: module-level variables. The language shall permit side effects that are necessary to instrument functions and to do storage management within functions. The order of side effects within an expression shall not be guaranteed. [Note that the latter implies that any program that depends on the order of side effects is erroneous.] (It actually says "own variables of encapsulations" in the third sentence, but module-level variables are what is meant.) Ada as we know it actually permits arbitrary side effects in expressions, but taking this seriously suggested to me a language design in which subroutines and functions are firmly separated but treated on an equal footing insofar as possible. Subroutines don't return values but can have call-by-value (Ada in), call-by-result (Ada out), and call-by-value-result (Ada inout) parameters, as required by Steelman requirement 7F. Functions have call-by-value parameters and return a single value. in out inout Syntactically, the body of a subroutine is a sequence of declarations of local variables with or without values (specifying a value is equivalent to a declaration plus assignment), primitive commands including assignments and calls to subroutines. The body of a function consists of declarations of local variables with values, commands that update module-level variables (possibly depending on the previous value of the variable), and an expression that provides the value of the function. Subroutines can contain conditional commands, functions can contain conditional expressions. So the impure part of the program (which includes the main program) is specified by subroutines that may invoke functions in order to compute values. The functions are the pure part of the program and may not invoke subroutines. Pure code may or may not be evaluated lazily; values returned to impure code are forced. So this is something like Haskell, but impurity is not a bag on the side and laziness is not an implementation requirement, just a choice. I like Ada, I especially like Ada's package and generics system, but I don't like the way they added the OO stuff using tagged objects. What I am interested in is the encapsulation of Impurity. The following: f(x, y) = { t := 0 while x < y: t += x ++x return t } Has an impure implementation, but has a pure interface. In Haskell this would need to be in the State/IO monad, but what I would like to see is that we look at the interface not the implementation. I am interested in observable purity/impurity. In Haskell, that would be in the ST monad. The impurity is encapsulated by runST. This is guaranteed by the type system by cleverly using a `forall` qualifier. The main disadvantage of ST is that we cannot use it to model continuations or generators (and hence concurrency) with impure implementations. This is ensured by the type system, but the fundamental issue is that the capability to "copy" a continuation value is incompatible with ongoing in-place mutation of captured STRefs. ST is only "safe" because we contained it to the linear context of a monad. Another useful technique for efficient in-place mutation in functional programming is to leverage unique references. When we have a unique reference to a value, mutation is not observed. This also allows for "copy on write" approaches when we might have shared references. Linear or affine types can protect uniqueness, but aren't strictly necessary. You have argued that objects should precede values, or at least be on equal footing. I'd call this goal a failure if we have major issues representing a pure interface to impurely implemented continuations. So ST and similar techniques won't work. (I suspect whatever you're envisioning would qualify as a "similar technique" in this regard.) But linear values can fulfill this role admirably. We can understand linear structures as objects in the computation, with spatial and temporal properties, a history and trajectory. We can model conventional object oriented systems by explicitly modeling an address space for message routing (separating concept of object from address). But the default is also interesting in its physical analog: mobile objects that have no fixed address and instead only interact with their local environment. But linear values can fulfill this role admirably. Linear values don't compose. Can you explain your assertion? In my experience, linear values compose easily enough that I've never considered it a problem. We can use them with normal data structures. We can literally compose two linear functions into a larger linear function. And so on. I grant this: the presence of linear values in a language pervasively influences how we represent data structures and algorithms. Conventional data composition patterns might not be compatible with linear types. For example, for record types, we conventionally we use `foo.x` syntax to access a value at label `x` and discard the remainder of `foo`. However, this is problematic because there might be a `foo.y` property with a relevant or linear type which cannot be discarded. So instead we must (in general) use a linear destructuring of records, e.g. `match rec with {x=myVar | rem} -> body` like row-polymorphic records. For large, recursively structured composites, the Huet Zipper (data structure) has proven very widely applicable for developing algorithms to safely access, update, and process trees or lists that may contain linear values. Uhm. I need to reconstruct the observation from memory but the problem was as I remember a linear array of linear values. Since you can't reference a component two times you're stuck to swapping it out, modifying it, and swapping it back in. Since that can be translated to an in-situ update I imagine that that problem is solvable but hasn't been solved yet. Though it follows the general pattern of 'introduce type system X to solve problem Y to end up with non-trivial problem Z.' My recommendation is to partition and append arrays. A runtime can implement append very efficiently in cases where we know (statically or dynamically) that the components are adjacent in memory. Also, because arrays are usually language primitives, it is reasonable to introduce primitive features to enforce O(1) logical append of adjacent array fragments, and to track "holes" - array fragments consisting of undefined entries. An advantage of partitioning compared to swap-and-modify is that partitions work nicely with fork-join parallelism. We can pass each partition to a separate task, update in place, then logically glue the pieces back together. My own language simply doesn't have arrays as a primitive data type. But I instead optimize some lists to semi-transparently use an array or array-fragment representation, controlling this optimization via annotations. The common list length, access, update, append, fold, scan, etc. functions are transparently replaced by the compiler or interpreter with with equivalent implementations for arrays. Of course, using an intmap or finger tree (or an LSM-tree variant thereof) is also a pretty good option given linear operations on these structures can also feasibly avoid allocations. Having small array fragments near the leaves might support greater efficiency, though. Sure, there are some solutions to ease the pain of the most obvious problems. But swapping is going to hurt when you've modeled a matrix as a linear array of linear arrays of linear values. The problem becomes worse when mixing linear and shareable resources in a data structure. I am not sure you run into Rice. You're looking at some language inclusion problem, at best that means equivalent to deciding FSM membership, maybe intersection. At worst, you're looking at language inclusion. Arrays are a polite fiction anyway. We don't really get "O(1)" update and access because of physical data layout and speed of transfer. If I were asked which is more fundamental - arrays vs. linear values - I'd say the latter. Hence, I attribute these "pains" you describe more to the fiction of flat arrays and random access memory. (An IntMap or finger tree zipper, for comparison, makes structurally clear which fragments are in "near" memory without relying on a hidden cache effect.) Regarding a matrix, partitioning works fine. We split one array, then the next, then operate on the value, according to structure. Swap is awkward because it doesn't generalize nicely (due to need for dummy values of the correct type, and the non-uniform overhead for swapping the dummy value for struct types). Partitioning with a gap generalizes easily. It's essentially zippers for arrays. The only issue is that "zippers for arrays" are a little troublesome to get "right" in a simple static type system when compared to zippers for trees or lists. (It would help a lot if the partition type contained the array size, for example, but that gets us into dependent types.) I've not encountered any difficulty mixing sharable values with linear ones. We can have records with both shared texts and linear components, for example. Can you illustrate the difficulty you're envisioning? Yah, but it's still a band-aid solution to one particular problem. And the problem with band-aid solutions is that you don't know what other problem you're going to hit around the corner. Moreover, it also depends on the setting. Using linear types in a functional language to allow for efficient in-situ updates is very different from using them for live time analysis in an imperative language. I am not convinced. Linear decomposition of structure, whether through techniques like zippers or row-polymorphic records, is a general and natural solution. Arguably, it's the symmetric dual to composing structures with linear elements. Partitioning of arrays is just one instance of this more general solution. That's essentially a zipper on the array type. Perhaps you believe it a "band-aid solution to one particular problem" because I did not show my work, did not explain above how I originally answered that problem. That's understandable. Arrays are popular enough that I've thought about them years ago, and consequently I have an answer available in my memory. But zippers are a concept and solution that can be systematically applied to algebraic data structures. If you've composed a well-behaved data structure with linear values, there is necessarily some way to decompose, access, and modify it linearly. Using linear types in a functional language to allow for efficient in-situ updates is very different from using them for live time analysis in an imperative language. For real-time interactive processing, what we need is a model to inject input data and extract required output data in small steps, and a real-time garbage collector. With this much, we can develop real-time systems. The developer needs only to ensure bounds for how much memory the program requires and how much work is performed between input and output. If the bound is smaller than the period between inputs, it can be real-time. Functional vs. imperative program model isn't a significant distinction here. Requests for effects are essentially a vector for output as far as the external real-time system is concerned; it doesn't matter how we express this within the program. The entire issue of paradigm seems irrelevant in this context. And introducing linear values is also nearly insignificant. It only offers greater efficiency of avoiding allocations and garbage collection for a significant portion of the work performed. And it makes working with arrays more tolerable, allowing update in a false "O(1)" instead of a naive O(N), so we might suddenly favor arrays instead of an intmap or whatever. The improved efficiency might indirectly enable live update for edge cases where raw performance was previously almost-sufficient to keep up with high frequency live inputs, but there are no guarantees. I'm curious what you believe is "very different". Well, I shouldn't have said very differently. I was roughly thinking about the difference between having mutability native or expressed through an interface on abstract functions for in-situ updates. Somewhat in a similar vein as the distinction Keaan made between monadic and imperative programming. But when I think about it, I assume that inlining and peephole optimization could take care of a lot of problems. The problem I have with linearity is how it interacts with generic programming. Take for example a very simple algorithm like "swap". We want swap to take two mutable references to values of the same type and swap them. The problem I have encountered in languages like Rust is that it won't allow two mutable references into the same array, which prevents you writing a simple algorithm like an in place sort using swaps. My view of programming is that algorithms are fundamental, and simple (efficient) algorithms are more valuable than complex or inefficient algorithms. So here linear typing prevents us using the simplest efficient algorithm, which means it is working against the programmer rather than with the programmer. Yes you can work around this by either giving up efficiency or simplicity, but if this happens with every simple algorithm, you will end up with a complex mess. I think there is a complexity budget,that limits the most complex system a programmer can work with, so you need to be very careful to not introduce unnecessary complexity or you reduce the maximum size of program that a programmer can reliably work on. Having established that, the array problem could be a limitation with Rust, and not fundamental to linear types. We could view an array as an index of mutable references, the index being trivially constructed from the range of addresses from the array start to the array end. You can the pass ownership of the whole array by passing a linear reference to the array, and pass individual cells to swap by their 'synthetic' mutable reference. You would of course have to write the sort in a way the type system can confirm the same mutable-cell-reference does not get passed to swap as both arguments. I can say from experience that linearity doesn't prevent generic programming. However! This is assuming a language designed for linearity in every primitive feature. Languages with non-composable features are hell on generic programming no matter what those features are. It's unfortunately easy to introduce features unfriendly to linearity. An example I already described in this thread: conventional record accessors conflict with linearity due to discarding data implicitly, whereas row polymorphic record deconstructors work well by allowing capture of the record's remaining data. Arrays are another primitive that needs special attention in context of linearity. We'll at least want some way to partition mutable access to arrays and treat partitions of one element as equivalent to other mutable references. I think I agree, with the right approach to modelling arrays I think you could design a language that looks like the nice bits of JavaScript, but is linearly typed in the IO monad. If you also added effect types (again without changing the syntax) and effect constraints, you could then selectively restrict effects for parts of the program. We can have a wide range of effect constraints like no-mutation, no-heap-allocation, no-stack-allocation, no-exceptions. The tightest constraint would effectively prevent any runtime failure by not allowing allocation (no out of memory) not allowing exceptions (division by zero not allowed), maybe even not allowing context switches or interrupts, if we define non-termination as an effect we could even constrain that, or with the right cost function constrain the maximum execution time of a block of code. Such things seem esoteric if you look at current languages, but even UI interactive programs could do with 300ms constraints on blocking the UI. The ST monad allows encapsulating state, but it's a bad way to do it. For a start ST Monads do not compose so to write an algorithm that needs access to two different state 'encapsulations' at the same time is clumsy and not generic. Further we might consider other encapsulations 'safe' for example of we have exclusive access to a file we might wish to encapsulate that in a pure function. For a simple example a function that is passed an exclusive capability to access a file and returns the entire contents as an array can be considered pure, because providing the capability was given at the start of the program the file cannot change. This leads to an interesting thought, purity can be for a given time-span only. We see this in Haskell that you can call a pure function from impure code. Considering the above we can also allow pure code to call encapsulated impure code, providing immutability is maintained for the scope of the pure code. This allows nested structures where impure code can give exclusive capabilities to a pure block of code, that can in turn call encapsulated impure functions that use the capabilities, with the restriction being that no mutation from the encapsulated impure code must be visible from the pure code, but such mutations can be visible from the outer impure context. That monads do not compose is not a big concern. Although concrete monads don't compose, it's trivial in Haskell to abstract monadic APIs under corresponding type classes, and hence compose feature sets. Writing an implementation for a set of monadic APIs isn't very different from writing a set of handlers for algebraic effects. We essentially can develop generic subprograms of type `(EffectA m, EffectB m, etc.) => args -> m results`. Or even more generically, `m args results` so we can potentially constrain compositions, e.g. use arrows or categories instead of monads. That Haskellers don't normally pursue this seems to mostly be a community style thing. To write code as generically as possible is not widely accepted as a goal. But there's also some inertia involved: the required extensions to Haskell (type families, rank N types, etc.) were developed later than the dominant style. We can leverage ST for pure implementations of a `run` method for many sets of effect classes. There is no need to compose ST generically. I agree that ST is insufficient in general. My reason is because `runST` doesn't let me return a continuation that preserves efficient access to encapsulated arrays. This constrains use of ST in incremental computation contexts. I cannot use ST to model generators that yield or coroutines that interact in small steps with external input from pure contexts. This is why I resort to linearity. ST continuations could be safely modeled if tagged as an affine type. Regarding your last few sentences, at "such mutations can be visible from the outer impure context", that's probably incompatible with optimizations on pure code. But if you're just building up a set of effects to run upon returning successfully, you could basically use a writer monad. I agree that effects offer a nicer way to do this, and with a large amount of typeclass gymnastics you can simulate row polymorphism (we did it back on 2004 in the HList paper), but the difficulty of doing it was a real effort. I even got as far as a complete web framework with runtime plugin modules and relational algebra, but monad transformers really killed it for me. On reflection I could have implemented an effect system on top of HList, but it felt like I was fighting the type system to achieve my goals. I was effectively implementing a new language inside of Haskell that did what I wanted, but I was stuck with the syntax, and having to duplicate code at the value and type level. They say that all languages that are Turing complete can implement any program, and can duplicate any style, it's all about whether they make that style easy. You can write OO code in 'C' by explicitly constructing the vtables, but that does not mean it is going to be easy to debug and maintain. To me trying to write the code I wanted to write in Haskell reminded me of trying to write OO code in 'C' back in the early days. A clear sign that a new language is needed. And people are developing functional programming languages with algebraic effects - e.g. Idris, Eff, and apparently your own ZenScript which I keep hearing about whenever Shelby tags me. Hacker News has over sixty comments as well. Several are insightful. Here. Just read through some of the HN comments. I think I need to clarify some things, Monads in themselves as in category theory are neither good morning bad, they are (as someone on HN pointed out) a design-pattern, an abstract interface. What is more interesting and seems to be missed is that a monad is there whether you explicitly name it or not. JavaScript code can be considered to be in the IO monad. We can probably give types to most JS statements providing we have some syntactic sugar. Monads have several problems, the biggest one being that they don't compose, and monad-transformers are a pain to work with. Algebraic effects seem a better way to handle this to me. Yes we can view algebraic effects as a row-polymorphic monad, and that may be how we actually type them Instead of starting with an pure function language like Haskell and adding Monads for state and IO, we could start with an impure imperative language and impose constraints on the allowed effects. This might be an interesting way to design a language. It seems very clear to me (but I haven't had much luck explaining this so it makes sense to programmers) that one of the major objections to monadic programming is the same as one of the major objections to quantum mechanics. In programming: The actual, real, practical, experienced world, the one that we live in, is a sequence of states. It's imperative. Pure functional programming isn't like that; it's declarative, and mathematicians like the formal well-behavedness properties of that, and would like to not have to deal with imperative state. So the pure functional folks came up with this monadic programming idea that lets them, for mathematical purposes, indefinitely postpone applying their pure functions to imperative-stateful reality. In quantum mechanics: The world we experience at any given moment has a classical state, that is, things are a certain way. However, the rules about how one such classical state relates to the next are probabilistic; moving forward from one classical state is a superposition of possible successor states. The mathematics of how this superposition of states evolves over time is rather elegant (comparatively speaking), a "wave function" propagating according to a straightforward wave equation. However, there is no actual classical successor-state, only a superposition of possible successor states. Sooner or later, the system has to be observed, at which point something happens (in the mathematical description) called wave function collapse, in which the quantum state (superposition of classical states) derives probabilities that various classical states will be observed. From whichever classical state you observe, you then start over with a new propagating wave function. It's possible to get along by using this tool, at least for some cases. The wave functions are nice clean mathematics (if sometimes hopelessly difficult to solve), the wave-function-collapse is really ugly but one hopes to nudge it into a place in one's calculations where it doesn't get in the way of producing a useful prediction. And some physicists are satisfied with this arrangement, or at least settle for it in practice, while others get really worried that this isn't a complete description of reality, we're missing some important piece. Physicists have batted this problem about for the better part of a century without resolving it; they can't even agree on whether or not it's a problem. A standard demonstration of the problem is the "Schrödinger's cat" thought-experiment. A cat is put into a box, with a device that might kill the cat depending on the outcome of some random quantum event such as a radioactive decay. The box is closed, and we suppose that while the box is closed we cannot tell what happens inside. Is the cat alive or dead? Neither, says quantum mechanics; it's in a superposition of states, essentially both alive and dead. Until we open the box, at which point either we observe that it's alive, or we observe that it's dead. But is it really okay to entertain a superposition of cat? Hopefully the parallel with monadic programming is visible, here. The pure-functional program with its monadic structure is like the quantum wave function, mathematically clean though not necessarily easily solved, but apparently missing a fundamental aspect of reality that can only be reintroduced by applying the program to an actual imperative state of reality to produce a new imperative state of reality, from which then one starts over. And some people find the arrangement satisfactory while others feel that the whole framework is missing an important part of reality without which the description must be (qualitatively?) flawed. It figures that this isn't going to be easily resolved, given that theoretical physicists have been at it for generations. About the only thing that might resolve the physics debate is some sort of theory that eliminates the wave-function collapse. Likely the same is true in programming — a whole new "paradigm" would be needed. The actual, real, practical, experienced world, the one that we live in, is a sequence of states. It's imperative. That first sentence I agree with. The second I find ludicrous. There is no particle or field in the real world that we (or any agent, other than a god) can manipulate imperatively. It seems terribly limiting to conflate stateful with imperative. There are lots of paradigms that involve a sequence of states. The closest I know to the real world is cellular automata. More distant, but much more convenient to program, is a temporal logic (cf. Dedalus programming language) or term rewriting (e.g. Maude, OBJ), which can loosely be understood in terms of physical syntactic structures evolving in-place according to global programmer-defined physics rules. I like to say that "computation is mechanical mathematics". To add two numbers requires their physical representations have spatial-temporal proximity. Moving information is not free. Destroying information creates heat. Unlike pure math, we must carefully consider costs and frictions in computation or programming. This mechanical and physical aspects of computation are most obvious when all states are syntactically representable. For example, it's very clear how cellular automata or term rewriting or even a Turing machine proceed mechanically through a sequence of states. Every step is visible. For those models, we can usefully view concrete syntax and source code itself as a linear object that has a sequence of states that an evaluator manipulates according to a set of rules. Essentially, the evaluation model is a disciplined approach to self-modifying code. Lambda calculus obscures this somewhat due to the sophisticated automation and optimizations surrounding variable substitution. But purely functional programming can also be done with confluent combinator rewriting, no need for variables or substitution. I favor combinators over lambdas, but we can easily translate between the two. Regardless of representation, purely functional programming is still mechanical in nature. Further, it's a very discrete and predictable mechanics, so I see no similarity with state superpositions. Effects are fundamentally interactions between a computation and its context. Like everything else, they must be implemented mechanically. That is, a context must inject or extract data between or during computation steps. This holds even for imperative system calls, which essentially must rendezvous between a process computation and OS context. The OS will extract the call parameters and inject result data. Monadic effects models are not different or special. We have a term that rewrites to yield some operation and a continuation. The external context, whether the OS or an intermediate interpreter, will rendezvous to extract the operation then inject data for the continuation. Unlike an imperative thread, it's a lot easier to think about a monadic computation as a value or as a stateful linear object. This is because the point of interaction is explicitly modeled as a value type. But the essential nature of state, interaction, and effects remains the same. There is nothing similar to wave-form collapse when we observe a proposed effect, whether monadic or imperative. The concept of state superposition or wave function collapse is neither useful to understand the state of a monadic computation, nor to understand effectful interactions between a monadic program and its environment. Well, I grant an exception if we're modeling a monad for probabilistic programming or similar. If we are modeling such a monad at the effects layer, then we should yield a set of proposed effects, each weighted with a probability, each accompanied by a corresponding continuation. It would then be up to our external system to pick one and continue - this choice would be analogous to a "wave function collapse". Although, intriguingly, in some effectful contexts it might be feasible to select multiple effects (e.g. reducing 100 possibilities to 3 instead of 1) or inject multiple probabilistic results for a path. The k paths chosen add up to 100% instead of selecting 1 path with one result at 100%. Partial collapse will naturally lead to anti-causal entanglements where the probability for chosen past effects is refined based on choice of future effects. There is no concept of state superposition or wave function required. I feel the point of my post has not come across to you. I drew an analogy between the machinery of programming and the machinery of quantum physics; I wouldn't expect the particulars on either side of the analogy to show up on the other side. Your analogy relies on ignoring the mechanical, observable, ultimately physical realization of computation. Purely functional programming is inherently restricted by the "programming" aspect to reject non-computable properties, such as law of excluded middle or axiom of choice. There is nothing unreal about computation. Hence, I reject your analogy. I also feel you're making invalid distinctions between imperative effects vs. monadic effects, despite both essentially having the same mechanical realization - a local rendezvous between a computation and its environment (e.g. a runtime or OS). Hence, I reject a major premise upon which your analogy was constructed. I'll edit the quoted segment to: "The concept of state superposition or wave function collapse is neither useful to understand the state of a monadic computation, nor to understand effectful interactions between a monadic program and its environment." I think this more clearly states my third point, which is that your analogy isn't worth much. As I mentioned, there are some interesting ways to realize an analogy between quantum physics and monadic programming, such as modeling, composing, and selecting among probabilistic effects. I mentioned this because it's something that interests me. I've contemplated such techniques in the past, in context of improving HCI (here). I hoped you'd be interested in these "particulars" of modeling probabilistic effects with quantum-like properties, but oh well. Your analogy relies on ignoring the mechanical, observable, ultimately physical realization of computation. My analogy isn't even related to the physical realization of computation. Nor does it have anything to do with imperative effects versus monadic effects as you mention in your second paragraph. Somewhere between the two of us, each putting thoughts into words interpreted by the other, by the end of the round trip the original thoughts are no longer in evidence (like the urban legend about the automatic translator that started with "The spirit is willing but the flesh is weak", translated to Russian and back to English). You claim your analogy has nothing to do with the nature of computation and expression of effects. Yet, you based the analogy on a distinction between imperative and purely functional monadic code regarding exactly those things. So I don't believe they are unrelated. The analogy doesn't hold simply because purely functional programming isn't like what you described. Yet, you based the analogy on a distinction between imperative and purely functional monadic code regarding exactly those things. No, I didn't. We're failing to communicate. I want to communicate. I have no interest whatever in "fighting", nor in causing offense. Yet I'm not sure how to explain the problem in a way that will help things along. It seems you have come to expect certain kinds of errors of thought from others, you look for them, and once you believe you've found them you look no further. But to me the big concepts are the point of the conversation, and you're pouncing on specific words. It's kind of as if one day I looked up and saw some truly incredible sight splashed across the sky, and pointed it out to my neighbor, only instead of looking up at the sky where I was pointing, they objected to the gesture I was using to point. But the sight really is worth seeing, and I'd still like to share. There's a difference between "look at this, I find it interesting" and "purely functional programming with monadic structure is like this thing." The latter involves an assertion about properties of things. Your earlier assertion, "the pure functional folks came up with this monadic programming idea that lets them, for mathematical purposes, indefinitely postpone applying their pure functions to imperative-stateful reality" is required to accept your analogy, "The pure-functional program with its monadic structure is like the quantum wave function, mathematically clean though not necessarily easily solved, but apparently missing a fundamental aspect of reality that can only be reintroduced by applying the program to an actual imperative state of reality". Yet it's hard for me to find a phrase I don't object to in your earlier assertion. Applying functions to reality? Effects don't work like that, neither monadic nor imperative. Postpone effects? No more or less than imperative (*), so why single out functional? Imperative-stateful reality? There is nothing imperative about reality's state model, consider cellular automata instead. (*) Because both have stateful evaluators (e.g. a linear structure in FP is no less "real" a stateful object than any object in context of OOP or imperative), and both can indefinitely delay emitting explicit externally observable effects whether by monadic yield or system call. I believe it was your intention to share an analogy that you found interesting. After rejecting your premise of similarity, I can't even begin to accept the analogy. But is that really due to miscommunication? I contribute to LtU because I hope to be part of interesting, constructive exchanges of ideas; but I reluctantly no longer think that is your goal. I did mention an idea I find interesting and constructive - how probabilistic effects monads and selecting among probable effects gives us something very similar to quantum entanglements, superimposed states, and wave-function collapse. You casually dismissed it as irrelevant to your analogy. That's fine. You don't need to be interested in the same things as me. But I would have enjoyed an engagement on it, even if you were critical. To me, a good exchange of ideas is one where the participants are also willing to give and receive criticism about those ideas. Without criticism, I suppose another option is a museum - a place dedicated to the muses, a place to share art and artifacts to spark the imaginations. I don't consider LtU a museum. Although, it sort of feels that way these days with the few front-page articles rarely receiving comment. If someone says, "imperative is like an apple because both are edible", how should an audience respond? Perhaps a clever responder might say, "no, but imperative is like an apple because both are full of wormholes", punning on an occasional name for side-effects that channel data behind the scenes. But there must be some misconceptions involved to create the analogy. Your analogy is based on your conceptions about purely functional programming, which you described when leading up to your analogy. I consider those conceptions deeply wrong for reasons I've since given. Although I do vaguely understand how you might reach those conceptions, if you have not actually done much purely functional programming and effects modeling. In your conception of LtU, should I have held my tongue? You have afaict consistently assumed that you understood my analogy. Your remarks indicate, to me, missing the point; it's only an added irony (or is it meta-irony) that the disconnect between us fits neatly into the pattern I'm describing that you're not seeing. I wondered, should I be trying to explain it a different way, hoping to get it across; but on one hand, it wasn't clear to me what to say that might work better, and on the other hand, you seemed to have become so obsessed with "debunking" what you claimed I was saying that it seemed unlikely you would pay any attention to an attempt to explain what I actually was saying. So it seemed my only options were either to just not respond to you (but that would be giving up hope of useful conversation, and I don't like to give up hope), or to try to politely point out that you'd misunderstood. At that point, the ball would be in your court. Your two likely responses would be either to ask some sort of question about what I had meant — indicating interest in communication — or to double down on your claim that what I was saying was invalid. You doubled down. I concluded, reluctantly, that tearing me down is a higher priority for you than communicating. To me, a good exchange of ideas is one where the participants are also willing to give and receive criticism about those ideas. Exactly. I'm uniquely well situated to recognize if you've misunderstood my analogy, yet when I indicate that you have, you prefer to insist my analogy is BS rather than entertain the possibility you might be fallible. You have afaict consistently assumed I don't understand your analogy. Yet you always STOP there, making no effort to explain or clarify based on what you have observed of my understanding. IMO, repeating that I misunderstood without a word to explain my misunderstanding or clarify your point is not only unconvincing, it's also condescending. Unconvincing because it seems at least as likely that you misunderstood my counterpoint or what it reveals of my understanding. Condescending because you've assumed I'm either so close-minded as to ignore an explanation if you were to offer one, or that I'm so far beneath you that I don't deserve an explanation. Seems you hoped for me to ask for said explanation, then assumed I was close-minded when I did not. Clearly we have very different ideas about how a discussion should proceed. Probably some cultural influence there. To me, if someone doesn't explain, it's because they don't want to explain, not because they're secretly hoping for a question. Asking can even be impolite - presumptuous, nosy, annoying. There is no body language or tone of voice in this medium to cover the gap. So if you don't volunteer an explanation for discussion, and I don't have explicit permission/authority to request an explanation, I am certainly not in the habit to ask. It's entirely up to you whether you actually "want to communicate". Perhaps the meta-discussion has been slightly useful. Or it has potential to be useful, if either of us were to remember these cultural differences next time. (Which seems optimistic.) So tell me, what do you believe I have misunderstood, and why? How will you clarify your original point to avoid this misunderstanding in the future? What other questions do you secretly hope to see on this topic? Monads may or may not be a waste of time, but this discussion most probably is. It may be time for the two of you to cool off, agree to disagree on this analogy, and go back to productive conversations another day on another topic. Though I take in good part the caveat, I expect to make one more (careful) comment in the main line of this subthread, when I get a chance to compose such. On one hand, I owe dmbarbour a reply to their question; and on the other, if we're to have productive conversations another day we need the air to be well cleared now. I fear gasche is only about one-third right. Probably right that this particular subsubbranch of discussion is no longer accomplishing anything useful, but wrong that we're disagreeing about the analogy, and probably wrong about the prospect of future productive conversations. And I really hate to give up on future prospects, which causes me no end of trouble. I'm thinking I should save my efforts to explain my thinking for the recent reply by someone else. And I really hate to give up on future prospects. Because it suggests that your language is not expressive enough :-) Or not abstract enough. a late comment: I disagree that "The actual, real, practical, experienced world, the one that we live in, is a sequence of states. It's imperative." This is just a very specific way to describe the world. For example it is really difficult to account for sound in such a world. But I do agree that there is a valid analogy, and also that "a whole new "paradigm" would be needed" - maybe by drawing from different metaphors, or by revising these metaphors fundamentally. I disagree that "The actual, real, practical, experienced world, the one that we live in, is a sequence of states. It's imperative." This is just a very specific way to describe the world. For example it is really difficult to account for sound in such a world. I could quibble a bit on this. For one thing, in that paragraph I was talking about programming, not physics. And even for a classical physics treatment of sound, one might take "sequence of states" to include a continuous sequence of states. But those are minor quibbles. More to the point, I think there's a flaw in the way I first presented the analogy (no surprise; I did say I've been having trouble explaining it). If, as you say, we're looking for new metaphors, perhaps the flaw is still worth trying to fix. At the heart what I was trying to describe, is a contrast between two different ways to approach describing reality, and my description of it was flawed because, being a participant in one of the two ways myself, I was describing it from the perspective of that side of the contrast. The contrast in how people view things should, perhaps, be emphasized over the technical details (and yet, how can one describe it all except in terms of the technical details?). This is going to take a bit of space, alas. (I'm also having trouble with whether to start with the physics side or the programming side; I seem to recall once before trying to express this and suspecting it had fallen flat because I started with the physics side and lost programmers that way. While if I start with programming — monads — it seems that's the less clear side of the analogy. Hm.) In physics, there was the famous.. or notorious... disparity of view between Einstein and Bohr; though it's not limited to just those two physicists. This is one of those things where people disagree about whether or not they understand what the disagreement is about; it's that fraught. But one of the issues floating around in that has to do with wave-function collapse. Is it really adequate to view the entire universe as a wave function that never collapses? The wave function is traditionally understood as describing a distribution of probabilities of classical states of the universe, but if the universe actually has no classical states... well, some people see that as a problem. [JS] Bell did some thinking on this that I, at least, found quite insightful. Recalling free-hand: In a (now old-fashioned) CRT, an electron gun fires an electron at a screen. It causes a scintillation. A quantum-mechanical wave function predicts the probability distribution; but there is nothing in the wave function that suggests the discrete event of the scintillation. Bell says it better, of course, and discusses various interpretations (such as many-worlds). But there's always going to be this basic contrast between those who see it as a problem that the wave-function doesn't have that discrete event in it, and those who don't see it as a problem. In programming,. Providing a stateful-reality parameter is like collapsing the wave function. And you see, by this point in my account of the analogy, some people who will be screaming to high heaven that this is not a problem, there's nothing "missing" from this monadic description of the program's interaction with stateful reality, while other people see the whole monadic approach as setting up a complicated mathematical device in order to pretend statelessness when reality is really stateful. Basic disagreement about whether there is a problem, and over a mathematical description that suspends choice between states, just as arose in physics. The flaw in my presentation was, apparently, that one really wants to present it in a way that doesn't require taking sides between the two contrasting views, within physics, or within programming, even though part of what the two sides disagree about is whether or not there's a problem. And, as for metaphors, well, physics still hasn't figured out what to do with these two contrasting views — they're still disagreeing about whether there's a problem. So we're not likely to borrow a successful solution from physics, although I'm still hoping there might be some sort of insight from connecting the physics and programming sides of the analogy. [Slipped up on the name; doh.] There are many forms of analogy. You've argued not just that "state monad is like a wave function" (which arguably has some merit), but rather the form of analogy you chose is "imperative IS TO reality AS state monad IS TO wave function". Hence, there's more to take issue with. I argue that state monads are just as real (and unreal!) as imperative. Insofar as state monads are like wave functions (due to manipulating a model of program state internally, rather than directly manipulating the greater universe), so is imperative. Insofar as imperative is like reality (due to evaluation requiring mechanical manipulations of concrete, physical representations of program state), so are state monads. Neither monadic programming nor imperative paradigm is especially close to reality. Physical states seem to be guided from past to future by physical laws. In that sense, temporal logics, term rewrite systems, cellular automata, and other rules-based programming models that simulate "laws" operating on a state representation would be much closer to reality than either imperative or monadic programming. In any case, you seem to misunderstand where the disagreement with your analogy arises. You say state monads are missing something. I say sure, but those things state monads are missing, imperative also is missing. And conversely, those features imperative has, state monads also have. (Well, state monad or variants such as state-continuation monads to model concurrent threads.) If your primary intention is to present an interesting relationship between program state or effects models and wave collapse, i.e. based on the fact that input to any program is a discrete observation on reality, or any program's model of world state is incomplete and simplified, then I think it would be better to leave out the whole issue of monadic versus imperative. As is, the impression I receive is that you favor imperative expression of programs because it's more "real" in your mind by some unjustifiable premise.. These phrases "state of reality" and "stateful world" here seem like a potential point of confusion. A subroutine written in a state monad receives a representation of program state. Imperative subroutines also operate on program state - the heap and stack and data structures represented within them. In either case, the "particular" state is effectively an unknown parameter at the time of writing the subroutine. Program state necessarily has a concrete, mechanical, physical realization during evaluation by a physical computer. In that sense, it could be considered a "state of reality". But also in that sense, it would be a state of reality regardless of whether we favor imperative or monadic expression for the program. No matter which way I interpret it, I'm unable to see the proposed 'reality' of state as a valid distinction in your analogy. AFAICT, the relevant differences between "state monads vs. imperative" are more along the lines of "explicit vs. implicit" or "precise vs. ad-hoc" rather than "simulated vs. real". And even explicitness and precision are just a matter of degree, based on the language conventions, type systems, or the specific choice/API of the stateful monad. Something is a monad because of its structure, not its name, hence the monad exists even where not explicitly named. Most imperative languages are monadic, as the monad expressed is a sequence with variable binding and a return value. It doesn't matter when analysing the program if the monad is explicit in the type system or not, but obviously language quirks can get in the way of a clean analysis. We can show by experiment that although you can generate a wave interference pattern with an electron gun firing at a phosphor screen with a double slit in the path, the electron actually only passes through one slit or the other. Hence the idea that the wave describes everything is clearly wrong. The wave is a probability function. I'm inclined to agree, and I take that to be Bell's position. Monads aren't a waste of time in the absence of an algebraic effect system, as others have noted. I haven't read the entire thread, so forgive me if this is essentially a repeat of other comments, but: monadic code, with or without syntactic sugar such as "do-notation," presents us with a well-defined algebraic structure that obeys a few simple laws, and can be reasoned about in terms of those laws. In addition, all monads are also functors, etc. so all of the derived functionality from all the typeclasses monads are also instances of is available for your monad. So while some people find the imperative-looking do-notation code disquieting (and some people even incorrectly call code that uses, e.g. IORef "impure"), it remains true that we can reason about such code via the substitution model of evaluation and equational reasoning—exactly the same intellectual tools as for non-monadic functional code. A better question is: should we put everything in IO, "the largest monad that can exist?" I think it's fair to say it would be preferable to work in more than one smaller monad and find ways to compose them. This is why we have debates today about MTL vs. monad coproducts vs. Eff vs. other algebraic effect systems... As a long time Haskell programmer, I still think it's reasonable to "call code that uses, e.g. IORef "impure"". We don't just evaluate an IO value. We expect to run it. Haskell does help us purely reason about correct abstraction and refactoring of IO fragments. But what we're most concerned about getting correct is the behavior when run, e.g. whether we need `atomicModifyIORef` at a given point, or whether asynchronous exceptions are masked correctly, etc.. Equational reasoning won't help us there. One of the things we spent time thinking about in BitC/Coyotos was how we could simplify reasoning about stateful programs. There was never any question that the programs would be stateful; operating system kernels are about as stateful as things get, and the state threading approach really doesn't generalize to multiprocessed multithreading. For such codes, much of the issue of dealing with state has to be handled by whole-program analysis that exploits (checkably enforceable) whole-program design constraints. Language tools and idioms can help a lot, but they aren't the whole answer, and one need not (indeed cannot) lean on the language exclusively. But... Whatever the means of expression, reasoning about stateful programming is hard, and limiting the amount of stateful program you need to analyze is overwhelmingly important. To this end, we attempted to focus on several things in BitC: Our goal in all of this was to limit the portion of the program that had to be analyzed using stateful methods. It turns out that a large proportion of most stateful is effectively accessor-only. Looking back, I would put more effort than I did into state-threading idioms. While it is true that monads do not compose especially well, any idiom that reduces the burden of stateful analysis is helpful. I don't think it does help stateful analysis though. Look at the two programs in the topic introductions, one is in the IO Monad in a Haskell like language, and one is in a JavaScript like language. My whole point was we can analyse the JS program _as_if_ it were in the IO monad, and hence there is no advantage to writing that program in Haskell. We can use the same analysis techniques in both cases. Unfortunately that isn't true. The reason it isn't true is that the JVM admits both concurrency and mutability as core concepts with defined sematics, and Java's concurrency semantics are somewhere between horrific and unspeakably bad. The closest thing to a sequence point in Java is the bytecode. Indeed, you cannot assume from one bytecode to the next that a cell of array type points to the same array. Further, Java shares with C# the problem that "readonly" members actually aren't because of a flawed constructor specification, so you get no benefit from that. Haskell, by contrast, has neither a problem with sequence points (because it is purely functional) nor a problem with concurrency (because it doesn't admit a notion of concurrency over shared mutable state). So while I agree that what you say *appears* to be true at first glance, the difference in the respective low-level execution semantics of the two languages is profound, and has very significant impact on the just the sort of analysis you are talking about. As with C, there are idioms that can be used to mitigate the analytic damage, most e.g. copying array references to a local (which can therefore be seen to be non-interfered on a thread-local basis) and computing from the local reference. But the point is: you actually have to, and even having done this sort of thing, the analysis is anything but straightforward. This may be true of Java, but I'm not a fan of Java partly for the reasons you state. My point is we could easily have an imperative language with sound semantics that conforms to a type system that uses a pure functional monadic model, yet is compiled like an imperative language direct to assembly. So we could start with the IO monad, define a 'C' like syntactic sugar, and have a beginner friendly, OO like imperative language with sound semantics.
http://lambda-the-ultimate.org/node/5504
CC-MAIN-2018-30
refinedweb
22,767
53.41
>>." What did we expect? (Score:5, Insightful) I mean, really? Re:What did we expect? (Score:5, Funny) I might be confusing Microsoft with a wife beater, but the mentality is roughly the same it seems. Re:What did we expect? (Score:4, Funny) Say what you will about Microsoft, but I'll start using Linux on my production machines when I want to start losing money. Get the facts [getthefacts.com], people. Re:What did we expect? (Score:4, Insightful) As opposed to LD_LIBRARY_PATH hell and no codecs at all? Comparing Windows and Linux feature by feature is always going to be futile. The two are different, and if trying to make Linux a direct replacement for Windows, you'll necessarily have to chop down the things that make Linux great (like the toolbox approach and not being designed from the "one user, one application, one machine" philosophy). And comparing Linux with Windows is like wrestling a pig. You'll just get dirty, and the pig enjoys it. Re:What did we expect? (Score:5, Funny) I might be confusing Microsoft with a wife beater, but the mentality is roughly the same it seems. What do you tell a user with two black eyes? (I propose that the answer is "Did you really think Apple was different from Microsoft?" but that might not win me too many points around here. The converse would work almost as well, but nobody would have believed that Microsoft was the good guys.) Re:What did we expect? (Score:5, Insightful) That's unfair. Apple have never made an iWorks product intentionally produce a broken ODF document! *cough* Re:What did we expect? (Score:5, Informative) nobody would have believed that Microsoft was the good guys. Actually there was a time when Microsoft was hailed as the white knight in the shiny armor freeing us from the evil IBM empire. Re:What did we expect? (Score:5, Insightful) Actually there was a time when Microsoft was hailed as the white knight in the shiny armor freeing us from the evil IBM empire. Yeah but that was ~twenty years ago, which is like two hundred in do^H^H computer years. Since then Lancelot has screwed the king's wife and is off in the wilderness slowly going insane. Re:What did we expect? (Score:5, Insightful) |, ... Re:What did we expect? (Score:5, Informative), ... It was pretty obvious to many techies by the early 90s that Microsoft software was crap. The printed press was one of its tools and perpetuated the myth that companies would be better off with Microsoft. By 1995 it was getting out to a more general crowd how bad Microsoft was but these people still required having their eyes and minds open. Considering where they are today, it's obvious many are still pretty ignorant to their business practices and technology in general. By 1995, even the author, Douglas Adams saw this: Microsoft Here's a quote from the end of that short article: ." Over $200 million in marketing spent on Window 95 and about the same amount the following year pushing NT as _the_ server OS suckered in enough to seal their position in the market. That seal is leaking now but unfortunately, the general population of computer users and IT execs are mostly just as naive as they were in the early 1990s. It's the OEM's who are driving the market now because of very low margins and the high relative cost of Microsoft software. LoB Re:What did we expect? (Score:5, Insightful) Yah. The real heros bringing us the PC revolution was the guys reverse engineering the hardware/BIOS, and made cheap clones. The OS was just what became the de facto standard. As we all know, DOS won over CP/M. CP/M was technically superior at the time, but lost for political and/or contract reasons, whatever. Digital Research then went on to create a better DOS to compete. MS fought it with all means it could, and it went into oblivition. At early stages, MS Windows was just a graphical shell on top of DOS. It wasn't particulary good either. There were competing graphical shells, for example Digital Research' GEM. Digital Research lost the patent lawsuit that MS essentially won, and GEM was limited to have only two windows simultaneously...who knows what it could have been. MS has not had the technical best/superior solutions at any time. It was just better at legal and marketing stuff than anyone else. The PC revolution would have come with or without MS. We'll never know how much innovation MS have killed on its way where it is, so to hail it as a savior is just plain stupid. Re:What did we expect? (Score:5, Insightful) While I certainly remember thinking of IBM as the evil monopolistic overlords in the '80s, I thought of Microsoft as more of the black knight working with IBM, then stabbing them in the back as soon as they got a chance in order to become the new evil overlords. Re:What did we expect? (Score:5, Funny) Godwin'd! That wasn't MS (Score:4, Insightful) Actually the early 80s. You see, before MSFT started the clone market by selling Compaq MS DOS and thus creating the IBM PC compatible market, things were VERY different. It was 'welcome to proprietary land" where my VIC wouldn't talk to your TRS80 [...] Actually, it was Digital Research's CP/M (and AT&T's UNIX) that were leading the charge against "proprietary land". Bill Gates just got lucky when DR's Gary Kildall was out the day IBM came calling, and managed to steal DR's thunder with a hastily-purchased CP/M clone and IBM's marketing power. BG doesn't deserve credit for anything except dumb luck and being in the right place at the right time. The market was already headed in the direction of platform-independent OSes as fast as it could go. Re:What did we expect? (Score:5, Funny) Nothing. He's already been told twice. Re:What did we expect? (Score:5, Informative) "...1 second or so that it took to open the "Save file as" dialog..." It takes 2 seconds for a menu to appear on my work XP laptop when I click the Start button. It takes forever to open a Word document. Virus scanning is now part of the Office experience and can't be disregarded. And this is on a more modern computer. What is your point. Re:What did we expect? (Score:4, Funny) Hey, it is different. Hence not compatible. Re:What did we expect? (Score:4, Informative) I use Windows for compatibility, but open-source for everything else: VLC, WinAmp, OpenOffice, Utorrent, et cetera. I don't think you understand what open source is. Winamp and uTorrent are not open source. Re: (Score:3, Funny) I dont see why you're comparing MS to congress. Why not compare it to being eaten by a shark (with frikkin laser beams if thats your thing) or abducted by aliens. Congress doesn't have a history of lying to people... oh hang on Congress doesn't have a history of screwing the public for money/business interests... wait a minute.. Congress... errr.. never mind Also... uTorrent isnt open source. Re:What did we expect? (Score:4, Insightful) Re: (Score:3, Interesting) Not likely that they'll embrace a competing standard antytime soon. Re:What did we expect? (Score:5, Interesting) Well, that depends on who you talk to. Here in the US, that's probably true. Pretty much it's up to Europe to send the lawyers back in. But, there is a comment at the end of the article to check for an obvious abuse:. Since I don't have access to Office 2007 until I get home tonight, I can't try this out. But if someone feels compelled in the meantime, I'd love to see the results. If the document "magically" works after changing the header, then Microsoft did *not* do enough to keep the lawyers at bay. Re: (Score:3, Insightful) Tried it. Not the case. Re:I tried as well (Score:5, Insightful) No, that's not it. (Score:4, Informative) The problem isn't that you can't open a Word 2007 ODF document in another ODF compliant program, it's that it refuses to open to other program's ODF documents. If you actually read the article, you'll find that Google, KSpread, Symphony, OpenOffice, and the Sun plugin are all unable to open documents created in Excel 2007. The issue here is not that it's one way, it's that the MS interpretation is different from what everyone else uses (though the actual specification leaves it open). And it's also about spreadsheets (Excel), not word-processor documents (Word). Excel, not Word (Score:4, Informative) Re:What did we expect? (Score:4, Insightful) You really think so? The EU will probably slap them with a hefty fine yet again. This is just another example of Microsoft being deliberately anti-competitive. Re:What did we expect? (Score:5, Interesting) You really think so? The EU will probably slap them with a hefty fine yet again. This is just another example of Microsoft being deliberately anti-competitive. Except if you look a little closer, the EU doesn't just fine them. The fine is trivial, and does nothing but make the news in the computer press. Just money. A fine is like a parking ticket. And if you are rich enough, you can theoretically see a parking ticket as a parking fee. Forcing them to correct the problem to the satisfaction of a neutral third party acting as a technical "expert witness" however, is a worthwhile activity. And this can really sting. This is more like taking away their car, or revoking their license. Way more than a slap on the wrist and a stern look. Re:What did we expect? (Score:4, Funny) Doh, how do Governments force people to do stuff? Just jail the people at the top of MS in the relevant countries. If they refuse to go to jail, send people authorized to inflict force and violence to drag them off to jail. That's well within the authority of any country which MS operates in. You don't even have to fine at all. Once you start jailing top executives, they'll start taking things really seriously. After all, if you're a CEO, the fines don't really come out of your pocket[1]. But time in prison comes out of your lifespan. [1] They might in theory affect your bonus etc, but in practice just look at the AIGs of the world. Re:What did we expect? (Score:5, Interesting) If it achieves 100% technical compliance with the standard, but zero interoperability, this is certainly a problem with the standard itself.. Did the author of the article test with anything else than a spreadsheet with formulas? Formula breakage was expected and mentioned in the comments to the previous article. The interesting part is are there other flaws with ODF 1.1, are they addressed by 1.2? Re:What did we expect? (Score:5, Informative). That is, curiously, not quite true. ODF 1.1 doesn't fully specify formulas, but it does specify the general syntax that should be used for them, and Microsoft seems to have ignored this. (Also, in practice, the major spreadsheets are quite similar in terms of what expressions they accept in formulas. This makes it relatively simple to convert between MS Office formulas and OpenOffice.org ones, which are what most ODF-based apps use.) Re:What did we expect? (Score:5, Informative) Re:What did we expect? (Score:5, Insightful) Software Engineers. It is what we do for a living. Re:What did we expect? (Score:5, Informative) From the article: inexplicably thing is why that code never made it into Excel 2007 SP2. Re:This is a REQUIREMENT so that Excel can be read (Score:5, Informative) On the contrary, it does make sense to alter them because there is something wrong with Microsoft's formulas. For example, consider the MAX() function in Excel: Now consider the OO.o (and forthcoming ODF 1.2 standard) equivalent: OO.o uses semicolons instead of commas to separate parameters; so what? Well, let's what would happen if you were European, and tried to do the same thing in Excel: Uh-oh! Now, since Europeans use commas instead of periods to indicate decimals, Excel suddenly thinks that there are 8 integer parameters instead of 4 decimal ones! Excel is wrong! In contrast, here's how it looks in OO.o: Hey, whaddya know: still four decimal numbers! It works! But that's just the tip of the iceberg. If you read previous posts in the linked blog, the guy points out how (for example) most of Excel's date and financial functions are wrong (not just because of syntax, but because they implement the wrong algorithms). Actually, it does -- 300-odd pages worth of one, in fact. But Excel doesn't follow that either! In fact, those date and financial functions tend to give answers different from both the OOXML standard and the original financial standards they are supposed to be based on! Agreed ... interoperability harms Microsoft (Score:5, Insightful) Clearly Microsoft's best interests are served by denying their customers interoperability. That's what drives Microsoft's policy: cash. Everything else is PR. Which is duly born out by their actions. Re:Agreed ... interoperability harms Microsoft (Score:5, Interesting) Oh course. This has always been true with Microsoft, where in the late 80s/early 90s they advertised they could read WordPerfect files from Amigas or Macs, but all it did was strip all the formatting to leave-behind plain text. Yuck. Even later when Word was released for early PowerMacs, I found that Windows Word could not read the Word documents from my Macintosh. Microsoft does not want interchanging of information. They want everybody using MS Word on an MS operating system. The end. Re:Agreed ... interoperability harms Microsoft (Score:5, Insightful) Microsoft does not want interchanging of information. They want everybody using MS Word on an MS operating system. The end. Every major vendor would probably like their own product to dominate. The difference is not the motivation, but the methods. Some vendors honestly try to make the best product and win customers by so doing. MS prefers to leverage monopolies to artificially break competing products and prevent users from being able to choose based upon the individual merits of the products in question. I have no problem with MS wanting their OS and office suite to dominate. I have a problem with their breaking the law and hurting the industry, innovation, and end users to make that happen. Re: (Score:3, Insightful) But being able to correctly read ODF files would just be a big plus in an already great product like Excel. Why break the reading part? Re:Agreed ... interoperability harms Microsoft (Score:4, Insightful) But being able to correctly read ODF files would just be a big plus in an already great product like Excel. Why break the reading part? Because they don't want to discourage just other products that use ODF, they want to slow and discourage adoption of ODF as a format. Anything that makes more users stick with MS proprietary formats longer, makes MS money. Every user who sends an ODF file from Google docs to an Excel user, then finds it doesn't work is discouraged from using Google docs and encouraged to buy a license for MSOffice so they can interoperate easily with that other person. Re:Agreed ... interoperability harms Microsoft (Score:5, Funny) To really add flavor to the discussion, let us further assume that planet Earth is spherical, and space is pretty big. Because you look ridiculous claiming you were able to follow the standard for reading documents, but unable to do so when writing them? Re:Agreed ... interoperability harms Microsoft (Score:5, Informative) Åpne dokumentstandarder blir obligatoriske i staten. [regjeringen.no] My rough translation from Norwegian: - Norway has so far lacked a policy regarding the area of software. This have now changed. This Cabinet has decided that IT-development in the public sector shall be based upon Open Standards. In the future we will not accept that State activities locks users of public information to Locked Formats. - Heidi Grande Røys [wikipedia.org] (Minister of Government Administration and Reform). Microsoft might play their games to hinder development as much as they can, but at least in this country the turn towards Open Standards seems inevitable. Re:Never ascribe to malice... (Score:5, Interesting) Never ascribe to malice that which is adequately explained by incompetence. from the referenced article.... [robweir.com] Re:Never ascribe to malice... (Score:4, Funny) Re:Never ascribe to malice... (Score:4, Funny) Am I the only person who reads that extension aloud as "Ex-Lax"? Actually, the first two times I read it, it parsed as "Excel sucks." Counter-adage (Score:5, Insightful) There's another saying, and one that I think better applies here: "Once is an accident, twice is a coincidence, three times is a conspiracy." And with Microsoft we're way past three times. They also claim Windows supports Posix (Score:5, Insightful) As they also claim Microsoft Windows is Posix compliant! It is simply to be able to tic a "mandated" requirement in some government procurement, not as something one would actually use or deploy. Re:They also claim Windows supports Posix (Score:4, Insightful) Well, Windows is at least somewhat POSIX compliant. A few semesters ago I took an Operating Systems class; our labs were simple programs involving forking processes, named pipes, sockets, and file I/O, which we were to develop on an old Solaris box. Not much of a Pico fan, I developed my programs on Vista using Visual Studio 2005. They all compiled and ran on Vista, and then also compiled and ran on gcc and Solaris. These were simple programs, mind you, but it worked. Now ODF... TFA only looks at spreadsheet compatibility, and evidently there is no way documented in the ODF standard to store spreadsheet formulas. Article claims that they should have reverse engineered it or reused code from some other plug-in, but really I'm surprised they included any ODF support at all - "new markets" be damned. But, if no-one's satisfied, they also introduced a whole new API for writing file format converters. Go write your own plug-in! Re:They also claim Windows supports Posix (Score:5, Funny) As they also claim Microsoft Windows is Posix compliant! It is simply to be able to tic a "mandated" requirement in some government procurement, not as something one would actually use or deploy. Ah, I think you might have misread that one. The latest version of Windows is fully compliant with the ISO's 'Piece of Shit v9' standard. POS IX, not POSIX. Re:They also claim Windows supports Posix (Score:5, Informative) Microsoft Windows is POSIX.1 compliant, which will not help anyone today but which is nonetheless true. Re:They also claim Windows supports Posix (Score:5, Informative) Well if you just go for the basic level of posix support, then yes it does support it. So does 100 other OSes, including weird embedded OSes that can't even run executables. Everything has to be compiled in, but they are "POSIX" too. To be far UNIX Services for Windows is pretty decent and gives you a very complete POSIX environment on Windows. Problem with the Spec (Score:5, Insightful) So, this is either a problem with the specification or a problem with other implementations. If MS has made a compliant program, who are we to complain? Good point! (Score:5, Interesting) I was thinking exactly the same thing. If MS have made a compliant implementation but it isn't compatible with anyone else's, doesn't that mean that ODF is broken? Isn't this exactly the sort of complaint certain people around here have made against Microsoft's own formats in the past: just because there's a standard that officially states what the document format is, it's no use if other people can't realistically implement it and then trust that interoperability will work? Re: (Score:3, Interesting) Not necessarily broken, but certainly incomplete. Re:Good point! (Score:5, Interesting) Sure, it might be "incomplete" rather than "incorrect", but if we're talking about a standard for interoperability, doesn't "incomplete" pretty much imply "broken"? That sort of standard only has one job, and it isn't going to do it... Which means it won't get used.... (Score:5, Insightful) ...which is probably the point of this. The only reason to use ODF instead of MS native formats is for interoperability. When people don't use it, MS can point and say "see people don't want or need it and didn't care when we put it in". Useful at all manner of legal proceeding (antitrust anyone) to show that it's not important. I'm shocked! (Score:5, Funny) The article speaks about spreadsheets. (Score:5, Insightful) The article speaks about spreadsheets, which the slashdot blurb neglected to mention. Re:The article speaks about spreadsheets. (Score:5, Interesting) Unfinished sayings (Score:5, Insightful) This is the trouble with people saying the first half of a saying and then trailing off. The people who know the saying get the point, and the people who don't remember a fragment and repeat it even though it makes no sense on its own. To the people tagging this "embraceandextend". Embracing and extending is not a particularly bad thing to do. Many formats, including XML (upon which ODF is based), are built with this in mind. The complete saying that is referred to with "embrace and extend" is embrace, extend and extinguish [wikipedia.org]. The extinguishing is the goal here, the former two are merely tools to help them achieve this. Next stop - customer support (Score:3, Funny) Now that'll be good for some fun calls to customer support. Still no OOXML!! (Score:4, Insightful) Surprisingly MS has decided to implement ODF in their own strange way, but OOXML is still not available.... why?? Everybody pile on Microsoft... (Score:5, Insightful) In the meantime, how the HELL is it possible the spec is so bad that you can be technically-compliant with it, and yet not be read by (almost) any existing implementation? Re:Everybody pile on Microsoft... (Score:5, Informative) this is how [wikipedia.org] Kind of looks like the whole thing was a farce to begin with given how they created a bad spec and then went on to support a worse one before imploding. Re: (Score:3, Interesting) And from the article, the format version 1.1 doesn't even define how spreadsheet formulas should be stored! Which is why Microsoft's implementation, which doesn't bother to store the formulas at all, is compliant with the standard. This is a joke. Gee, I wonder why Microsoft fought a bunch of non-technical government offices from forcing them to use a file format that's woefully insufficient for their (both Microsoft's and the government offices') needs? Re: (Score:3, Informative) Re:Everybody pile on Microsoft... (Score:4, Insightful) The reason for this is that it's a hard problem I don't think you can really use that blog post for that citation, because it's the same source as TFA [robweir.com] which is both more relevant, and substantially newer... and which says: Editorial [brackets] and note mine. In summary: Your source, the same person who wrote the article which explains why it isn't hard also says Ecma dropped the ball. (in your link.) Another particular gem, this time from the current FA again: Everyone knows what TODAY() means. Everyone knows what =A1+A2 means. To get this wrong requires more effort than getting it right. So to say "The trouble is, it doesn't standardise them - in particular, there's no standard list of spreadsheet functions and what they should do." is just crazy talk which actually apologizes for Microsoft. In fact, there is such a list; the list documents what Excel does, since there was nothing else available; Microsoft itself had this functionality in a previous version, and now it is gone. Therefore the trouble is that Microsoft has deliberately broken spreadsheet compatibility in Office 2007 SP2. There is really no other way to look at it. It might not have been the goal (an alternate excuse might be to take advantage of another, newer codebase in order to eliminate some old code which is otherwise unnecessary) but it was trivially testable and therefore is inexcusable. Re:Everybody pile on Microsoft... (Score:5, Insightful) Except...Microsoft already have a perfectly good plugin that can read & write ODF documents. It appears they've gone out of their way to break that existing code and do things differently to how everyone else (including themselves) are already doing things. As the author of the blog says "If your business model requires only conformance and not actually achieving interoperability, then I wish you well.". If Microsoft have put all that effort into adding ODF support without actually achieving interoperability then it's a thinly veiled paper exercise on their part. Re:Everybody pile on Microsoft... (Score:5, Insightful) The current spec doesn't cover spreadsheet formulas: it has a big whole and basically says "Do what OpenOffice.org does for now". The problem with MS's specs saying "Do what Word 97 does" is that no one other than MS knows what Word 97 does. But OpenOffice's source code is... open. Anyone can know what OpenOffice does, and if MS is afraid of GPL, they're big enough for proper cleanroom approach. Re:Everybody pile on Microsoft... (Score:5, Insightful) Because specifications are written by people and then read and interpreted by others. While specification creators try to be as complete and thorough as possible, there are still gaps. In something as complex as a document format like spreadsheets, I'd imagine it's an impossible task. Bake-offs where all the stakeholders get into a room, try to get this shit to interoperate, and then decided the proper interpretation, is where the interoperation work gets done. All of the Internet protocols went through a similar cycle. Then, when there is consensus on the interpretations, guidance and reference implementations can be written. Re:Everybody pile on Microsoft... (Score:5, Insightful) Re:Everybody pile on Microsoft... (Score:5, Insightful). Re:Everybody pile on Microsoft... (Score:4, Interesting). Conversely, if the files produced by MS Office are valid standards-compliant ODF files (which they may be according to the letter of the standard) we should also blame the other apps if they fail to use them, isn't so? They will also fail to open standards-compliant ODF files. Well, interoperability wasn't the goal. (Score:5, Interesting) Even if MS fails all interoperability (which I would bet they do), at least someone could use ODF with office 2007 and 10-20 years later be able to use the spec to develop an app to recover the documents. EXCELLENT article (Score:3, Interesting) This is one of the best-written articles submitted to slashdot in a long time. Not only is it well-written (at least, it didn't make my brain hurt) but it gives you the technical background AND it tells you in advance how to debunk the stupid arguments which will certainly by coming from M$ trolls and astroturfers. Scrapbook this one, kids. You're going to be referring back to it for months, if not years. Hypocrisy (Score:4, Insightful) I'd say that it had a bad smell of Hypocrisy. If the standard doesn't cover important(I dare say) areas such as the friggin formula language, what good is the standard? No, the author is trying to preempt the obvious and very valid argument that if the standard didn't cover this and implementers need to reverse engineer a specific implementation (OpenOffice), maybe the standard wasn't good enough? The author is making silly analogies with someone willfully going through hoops (investing time) to sabotage interoperability with an implementation in which the implementor has chosen not to invest time and effort reverse engineering and testing functionality which is clearly outside the specification. Sun ODF plugin for Microsoft Office (Score:5, Informative) holes in the standard (Score:5, Interesting) Spreadsheets, people, spreadsheets (Score:5, Insightful) Bullshit (Score:3, Insightful) This article focuses very specifically on formula support in OpenDocument Spreadsheet. The problem with that is that ODF 1.x does not provide ANY specification for formulas whatsoever. This article claims that the standard be damned and that Microsoft should go and reverse engineer the implementation by OpenOffice. This is only demonstrative of how incomplete and irrelevant the ODF specification really is. There are massive gaping holes in it that implementers are filling on their own which will invariably lead to incompatibilities. The ISO OOXML specification may be absolutely massive, but that's because it's complete, and very specific (I'm referring specifically to the one that did pass ISO, not the first few iterations). This is like bitching that Internet Explorer can't be CSS compliant because it doesn't implement the moz-* CSS extensions. Either fix the spec, or get used to this. Re:Bullshit (Score:4, Interesting) Re:Bullshit (Score:4, Insightful) Microsoft should go and reverse engineer the implementation by OpenOffice Reverse-engineer it? You have the source code. You don't have to reverse-engineer anything. The problem is formulas. (Score:5, Informative) ODF does not specify the a language for formulas. Everybody but MS uses one language, MS uses another. Of course there are incompatibilities. Why did ODF not specify a spreadsheet formula language? Re:The problem is formulas. (Score:4, Informative) Because it's bloody hard to do. Microsoft's spreadsheet formula language in OOXML is actually a copy-and-paste job from the Excel help files. It doesn't provide nearly enough information to re-implement. It was only added as an afterthought, when Microsoft started complaining that ODF didn't have a spec for spreadsheet formulas, made a big deal about it, and then realised that OOXML didn't either. ODF does have a formula language specification. It specifies something like 400 functions in precise detail, loosely based on what OOo, Gnumeric, and others (including Excel) already do. This has been a work-in-progress since 2005 (before Microsoft started complaining about ODF), and is basically finished (for now). It's to be included in OpenDocument 1.2 (the next version), but most other OpenDocument-capable spreadsheet apps already use these formula specifications on OpenDocument 1.1 documents. Microsoft just chose to ignore it, and roll their own. As usual. Badly Specified Standard (Score:4, Insightful) Pigs (Score:4, Funny) Now, ODF == .doc and .xls (Score:4, Insightful) Microsoft plays dirty. All the time. This was totally expected, of course. It's ok though; we're still in better shape than we were just a few years ago. A Microsoft ODF document, or even a Microsoft OOXML document, is still at least roughly following a standard that has some documentation somewhere. The free world can develop Microsoft Office compatibility in this space a lot easier than in the Self-defense, perhaps? (Score:5, Insightful) It looks like Microsoft has learned from its IE experience. Instead of chasing an "anything but Microsoft" standard put together by a community that's actively hostile to Microsoft, they've decided to wait them out. Microsoft is refusing to give them a target and telling them to get off the pot. What Microsoft has done should speed up the ODF standards process. We should thank them for that. The Microsoft formulas aren't actually conformant (Score:5, Informative) Microsoft's supposed ODF 1.1 spreadsheet output is not compliant with the ODF 1.1 specification. From 8.1.3 (emphasis mine): From 8.3.1 Referencing Table Cells (emphasis mine): Now look at a Microsoft formula in their ODF 1.1 spreadsheets. You'll see a formula attribute value of "msoxl:=B4-B3". For that to be correct per the ODF 1.1 specification, that should be "msoxl:=[.B4]-[.B3]". Compare this to the OpenOffice.org and OpenFormula syntax: msoxl:=[.B4]-[.B3] oooc:=[.B4]-[.B3] of:=[.B4]-[.B3] Ignoring the prefix, they're identical. Furthermore, the formula functions used by OpenOffice.org are generally based on the functions in Excel to begin with (such as "TODAY", for example), so I can only conclude that Microsoft is intentionally sabotaging interoperability to keep people from using ODF while still claiming conformance. Re: (Score:3, Funny) Bloody hell. I wonder why they would ever want to ship a software product that did that. You must be new here. (grin) Re:Really? (Score:5, Insightful) Well, from the article: "First, we might hear that ODF 1.1 does not define spreadsheet formulas and therefore it is not necessary for one vendor to use the same formula language that other vendors use." Seems like a rather large hole in the spec itself. ODF 1.1 doesn't define spreedsheet forumlas? So, what version will? I wouldn't put any effort into guess, nor making my application read various other vendor formats.. when I may well have to recode again when 1.2 comes out. If anyone's to blame here, it's the ODF people for not having a COMPLETE spec. If formulas are so important to spreadsheets (and they are), why the hell would your spec not include how to store said forumlas? Re:Really? (Score:5, Insightful) Because apparently it's really difficult: [robweir.com] Oasis and ODF committees would rather get it right than have something busted and broken like competing suites. Re:Really? (Score:4, Insightful) If Microsoft is ODF 1.1 compliant, and other ODF 1.1 compliant software can't use the software, then it looks like the ODF committee didn't get it right and has something busted and broken. I think the ODF committee was more concerned about getting their standard approved quickly than having a complete specification. Re:Really? (Score:5, Insightful) Microsoft put all their Excel formulas into a private namespace. This is almost as bad as, say, writing a compiler that claims to be a C compiler, but really, all it does is validate the syntax of the C program and then look for C comments containing Pascal code, then compiling the Pascal code instead. BEGIN writeln("Microsoft rules!"); END */ int main(int argc, char *argv[]) { printf("This is standard C code.\n") } Is it a problem with the C standard that I can embed Pascal in a C comment? Re:Really? (Score:5, Informative) Interesting. According the article [linux.com] referenced in the Wikipedia [wikipedia.org] even OpenOffice and KOffice don't get along. Re:Really? (Score:5, Insightful) Interesting. According the article referenced in the Wikipedia even OpenOffice and KOffice don't get along. The difference is OpenOffice reads everything fine. KOffice fails to read the latest OpenOffice docs perfectly because OpenOffice uses the new draft version of the spec as the default... and it is perfectly appropriate for KOffice to fall back to reading those formulas as the last value until they release a new version of KOffice that supports the new spec. That is why there is a failback mode in the spec. MSOffice, however, fails back even when reading the old version of the spec, because they seem to have decided understanding Excel style formulas in Excel was too hard, despite the existence of several open source implementations and the spec being the formulas they already use. The difference is huge. Koffice is doing the right thing and being reasonable. MS is going out of their way to be as poor at interoperability as the spec allows by feigning extreme incompetence. I mean, did you look at the chart in the article. Why is it even small, unfunded projects seem to work interoperably pretty well, while MS can't manage to work with anyone else's implementation. Do you truly believe they are that incompetent? Re:Really? (Score:5, Insightful) Re:Really? (Score:5, Insightful) In order to claim (in a legalistic sense) technical compliance with the spec in order to be able to sell Office to companies/governments who have adopted policies requiring this, while at the same time making it virtually impossible for those organizations to actually USE a competing office product. Re:I just hope (Score:5, Insightful) Re:Chickens are coming home to roost (Score:4, Insightful) One the one hand we require Microsoft to follow specs to the letter, and now we somehow fault them for doing so? No, we're faulting them for following the specs to the letter and at the same time going out of their way to make sure their technically compliant implementation still doesn't work with all the other, existing implementations. What is wrong about asking OpenOffice to follow the specs? ODF does, for the most part, follow the specs. The problems between OpenOffice and MSOffice's implementations are that ODF implements a newer version of the spec and MS hasn't caught up to that, and MS decided the suggested (but not required) formulas, which use the same syntax as Excel and for which their is already BSD licensed code that works in MS Office as a plug-in, were "too hard to understand" so they just strip all the formulas out. MS may, technically, be minimally compliant with the spec, but it is clear they went out of their way to be as minimally compliant as possible to make their version as incompatible and unfriendly as they could manage while still being within the spec. This was not an honest attempt at being compatible, despite MS's claims that they were making an honest attempt. What goes around comes around. ODF was initially just a clever assault launched by Sun and IBM. Yeah, but it was an attempt to level the playing field and let products win based upon merits instead of criminal leveraging of monopolies. I don't understand why people have such a hard time understanding antitrust laws and how they work and why we have them. OpenOffice and derivatives, Sun and IBM just have to eat their own dogfood. Admit that the "perfect" ODF was at least partly a hype. No one claimed ODF was perfect and the early spec MS is using left room for ambiguity... which is why they also provided several open source reference implementations which everyone else has had no real problem implementing. Aside from MS, the only real problems are bugs between the stable and draft versions of the spec. MS is just playing dumb. "Oh they say if we can't understand Excel formula's, we can fail back to just reading the value the formula would produce. We're so stupid we can't understand formulas identical to the one we already use, har har, and we're too stupid to use the free BSD licensed implementation that already works with MSOffice, har har." The "problem" with the ODF spec in this case is that they wrote it as a spec assuming it would be used to make interoperable implementations, instead of as an ironclad legal contract with no loopholes for dishonest companies that wanted to try to be compliant but as non-interoperable as possible. After all, only one company had motivation to do that, and for them to attempt it would be criminal. That doesn't seem to have stopped MS though, as usual. The chickens are coming home to roost. Suck it up. Fix it instead of point fingers. Please. They already have a draft that removes the ambiguity and it is already implemented by several companies. If MS were interested in being honest or even obeying the law, there would be no issue. There is room for more than finger pointing, MS should be prosecuted for one more criminal antitrust violation. Why do you hate free market competition so much?
https://slashdot.org/story/09/05/04/1246249/office-2007sp2-odf-interoperability-very-bad
CC-MAIN-2017-09
refinedweb
6,780
65.32
Adding a second axis¶ Adding a second axis actually involves creating a second chart that shares a common x-axis with the first chart but has a separate y-axis. from openpyxl import Workbook from openpyxl.chart import ( LineChart, BarChart, Reference, Series, ) wb = Workbook() ws = wb.active rows = [ ['Aliens', 2, 3, 4, 5, 6, 7], ['Humans', 10, 40, 50, 20, 10, 50], ] for row in rows: ws.append(row) c1 = BarChart() v1 = Reference(ws, min_col=1, min_row=1, max_col=7) c1.add_data(v1, titles_from_data=True, from_rows=True) c1.x_axis.title = 'Days' c1.y_axis.title = 'Aliens' c1.y_axis.majorGridlines = None c1.title = 'Survey results' # Create a second chart c2 = LineChart() v2 = Reference(ws, min_col=1, min_row=2, max_col=7) c2.add_data(v2, titles_from_data=True, from_rows=True) c2.y_axis.axId = 200 c2.y_axis.title = "Humans" # Display y-axis of the second chart on the right by setting it to cross the x-axis at its maximum c1.y_axis.crosses = "max" c1 += c2 ws.add_chart(c1, "D4") wb.save("secondary.xlsx") This produces a combined line and bar chart looking something like this:
http://openpyxl.readthedocs.io/en/latest/charts/secondary.html
CC-MAIN-2017-30
refinedweb
180
54.29
1 I started c++ a few days ago and I am trying to make this program for my math class just to test myself. This is my code. #include <iostream> using namespace std; int main () { int goldennumber; int finalnumber; int ratio; cout<<"Welcome to Easy Golden Ratio Finder!\n"; cout<<"\n"; cout<<"\n"; cout<<"\t Please enter the length of the rectangle: \n"; cin>>"goldennumber"; cin.get(); cin.ignore(); ratio = 0.618; finalnumber = goldennumber * ratio; cout<<"Your number is: "<< finalnumber <<"\n"; return 0; } I'm trying to make this console program where you enter a number and the program does an equation for you and you get the final number. I tried compiling and this are the error I get: - error: ambiguous overload for 'operator>>' in std::cin >> "goldennumber"' Can someone explain what I did wrong and what this error means so I know how to fix it in the future?
https://www.daniweb.com/programming/software-development/threads/104446/school-program
CC-MAIN-2017-39
refinedweb
151
59.74
Another interesting question from StackOverflow. That thing is a gold mine for blog topics. Consider the following: class B { public int X() { return 123; } } class D : B { new protected int X() { return 456; } } class E : D { public int Y() { return X(); } // returns 456 } class P { public static void Main() { D d = new D(); Console.WriteLine(d.X()); } } There are two possible behaviours here. We could resolve X to be B.X and compile successfully, or resolve X to be D.X and give a "you can't access a protected method of D from inside class Program" error. [UPDATE: I've clarified this portion of the text to address questions from the comments. Thanks for the good questions.] We do the former.To compute the set of possible resolutions of name lookup, the spec says"the set consists of all accessible members named N in T, including inherited members" but D.X is not accessible from outside of D; it's protected. So D.X is not in the accessible set. The spec then says "members that are hidden by other members are removed from the set". Is B.X hidden by anything? It certainly appears to be hidden by D.X. Well, let's check. The spec says "A declaration of a new member hides an inherited member only within the scope of the new member." The declaration of D.X is only hiding B.X within its scope: the body of D and the bodies of declarations of types derived from D. Since P is neither of those, D.X is not hiding B.X there, so B.X is visible, so that's the one we choose. Inside E, D.X is accessible and hides B.X, so D.X is in the set and B.X is not. What's the justification for this choice? Doesn't this conflict with our rule that methods in more derived classes are better than methods in base classes? No, it doesn't. Remember, the rule about prefering derived to base methods is to mitigate the brittle base class problem. So is this rule! Consider this brittle base class scenario: FooCorp makes Foo.DLL: public class Foo { public object Blah() { ... } } BarCorp makes Bar.DLL: public class Bar : Foo { // stuff not having to do with Blah } ABCCorp makes ABC.EXE: public class ABC { static void Main() { Console.WriteLine((new Bar()).Blah()); } } Now BarCorp says "You know, in our internal code we can guarantee that Blah only ever returns string thanks to our knowledge of our derived implementation. Let's take advantage of that fact in our internal code." public class Bar : Foo { internal new string Blah() { object r = base.Blah(); Debug.Assert(r is string); return (string)r; } } ABCCorp picks up a new version of Bar.DLL which has a bunch of bug fixes that are blocking them. Should their build break because they have a call to Blah, an internal method on Bar? Of course not. That would be terrible. This change is a private implementation detail that should be invisible outside of Bar.DLL. The fact that hiding methods are ignored outside of their scopes means that they can be safely used for internal implementation details without breaking downstream users. (Eric is in Oslo at NDC; this posting was prerecorded.) The specification says "A declaration of a new member hides an inherited member only within the scope of the new member.", but says nothing about the lower accessibility. if we replace protected to public class D : B { new public int X() } D.X won't hide B.X in the main method? Excellent question. The way I originally wrote this article implied what you stated, which of course is incorrect. I've clarified the text. The relevant portion of the spec is in the member lookup section. – Eric Yes it does. The new member is public so any call to it is within it's scope. You are confusing scope with accessibility domain. The scope of an entity is the region of program text in which it is legal to refer to the entity by an unqualified name; a public field of a class is in scope only inside the class. Anywhere else you have to qualify its name to access it. The accessibility domain of a public member of a public class is everywhere; the accessibility domain is the region of program text where it is legal to refer to the entity by qualified or unqualified name. The problem was that I was not calling out the specific part of the spec that dealt with the relationship between member lookup and hidden members. I've clarified the text. – Eric Good to learn something new. I didn't realize freeborn's question had a catch to it, as D.X obviously does hide B.X in that case. I get lost with some of these terms in english (not my native language). Do you have any blog where you explain what we are exactly referring to when we talk about scope, domains, declaration spaces, etc? So what is the recommended way for a subclass to hide a function from the base class? A public implementation that throws an exception when called? You cant really hide a method, if someone really wants to call the "hidden" method they will always be able to. Anyhow, IMHO if some class in you're inheritance chain needs to hide public inherited members then probably something is wrong with your class hierarchy to begin with. You should think more in a "has a" relationship than a "is a" type relationship in most of those cases. If hiding only happens within the scope of a member (which Main is outside of), then if D.X were public, why does B.X appear to be hidden in Main? Is it only because of the betterness algorithm? oReally here is something about scope, declaration space and lifetime.: blogs.msdn.com/…/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx "So what is the recommended way for a subclass to hide a function from the base class? A public implementation that throws an exception when called?" I have no idea if this is a recommended way (I doubt it is) but here goes. Use "new" to hide the method. In you new method throw the error. Then apply the EditorBrowsableAttribute on the method to hide it from intellisense. If it is not in intellisense then it does not exist right =). You do not get a compile time error but this may get you 90% of the way there.
https://blogs.msdn.microsoft.com/ericlippert/2010/06/14/hide-and-seek/
CC-MAIN-2017-39
refinedweb
1,104
68.36
Hey, Scripting Guy! How can I change the Copy music to this location folder in Windows Media Player? — BD Hey, BD. You know, a lot of people think that the reason we Scripting Guys don’t do very much work is because we’re just plain lazy. Those people are right. However, what we tell our bosses is this: it’s hard for us to do any work because every time we write a script we get hundreds of questions related to that script. That proved to be the case when we released our article – The Scripting Guys Really Do Rock – that talked about scripting Windows Media Player. No sooner did we release the article than we were inundated with millions of questions about scripting Windows Media Player. Trust us, it’s not easy for a bunch of lazy guys to answer millions of questions. Editor’s Note: “Millions” might be exaggerating just a little. But while we look into doing more articles on Windows Media Player we’ll try to address a few of these million or so questions in this column. As you noted in your email, BD, you’re having a problem with users automatically saving music files to your file servers; you’d like to be able to set the default location for saving music files and you’d like to be able to do it using a script. Before we go any further we should point out that in Windows Media Player 10 this option is no longer called Copy music to this location; instead, it’s called Rip music to this location. You can find the default folder setting in the Options dialog box on the Rip Music tab: As you can see, on this computer new music files will be saved, by default, to the folder D:\Music. So can you change the default location using a script? As a matter of fact, you can. The value for the rip music folder is actually stored in the registry; you’ll find it here: HKEY_CURRENT_USER\Software\Microsoft\MediaPlayer\Preferences\CDRecordPath And, yes, for some reason the registry value is named CDRecordPath. But the name doesn’t matter; all that matters is that we can use a script to connect to this registry value and then set the default folder path to any valid folder we have access to. (Note that if you’ve never changed the path, you might not see CDRecordPath in your registry until after you’ve changed the value. But trust us, this will still work.) In fact, here’s a script that changes the default folder setting to C:\Audio: Const HKEY_CURRENT_USER = &H80000001 strComputer = “.” Set objRegistry=GetObject(“winmgmts:\\” & _ strComputer & “\root\default:StdRegProv”) strKeyPath = “SOFTWARE\Microsoft\MediaPlayer\Preferences” strValueName = “CDRecordPath” strValue = “C:\Audio” objRegistry.SetStringValue HKEY_CURRENT_USER,strKeyPath,strValueName,strValue We begin by defining a constant named HKEY_CURRENT_USER and setting the value to &H80000001; we’ll use this later on to indicate which portion of the registry we want to work with. We then connect to the WMI service, binding to the standard registry provider class (StdRegProv) in the root\default namespace. We then assign values to three variables: Next we call the SetStringValue method, passing the HKEY_CURRENT_USER constant and the preceding three parameters. That will change the value in the registry and, in turn, change the default folder location for copying (or, if you prefer, ripping) music. Join the conversationAdd Comment
https://blogs.technet.microsoft.com/heyscriptingguy/2005/05/27/how-can-i-change-the-copy-music-to-this-location-folder-in-windows-media-player/
CC-MAIN-2016-30
refinedweb
571
59.84
I added a major release of jQuery.SerialScroll. It doesn't have that many changes, but I really feel it made one step ahead. Optimizations - The animation is skipped if a bad position was received or it's the same as the actual. Saving some overhead. Changes - Changed the licensing from GPL to GPL+MIT. Features - The plugin binds 3 events to the container to allow external manipulation. They are clearly explained in the main post, please check it. - Added 2 more arguments to the onBefore callback: actual item collection, index of the actual item in the collection. - Added option 'interval', can be a number specifying the amount of milliseconds for autoscrolling. Links Downloads - jQuery.SerialScroll 1.2.2 Source(to learn or test) - jQuery.SerialScroll 1.2.2 Minified(recommended) - jQuery.ScrollTo 1.4.3.1 Source(to learn or test) - jQuery.ScrollTo 1.4.3.1 Minified(recommended) 115 comments: Isn't there any way to get a cycle to work which constantly - as the word says - cycles around the images of a slideshow. I'd call the behaviour it has at the moment "rewind=true" not "cycle=true"... Is there any trick to get a constanly cycling slideshow to work - even better without delay between moving the pictures? Hi The endless scrolling requires to clone or move nodes. The plugin doesn't do that (and won't). For constant scrolling with no stops, you can set the step option to the amount of items - 1, that's the closest you can get with this approach. Cheers Thank you!!! It was the comma's fault, and it's time to go learn JavaScript... How do your demo navigation links work for section 1, 3, 5? I don't see how each link is related to the target? - Thanks! Hi They're linked by index. Using the option 'navigation'. If you need a more "consistent" relation, you can use LocalScroll for that part (also on this blog). That will link them by id/href. re: navigation linked by index - the demo has 5 scrolling "sections" but only three navigation links, pointing to the first, third and fifth items; so where in the demo is the index set for nav link #2 to scroll to item #3? ... Regards, Phillip It is by index. But it will do rounding if you have less links than panes. rounding ... OK ... thanks, Phillip Hi Ariel, I'm trying to use your serial scroll to accomplish scrolling on rollOver, much like this site. Can you help out? Hi You need to set 2 transparent divs, one on each side. Set them as 'prev' and 'next' respectively and set the 'event' setting as 'mouseover'. That will scroll like that, only that won't go on scrolling automatically. For that, you need a "smarter" mouseover that keeps triggering each X seconds. I think there was a plugin for that. Thank you for such a wonderful plugin. By the way, I have figured out a way to get a real 'cycle'. Will post here if anyone need it. I upload a demo here. It's not perfect though. But plz see it and make it perfect if possible. Thanks le/serialscroll.htm I only made changes in jquery_serialscroll.js and the html file Finally, I make the 'cycle' working like I want. budsicecream.com.vn/demo/scroll.htm @Anonymous The noConflict needs to be called after including all the plugins. @Hai Seems pretty neat, it's only a bit quirky when going backwards. Good job. @Niclas The server is giving me an internal error. thanks for the reply :) yes I tryed localscroll but, it won't scroll too :( however I added items to my demo but it doesn't resolve the problem :( Hi and thanks for your great plugin. I got the problem that my pages (doing paging) have different height. In a previous comment you recommend to use onBefore to adjust the height. Imho it looks ugly when first adjusting height and then scrolling. Sometimes the height-adjustment could even be out of the screen, so the user wont see it. If I do it afterwards I got the problem that if the current canvas is longer than the last page, it wont scroll correctly to it. This might be solved with a dummy-div or something. Anyway, is there a option for joining the scrolling animation an do the height-adjusting as well as "scroll to top" simultaneously? @Lars The plugin doesn't include stuff like this "built-in". As you said, Any parallel animation can be initiated from within the onBefore, or even a new click handler... you problably need to tune both animations' settings to synchronize them correctly. @Jono Oops, I missed the comment. I checked the demo and all the initialization code is commented out... Hi your plugin is great, thank you very much for it. But there's a question... Is it possible to use SerialScroll on one content-div twice? I mean, first navigation panel scrolls content-div through items-A and there's a second navigation panel with I'd like to scroll the same content-div but through different items let's say items-B? Cheers It should work alright. I intentionally ensure it'd basically work with several calls. Just call the plugin twice with different navigation/prev/next/items. ok I know the reason. But I need your help to solve it. this line is the problemmaker ;) $contentDiv.trigger('goto', 0); Since there are two sets of items. It doesn't know which item[0] should it scroll to. Yeah, that's why I said "basically". If you intend to use the custom events, then that'll be a problem. I only add them for the first call, else it'd go mad. At this point, I think you need 2 containers or a similar workaround :) Fab plugin Ariel... I got it working on 2 sites. Now I want to make the nav menu on 1 of the sites scrollable too using prev/next: See for an example. Clicking on each nav thumbnail brings up the desired slider underneath, but I just can't seem to get the prev/next buttons to move the nav along (there are 2 more thumbnails out of view). I've tried specifying "items" as both the individual LIs in the nav, and also just the UL. Am I missing something obvious? YO ARIEL, thank you so much for building this. you rock Ariel, I have alomost fixed the scrolling navigation problem I reported last week. See "" for an example. Thumbnail navigation scrolling pane works fine in FF and IE7/IE6. But not in Safari and Google Chrome: The "next" arrow/button works OK the first time it is clicked - the nav pane scrolls to the next set of thumbnails - but clicking the "prev" arrow doesn't scroll back again. Any ideas?? The demos are back @Basher I don't know what's the problem, please put the unminified versions and I'll re-check. Thanks Ariel. I have now uploaded unminified versions of ScrollTo & SerialScroll. I've changed the site since I last posted, so please now look at this page instead: @Basher It's pretty odd actually. The scrollLeft property of the element IS changing when scrolling backwards, but it's not reflecting that, maybe a browser quirk? It's something that has to prolly be changed within the css, so that the browser won't go mad. Can you try switching the doctype to transitional ? Thanks Ariel, I've changed doctype to transitional. I did do a test whereby I took just the nav scroller code and dumped it into a new html page with no formatting (e.g. no floats, etc) - the arrows still didn't function correctly. Also, I've just noticed that scrolling forward on "pics" page, a whole panel is missed out - there should be 18 pics in total, but Safari just renders 14. And on "scribbles" page, Safari only renders 13 instead of 21. Safari is jumping to the last pane after showing the first 3 correctly. Sorry to be a pain...! Ariel, Sorry for the confusion. Try basher.biz/dreamloft then select any of motion/photos/scribbles pages. Or try the "live" site - thedreamloft.co.uk. Not sure what's going on with the formatting on 2 of the pages - doesn't happen on live site - but that's for me fix!! Cheers for pointing it out. Hi This is a brilliant plug-in, thanks. I have a question though. Is there any way to add multiple carousels to a page without giving each one a seperate ID? I currently have several on one page and have targeted them using the class name, but when I click a button all five scroll simultaneously. Thanks! @Basher The property that is annoying the browser is the display:inline on #portfolioNav. With that removed, all works well. @Irishsteve Yes, that's why the target option is there. If you specify a target, then each matched node will become just a context to each one of prev,next,target,items selectors. That means they become relative, though reusable. Many thanks Ariel... how random, eh! Happy new year. Hi Ariel, for the life of me I cannot get this to work, and it looks amazing, really excited about using it. I mocked up something quickly and I was hoping you could give me a pointer to what is wrong.. Thanks Ariel, wish I had your skills. Hi, Great work, I love this plugin. I am using it for a Coda type slider/slideshow. Works perfect but I just ran into a bug by adding a simple anchor <a href="#someAnchor"> to the page (unrelated to the slideshow) On clicking that anchor i get: error on line 184 of SerialScroll Error: elem is null elem = elem.parentNode; Have you run into this? Any ideas? Thanks again! Ariel thanks a ton for your work. You are a really amazing programmer. I truly appreciate your work.....however unfortunately the documentation is really terrible. Just examples no code snippets. When should I use scrollTo vs serialscroll vs localscroll...all the examples look the same and there is no code provided for any of then??? I know you can just view your source but... Why can't you post a simple example with js and html for each plugin. It would save you thousands of help requests. Almost every other jquery plugin seems to manage to do this. Every time I use this plugin it takes 30min to an hour to figure out/remeber the syntax for your methods....jeepers Hi! I have a quite strange question about this great jplugin. I'd like to make just an ordinary menu using this plugin, where after clicking the link (just "a href" link) in the "ul list" you go to the next page. Now, after clicking on the link in menu I have nothing :-( It just stands still and doesn't do anything... @cmacG1970 and @Bartłomiej Got a demo online ? @no one will read me I can accept that the demos are not the greatest, and yes, you're meant to check the init.js. I'm quite slow at html/css so many demos would take me too long. On the other hand, I think the documentation (blog post) is really clear and descriptive for all three plugins. I'm sorry to hear it's not clear enough for you. " #goto.serialScroll Scrolls to the specified index " Is there a way to do this but without the scroll? I want to go straight to say image number 10 but I don't want to scroll to it, I just want it to start there. ? Cheers $('#container').scrollTo('li:eq(9)'); You can of course add settings. Thanks for your reply! It's weird. I tried your suggestion and also took a look at the scrollto demo. None of the following did anything, except the last line, which isn't scrollTo. No error is thrown though... it just doesn't move the lis at all. $('#slideshow').scrollTo( '+=340px', { axis:'y' } ); $('#slideshow').scrollTo( 150, 800); $('#slideshow').scrollTo('li:eq(9)'); $("#slideshow").trigger( 'goto', [ 9 ] ); Hi Ariel, I just find out this project and it's really a great job. Congratulation. However I still have a problem and I hope you can help me. So I m looking to make a circular auto scroll list but I would like that on the last item, it doesn't go back to the first but continue as the list as no ending. Is it possible to do it ? and how to do it ? In advance thanks Hi, First of all congratulations and thanks for this amazing pluging. I would like to know if there is a way to add a "slider" like in here: I have checked the different demos that you have but I haven't found anything similar. Thanks H, Thanks for such a nice plug in. Its really nice and easy to customize. I am trying to use swf videos inside the li instead of your sample loreum ipsum text. If I use flash swf's then the first and second swf are visible and if click next then 2 and 3 are visible. I tried changing the width for sections but it doesn't help. I can post the code or email it, if you can help me out! regards Pragan forgot to mention that it works fine in IE 7.0.5730.13 and not in FF 3 Hi Ariel, well done man! I want to put more than one news ticker in my page and start the second and the third after some time from the first. For instance the first news ticker starts when the page loads, the second one starts after 3 seconds and the third one after 6 seconds. Can I do that? Thanks. Hi, I can't make the news ticker work. What am I missing: $(document).ready(function() { $('#news-ticker').serialScroll({ interval: 1,//auto scroll constantly easing:'linear' }); }); Hey Ariel Thanks for this amazing plugin. However, I wonder if this is possible: I have one page with links. When I click on the link, can I have it open to a new page and automatically slide to the currently selected "page" in the sliding list? @Anonymous Do you have a demo online ? @Bucheron I haven't provided a way, some users added propositions within the comments. @Alberto Same as Bucheron, that requires additional coding (outside of the plugin). @Pragan I don't fully get it, do email me a demo please. @Nicola Call the plugin many times, with within a setTimeout with different delay, or.. just use a different auto scrolling interval. @Anonymous2 You must specify a selector to the items. @Chris You should pass the id of the target element as hash (#foobar). Then read it from the other page. I'd do something related to the 'start' and 'force' options of serialScroll. Thanks for replying so quickly. But I'm not quite sure what the code would look like. Would I pass the ID through the a href similar to local scroll? And how would the start/force javascript look like and where would it go? Hey, I'm a novice at Javascript, and I've got the serialscroll,localscroll and scrollto commands working for a horizontal slider. However for the life of me I cannot seem to get it to become a vertical slider. I was just wondering if you can help me!! As in which bit of code in which js file I need to alter. Thanks Hello Ariel, beautiful plugin. I am having a difficult time finding detailed information on the callback behavior. (example: I would like to control behavior after the last element. Instead of scrolling all the way back (kind of distracting), I would fade it, then manually change the position of the element and then fade the first element back in. Could you point me in the right direction? Or will this require hack? Let me know! i'm wondering if you got a solution for the fact if you click 5 times next after 'last' element, you got to click 5 times on previous to begin scrolling again. thx in advance Hi Ariel - Awesome work on your end. I am running into an issue that I can't seem to find an answer to. I have the scroll automatically starting, it is powered by both next and prev buttons as well as a navigation. How do I get the scroll to stop if a user clicks one of the options? right now it keeps scrolling automatically. Any guidance is appreciated. Thanks, Phil @Chris Quite complex to explain in a blog post or email. Can you add me on Gtalk/MSN ? aflesler[at]gmail for both. @dirtymole You should be changing the setting axis from 'x' to 'y'. Got a demo online ? @anonymous Something like this maybe ? probably needs some tuning. @sven Try removing the line that says 'offset' if you have it. Else you need to play with the option 'exclude' so that it works nicely. Check the docs about it. @phil Check the post called "doctorate on serialScroll". There's a snippet on how to do "stop on hover". This should be similar. Thanks for your Reply Ariel - my last query here again for clarification " It's weird. I tried your suggestion and also took a look at the scrollto demo. None of the following did anything, except the last line 'trigger', which isn't scrollTo. No error is thrown though... $('#slideshow').scrollTo( '+=340px', { axis:'y' } ); $('#slideshow').scrollTo( 150, 800); $('#slideshow').scrollTo('li:eq(9)'); $("#slideshow").trigger( 'goto', [ 9 ] ); " Yes I do have an online demo!: ^ You can use the 'test' link on that demo page to see what I mean. Thanks. Hi The axis should be 'x', as it is horizontal. Something like this: $('#slideshow') .scrollTo('li:eq(5)', {axis:'x'}) .trigger('notify',[5]); Where 5 means: to the 6th. Hi, Love this plugin! I'm scrolling a horizontal list (ul/li) and controlling the scroll with left and right buttons. The buttons are placed over the list. My intention is to have the "active" item between the buttons and the other items to the left and right of the buttons. Like this: item1 item2 << ITEM3 >> item4 item5 It works ok but I can't get it to start with item1 between the buttons. How do you position item1 to be in the middle of the visible area? Have tried offset without any luck. You should add either padding-left to the container or an invisible element on the left side of the container. Make sure the option 'force' is set to true. Is it possible to "refresh" some variables used for serialScroll with another js junction after the fact? Hmmm....That's not very clear--just look at my demo page:. The need for this arises because I've got a function to resize the content area depending on the user's screen size. I want to set the "step" (and some other values which are based on the step number) to equal the number of items that can fit on the screen. This number will change when the screen is resized so I need to have my resize function update this "step" variable. The problem is that if I put the serialScroll code after the resize function the resize doesn't work--the content size will be stuck at the default small size and will not expand. So I've put the serialScroll code before the resize and it works fine. So now I need to way to have the resize function update the serialScroll function with the new "step" value. Is this possible--or is that step value stuck on whatever it was when serialScroll initiated and there's no way to update it? See for the code. Would be very grateful if you could offer some help. Thanks again for the great scripts! @Benek Not at the moment. It's on my TODO list, not sure when will I be able to get that it. I'm now working on scrollTo as much as I can. Will let you know if I add that. Thanks for the reply Ariel. If I cannot change that value after serialScroll has initiated, do you have any idea on how I can initiate serialScroll after my resize function without messing it up? Currently, if I put serialScroll after my resize it will override the width's that have been set by the resize function and will put the scroll container back to it's default width (as set in CSS). Is it possible to initiate serialScroll without it having any effect on the width of the container? You mean cleanup up and re-call serialScroll ? To cleanup, you need to do: $('#container').unbind('.serialScroll'); And then clean the arrows, check the source to see all the bindings. Will try to expose the settings asap. Hi Ariel, I am having a hard time with 2 things. First, the onBefore callback will not see past a third argument. I have a function defined to test it like this: beforeCallback(a, b, c, d, e, f, g){ console.log(a); ... console.log(g); } and after it hits c, it prints 'undefined'. Also, i am passing in valid prev and next buttons, but they are not making the buttons active. here is an example: Thanks That's because you're using the same callback for LocalScroll, which doesn't pass that many arguments. Hey Ariel, Sorry for bothering you again, but I have another question. So far I have updated my sculpture page () and passing the id from the works page () as you suggested. However, a funny thing happened. The prev/next buttons seem to assume I am on the first item of the list and scrolls accordingly () How can I let the prev/next buttons know I've started on a later element? Also, the hash seems to force the page up a little bit when it's not suppose to. What's wrong? Thanks! Hi, I can't find the place where you use the location hash. But anyway, you can let serialScroll know about a change like this (in the docs!): $('#scrollable').trigger('notify',[what]); Where 'what' is either a number (index) or a dom element. Hi Ariel, I'm a bit confused by what you mean when you say "cleanup up and re-call serialScroll"(march 10). What specifically does that do, and how will it help with my problem of resizing the container? Do you have any documentation on what you are referring to? I'm a JS beginner here so I need a bit of hand-holding unfortunately. Would you be willing to help some more? I meant that you can call serialScroll again with different settings. That's what you wanted to do, right ? Whoa thanks for the fast reply! So I added this to the javascript code: var elem = location.hash && $(location.hash)[0]; if( elem ) $('#s_gallery').trigger('notify',[elem]); where #s_gallery is the element for sculpture. So far, the nothings happening. My problem is that serialScroll works fine when called before my resize function, but if I call it after the resize function it resets the width of the container to it's CSS width rather than what the resize function reset it to be. So I need a way to call serialScroll after the resize function without it affecting the resize of the container or I need to call serialScroll first but then recall it somehow after the resize to update a few of the variables which should be based on screen width. What would you suggest? I need an online demo, I'm not really understanding. Excellent script thanks! One problem...can't seem to get it to scroll in IE7 on either of two machines I've tried. Tried to make sure that the style includes position:relative but it still isn't sliding. FF works perfectly. Any thoughts. I've tried all I can think of but I don't have tons of experience with jquery. Thanks Hi, can't tell without a demo. Sorry...thought the link to the page was included in the form. Here it is. Any insights would be helpful. Thanks Ariel, Please refer to my first post (March 5, 2009 8:48 PM) for links to online demo and my JS file. As you'll see in the file the container for serialScroll resizes based on screen size. I need to be able to change the "step" and "exclude" settings dependent on that screen size. So I need to be able to initialize serialScroll after those variables can be adjusted by the resize function. But I've tried this and it doesn't work. When initialized after the resize function serialScroll resets the size of my container to the default size overriding the size set by the resize function. Which means I need to find a way to stop serialScroll from messing with the container width, or I need to leave it as it is now (serialScroll initializing before resize) but then somehow recall the function after the resize to update the "step" and "exclude" settings. Does that make sense now? @Wendy Right, didn't see it. The problem is the with trailing commas in the last element of an object. In english, you need to remove the comma from lines 87 and 112 within serialScroll.init.js. Appart from that, you probably want to clean up that file, you're calling the plugin a lot of times and I doubt they're all used. You're also including jQuery twice. All these isn't crucial, the problem is with the commas. @Benek No, it doesn't. SerialScroll doesn't alter any CSS attribute, nor height, width or any other. IF you need to clean up the original call to the plugin, just unbind all the bound events. They all have the .serialScroll namespace (except the one on the 'event' setting) so that should be easy. Thanks Ariel, That did the trick! Much appreciated. Wendy Hi Ariel, Sorry to ask another question, but now that my horizontal slider is working beautifully in both FF and IE I tried a vertical one, and you guessed it, it's not working in IE. I made sure that all my end line commas were correct too. Can you have a look and see if you can spot anything? Thanks Hey Ariel, Sorry to bug you again...I'm not having a lot of luck setting up SerialScroll. I tried following your instructions in setting it up, and when that worked I tried just using one of your examples and building my serial scroll around that, and it still didn't work. Would you mind checking over what I've got and see if what the problem is jumps out at you? I'm sure its something obvious, but I'd greatly appreciate it I'm sorry, there was a typo in my previous post.... "I tried following your instructions in setting it up, and when that worked" I meant, when that DIDN'T work. =P Wouldn't need to ask for help if I could get it to work, lol Hey Ariel, First of all, thanks for a seriously amazing plugin. I'm having the same problem as Benek. Maybe I'll be able to explain it a bit better? Let's hope! Okay, here goes... I've got a serialScroll side-scroll implemented where the viewable area of the target changes when you resize your browser window. The target has a constant width with padding that changes. Because of this padding I set the offset to the padding value. The problem arises when you resize the window. The offset then needs to be reset to match the padding of the target that changed. I've tried unbinding, but I'm at a loss of how to correctly do this. Here's what I have: $('#container') .unbind('prev.serialScroll') .unbind('next.serialScroll') .unbind('goto.serialScroll') .unbind('start.serialScroll') .unbind('stop.serialScroll') .unbind('notify.serialScroll'); Then I try to recall serialScroll using: $('#container').serialScroll(options with new offset); Any words of wisdom on successfully unbinding everything associated with serialScroll? @Wendy I'm not sure but it's related to styling (not js) I'm pretty sure of that. @PJ Something's wrong with the markup and/or the 'target' setting. Try changing overflow:hidden to auto where applicable and you'll see it's messed up. @Sean Try: $('#container').find('*').andSelf() .unbind('.serialScroll'); You should also add the namespace serialScroll to your 'event' setting: event:'click.serialScroll' That worked!! Brilliant, really. Thanks so much for the quick response. Your commitment to this community is much appreciated! Hi Ariel, Your plugin is awesome, I plan on using it on a number of Drupal instances as a sliding gallery. What do you recommend for a continuous cyclic loop? Is there another plugin that can work with SerialScroll to achieve this effect? Would the looped slider help? @Krisbfunk There're no plugins to use WITH serialScroll, you need to use one or the other. Is there a way to have a loading graphic display until the slider has finished loading? Thanks @Wendy It's possible to do that, yes, but that's not provided by this plugin. I've come across a bug which only shows in Safari 3 / IE8. It can be demonstrated on the demo page. 1. Open demo page: 2. On the top demo, click "Section 5". The panel scrolls to section 5. 3. In the JS console, enter: $('#screen').hide() to hide the scroller 4. Then show it again, with: $('#screen').show() The scroller returns back to section 1. However it still thinks it is at section 5 - the right arrow does not work, and the previous arrow takes you to section 4. The way to get it back on track is to notify the scroller where it really is, and tell it to go back to where it should be. Surely it shouldn't move just by showing / hiding?? These browsers seem to reset the scrolling position when hiding the element. Not much to do from the plugin. If, for some reason, you need to hide one and then show it. You'll need to either fix the scroll (with scrollTo or something) or either trigger the notify event passing 0 as the argument so it realizes it is back at 0. Thanks, yes, I did the latter. Is it possible for the plugin to detect if this happens and compensate?? Not really. I think it's out of scope, sorry. Hi, First, great plugin. Thanks! Here's my page in queston: GameI'm trying to get the numbers to stop, but nothing I try seems to work. Could I get some suggestions please? Thanks! Just after the area that tries to explain how to use triggers, you say "Note that to use 'start' and 'stop' you need to use the option 'auto' first." Where do I use the 'auto' option? Also, if this is my code: $("#slot1").serialScroll({ items : 'div', duration : 50, force : true, axis : 'y', lazy : true, interval : 1, step : 9 }); How do I get a trigger to work with that? I'm trying to use the 'goto' but this: $("#step1").trigger( 'goto', [3] ); Isn't doing anything. Thanks again! @Clint Meant 'interval' not 'auto' (fixed). Can't believe this was wrong all this time :) It should be: $("#slot1").trigger('stop').trigger( 'goto', 3 ); Ok, then I must have something else bothering that. It's depending on an element being clicked. So when I click to stop, it stops but does not goto until I click the element again. $("#endGame a").click(function(){ setTimeout(function(){ $("#slot1").trigger( 'stop' ).trigger( 'goto', 4); }, 5); }); Like I said, I have to click $("#endGame a") twice to get it to 'goto'. Any ideas? Thanks again. @Clint Try adding the settings: lock:false, stop:true or set: step:1 or do this: $("#slot1").trigger('stop').stop().trigger('goto',4) Problem is that as step is 9, it always continues to the end. Hi Ariel, I'd like to change the appearance of the next/prev buttons when there are no more items to scroll. How can I find the first and the last item and how can I address the buttons ? Thanks + regards, Hans Thanks a ton Ariel! The lock and stop settings did the trick. @Hans Check the post called "Doctorate on SerialScroll". There's a snippet called "hide the arrows....". You need to do just that but instead of hiding, add a css class or something. Hi there, I'm stumped when it comes to making the slider autoscroll on page load. I've set the interval ok, but it will only start when one of the navigation links is selected, whereas I want it to start on page load. I can't seem to figure out where / how to set start.serialScroll - which I think is the thing i need to set? Any help would be greatly appreciated, cheers. @Jeremy You just need to set force = true, which will force an initial scroll event, as noted here: @Sean - you're bang on, thanks very much for that :) Hello Ariel, great work. One question: I have an autoscrolling list of items, now i have prev/next-buttons too. I wonder if it's possible to "jump" 3 or 4 elements forward or back when i click on the buttons and then let the list continue its normal scrolling. Any idea? @Sean Thanks for answering :) @Anon You can call the plugin twice. Once with step:1, autoscrolling, w/o prev & next. Then you call again with step:3 and prev & next. @Ariel or Sean (or anyone for that matter!), Me again ;) I was wondering, now that I have the automated sliding, if a user selects any of the links manually, I need to stop auto scrolling, is this doable? I'm guessing perhaps I'm back to serialscroll('stop') - don't follow how to apply this though. Any clues? Hi Ariel, it's not the first time when I use your plugins. Here I have a problem with SerialScroll stopping working. Demo is here, click the first row of the table that is named "Demo", and then "Foto" button. The slideshow was working when most of JS was inline with onclick events. There's another SerialScroll object on the page which works without any trouble but this one has cost me already two days, and yet I haven't got any idea why it's not working. @Jeremy If you check the post called "doctorate on serialScroll", there's a snippet to stop on hover. You just need to change the event and the context element. @Jay The prev and next selectors don't match the buttons. @Ariel, thanks for the advise - I've tried it out but it's not happening for me - It is going into the function, I've verified this using Firebug and some window alerts for checking the on hover and off hover, but with the triggers nothing seems to happen. You can see the code here: Do you have any thoughts? This is great. Much easier than scrollable! I wasted two days with that thing but I have the same issue with this scroller. I have multiple items (product thumbnails) shown at once. I am using this to scroll product thumbnails left and right. I want it to stop when it gets to the last one and not be able to go any further. But the only time it resets is when all the products are off except for the last one. Please see my page for yourself: Click the right arrow and keep clicking it. @Buddy You need to set 'cycle' to false and exclude to 6 (play with it). @Jeremy You need to trigger the events on $scroll, not on $('#slider'). I've tried everything I can think of and this does not work from my house. Maybe it could use a tutorial unless it is only for those who really want to dig deep into learning how this works The main blog post is the tutorial/documentation. Thanks Ariel, appreciate the work you've put into this plug-in. Regarding updating serialScroll settings on a container using $(...).unbind('.serialScroll') then re-instantiating it. Thought I'd share my experience with this as it may help others. I was banging my head against this as I could unbind serialScroll from the container fine but when I re-instantiated it the scroll would not automatically advance any more. I'm sure you're aware why. Once I downloaded the source I discovered the line "if( !pane.ssbound )// don't bind more than once" was preventing serialScroll working properly the second time around. Commenting out line 109: pane.ssbound = true; fixed the problem. Is there a way to do this without editing the source? Hope this helps someone else anyhow. Cheers - Scott
http://flesler.blogspot.com/2008/03/jqueryserialscroll-110-released.html?showComment=1236685680000
CC-MAIN-2016-44
refinedweb
6,212
75.3
An additional set of operators that is common to virtually all programming languages is the set of operators for manipulating values in their binary formats: the bit operators. All values within a computer are represented in a binary format of 1s and 0s, called bits. Bits are grouped together in sets of eight, called bytes. In a byte, each successive bit corresponds to a value of 2 raised to a power, starting from 20 on the right, to 27 on the left, as shown in Figure 3.1. In many instances, particularly when dealing with low-level or system services, information is retrieved as binary data. In order to manipulate these devices and services, you need to perform manipulations of binary data. As shown in Figure 3.2, each box corresponds to a value of 2 raised to the power shown. The value of the byte (8-bit number) is the sum of the powers of 2 of all of the eight bits that are set to 1. The binary translation just described is significantly different for signed numbers. Signed numbers (long, short, int) are represented using a 2s complement notation. With this notation, negative numbers behave differently than positive numbers. Negative numbers are identified by a 1 in the leftmost location. If the leftmost location contains a 1, you add the locations with 0s rather than the locations with 1s. Each location corresponds to the negative power of 2 value. Furthermore, from the result, it is also necessary to subtract 1. This is demonstrated in Figure 3.3. Therefore, 1111 1111 1111 1111 corresponds to a1 and 1111 1111 1111 1001 holds the value7. 1000 0000 0000 0000 corresponds to the lowest negative value that a 16-bit integer can hold. negative, then.36 you right-shift the binary representation of the number7 by two locations. int x; x = (-7 >> 2); // 11111111111111111111111111111001 becomes // 11111111111111111111111111111110 // Write out "x is -2." System.Console.WriteLine("x = {0}.", x); Output 3.17 shows the results of Listing 3.36. x = -2. Because of the right shift, the value of the bit in the rightmost location has "dropped off" the edge and the negative bit indicator on the left shifts by two locations to be replaced with ones. The result is -2. In some instances, you might need to perform logical operations, such as AND, OR, and XOR, on a bit-by-bit basis for two operands. You do this via the &,|, and ^ operators, respectively. If you have two numbers, as shown in Figure 3.4, the bitwise operations will compare the values of the locations beginning at the leftmost significant value and continuing right until the end. The value of "1" in a location is treated as "true," and the value of "0" in a location is treated as "false." Therefore, the bitwise AND of the two values in Figure 3.4 would be the bit-by-bit comparison of bits in the first operand (12) with the bits in the second operand (7), resulting in the binary value 000000100, which is 4. Alternatively, a bitwise OR of the two values would produce 00001111, the binary equivalent of 15. The XOR result would be 00001011, or decimal 11. Listing 3.37 demonstrates how to use these bitwise operators. The results of Listing 3.37 appear in Output 3.18. byte and, or, xor; and = 12 & 7; // and = 4 or = 12 | 7; // or = 15 xor = 12 ^ 7; // xor = 11 System.Console.WriteLine( "and = {0} \nor = {1}\nxor = {2}", and, or, xor); and = 4 or = 15 xor= 11 In Listing 3.37, the value 7 is the mask; it is used to expose or eliminate specific bits within the first operand using the particular operator expression. In order to convert a number to its binary representation, you need to iterate across each bit in a number. Listing 3.38 is an example of a program that converts an integer to a string of its binary representation. The results of Listing 3.38 appear in Output 3.19. public class BinaryConverter { public static void Main() { const int size = 64; ulong value; char bit; System.Console.Write ("Enter an integer: "); // Use long.Parse() so as to support negative numbers // Assumes unchecked assignment to ulong. value = (ulong)long.Parse(System.Console.ReadLine()); // Set initial mask to 100.... ulong mask = 1ul << size - 1; for (int count = 0; count < size; count++) { bit = ((mask & value) > 0) ? '1': '0'; System.Console.WriteLine(bit); // Shift mask one location over to the right mask >>= 1; } } } Enter an integer: 42 0000000000000000000000000000000000000000000000000000000000101010 Notice that within each iteration of the for loop (discussed shortly), you use the right-shift assignment operator to create a mask corresponding to each bit in value. By using the & bit operator to mask a particular bit, you can determine whether the bit is set. If the mask returns a positive result, you set the corresponding bit to 1; otherwise, it is set to 0. In this way, you create a string representing the binary value of an unsigned long. Listing 3.38 again used the keyword new, but this time, you instantiated a StringBuilder object, not an array. Chapter 5 covers the concept of instantiation and using the new operator in depth. Not surprisingly, you can combine these bitwise operators with assignment operators as follows: &=, |=, and ^=. As a result, you could take a variable, OR it with a number, and assign the result back to the original variable, which Listing 3.39 demonstrates. byte and, or, xor; and = 12; and &=7; // and = 4 or = 12; or |= 7; // or = 15 xor = 12; xor ^=7; // xor = 11 System.Console.WriteLine( "and = {0} \nor = {1}\nxor = {2}", and, or, xor); The results of Listing 3.39 appear in Output 3.20. and = 4 or = 15 xor = 11 The bitwise complement operator takes the complement of each bit in the operand, where the operand can be an int, uint, long, or ulong. ~1, therefore, returns 1111 1111 1111 1111 1111 1111 1111 1110 and ~(1<<31) returns 0111 1111 1111 1111 1111 1111 1111 1111.
https://flylib.com/books/en/2.888.1.31/1/
CC-MAIN-2019-09
refinedweb
1,009
64.51
Definition of JavaFX Timeline Timeline in JavaFX is basically used to define free and flexible forms of animation. Timeline in JavaFX works on using the keyframes processing each of the keyframes individually and sequentially. It does not guarantee the timing of processing of each keyframe; instead it processes each keyframe at a specified time interval. Programmers have the facility to add the keyframes to the timeline either at the time of creation or afterwards. Timeline is a subclass of javafx.animation.Animation class. A lot of other things can be performed using timeline like setting the reverse of timeline, loop of how many times it should run, etc. Syntax: Below given is the basic syntax of using the Timeline in JavaFX: Final Timeline tm = new Timeline(); tm.add(new KeyFrame(Duration.millis(10000), new KeyValue (button.translateXProperty(), 8))); tm. setCycleCount(8); . .. .. How does the JavaFx Timeline Function Work? Some of the important points defining the working of JavaFX timeline are given below: - Timeline in JavaFX is nothing but an animation consisting of many KeyFrame objects , each of which needs to be run sequentially. - Some of the standard attributes of Timeline are auto- reverse and cycle count. - Cycle count is nothing but the count of the number of times, an animation should be played. We can also play the animation infinite times using Timeline.INDEFINITE. But by default animation runs only 1 time. - Auto- reverse is nothing but a boolean value to indicate whether the animation can play backwards or not. - In order to set the largest time of the Timeline, KeyFrameAnimation.cycleDurationProperty() is used. - We can not change the keyFrames of the running timeline. In order to use the new value, one needs to stop and start it again. - In the timeline of JavaFX, cycle count is 1 and the auto-reverse feature is set to TRUE. - Method start() contains the main logic of timeline animation. Constructors Below given are the constructors of the Timeline in JavaFX: Methods: Below given are the methods along with their description used in the timeline of JavaFX: Some of the methods inherited from the javaFX.animation.Animation class are given below: Example of JavaFX Timeline Some of the examples implementing the usage of Timeline in JavaFX code are given below: Example #1 Code: import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; public class TimelineFX extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { // Create the Text using text object Text text = new Text("Hello Hello!"); VBox root = new VBox(text); // Setting the text font size text.setFont(Font.font(12)); // Creating the Scene using its object Scene scene = new Scene(root); // Adding the Scene to the Stage stage.setScene(scene); // Now Setting the title of the above Stage stage.setTitle("This is stage title"); // Displaying the Stage using the show() method stage.show(); // Getting the Scene width and the Text width double sw = scene.getWidth(); double tw = text.getLayoutBounds().getWidth(); // Defining the Durations of animations Duration startD = Duration.ZERO; Duration endD = Duration.seconds(50); //Creating the keyFrames to use in timeline KeyValue startValue = new KeyValue(text.translateXProperty(), sw); KeyFrame startFrame = new KeyFrame(startD, startValue); KeyValue endValue = new KeyValue(text.translateXProperty(), -6.0 * tw); KeyFrame endFrame = new KeyFrame(endD, endValue); // Creating a Timeline using above values Timeline t1 = new Timeline(startFrame, endFrame); // Setting the cycle count of animation t1.setCycleCount(t1.INDEFINITE); //Setting the auto reverse property of animation t1.setAutoReverse(false); // Running the animation using play() method t1.play(); } } Output: Conclusion The above description clearly explains what is a Timeline in JavaFX and how it is used for animation using keyFrames. Using the timeline infinite times can result in memory leaks and other serious issues if not started and stopped properly. So one needs to understand each concept of Timeline, its constructors, methods, everything and needs to be very careful before using it. Recommended Articles This is a guide to JavaFX Timeline. Here we discuss the definition and How does the JavaFx Timeline Function Work? along with examples. You may also have a look at the following articles to learn more –
https://www.educba.com/javafx-timeline/?source=leftnav
CC-MAIN-2021-25
refinedweb
719
50.84
In this sample console app program, we will do a few things (just as a reminder, I am using Visual Studio) - take a numerical user input and convert it to an integer - generate a random number - take a look at a simple if statement - and add 2 numbers. Before we begin, I would like to note that the only instance of math used is addition. However you might want to explore further by substituting the operators. (subtraction (-), multiplication (*) and division(/)) I would also like to note that when doing division, if variabes of int type are used you will not get any remainders (i.e. n.345984) To be able to work with real numbers, numbers with decimals, you can use float. Below is a way to declare a float and assign it a value: float floatNumber; floatNumber = 22.34f; As you can see this code was commented quite a bit. I will probably do a few more console app lessons and move onto windows apps. In the mean time I hope this is useful to someone.As you can see this code was commented quite a bit. I will probably do a few more console app lessons and move onto windows apps. In the mean time I hope this is useful to someone.Code:using System; namespace lessonThree { ///<summary> /// In this lesson we will cover some basic math /// operations, look at an if statement and a few other /// useful things that should be understood when /// programming in C# ///</summary> class thirdLesson { ///<summary> /// Ask an age. /// If under 18 -> Exit Program /// Give lucky number for the day /// Predict when person will get rich. ///</summary> [STAThread] static void Main(string[] args) { int age; //Random object createRand Random createRand = new Random(); int luckyNumber; Console.Write("Enter your age: "); //grab the input from user and convert it to //an integer, hence the 'Convert.ToInt32(); age = Convert.ToInt32(Console.ReadLine()); //skip line Console.WriteLine(); if (age > 17) { //Random generated numbers range from 0 to 1, //therefore we multiply by ten (10) below //The .NextDouble() method helps retrieve the value luckyNumber = (int)(createRand.NextDouble()*10); Console.WriteLine("Your Lucky Number is: {0}", luckyNumber); //Here you use the value of luckyNumber and add it to his age Console.WriteLine("You are {0} years old and will be rich at age: {1}", age, age+luckyNumber); //As you can see the zero in braces {0} holds the variable age //and the one in braces {1} holds the sum of the variables "age and luckyNumber" age+luckyNumber }//If the age is not 18 or above we conclude by saying Console.WriteLine("Thanks and Have a Great Day"); Console.WriteLine(); Console.WriteLine("Press [ENTER] to Exit"); Console.ReadLine(); }//end Main() }//end class }//end namespace
http://cboard.cprogramming.com/csharp-programming/78448-lesson-sharp3-math.html
CC-MAIN-2014-10
refinedweb
454
62.68
So far in this blog series, we’ve set up our local machine and cloud environment, and built the initial portion of a continuous delivery pipeline. That pipeline, built using the popular OSS tool Concourse, pulls source code from GitHub, generates a Docker image that’s stored in Azure Container Registry, and produces a tarball that’s stashed in Azure Blob Storage. What’s left? Deploying our container image to Azure Kubernetes Service (AKS). Let’s go. Generating AKS credentials Back in blog post one, we set up a basic AKS cluster. For Concourse to talk to AKS, we need credentials! From within the Azure Portal, I started up an instance of the Cloud Shell. This is a hosted Bash environment with lots of pre-loaded tools. From here, I used the AKS CLI to get the administrator credentials for my cluster. az aks get-credentials --name seroter-k8s-cluster --resource-group demos --admin This command generated a configuration file with URLs, users, certificates, and tokens. I copied this file locally for use later in my pipeline. Creating a role-binding for permission to deploy The administrative user doesn’t automatically have rights to do much in the default cluster namespace. Without explicitly allowing permissions, you’ll get some gnarly “does not have access” errors when doing most anything. Enter role-based access controls. I created a new rolebinding named “admin” with admin rights in the cluster, and mapped to the existing clusterAdmin user. kubectl create rolebinding admin --clusterrole=admin --user=clusterAdmin --namespace=default Now I knew that Concourse could effectively interact with my Kubernetes cluster. Giving AKS access to Azure Container Registry Right now, Azure Container Registry (ACR) doesn’t support an anonymous access strategy. Everything happens via authenticated users. The Kubernetes cluster needs access to its container registry, so I followed these instructions to connect ACR to AKS. Pretty easy! Creating Kubernetes deployment and service definitions Concourse is going to apply a Kubernetes deployment to create pods of containers in the cluster. Then, Concourse will apply a Kubernetes service to expose my pod with a routable endpoint. I created a pair of configurations and added them to the ci folder of my source code. The deployment looks like: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: demo-app namespace: default labels: app: demo-app spec: replicas: 1 template: metadata: labels: app: demo-app spec: containers: - name: demo-app image: myrepository.azurecr.io/seroter-api-k8s:latest imagePullPolicy: Always ports: - containerPort: 8080 restartPolicy: Always This is a pretty basic deployment definition. It points to the latest image in the ACR and deploys a single instance (replicas: 1). My service is also fairly simple, and AKS will provision the necessary Azure Load Balancer and public IP addresses. apiVersion: v1 kind: Service metadata: name: demo-app namespace: default labels: app: demo-app spec: selector: app: demo-app type: LoadBalancer ports: - name: web protocol: TCP port: 80 targetPort: 80 I now had all the artifacts necessary to finish up the Concourse pipeline. Adding Kubernetes resource definitions to the Concourse pipeline First, I added a new resource type to the Concourse pipeline. Because Kubernetes isn’t a baked-in resource type, we need to pull in a community definition. No problem. This one’s pretty popular. It’s important than the Kubernetes client and server are expecting the same Kubernetes version, so I set the tag to match my AKS version. resource_types: - name: kubernetes type: docker-image source: repository: zlabjp/kubernetes-resource tag: "1.13" Next, I had to declare my resource itself. It has references to the credentials we generated earlier. resources: - name: azure-kubernetes-service type: kubernetes icon: azure source: server: ((k8s-server)) namespace: default token: ((k8s-token)) certificate_authority: | -----BEGIN CERTIFICATE----- [...] -----END CERTIFICATE----- There are a few key things to note here. First, the “server” refers to the cluster DNS server name in the credentials file. The “token” refers to the token associated with the clusterAdmin user. For me, it’s the last “user” called out in the credentials file. Finally, let’s talk about the certificate authority. This value comes from the “certificate-authority-data” entry associated with the cluster DNS server. HOWEVER, this value is base64 encoded, and I needed a decoded value. So, I decoded it, and embedded it as you see above. The last part of the pipeline? The job! jobs: - name: run-unit-tests [...] - name: containerize-app [...] - name: package-app [...] - name: deploy-app plan: - get: azure-container-registry trigger: true passed: - containerize-app - get: source-code - get: version - put: azure-kubernetes-service params: kubectl: apply -f ./source-code/seroter-api-k8s/ci/deployment.yaml -f ./source-code/seroter-api-k8s/ci/service.yaml - put: azure-kubernetes-service params: kubectl: | patch deployment demo-app -p '{"spec":{"template":{"spec":{"containers":[{"name":"demo-app","image":"myrepository.azurecr.io/seroter-api-k8s:'$(cat version/version)'"}]}}}}' Let’s unpack this. First, I “get” the Azure Container Registry resource. When it changes (because it gets a new version of the container), it triggers this job. It only fires if the “containerize app” job passes first. Then I get the source code (so that I can grab the deployment.yaml and service.yaml files I put in the ci folder), and I get the semantic version. Next I “put” to the AKS resource, twice. In essence, this resource executes kubectl commands. The first command does a kubectl apply for both the deployment and service. On the first run, it provisions the pod and exposes it via a service. However, because the container image tag in the deployment file is to “latest”, Kubernetes actually won’t retrieve new images with that tag after I apply a deployment. So, I “patched” the deployment in a second “put” step and set the deployment’s image tag to the semantic version. This triggers a pod refresh! Deploy and run the Concourse pipeline I deployed the pipeline as a new revision with this command: fly -t rs set-pipeline -c azure-k8s-final.yml -p azure-k8s-final I unpaused the pipeline and watched it start up. It quickly reached and completed the “deploy to AKS” stage. But did it actually work? I jumped back into the Azure Cloud Shell to check it out. First, I ran a kubectl get pods command. Then, a kubectl get services command. The first showed our running pod, and the second showed the external IP assigned to my pod. I also issued a request to that URL in the browser, and got back my ASP.NET Core API results. Also to prove that my “patch” command worked, I ran the kubectl get deployment demo-app –output=yaml command to see which container image my deployment referenced. As you can see below, it no longer references “latest” but rather, a semantic version number. With all of these settings, I now have a pipeline that “just works” whenever I updated my ASP.NET Core source code. It tests the code, packages it up, and deploys it to AKS in seconds. I’ve added all the pipelines we created here to GitHub so that you can easily try this all out. Whatever CI/CD tool you use, invest in automating your path to production. Categories: .NET, Cloud, DevOps, Docker, General Architecture, Microservices, Microsoft Azure, OSS, Pivotal Hi, this is good post. is it possible without concourse like deploy blog 1,2 & 3.
https://seroter.wordpress.com/2019/08/21/building-an-azure-powered-concourse-pipeline-for-kubernetes-part-3-deploying-containers-to-kubernetes/
CC-MAIN-2019-47
refinedweb
1,226
57.16
Spring Boot Redis Cache Let’s learn how to implement redis as a cache store in spring boot with an example. Previously, We discussed how to enable caching implementation in Spring Boot using an in-memory cache manager. But, there were few drawbacks to that approach. This is where the Redis cache store comes into the picture. Introduction Redis is a high performance datastore with high read/write throughput. This is why it is a perfect candidate to storing cache and session information. Setup Local Server for Redis The best way to setup server in local is to use docker. In this case, I’m using redis along with redis-commander GUI" The above step is only for testing things locally. For production, please follow official Redis documentation for the server installation. Run the following command for starting the containers. Code language: CSS (css)Code language: CSS (css) docker-compose docker-compose.yml up -d Once the docker container is up, You can view redis commander at. Add redis dependencies Like always, Spring boot makes things easier with the help of sophisticated starter dependencies. All you have to do is to add the redis starter. Code language: HTML, XML (xml)Code language: HTML, XML (xml) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> Add appropriate settings for the redis configuration. You can skip the following if you are using redis locally. Code language: Properties (properties)Code language: Properties (properties) localhost =6379= In production you may need to add spring.redis.username and spring.redis.password based on your server. Enable Caching To enable caching support in Spring boot , first you need to annotate the main class with @EnableCaching. Code language: Java (java)Code language: Java (java) public class SpringBootRedisCacheExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRedisCacheExampleApplication.class, args); } } Add @Cacheable annotation Find a long running method and annotate it with @Cacheable. This annotation takes a value which is the cache name. And the key is an unique object to lookup the value in cache later. Code language: Java (java)Code language: Java (java) "items", key = "#id") public Item getItem(Integer id) { Item item = itemRepository.findById(id).orElseThrow(RuntimeException::new); logger.info("Loading data from DB {}", item); return item; }(value = In this case, We used Spring Expression Language(SpEL) to pass the argument value as key. Add @CacheEvict annotation Once cached, The values stay there indefinitely. Thus, the cache abstraction will never pick updated values from the database. For this reason, you should use @CacheEvict on update. Code language: Java (java)Code language: Java (java) "items", key = "#id") public Item updateItem(Integer id, Item request) { Item item = getItem(id); item.setPrice(request.getPrice()); item.setProductName(request.getProductName()); return itemRepository.save(item); }(value = See Redis in Action Once we start the application, The first request goes to the database. And the subsequent requests fetch data from redis cache store. We know this because, - The logs says the records is from the database. Code language: Java (java)Code language: Java (java) c.s.e.s.cache.service.ItemService:Loading data from DB Item{id=2,productName='Pants Large',price=21.99} - When we open redis-commander, we can see that itemscache containing entry with key 2.These cached value is in the form of binary. What about the cache evict? Let’s try updating item 2. Code language: Bash (bash)Code language: Bash (bash) curl -X PUT \ \ -H 'cache-control: no-cache' \ -H 'content-type: application/json' \ -d '{ "productName": "Pants Large", "price": 14.99 }' HTTP/1.1 200 Content-Type: application/json Transfer-Encoding: chunked Date: Sun, 13 Dec 2020 18:11:16 GMT {"id":2,"productName":"Pants Large","price":14.99} As you see the cached value for key 2 is now gone. The next time a getItem call happens, the values will be cached again. Caching between multiple application instances As redis server runs outside the application, multiple application instances can share the same cache store. For example, Let’s run the same application again on different port 7070 (using —server.port=7070). Code language: Bash (bash)Code language: Bash (bash) java -jar redis-demo.jar --server.port=7070 We can confirm that the second instance had successfully connected to the redis server by various means. - By checking logs. There should not be any error when RedisAutoConfiguration takes place. - By checking the client connections on the server. Click the local (redis:6379:0)element at the side nav of redis-commander, and it will give the server stats. In the results, find the value for Connected clients. The value should be 3. This is due to 2 connections from the application and 1 connection from the redis-commander itself. Let’s call the API from application running on port 8080. Code language: Bash (bash)Code language: Bash (bash) curl -X GET This creates a cache entry in redis. Now try hitting server on 7070 for the same resource. Code language: Bash (bash)Code language: Bash (bash) curl -X GET The response is immediate and there is no logs that says the record is from the database. Timeout for cached values You can also specify how long the value can live in the cache store. Code language: Access log (accesslog)Code language: Access log (accesslog) spring.cache.redis.time-to-live=5m The above configuration will automatically evict any cached entry after 5 minutes. Summary To summarize, We learned how to use redis data store as cache for spring boot application. The code and the docker-compose.yml for this example is available in this github repository. Also, if you like this article, You may find the following write-ups helpful.
https://springhow.com/spring-boot-redis-cache/
CC-MAIN-2021-31
refinedweb
947
50.43
In this React Native source code example, the source code below illustrate how to load local image in React Native. You can copy and adopt this source code example to your React Native project without reinventing the wheel. import React, {Component} from 'react'; import {StyleSheet, Text, View, Image} from 'react-native'; export default class App extends Component { render() { return ( <View style={styles.container}> <Image style={{width: '250', height:'250'}} source={require('./images/testImage.jpeg')} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, }); If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below. Posts you might be interested on: How to set Cookie in React Native WebView How to place a View at the top of the screen in React Native How to limit the character count in Text Input in React Native How to layout Views in row with full height using align items in React Native How to show and hide keyboard in React Native How to set initial value of React Native Picker to empty How to style React Native Picker How to position a View at the bottom right side of a page in React Native
https://inducesmile.com/react-native-source-code/how-to-load-local-image-in-react-native/
CC-MAIN-2020-34
refinedweb
208
51.21
Those tutorials reference AspectWerkz 2.0 They can run with both AspectWerkz 1.0 final and 2.0.RC1 unless otherwise specified. - Hello World - Hijacking Hello World - How to integrate Aspects in J2EE apps with aop.xml - How to write reusable aspects You can also take a look at one of the external tutorials. 6 Comments Anonymous Hello, I'm not sure how to write the authors so I'll put a comment here and hope someone sees it. Referring to the HelloWorld example I noticed that the second method "greet" is of type String but does not have a return statement in the execution part. I added that and the code compiled fine. Also the command, in the tutorial, to recompile HelloWorld with AspectWorksz 2.0 is javac -d target -classpath $ASPECTWERKZ_HOME/lib/aspectwerkz-2.0.RC1.jar MyAspect.java I could not get this to work because the zip file does not contain aspectwerkz-2.0.RC1.jar. I tried many of the other jar files but I kept getting the following: C:\testAOP>javac -d target -classpath $ASPECTWERKZ_HOME/lib/aspectwerkz-2.0.RC1. jar MyAspect.java MyAspect.java:3: package org.codehaus.aspectwerkz.joinpoint does not exist import org.codehaus.aspectwerkz.joinpoint.JoinPoint; ^ MyAspect.java:7: cannot resolve symbol symbol : class JoinPoint location: class testAOP.MyAspect public void beforeGreeting(JoinPoint joinPoint) { ^ MyAspect.java:11: cannot resolve symbol symbol : class JoinPoint location: class testAOP.MyAspect public void afterGreeting(JoinPoint joinPoint) { ^ 3 errors I hope someone can advise and fix the problems in this example. Anonymous Hello, I'am trying to build the first simple example but keep getting complains about org/xml/sax/EntityResolver that could not be found. I'v been on this al day now and tried every jdk / xml lib etc. It propbably has got to do with my configuration but it is driving me nuts so every suggestion is highly appreciated , i cannot wait to start with AOP. Thanks upfront, Dennis exec []META-INF>set ASPECTWERKZ_HOME=[]aspectwerkz-2.0\aspectwerkz-2.0 exec java.lang.NoClassDefFoundError: org/xml/sax/EntityResolver exec at org.codehaus.aspectwerkz.definition.DefinitionLoader.getDefaultDefinition(DefinitionLoader.java:49) exec at org.codehaus.aspectwerkz.compiler.AspectWerkzC.compile(AspectWerkzC.java:667) exec at org.codehaus.aspectwerkz.compiler.AspectWerkzC.main(AspectWerkzC.java:721) exec Exception in thread "main" Anonymous another (working) day, solved the xml thing but had so many other issues that i am off now , bye bye see you later, this is killing me man. Anonymous Hi, If u solved problems in executing Aspectw* pls tell me the steps to do... mail me if u r having any docs regarding this.... samu_3000@rediffmail.com thanx in advance samu Anonymous you have to do this operations to solve the problem: 1) C:\aspectwerkz-2.0\bin>edit aspectwerkz.bat 2) insert this strings after the istruction @ECHO OFF set aspectwerkz_version=2.0 set aspectwerkz_home=c:\aspectwerkz-2.0 set java_home=c:\programmi\java\jre1.5.0\lib\ext\qtjava.zip Kunal Kejriwal hi I want to weave my advice before and after public methods of public class. I tried using execution AND within pointcut() together to limit the scope... The XML is used is <aspectwerkz> <system id="AspectWerkzExample1"> <aspect class="expressionTesting.ExpressionAspect"> <pointcut name="greetMethod" expression="within(public expressionTesting.*) AND execution(public * *(..)) "/> <advice name="beforeGreeting" type="before" bind- <advice name="afterGreeting" type="after" bind- </aspect> </system> </aspectwerkz> note expressionTesting is the name of the package but this doesn't work out ... seems there is some problem with the expression ....help me to get the correct expression reply asap...
http://docs.codehaus.org/display/AW/Tutorials?showChildren=true
CC-MAIN-2014-42
refinedweb
595
51.34
. Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected. public class myPosition implements Position{ private Comparable c; private int index; public myPosition(Comparable o, int i) { c = o; index = i; } public Comparable element () { return c; } public int index(){ return index; } } now, my method needs to take the index value out of here, and find the slot in the array (which is elsewhere in a different class) that contains this value. I then go to the previous slot in the array and grab its value. THEN (the part i don't get) I need to sort through the myPosition instances until I find the one with an index variable equal to the new index value from the array. and then i need to return that position. In that case, you'll have to check every single one, one by one (i.e. if (pos1.index() == prev){}, etc.). If there's an array of myPositions you can use a for-loop. Then you can do: myPosition[] arrayName = new myPosition[100]; //100 is however many myPositions there are for( int c = 0; c < numberOfInstances; c++){ arrayName[c] = new myPosition(o, n); } That loop would just create a bunch of myPositions. You'd want one like this to check them against prev: for( int c = 0; c < numberOfInstances; c++){ if (arrayName[c].index() == prev){/*Do whatever you want once you've found a match. Perhaps store c in a different variable so you know what position the matching value is in.*/ } ie. why can't you just use: Object previous = list.get(prev); Field: 0 1 2 3 Value: 0 1 3 4 Now what do you need to do with this? Now, say I want to getPrev(Position p) from this array: Field: 0 1 2 3 4 Value: 0 1 3 4 5 where the instance of myPosition being passed (p) contains index = 3; I will then take that instance, go to the array, and find the field with a value of 3...in this case its field 2 I decrement by 1 and so I know the previous is in field 1, aka the myPosition containing index 1 (getting 1 from the value stored in field 1 of the array) THEN, where the //HERE mark is in my getPrev method, I need a way to loop through all instances of myPosition, checking their index variables for the one equal to 1. Then I need to return that position. if (arrayList.get(c).index() == 1){return arrayList.get(c);} } That do it? for (int c = 0; c < arrayList.size(); c++){ if (arrayList.get(c).index() == 1){return arrayList.get(c);} } return (Position)arrayList.get(c) P.S. Put a default return statement after the loop so the compiler doesn't complain. This return statement should never be executed. Where are all the myPositions/Positions stored then? THATS my question!! i have no clue! here is what my insert statement is: public Position insert(Comparable o) { return new myPosition(o, _seq.insert(o)); } and this is what i've been told about this: Almost. Remember that on a list, the position is the list node itself. The position has "permancence". It lives as long as the object it refers to. In the code above, the element could outlive the position that "points" to it. Your position above does indeed refer to the element. But it suffers from this annoying problem that if we modify the ArrayList by adding anything in front or behind, the relative name will be changed. wow, i'm so confused...and my insert method may be very wrong...as I see it does insert an object o into the arrayList. Then, to insert something, do it like a bubble sort: myPosition temp = positionArray[insertPoint] myPosition temp2; positionArray[insertPoint+ for (int c = insertPoint; c <= positionArray.length; c++){ temp2 = positionArray[c].clone(); positionArray[c] = temp.clone(); temp = positionArray[c+1].clone() positionArray[c+1] = temp2.clone(); } myPosition temp = positionArray[insertPoint] myPosition temp2; positionArray[insertPoint] for (int c = insertPoint + 1; c <= positionArray.length; c++){ temp2 = positionArray[c].clone(); positionArray[c] = temp.clone(); temp = positionArray[c+1].clone() positionArray[c+1] = temp2.clone(); }
https://www.experts-exchange.com/questions/21155814/Even-more-Advice-requested.html
CC-MAIN-2017-51
refinedweb
714
58.48
- Namespaces The last OOP topic we'll look at in this chapter is how to create your own namespaces. As you know, namespaces let you divide programs up to avoid clashes between identifiers (even if you don't declare your own namespace, your code is given its own default namespace, the global namespace). To create your own namespace, you use the namespace keyword: namespace name[.name1] ...] { type-declarations } Here are the parts of this statement: name, name1A namespace name can be any legal identifier, and it can include periods. type-declarationsWithin a namespace, you can declare one or more of the following types: another namespace, a class, interface, struct, enum, or delegate. You can create as many namespaces in a file as you want; just enclose the code for each namespace in the code block following the namespace keyword. For example, here's how we can put the Messager class into the namespace Output: namespace Output { class Messager { public string message = "Default message."; public void DisplayMessage() { System.Console.WriteLine(message); } } } To access Messager outside the Output namespace, you qualify its name as Output.Messsager, just as you can qualify Console.Writeline as System. Console.WriteLine. (Alternatively, you can use a using Output directive, just as you use a using System directive.) You can see this at work in ch03_15.cs, Listing 3.15. Naming Namespaces Microsoft's suggestion is to name namespaces this way: CompanyName.ProjectName.Component. SubComponent. Listing 3.15 Namespace Example (ch03_15.cs) class ch03_15 { public static void Main() { Output.Messager obj = new Output.Messager(); obj.message = "Hello from C#."; obj.DisplayMessage(); } } namespace Output { class Messager { public string message = "Default message."; public void DisplayMessage() { System.Console.WriteLine(message); } } } Here's what you see when you run ch03_15.cs: C:\>ch03_15 Hello from C#. Namespaces can also extend over multiple filesmore on how that works when we discuss assemblies. We took a look at overloading in this chapterhow about overriding? As OOP programmers know, overriding is one of the most important aspects of class inheritance, and it's covered in the next chapter.
https://www.informit.com/articles/article.aspx?p=98855&seqNum=16
CC-MAIN-2022-05
refinedweb
344
59.19