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 |
|---|---|---|---|---|---|
This is how AngularJS announces itself on its home page:
HTML enhanced for web apps!
Hm, ok, but not terribly informative. Here’s the next paragraph:
HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.
That’s better. Let me try to ease you into this “framework” on which HouseMon is based:
- Angular (“NG”) is client-side only. It doesn’t exist on the server. It’s all browser stuff.
- It doesn’t take over. You could use NG for parts of a page. HouseMon is 100% NG.
- It comes with many concepts, conventions, and terms you must get used to. They rock.
I can think of two main stumbling blocks: “Dependency Injection” and all that “service”, “factory”, and “controller” stuff (not to mention “directives”). And Model-View-Something.
It’s not hard. It wasn’t designed to be hard. The terminology is pretty clever. I’d say that it was invented to produce a mental model which can be used and extended. And like a beautiful clock, it doesn’t start ticking until all the little pieces are positioned just right. Then it will run (and evolve!) forever.
Dependency injection is nothing new, it’s essentially another name for “require” (Node.js), “import” (Python), or “#include” (C/C++). Let’s take a fictional piece of CoffeeScript code:
value = 123 myCode = (foo, bar) -> foo * value + bar console.log myCode(100, 45)
The output will be “12345”. But with dependency injection, we can do something else:
value = 123 myCode = (foo, bar) -> foo * value + bar define 'foo', 100 define 'bar', 45 console.log inject(myCode)
This is not working code, but it illustrates how we could define things in some more global context, then call a function and give it access to that context. Note that the “inject” call does something very magical: it looks at the names of myCode’s arguments, and then somehow looks them up and finds the values to pass to myCode.
That’s dependency injection. And Angular uses it all over the place. It will often call functions through a special “injector” and get hold of all args expected by the function. One reason this works is because closures can be used to get local scope information into the function. Note how myCode had access to “value” via a normal JavaScript closure.
In short: dependency injection is a way for functions to import all the pieces they need. This makes them extremely modular (and it’s great for test suites, because you can inject special versions and mock objects to test each piece of code outside its normal context).
The other big hurdle I had to overcome when starting out with Angular, is all those services, providers, factories, controllers, and directives. As it turns out, that too is much simpler than it might seem:
- Angular code is packaged as “modules” (I actually only use a single one in HouseMon)
- in these modules, you define services, etc – more on this in a moment
- the whole startup is orchestrated in a specific way: boot, config, run, fly
- ok, well, not “fly” – that’s just my name for it…
The startup sequence is key – to understand what goes where, and what gets called when:
- the browser starts by loading an HTML page with
<script>tags in it (doh)
- all the code needed on the browser side has to be loaded up front
- what this code does is define modules, services, and so on
- nothing is really “running” at this point, these are all function definitions
- the last step is to call
angular.bootstrap(document, ['myApp']);
- at this point, all the
configsections defined in the modules are run
- once that is over, all the
runsections are run, this is the real application start
- when that is done, we in essence enter The Big Event Loop in the browser: lift off!
So on the client side, i.e. the browser, the entire application needs to be structured as a set of definitions. A few things need to be done early on (config), a few more once everything has been defined and Angular’s “$rootScope” has been put in place (read: the main page context is ready, a bit like the DOM’s “document.onload”), and then it all starts doing real work through the controllers tied to various HTML elements in the DOM.
Providers, factories, services, and even constants and values, are merely variations on a theme. There is an excellent page by Matt Haggard describing these differences. It’s all smoke and mirrors, really. Everything except directives is a provider in Angular.
Angular is like the casing of a watch, with a powerful pre-loaded spring already in place. You “just” have to figure out the role of the different pieces, put a few of them in place, and it’ll run all by itself from then on. It’s one of the most elegant frameworks I’ve ever seen.
With HouseMon, I’ve put the main pieces in place to show a web page in the browser with a navigation top bar, and the hooks to tie into Primus and RPC. The rest is all up to the modules, i.e. the subfolders added to the
app/ folder. Each
client.coffee file is an Angular module. HouseMon will automatically load them all into the browser (via a
/primus/primus.js file generated on-the-fly by Primus). This has turned out to be extremely modular and flexible – and it couldn’t have been done without Angular.
If you’re looking for a “way in” for the HouseMon client-side code, then the place to start is
app/index.jade, which uses Jade’s extend mechanism to tie into
main/layout.jade, so that would be the second place to start. After that, it’s all Angular-structured code, i.e. views, view templates with controllers, and the services they call.
I’m quite excited by all this, because I’ve never before been able to develop software in such a truly modular fashion. The interfaces are high-level, clean (and clear) and all future functionality can now be added, extended, replaced, or even removed again – step by step.
Hi. I am going to have to disagree with this statement “Dependency injection is nothing new, it’s essentially another name for “require” (Node.js), “import” (Python),” I can’t speak for require in Node.js but DI is not the equivalent of “import” in python. All import does is pull code/modules in to the current namespace. There are DI modules for python, and there are other frameworks for achieving loose coupling at runtime. zopes component architecture does something similiar using adapators via component look up based on interface patterns.
Ok. I was just looking for an analogy to introduce DI. You’re right, it’s not really a code import – it brings values into a function scope, but since functions are first-class values, that includes code here as well. The effect is similar, IMO: you define the stuff you need, and then you can use it. It’s also called inversion-of-control: the callee declares what it needs, instead of the caller supplying this information. In a way, this is still quite similar to an import mechanism, isn’t it?
Not really – in the sense that you are explicit about what code you are importing. The key for DI as I understand it is loose coupling – not having to be specific about which implementation you need to achieve the desired result. Either way you have to import something somewhere ;-) but the decision about what is used is determined at runtime based on other types of criteria – cheers !
You can adjust Python’s import path: add a new one in front at run time, and put overriding imports there, though it’s not as fine-grained as real per-function DI.
For loose coupling in python there are a number of real DI options as well as aspect oriented solutions and adapter based solutions, all have strengths and weaknesses and go beyond basic plugin approaches. I personally like interface component lookup and adaptors. | http://jeelabs.org/2013/09/20/in-praise-of-angularjs/ | CC-MAIN-2014-52 | refinedweb | 1,388 | 62.88 |
17 May 2012 16:50 [Source: ICIS news]
LONDON (ICIS)--Shareholders in ?xml:namespace>
Acron, which has proposed paying a total of Zl 1.5bn ($440m, €340m) for shares which it has valued at Zl 36 each, would probably have to up its offer to at least Zl 40 per share to obtain a favourable response from shareholders, CEO Jerzy Marciniak said.
“This is the impression we have from talks with our shareholders,” he said.
Pension fund AVIVA, which owns around 9% of ZAT, has described the bid price as “exceptionally unsatisfying”.
The Polish treasury ministry, which holds a 32.05% stake in ZAT and controls the group by voting rights at the board level, said it would not compare Acron’s offer against ZAT’s current market price but rather against the value it believes will be unlocked by the consolidation of the group's 2011 takeovers of Zaklady Azotowe Kedzierzyn (ZAK) and Zaklady Chemiczne Police (ZChP).
Acron said its bid price represents a premium of 18.3% over ZAT's six-month average market price and pointed out the subdued prospects for chemical companies in the coming year given the international economic difficulties.
The ZAT group produces nitrogen and multi-component fertilizers, caprolactam (capro), polyamide 6, oxo-alcohols, plasticisers and titanium dioxide (TiO2).
($1 = €0.79)
($1 = Zl 3.42, €1 = Zl | http://www.icis.com/Articles/2012/05/17/9560859/bid-price-of-russias-acron-deemed-too-low-by-polands-zat.html | CC-MAIN-2014-52 | refinedweb | 224 | 62.27 |
#include <djv_serialize.h>
This structure takes an entry of
DIRM chunk table.
Initializes the structure.
Actual chunk.
The actual chunk is loaded when you access to it. In other words, if you don't access to it, it's never loaded onto the memory.
Chunk file name.
If the DjVu file is in indirect format, this member is the name of the file which contains the chunk.
For bundled files, this is the internal name for the chunk.
Chunk offset.
The byte offset in the file if the DjVu file is bundled format.
Chunk size.
The byte size of the chunk.
Chunk type. | https://www.cuminas.jp/sdk/structCelartem_1_1DjVu_1_1IFF_1_1DIRMEntry.html | CC-MAIN-2017-51 | refinedweb | 103 | 77.13 |
What is an ASP.NET MVC View and how does it differ from a HTML page? In this tutorial, Stephen Walther introduces you to Views and demonstrates how you can take advantage of View Data and HTML Helpers within a View.
The purpose of this tutorial is to provide you with a brief introduction to ASP.NET MVC views, view data, and HTML Helpers. By the end of this tutorial, you should understand how to create new views, pass data from a controller to a view, and use HTML Helpers to generate content in a view.
Understanding Views.
Listing 1 contains a simple controller named the HomeController. The HomeController exposes two controller actions named Index() and Details().
Listing 1 - HomeController.cs
using System.Web.Mvc; namespace MvcApplication1.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Details() { return RedirectToAction("Index"); } } }
You can invoke the first action, the Index() action, by typing the following URL into your browser address bar:
/Home/Index
You can invoke the second action, the Details() action, by typing this address into your browser:
/Home/Details
The Index() action returns a view. Most actions that you create will return views. However, an action can return other types of action results. For example, the Details() action returns a RedirectToActionResult that redirects incoming request to the Index() action.
The Index() action contains the following single line of code:
View();
This line of code returns a view that must be located at the following path on your web server:
\Views\Home\Index.aspx
The path to the view is inferred from the name of the controller and the name of the controller action.
If you prefer, you can be explicit about the view. The following line of code returns a view named Fred :
View( Fred );
When this line of code is executed, a view is returned from the following path:
\Views\Home\Fred.aspx
If you plan to create unit tests for your ASP.NET MVC application then it is a good idea to be explicit about view names. That way, you can create a unit test to verify that the expected view was returned by a controller action.
Adding Content to a View
A view is a standard (X)HTML document that can contain scripts. You use scripts to add dynamic content to a view.
For example, the view in Listing 2 displays the current date and time.
Listing 2 - \Views\Home\Index <% Response.Write(DateTime.Now);%> </div> </body> </html>
Notice that the body of the HTML page in Listing 2 contains the following script:
<% Response.Write(DateTime.Now);%>
You use the script delimiters <% and %> to mark the beginning and end of a script. This script is written in C#. It displays the current date and time by calling the Response.Write() method to render content to the browser. The script delimiters <% and %> can be used to execute one or more statements.
Since you call Response.Write() so often, Microsoft provides you with a shortcut for calling the Response.Write() method. The view in Listing 3 uses the delimiters <%= and %> as a shortcut for calling Response.Write().
Listing 3 - Views\Home\Index2 <%=DateTime.Now %> </div> </body> </html>
You can use any .NET language to generate dynamic content in a view. Normally, you�ll use either Visual Basic .NET or C# to write your controllers and views.
Using HTML Helpers to Generate View Content
To make it easier to add content to a view, you can take advantage of something called an HTML Helper. An HTML Helper, typically, is a method that generates a string. You can use HTML Helpers to generate standard HTML elements such as textboxes, links, dropdown lists, and list boxes.
For example, the view in Listing 4 takes advantage of three HTML Helpers -- the BeginForm(), the TextBox() and Password() helpers -- to generate a Login form (see Figure 1).
Listing 4 -- \Views\Home\Login.aspx
<%@ Page <html xmlns="" > <head id="Head1" runat="server"> <title>Login Form</title> </head> <body> <div> <% using (Html.BeginForm()) { %> <label for="UserName">User Name:</label> <br /> <%= Html.TextBox("UserName") %> <br /><br /> <label for="Password">Password:</label> <br /> <%= Html.Password("Password") %> <br /><br /> <input type="submit" value="Log in" /> <% } %> </div> </body> </html>
Figure 01: A standard Login form (Click to view full-size image)
All of the HTML Helpers methods are called on the Html property of the view. For example, you render a TextBox by calling the Html.TextBox() method.
Notice that you use the script delimiters <%= and %> when calling both the Html.TextBox() and Html.Password() helpers. These helpers simply return a string. You need to call Response.Write() in order to render the string to the browser.
Using HTML Helper methods is optional. They make your life easier by reducing the amount of HTML and script that you need to write. The view in Listing 5 renders the exact same form as the view in Listing 4 without using HTML Helpers.
Listing 5 -- \Views\Home\Login.aspx
<%@ Page <html xmlns="" > <head id="Head1" runat="server"> <title>Login Form without Help</title> </head> <body> <div> <form method="post" action="/Home/Login"> <label for="userName">User Name:</label> <br /> <input name="userName" /> <br /><br /> <label for="password">Password:</label> <br /> <input name="password" type="password" /> <br /><br /> <input type="submit" value="Log In" /> </form> </div> </body> </html>
You also have the option of creating your own HTML Helpers. For example, you can create a GridView() helper method that displays a set of database records in an HTML table automatically. We explore this topic in the tutorial Creating Custom HTML Helpers.
Using View Data to Pass Data to a View
You use view data to pass data from a controller to a view. Think of view data like a package that you send through the mail. All data passed from a controller to a view must be sent using this package. For example, the controller in Listing 6 adds a message to view data.
Listing 6 - ProductController.cs
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ProductController : Controller { public ActionResult Index() { ViewData["message"] = "Hello World!"; return View(); } } }
The controller ViewData property represents a collection of name and value pairs. In Listing 6, the Index() method adds an item to the view data collection named message with the value Hello World! . When the view is returned by the Index() method, the view data is passed to the view automatically.
The view in Listing 7 retrieves the message from the view data and renders the message to the browser.
Listing 7 -- \Views\Product\Index.aspx
<%@ Page <html xmlns="" > <head id="Head1" runat="server"> <title>Product Index</title> </head> <body> <div> <%= Html.Encode(ViewData["message"]) %> </div> </body> </html>
Notice that the view takes advantage of the Html.Encode() HTML Helper method when rendering the message. The Html.Encode() HTML Helper encodes special characters such as < and > into characters that are safe to display in a web page. Whenever you render content that a user submits to a website, you should encode the content to prevent JavaScript injection attacks.
(Because we created the message ourselves in the ProductController, we don�t really need to encode the message. However, it is a good habit to always call the Html.Encode() method when displaying content retrieved from view data within a view.)
In Listing 7, we took advantage of view data to pass a simple string message from a controller to a view. You also can use view data to pass other types of data, such as a collection of database records, from a controller to a view. For example, if you want to display the contents of the Products database table in a view, then you would pass the collection of database records in view data.
You also have the option of passing strongly typed view data from a controller to a view. We explore this topic in the tutorial Understanding Strongly Typed View Data and Views.
Summary
This tutorial provided a brief introduction to ASP.NET MVC views, view data, and HTML Helpers. In the first section, you learned how to add new views to your project. You learned that you must add a view to the right folder in order to call it from a particular controller. Next, we discussed the topic of HTML Helpers. You learned how HTML Helpers enable you to easily generate standard HTML content. Finally, you learned how to take advantage of view data to pass data from a controller to a view.
This article was originally created on February 16, 2008 | http://www.asp.net/mvc/overview/older-versions-1/views/asp-net-mvc-views-overview-cs | CC-MAIN-2015-48 | refinedweb | 1,424 | 65.93 |
From: Ulrich Eckhardt (doomster_at_[hidden])
Date: 2007-06-01 00:40:07
On Thursday 31 May 2007 20:09:37 Gmane wrote:
> as sparent_at_[hidden] pointed out in
> <>, the EBO is not possible in
> some cases. I fixed the operators library, but now I wonder if we should
> fix boost::noncopyable as well.
>
> Consider:
>
> class A : boost::noncopyable {};
> class B : boost::noncopyable { A a; };
>
> now sizeof(B)==2 instead of the expected 1. To fix it, we have to change
> the interface (or at least allow an alternative interface). Example with
> the interface I'd like to suggest:
>
> class A : boost::noncopyable_<A> {};
> class B : boost::noncopyable_<B> { A a; };
>
> now sizeof(B)==1, as expected.
>
> The crucial point of such a change is IMHO the interface. Breaking
> noncopyable is bad, so I'd like to add noncopyable_<T> and make
> noncopyable a typedef to noncopyable_<void>. This should provide
> backwards compatibility and provides users with a better, but less brief
> alternative in case they need the additional EBO opportunity. Comments?
I added a comment inline which I hope explains the rationale for this class,
because it is far from obvious IMHO. If the reasons there are wrong, please
correct me. Other than that, I'd suggest naming it noncopyable_base<T>.
> namespace noncopyable_impl // prevent unintended ADL
> {
/* baseclass for noncopyable objects
Usage:
// A is noncopyable and non-assignable now
class A: noncopyable_<A>
{};
Note: the reason this is a template and not a plain class like
it used to be is that it improves EBO. If an (otherwise empty)
object inherits noncopyable and includes (via a member)
noncopyable, too, the compiler is required to assign each a
unique address (TODO: insert standard reference), thus the
resulting size of the object must be at least 2.
If the two non-copyable subobjects are of different types (as
they are when templated) they are allowed to have the
same address and the compiler can fully exploit EBO. */
> template< typename > class noncopyable_
> {
> protected:
> noncopyable_() {}
> ~noncopyable_() {}
> private:
> noncopyable_( const noncopyable_& );
> const noncopyable_& operator=( const noncopyable_& );
> };
> typedef noncopyable_<void> noncopyable;
> }
>
> using namespace noncopyable_impl;
Why this? I guess it is intended to prevent ADL, right? Can you point me to a
rationale for this?
thanks
Uli
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2007/06/122608.php | CC-MAIN-2020-29 | refinedweb | 391 | 54.22 |
Subject: Re: [boost] Fw: Interlibrary version cchecking
From: David Abrahams (dave_at_[hidden])
Date: 2010-10-18 13:03:42
At Mon, 18 Oct 2010 09:05:15 -0800,
Robert Ramey wrote:
> "Robert Ramey" <ramey_at_[hidden]> wrote in message
> news:<hsdfuq$prj$1_at_[hidden]>...
> > Turns out that the idea of a single boost library deployment has
> > come up a couple of times here at BoostCon 2010. While preparing
> > my presentation I considered the problem of what would happen if
> > one installed one library which depended on an newer version of a
> > different library than the user already had installed. I actually
> > woke up in the middle of the night imagining someone would ask
> > about that during my talk. I puzzled about it
>
> > for some time and the day before I found a way to address it - in my own
> > mind at least. It also seems that it turns out that there are tools that
> > can also manage this.
> >
> > It's not that I don't trust tools but I wear a belt AND
> > suspenders. So I would like a method which guarentees that when I
> > build one library, I don't accidently include code from a
> > prerequisite library which is a version so old that things won't
> > work. I would also like to know that I'm not accidently running
> > with a DLL built with an old version.
> >
> > Basically each library includes a file "manifest.hpp". This gets
> > included when any header gets included (once at most due to
> > include guards). This includes a static assert that checks that
> > the prequiste libraries are of sufficiently recent version that a
> > dependent library (or user application) requires. There is also a
> > manifest.cpp file included in the library which checks any
> > prequiste DLLS. This would be an exheedingly small overhead to
> > avoid what could be an incredibly large headache. I just verified
> > that the code compiles so at this point it's only an idea.
>
> > But it seems that some kind of check like this is un-avoidable of
> > one want's to deploy libraries as needed rather than as a
> > monolithic distribution.
Seems like you need something like this somewhere. Whether belt and
suspenders are needed or not is open to debate I suppose. If you
think your source code will be used outside the environment of any
given tool, it's probably a good idea to have these internal checks.
One issue, of course, is that some library dependencies aren't Boost
libraries, and they have (or don't) their own way of indicating their
version. Your scheme seems a lot more complicated than industry
standard practice, which is to use one or two long integer constants
as macros (c.f. __GCC_VERSION__ and friends). That's also useful for
#ifdefing, whereas mpl::int_<>s are not.
> #ifndef BOOST_ITERATOR_MANIFEST_HPP
> #define BOOST_ITERATOR_MANIFEST_HPP
>
> // MS compatible compilers support #pragma once
> #if defined(_MSC_VER) && (_MSC_VER >= 1020)
> # pragma once
> #endif
>
> /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
> // manifest.hpp: Verify that all dependent libraries are at the correct
> // versions
>
> // (C) Copyright 2010 Robert Ramey - .
> // Use, modification and distribution is subject to the Boost Software
> // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
> //)
>
> #include <boost/mpl/int.hpp>
>
> namespace boost {
> namespace iterator {
>
> class manifest {
> public:
> // specify the current version numbers for this library
> typedef boost::mpl::int_<2> interface_version;
> typedef boost::mpl::int_<3> implemenation_version;
> };
>
> } // serialization
> } // boost
>
> #endif // BOOST_ITERATOR_MANIFEST_HPP
-- Dave Abrahams BoostPro Computing
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2010/10/172171.php | CC-MAIN-2020-50 | refinedweb | 593 | 54.93 |
Some pods will require user input of some kind to interact with the running container.
An example of this might be a web application. Without the user being able to browse the application in their web browser, the application is useless.
Within Kubernetes, setting up access to a pod from outside is referred to as Ingress. Ingress allows you to manage traffic and routing rules via a resource that is running as part of your cluster or via an external offering such as a load balancer, which is then also managed from within the cluster.
An Ingress resource is essentially a collection of rules for routing that allow or deny users access to services running within a cluster. …
In this article, I will be working with the following software, it makes sense to have these pre-installed before continuing.
You can install all by using brew if on OSX, or check out the website for detailed installation instructions.
Kubernetes supports multiple virtual clusters backed by the same physical cluster. …
When working with kubernetes, it is sometimes useful to spin up a container within a cluster to just test something quickly.
Sure, you can just exec onto a pod, but sometimes you need to work with jobs or cronjobs, which are not so easy to just exec onto.
One way to do this is to create a pod temporarily with the tools you need (such as busybox) just to test something, such as connectivity to a server (because of a recent firewall change) or to test inter-pod communication.
NAMESPACE=my-namespacecat <<EOF | kubectl apply -n $NAMESPACE -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: debug
spec:
podSelector:
matchLabels:
app: debug
policyTypes:
- Egress
egress:
- {}…
AWS Client VPN is a managed client-based VPN service that enables you to securely access your AWS resources and resources in your on-premises network. With Client VPN, you can access your resources from any location using an OpenVPN-based VPN client.
With mutual authentication, Client VPN uses certificates to perform authentication between the client and the server.
In order to use this using this guide, you will want to generate some certs, and import them into the certificate manager in AWS.
There is a pretty good guide here:
In my case, I generated the following files:
CA: ca.crt
Client: craig.vpn.management.XXX.com.crt
Client: craig.vpn.management.XXX.com.key
Server: vpn.management.XXX.com.crt …
GitOps is a broad term, which generally describes some processes used when deploying cloud-native applications.
A source control repository is used as a mechanism to provide a declarative description of the current state of some infrastructure.
The idea is that this source control repository is updated when there is a change, such as a new version or a change to the infrastructure.
Some automated process detects the change and updates the environment to become eventually consistent with what is described within the repository.
GitOps uses tools that developers are familiar with already, hence the git part of GitOps. …
I’ve recently had to work on services that require to be installed on Windows, and because of this, using a container was out of the question.
It was part of a migration which due to time constraints required lifting and shifting the machines rather than spending time automating and getting it right.
Due to cost, it was not necessary to create high availability as long as the service could recover within a reasonable time (10 minutes) without any loss of backing data.
The idea was to use EC2 in combination with an autoscaling group, to allow an almost always running service, which would automatically recover if terminated either by ourselves, or AWS. …
I had an underutilized raspberry pi, running raspian headless.
I set it up a couple of months back to run pihole
To utilise my pi further, I decided to see if I could run Airflow on it. I have used airflow in the past to run python tasks and thought it could come in handy for running some automation tasks at home.
Turns out it is very easy to set up and runs really well!
Apache Airflow
Airflow is a platform created by the community to programmatically author, schedule and monitor workflows.
First SSH onto the raspberry pi.
The version I am running of Raspian was Raspbian GNU/Linux 10…
SSH tunneling is something I have to do all the time, yet its something that never seems to stick in my brain.
I have created a guide (with examples) to quickly and easily demystify SSH tunneling and get you going.
Use ssh config to save your connections, to save having to go through your bash history to find the command you used last week that worked.
I am a serial bash history searcher, but there are easier ways to setup your ssh tunnels and connections in general using SSH config.
SSH config is usually located at: ~/.ssh/config
If it isn’t you should just be able to create that file. …
I don’t usually like to write articles about myself, as it feels a bit self-indulgent, but I thought it would be useful to show examples of how I became ‘T’ shaped and how my career progressed.
I’ve been working in tech for over ten years. My passion first started when I was young. When I was five years old, my parents bought a commodore 64, and it sparked something inside of me.
I enjoyed playing games and eventually going on to writing small bits of code in basic and watching the output.
As a teenager, I played a lot with a tool my parents got for me called ‘Klik and Play’ which was a drag and drop game creator, which allowed scripting of events to create custom behaviors. It was awesome and helped me understand event-driven programming. …
People have a love-hate relationship with Twitter bots. They can be useful for retweeting content that is relevant to things you are looking for, but they can also be annoying if they tweet too much or if they tweet about stuff that you don't care about. However, you can get around this issue by creating your own bot.
Creating a Twitter bot is relatively straightforward. In true serverless style, it is possible to build your own in a cost-effective way. This article will focus on creating a Twitter bot in Node, hosted in AWS Lambda.
Using serverless patterns for a Twitter bot makes complete sense. …
About | https://craig-godden-payne.medium.com/?source=post_internal_links---------7---------------------------- | CC-MAIN-2020-50 | refinedweb | 1,089 | 60.85 |
Introduction
Statistics is the foundation of Data Science. Before jumping to any Machine Learning model or complex modeling techniques, one should be well versed in the basics which are Statistics.
There are two areas of Statistics which is used in Data Science – Descriptive Statistics and Inferential Statistics.
Today, In this article we will learn about the simplest concept of Descriptive Statistics which is used in understanding our datasets before applying any transformations to the data. The topic of today’s discussion is Five Number Summary.
I will try to explain this concept in the most simplistic way so keep on reading 🙂
Table of Contents
What is Five Number Summary
How to calculate Five Number Summary
How it is used in the interpretation of data
Box plots and How they are constructed
What is Five Number Summary
Descriptive Statistics involves understanding the distribution and nature of the data. Five number summary is a part of descriptive statistics and consists of five values and all these values will help us to describe the data.
The minimum value (the lowest value)
25th Percentile or Q1
50th Percentile or Q2 or Median
75th Percentile or Q3
Maximum Value (the highest value)
How to calculate Five Number Summary
Let’s understand this with the help of an example . Suppose we have some data such as : 11,23,32,26,16,19,30,14,16,10
Here, in the above set of data points our Five Number Summary are as follows :
First of all , we will arrange the data points in ascending order and then calculate the summary : 10,11,14,16,16,19,23,26,30,32
Minimum value: 10
25th Percentile: 14
Calculation of 25th Percentile : (25/100)*(n+1) = (25/100)*(11) = 2.75 i.e 3rd value of the data
50th Percentile : 17.5
Calculation of 50th Percentile : (16+19)/2 = 17.5
75th Percentile : 26
Calculation of 75th Percentile : (75/100)*(n+1) = (75/100)*(11) = 8.25 i.e 8th value of the data
Maximum value: 32
How is it used in the interpretation of data?
Now, our major question is that How the Five number Summary values describe our data? Let’s understand this practically using a dataset.
We are going to use a subset of the famous Titanic dataset.
#importing data #read_csv function is used to read titanic.csv file data=pd.read_csv('titanic.csv') data=data[['Age','Fare','Survived']] data.head()
Output :
Here our data consists of 3 columns, Age, Fare, and Survived. Age and Fare are independent variables and Survived is a dependent variable with two categories, 1 means Survived and 0 means not survived.
Please find the link to the dataset attached.
We will use the describe function in Python to see the Five Number Summary and other details of the data. describe() function gives us the count and mean of the features including the summary values.
data.describe()
Output :
Understanding Summary values from data’s perspective and describing our data based on the same :
From the Fare Column, we can analyze that our 25th Percentile is 7.9 i.e 8 which means 25% of the data is less than 8.
75th Percentile value is 31 meaning 75% of data lies below 31.
One major thing to note is that there is a major difference between the 75 percentile value and maximum value, which can be interpreted as the Fare feature is highly skewed and does not follow a Normal Distribution.
The presence of outliers can also be detected from such differences.
Another thing to note is that Mean>Median(50th Percentile) i.e 32>14 so the distribution is skewed to the right. We can also check the value of skewness using a python function called data.skew().
Same interpretations can be made for the Age column. There is not a huge difference between the maximum and 75th percentile values and Median and Mean values are kind of the same so the distribution is not highly skewed.
Checking the distribution of Fare column in Python. We can confirm from the below figure that Fare is skewed towards the right and the presence of outliers can also be detected.
import matplotlib.pyplot as plt plt.hist(data.Fare,bins=20)
Output :
Now, Checking the distribution of the Age column. We can justify our interpretation of the Age column from the below figure.
plt.hist(data.Age,bins=20);
Output :
Another and more efficient way to detect outliers is Boxplot which is constructed from the Five Summary values.
Box plots and how they are constructed?
Boxplots are the graphical representation of the distribution of the data using Five Number summary values. It is one of the most efficient ways to detect outliers in our dataset.
In statistics, an outlier is a data point that differs significantly from other observations. An outlier may be due to variability in the measurement or it may indicate experimental error; the latter are sometimes excluded from the dataset. An outlier can cause serious problems in statistical analyses.
Plotting the boxplot of the data points taken for the above example (11,23,32,26,16,19,30,14,16,10) where the Five number summary was :
- Minimum value: 10
- 25th Percentile: 14
- 50th Percentile: 17.5
- 75th Percentile: 26
- Maximum value: 32
Plotting the boxplot of Fare Column of Titanic Dataset. We can see the number of outliers present in the column Fare in the below graph and it needs to be treated before Model building.
import seaborn as sns sns.boxplot(data.Fare);
Output :
End Notes :
Another use of 5 Number Summary is the calculation of IQR i.e Inter Quartile Range which helps to deal with outliers. We will study this some other time, but for now, I hope you understood the basic interpretation of data from this simple concept of Five Number Summary.
Feel free to share your thoughts and suggestions here<< | https://www.analyticsvidhya.com/blog/2021/05/five-number-summary-for-analysis/ | CC-MAIN-2021-25 | refinedweb | 984 | 54.52 |
Last Updated on August 28, 2019
Data transforms are intended to remove noise and improve the signal in time series forecasting.
It can be very difficult to select a good, or even best, transform for a given prediction problem. There are many transforms to choose from and each has a different mathematical intuition.
In this tutorial, you will discover how to explore different power-based transforms for time series forecasting with Python.
After completing this tutorial, you will know:
- How to identify when to use and how to explore a square root transform.
- How to identify when to use and explore a log transform and the expectations on raw data.
- How to use the Box-Cox transform to perform square root, log, and automatically discover the best power transform for your dataset.
Kick-start your project with my new book Time Series Forecasting With Python, including step-by-step tutorials and the Python source code files for all examples.
Let’s get started.
- Updated Apr/2019: Updated the link to dataset.
- Updated Aug/2019: Updated data loading to use new API.
Airline Passengers Dataset
The Airline Passengers dataset describes a total number of airline passengers over time.
The units are a count of the number of airline passengers in thousands. There are 144 monthly observations from 1949 to 1960.
Download the dataset to your current working directory with the filename “airline-passengers.csv“.
The example below loads the dataset and plots the data.
Running the example creates two plots, the first showing the time series as a line plot and the second showing the observations as a histogram.
Airline Passengers Dataset Plot
The dataset is non-stationary, meaning that the mean and the variance of the observations change over time. This makes it difficult to model by both classical statistical methods, like ARIMA, and more sophisticated machine learning methods, like neural networks.
This is caused by what appears to be both an increasing trend and a seasonality component.
In addition, the amount of change, or the variance, is increasing with time. This is clear when you look at the size of the seasonal component and notice that from one cycle to the next, the amplitude (from bottom to top of the cycle) is increasing.
In this tutorial, we will investigate transforms that we can use on time series datasets that exhibit this property.
Stop learning Time Series Forecasting the slow way!
Take my free 7-day email course and discover how to get started (with sample code).
Click to sign-up and also get a free PDF Ebook version of the course.
Start Your FREE Mini-Course Now!
Square Root Transform
A time series that has a quadratic growth trend can be made linear by taking the square root.
Let’s demonstrate this with a quick contrived example.
Consider a series of the numbers 1 to 99 squared. The line plot of this series will show a quadratic growth trend and a histogram of the values will show an exponential distribution with a long trail.
The snippet of code below creates and graphs this series.
Running the example plots the series both as a line plot over time and a histogram of observations.
Quadratic Time Series
If you see a structure like this in your own time series, you may have a quadratic growth trend. This can be removed or made linear by taking the inverse operation of the squaring procedure, which is the square root.
Because the example is perfectly quadratic, we would expect the line plot of the transformed data to show a straight line. Because the source of the squared series is linear, we would expect the histogram to show a uniform distribution.
The example below performs a sqrt() transform on the time series and plots the result.
We can see that, as expected, the quadratic trend was made linear.
Square Root Transform of Quadratic Time Series
It is possible that the Airline Passengers dataset shows a quadratic growth. If this is the case, then we could expect a square root transform to reduce the growth trend to be linear and change the distribution of observations to be perhaps nearly Gaussian.
The example below performs a square root of the dataset and plots the results.
We can see that the trend was reduced, but was not removed.
The line plot still shows an increasing variance from cycle to cycle. The histogram still shows a long tail to the right of the distribution, suggesting an exponential or long-tail distribution.
Square Root Transform of Airline Passengers Dataset Plot
Log Transform
A class of more extreme trends are exponential, often graphed as a hockey stick.
Time series with an exponential distribution can be made linear by taking the logarithm of the values. This is called a log transform.
As with the square and square root case above, we can demonstrate this with a quick example.
The code below creates an exponential distribution by raising the numbers from 1 to 99 to the value e, which is the base of the natural logarithms or Euler’s number (2.718…).
Running the example creates a line plot of the series and a histogram of the distribution of observations.
We see an extreme increase on the line graph and an equally extreme long tail distribution on the histogram.
Exponential Time Series
Again, we can transform this series back to linear by taking the natural logarithm of the values.
This would make the series linear and the distribution uniform. The example below demonstrates this for completeness.
Running the example creates plots, showing the expected linear result.
Log Transformed Exponential Time Series
Our Airline Passengers dataset has a distribution of this form, but perhaps not this extreme.
The example below demonstrates a log transform of the Airline Passengers dataset.
Running the example results in a trend that does look a lot more linear than the square root transform above. The line plot shows a seemingly linear growth and variance.
The histogram also shows a more uniform or squashed Gaussian-like distribution of observations.
Log Transform of Airline Passengers Dataset Plot
Log transforms are popular with time series data as they are effective at removing exponential variance.
It is important to note that this operation assumes values are positive and non-zero. It is common to transform observations by adding a fixed constant to ensure all input values meet this requirement. For example:
Where transform is the transformed series, constant is a fixed value that lifts all observations above zero, and x is the time series.
Box-Cox Transform
The square root transform and log transform belong to a class of transforms called power transforms.
The Box-Cox transform is a configurable data transform method that supports both square root and log transform, as well as a suite of related transforms.
More than that, it can be configured to evaluate a suite of transforms automatically and select a best fit. It can be thought of as a power tool to iron out power-based change in your time series. The resulting series may be more linear and the resulting distribution more Gaussian or Uniform, depending on the underlying process that generated it.
The scipy.stats library provides an implementation of the Box-Cox transform. The boxcox() function, we can perform a log transform using the boxcox() function as follows:
Running the example reproduces the log transform from the previous section.
BoxCox Log Transform of Airline Passengers Dataset Plot
We can set the lambda parameter to None (the default) and let the function find a statistically tuned value.
The following example demonstrates this usage, returning both the transformed dataset and the chosen lambda value.
Running the example discovers the lambda value of 0.148023.
We can see that this is very close to a lambda value of 0.0, resulting in a log transform and stronger (less than) than 0.5 for the square root transform.
The line and histogram plots are also very similar to those from the log transform.
BoxCox Auto Transform of Airline Passengers Dataset Plot
Summary
In this tutorial, you discovered how to identify when to use and how to use different power transforms on time series data with Python.
Specifically, you learned:
- How to identify a quadratic change and use the square root transform.
- How to identify an exponential change and how to use the log transform.
- How to use the Box-Cox transform to perform square root and log transforms and automatically optimize the transform for a dataset.
Do you have any questions about power transforms, or about this tutorial?
Ask your questions in the comments below and I will do my best to answer.
Thanks for this article. A lot of people write about log transformations and provide no explanation of when to not do a log transform, and Box-Cox fills in a lot of the gaps. Thanks!
A few follow up questions:
– Assuming the minimum value of a variable is > 0, are there situations in which you would not try and use Box-Cox? The scipy.stats.boxplot module will also decide when a transformation is unnecessary, so seems like there’s no harm in trying it for every variable. I’d imagine the main cost is loss of interpretability if you’re visualizing model results.
– In situations where you shouldn’t use a Box-Cox, what alternative transformations do you recommend?
I agree, try, evaluate and adopt if a transform lifts skill. Often model skill is the goal for a project.
A “Yeo-Johnson transformation” can be used as an alternative to box-cox:
Thanks for the blog. It’s very helpful for me since I’m currently working on a project where I need to log transform the data.
I have the following question, if I fit the transformed data to extract information such as the mean and variance or the forecasted value. Does scipy have a way to transform the data back?
Off hand, I don’t think so.
You can invert the power transform if you know the lambda.
I show how here:
Hi, thanks much for the tutorial.
When taking the square root of the airline, you say we expect the distribution to be Gaussian, while in the previous example with generated quadratic data, you expected a uniform distribution.
When will we expect one over the other ?
Thanks !
It really depends on the data.
Hi Jason! Currently working on the e-book right now. Could you explain a bit how would a linear line plot will have a Gaussian distribution? Should it only create a uniform distribution? Thanks!
Yes, this gives examples:
Please, help!
after writing the first code line from the first example I have got the following error message:
>>> from pandas import Series
Traceback (most recent call last):
File “”, line 1, in
from pandas import Series
ImportError: No module named pandas
>>>
You need to install Pandas. This tutorial will help you:
Dear Jason, I love this tutorial!
Much of the data I work with contains many zeros and is heavily skewed to the right. I have sometimes added a small value (like 0.1) to each record in order to perform a log transformation.
Can the Box-Cox package handle data that contains zeros?
Thanks again for your great information 🙂
Generally, no.
Nevertheless, try it (with an offset to get all values >0) to see if it has an impact.
FYI – scipy.stats.boxcox is buggy. 🙁
Why do you say that?
This thread shows the problem. I ran into the problem running your code but on my data.
The problem occurs when stats.boxcox calls stats.boxcox_normmax Very annoying.
Sorry to hear that.
Hi Jason, thanks for your blog.. It is good as like your other blog posts. However got a questions, if I use to box_cox to automatically use for transformation for my series, how can I convert it back..i meant transform back to original values..is there a function that does automatically as well?
You can invert the process with a function like the following:
nice one; i was interested in a first-principles explanation of Box-Cox; at university many years ago was the last time had this understanding. I don’t work in python so i didn’t use your code; however, your use of clear shot snippets to explain step-by-step what is B-C, is excellent
Thanks Doug, I’m happy it was useful.
Hi Jason,
How do we inverse the log transformed data or time series back to the original time series scale?
Secondly, I used log transform on my time series data that shows exponential growth trends, to make it linear, and I had a histogram plot that is more uniform and Gaussian-like distribution. The log transform lifted model skills tremendously, but in log scale, rather than the original time series scale. In addition, I did not do any further transform on my time series data, even though, they contain zeroes and negative values. Does it really matter?
Regards,
Kingsley
Thanks
The inverse of log is exp()
The transforms required really depend on your data.
Thanks
I’m happy that it helped.
Hi Jason,
Thanks a lot for the great post. So my question is that, the box-cox algorithm helps to determine if there is any trend or seasonality. How do we remove that trend and make the time series stationary ? Do we need to substract the trend or seasonality factor from the original data set and feed to the ARIMA model to decide the value of p,q and d? If you have any article related to this, please share.
Also, for an ARIMA model, a stationary time series is mandatory ? I have a data set similar to the air passeneger data set. I have the data set from 2014 to 2017. I want to predict it for 2018.
Your help will be highly appreciated 🙂
No, box-cox shifts a data distribution to be more Gaussian.
You can remove a trend using a difference transform.
When using ARIMA, it can perform this differencing for you.
Thank you for your post. It is very useful.
My time series data is multiplicative.
2 Questios::
1. What do I need to calculate log of? Dependent variable Y or Resduals r? To elaborate,
Once I calculate log(Y), should I then calculate residual as r = log(Y) /(trend x seasonality). Or should I calculate r = Y/(tend x seasonality) and then calculate log (r)?
2. If my trend and seasonality are independent variables (features) then should I also calculate log of them before doing
r = log(Y) /(trend x seasonality)
You transform the raw data that you’re modeling.
I recommend subtracting the trend and seasonality from the data first, e.g. make the series stationary.
But if I substract seasonality and trend then it will make the data negative? And you mentioned calculating log of negative data isn’t allowed
You can force the data to be positive by adding an offset.
Hi Jason,
Currently working through your eBook on TimeSeries. Learned loads already, very exciting.
If I run the code of the Box-Cox with optimized Lambda, my Lambda is optimized for 8.4.
Have you seen this issue before?
Thanks,
Thomas
Wow, that is a massive value.
No, I have not seen that before.
Hi Dr Jason,
Good article!!
I want to transform Generalized Normal Distribution to Normal Distribution (through uniform distribution??, read from some literature, there not much ICDF is available for Gennorm). I follow similar technique of that you have indicated. Not able to get the required outcome!
Can you help me out please?
Sorry, I don’t have a tutorial on this topic – I don’t have good off the cuff advice.
Hi. Useful post. Thank-you.
Let me see if I understand you correctly from a Mada’s question from above so I can avoid
any foobar-ing on my part. If I am doing ARIMA I should be doing the differencing BEFORE
applying Box_cox or Yeo? Then do Box_cox?
Thanks.
Yes, differencing first. I outline a suggested ordering here:
Hi Jason,
As always, it’s a treat reading your articles. Just a quick question.
I have seen people applying Box-Cox transform AFTER performing train-test split. Which is okay until there is not data leakage in pipeline. But is it really required to perform ANY transformation (including differences etc.) on test data? We anyways inverse transform the predictions generated using train data before actual model evaluation.
In short, you do we apply any transformation on test data when it’s supposed to be hidden during training?
Thanks.
Correct. Calculate on training, apply to train, test, and any other data.
Hello Jason,
Great tutorial! Will the transforms hold good if I’m performing time series classification?
Perhaps develop a prototype for your dataset and discover the answer.
Thank you very much! I will try it out!!
You’re welcome.
Hello Jason, thanks for this awesome post! I’ve searched through the internet but am still confused about how we apply power transformation to multiple examples. Say if we have about 20 univariate datapoints of length 20, do we treat each datapoint as an independent feature or do we want to concatenate all of the datapoints since they are describing the same variable? Thanks!
Each “series” would be a separate input feature:
Hi Jason,
If I have a time series with no general trend but a strong seasonality, and its distribution is bi-modal. What transform should I use ? Without any transforms, I have used a DNN and it pretty much works good but I am curious to know if there’s any room for improvement using transforms, if yes which one? Thanks!
Seasonal transform to remove the seasonality.
Thank you for the prompt reply. Another doubt I had is about minmax scaler. In the case of scaling univariate time series to 0-1, we should treat each datapoint in training set as the same feature instead of each single datapoint as a feature, right? Otherwise we won’t have shared min/max parameter?
Correct.
Hi Jason, I am reading your book on time-series. I wanted to ask you two questions:
1. Do we remove seasonality and trend before applying power transform?
2. Which power transform is better for data like the mean temperature of a city?
Thanks in advance!
Great questions.
Yes. This can help with the order of transforms:
Perhaps test a few transforms and discover which results in a better performing model on your dataset.
My time series experienced a huge fall in values that makes it non-stationary.
I got a lambda value =1 which means no transformation is needed. However, the time series is still non-stationary.
What should I do for time series with abrupt change?
I believe they call this a regime change. Perhaps there are techniques designed specifically for that, you can try checking the literature.
Perhaps manually separate the data before and after the change in level and model them as separate problems.
Hi, your code for log transform in airplane is wrong, because it has some errors
Sorry to hear that you are having problems running the code, perhaps this will help:
Dear Jason
I need to use Yeo–Johnson transformation for both negative and positive “one dimensional” data, as well as inverting the predicted values to their origins I couldn’t find an appropriate python code for it. please help me.
See this example:
I am performing the box-cox method in my data and want to use it as a label for ML. It makes the error so low, yet I am skeptical about the procedure. Do I need to change the data back to the normal form for doing any further analysis? As the range of data becomes so compact( between 0.85 to 1) [although I am using percent error for my decision making] and in contrast with the low error, the predictions are in contrast with any common sense. I really appreciate your guidance.
Thanks
Yes, the transform must be inverted on expected and predicted values before calculating an error value in the original units. | https://machinelearningmastery.com/power-transform-time-series-forecast-data-python/ | CC-MAIN-2021-31 | refinedweb | 3,367 | 65.22 |
As a developer, think of a 'with' statement as a try/finally pattern
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()
This can now be viewed as:
with f = opening(filename):
#...read data from f...
This makes writing code easier to understand, and you don't have to always remember to delete the object reference using the del().
How does this apply to the Cursor object? Well natively, the Cursor object does not support 'with' statement use. To extend the Cursor, more specifically SearchCursor, first create a class:
class custom_cursor(object):
"""
Extension class of cursor to enable use of
with statement
"""
def __init__(self, cursor):
self.cursor = cursor
def __enter__(self):
return self.cursor
def __exit__(self, type, value, traceback):
del self.cursor
Now you have an object called custom_cursor that has the minimum required class properties of __enter__() and __exit__(). Notice that __exit__() performs that annoying del() to remove the schema locks on our data.
How do you use this? It's not hard at all. In this example, the function searchCursor() takes a feature class or table and a where clause (expression) and returns the results as an array of Row objects.
def searchCursor(fc,expression=""):
"""
Returns a collections of rows as an array of Row Objects
:param fc: Feature Class or Table
:param expression: Where Clause Statement (Optional)
:rtype Rows: Array of Rows
"""
rows = []
with custom_cursor(arcpy.SearchCursor(fc,expression)) as cur:
for row in cur:
rows.append(row)
return rows
The del() is taken care of automatically, and when the process is completed the __exit__() is called launching the del().
I got this idea from Sean Gillies Blog | https://anothergisblog.blogspot.com/2011/06/advanced-extending-search-cursor-object.html | CC-MAIN-2018-05 | refinedweb | 276 | 57.16 |
[
]
Jukka Zitting commented on JCR-727:
-----------------------------------
Thanks for the terminology update! The devil's in the details...
The XML namespace spec says: "An XML namespace is identified by a URI reference [RFC3986]",
meaning both full URIs and relative URI references. The current version adds a note that deprecates
the use of relative URI references.
The JCR spec somewhat vaguely says: "Namespacing in a content repository is patterned after
namespacing in XML. As in XML, the prefix is actually shorthand for the full namespace, which
is a URI."
It seems fair to interpret this as meaning that only full URIs are allowed as JCR namespaces.
> NamespaceRegistryTest uses an invalid URI as namespace URI
> ----------------------------------------------------------
>
> Key: JCR-727
> URL:
> Project: Jackrabbit
> Issue Type: Bug
> Components: test
> Reporter: Julian Reschke
> Priority: Trivial
>
> The test cases use "..." as a namespace URI, but this is not a URI.
> Suggest to fix by using a proper URI, such as by prefixing with "http://".
> A related question is what our expectation is for JCR implementations. Are they allowed
to reject something that doesn't parse as a URI according to RFC3986?
--
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online. | http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/200702.mbox/%3C27351475.1171579505701.JavaMail.jira@brutus%3E | CC-MAIN-2014-52 | refinedweb | 204 | 65.42 |
I am trying to create an EJB that takes a single java.io.Serializable argument. Then I call this method with an instance of some UserData class from a client. The UserData class is in the deployment jar file; however, I get a ClassNotFound exception when WebLogic tries to unmarshal the argument from the input stream.
Now, the weird part. If I add a dummy method in the bean that returns (or, after service pack 3, accepts) an explicit argument of the UserData type, then everything works!
Why, you ask, do I declare the argument as Serializable, and not UserData. There are two reasons. First would be, if I wanted to pass one of several child classes to a method that is declared to accept a common parent. Second, which happens to be my real case, is that I really want to pass a Vector of objects, and since there is no reasonable way I can declare that the objects are of my UserData type, I have this problem. Maybe, we can solve this by adding C++ templates to Java - that would make Sun happy ;)
The situation is made worse by the fact that if my UserData object happens to contain a NestedData field, I also have to declare NestedData in a dummy method, to make WebLogic pull that class in.
Finally, the J2EE SDK app server (Sun's) eats this with no problems. I think that WebLogic folks either have a bug, or they came up with a very strange feature. Does everyone agree that a well-behaved app server should be able to marshal serializable classes loaded from the deployment jar, even if they are not statically referenced from the bean interface? It's in the jar, load it!
- Gene Florintsev
gene at florintsev dot com
Discussions
EJB programming & troubleshooting: WebLogic won't marshal classes unreferenced from the bean API???
WebLogic won't marshal classes unreferenced from the bean API??? (6 messages)
- Posted by: Gene Florintsev
- Posted on: July 06 2000 12:37 EDT
Threaded Messages (6)
- WebLogic won't marshal classes unreferenced from the bean API??? by Kumar Mettu on July 06 2000 20:30 EDT
- The problem is more tricky than this... by Gene Florintsev on July 07 2000 11:12 EDT
- The problem is more tricky than this... by Hari Velappan on July 10 2000 02:16 EDT
- This is exactly what does not work!!!!!!!!! by Gene Florintsev on July 12 2000 07:29 EDT
- This is exactly what does not work!!!!!!!!! by David Kempster on July 17 2000 04:08 EDT
- Should I have to put my classes in the WebLogic classpath? by Gene Florintsev on July 18 2000 12:43 EDT
WebLogic won't marshal classes unreferenced from the bean API???[ Go to top ]
The UserData class is in the deployment jar file; however, >I get a ClassNotFound exception when WebLogic tries to >unmarshal the argument from the input stream.
- Posted by: Kumar Mettu
- Posted on: July 06 2000 20:30 EDT
- in response to Gene Florintsev
Take the case of code below:
public void setContactProfileProxy(ContactProfileProxy contactprofile){
contactid = contactprofile.contactid;
interfacename = contactprofile.interfacename;
busdescription = contactprofile.busdescription;
}
Here ContactProfileProxy is simple class that implements Serializable. I am not facing any problem you mentioned.
Regards,
Mettu.
The problem is more tricky than this...[ Go to top ]
Hi,
- Posted by: Gene Florintsev
- Posted on: July 07 2000 11:12 EDT
- in response to Kumar Mettu
I must not have made myself clear.
The bean method is declared like this:
public void test (Serializable arg);
The client calls it like this:
bean.test (new UserData ());
If I declare the method as:
public void test (UserData arg);
then everything works, because WebLogic's bean class loader recognizes UserData as an interface class and exports it to the parent class loader. But I think this behavior is inconsistent with the EJB spec.
- Gene
The problem is more tricky than this...[ Go to top ]
If you want to pass a list of User objects then you should be able to pass instance of the various container classes java provides like List and Vector. Your user objects should be element of this container classs.
- Posted by: Hari Velappan
- Posted on: July 10 2000 14:16 EDT
- in response to Gene Florintsev
If you are expecting an argument serialazable just because you wantr to have a common parent. why not have a commom parent . for eg: an inteface with no method.
public interface Tag
{
};
public class A implements Tag
{
}
public class B implements Tag
{
}
In the bean you can have a method test(Tag)
This is exactly what does not work!!!!!!!!![ Go to top ]
Hari,
- Posted by: Gene Florintsev
- Posted on: July 12 2000 19:29 EDT
- in response to Hari Velappan
this is exactly what does not work! If I do what you propose, and no method in the bean's API explicitly returns or accepts A or B, then I get a ClassNotFoundException when an instance of A or B is being unmarshalled from the input stream - see for yourself.
- Gene
This is exactly what does not work!!!!!!!!![ Go to top ]
Actually what is happing is that Weblogic needs the classes loaded into its classpath and for some reason Weblogic doesn't really add your bean.jar to the weblogic classpath even when you set it in the property file. Try this, put the class in question into /myserver/server_classes. This is in the weblogic classpath. Then run the startweblogic script and I think you will find it works. If you have classloading problems in welogic it is almost always because you haven't put it in the weblogic classpath and the weblogic classloader doesn't find it.
- Posted by: David Kempster
- Posted on: July 17 2000 16:08 EDT
- in response to Gene Florintsev
Should I have to put my classes in the WebLogic classpath?[ Go to top ]
David,
- Posted by: Gene Florintsev
- Posted on: July 18 2000 12:43 EDT
- in response to David Kempster
thank you for your advice. I know about this trick, and things do start to work if I use it. But I think that this contradicts to the spirit of the EJB spec, which is that I sholuld be able to package my app in a single deployment jar file. Would you agree with that?
So far, the workaround I will use is adding dummy methods to the bean, pulling the classes into the interface class loader.
- Gene | http://www.theserverside.com/discussions/thread/153.html | CC-MAIN-2018-05 | refinedweb | 1,076 | 61.06 |
the base class for language implementations that support arrays. However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language.
An element is a value in an Array. The length of an Array is the total number of elements it can contain.).
Type objects provide information about array type declarations. Array objects with the same array type share the same Type object.
Type.IsArray and Type.GetElementType might not return the expected results with Array because if an array is cast to the type Array, the result is an object, not an array. That is, typeof(System.Array).IsArray returns false, and typeof(System.Array).GetElementType returns null.
Unlike most classes, Array provides the CreateInstance method, instead of public constructors, to allow for late bound access.
The Array.Copy method copies elements not only between arrays of the same type but also between standard arrays of different types; it handles type casting automatically.
Some methods, such as CreateInstance, Copy, CopyTo, GetValue, and SetValue, provide overloads that accept 64-bit integers as parameters to accommodate large capacity arrays. LongLength and GetLongLength return 64-bit integers indicating the length of the array.
The Array is not guaranteed to be sorted. You must sort the Array prior to performing operations (such as BinarySearch) that require the Array to be sorted.
Using an Array object of pointers in native code is not supported and will throw a NotSupportedException for several methods.
The following code example shows how Array.Copy copies elements between an array of type integer and an array of type Object.
public class SamplesArray { public static void Main() { // Creates and initializes a new integer array and a new Object array. int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 }; Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 }; // Prints the initial values of both arrays. Console.WriteLine( "Initially," ); Console.Write( "integer array:" ); PrintValues( myIntArray ); Console.Write( "Object array: " ); PrintValues( myObjArray ); // Copies the first two elements from the integer array to the Object array. System.Array.Copy( myIntArray, myObjArray, 2 ); // Prints the values of the modified arrays. Console.WriteLine( "\nAfter copying the first two elements of the integer array to the Object array," ); Console.Write( "integer array:" ); PrintValues( myIntArray ); Console.Write( "Object array: " ); PrintValues( myObjArray ); // Copies the last two elements from the Object array to the integer array. System.Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 ); // Prints the values of the modified arrays. Console.WriteLine( "\nAfter copying the last two elements of the Object array to the integer array," ); Console.Write( "integer array:" ); PrintValues( myIntArray ); Console.Write( "Object array: " ); PrintValues( myObjArray ); } public static void PrintValues( Object[] myArr ) { foreach ( Object i in myArr ) { Console.Write( "\t{0}", i ); } Console.WriteLine(); } public static void PrintValues( int[] myArr ) { foreach ( int i in myArr ) { Console.Write( "\t{0}", i ); } Console.WriteLine(); } } /* This code produces the following output. Initially, integer array: 1 2 3 4 5 Object array: 26 27 28 29 30 After copying the first two elements of the integer array to the Object array, integer array: 1 2 3 4 5 Object array: 1 2 28 29 30 After copying the last two elements of the Object array to the integer array, integer array: 1 2 3 29 30 Object array: 1 2 28 29 30 */
The following code example creates and initializes an Array and displays its properties and its elements.
public class SamplesArray2{ public static void Main() { // Creates and initializes a new three-dimensional Array of type Int32. Array myArr = Array.CreateInstance( typeof(Int32), 2, 3, 4 ); for ( int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++ ) for ( int j = myArr.GetLowerBound(1); j <= myArr.GetUpperBound(1); j++ ) for ( int k = myArr.GetLowerBound(2); k <= myArr.GetUpperBound(2); k++ ) { myArr.SetValue( (i*100)+(j*10)+k, i, j, k ); } // Displays the properties of the Array. Console.WriteLine( "The Array has {0} dimension(s) and a total of {1} elements.", myArr.Rank, myArr.Length ); Console.WriteLine( "\tLength\tLower\tUpper" ); for ( int i = 0; i < myArr.Rank; i++ ) { Console.Write( "{0}:\t{1}", i, myArr.GetLength(i) ); Console.WriteLine( "\t{0}\t{1}", myArr.GetLowerBound(i), myArr.GetUpperBound(i) ); } // Displays the contents of the Array. Console.WriteLine( "The Array contains the following values:" ); PrintValues( myArr ); }. The Array has 3 dimension(s) and a total of 24 elements. Length Lower Upper 0: 2 0 1 1: 3 0 2 2: 4 0 3 The Array contains the following values: 0 1 2 3 10 11 12 13 20 21 22 23 100 101 102 103 110 111 112 113 120 121 122 123 */
an Array; however, .NET Framework classes based on Array provide their own synchronized version of the collection. | http://msdn.microsoft.com/en-us/library/system.array(d=printer).aspx | CC-MAIN-2014-35 | refinedweb | 795 | 51.14 |
Debouncing forms in React with Redux
Basic react form
Before we jump into debouncing and what it means I want to present you a simple react form. It looks like this:
I made this using awesome Tailwind CSS. The code for this form sits mainly
in two components -
App.js:
class App extends Component {
constructor(props) {
super(props);
this.state = { typedWords: [] };
}
handleChange = (event) => {
const { value } = event.target;
let typedWords = [...this.state.typedWords, value];
this.setState({ typedWords });
};
render() {
return (
<div className="bg-teal-lighter flex min-h-screen w-full flex-col items-center bg-repeat">
<div className="container md:mx-auto md:max-w-sm">
<h1 className="text-grey-darkest mb-6 block w-full text-center">Debounce in React</h1>
<SearchInput handleChange={this.handleChange} />
</div>
{this.state.typedWords.map((word, key) => (
<SearchResult text={word} key={key} />
))}
</div>
);
}
}
and
SearchInput:
class SearchInput extends Component {
render() {
const { handleChange } = this.props;
return (
<form className="mb-4" onChange={handleChange}>
<div className="mb-4 flex flex-col md:w-full">
<label
className="text-grey-darkest mb-2 text-lg font-bold uppercase"
htmlFor="search-input"
>
Search input:
</label>
<input className="field" name="search" type="text" id="search" />
</div>
</form>
);
}
}
How it works
In my
App component I define a
handleChange function which then will be used inside
SearchInput
as a callback. In
handleChange, I extract typed character from html input. Then I make a copy of state
and insert a new value from
SearchInput component.
SearchInput is representing html form so I treat it as a representational component.
You may notice another component -
SearchResult which looks like this:
function SearchResult(props) {
const { text } = props;
return (
<div className="container md:mx-auto md:max-w-sm">
<span>{text}</span>
</div>
);
}
it is still only representing html.
Whoa! What is happening here?
onChange event handler fired up every time I typed something into an
input. That's not exactly what I wanted - I want my handler to capture only full typed words. How to
do it?
What is debounce
As you saw in a previous blog post my
handleChange event is firing up every time I type the letter. I don't
want that. I want it to be called when a user stops typing. One way of doing this will be using debounce.
Debounce is limiting a rate which given function will be called. Thanks to that I can tell my app
to run
handleChange every 250ms. It is very useful when we have event handlers that are attached
to the e.g scroll of change events.
Debounce in react
I will be using lodash.debounce as it is widely used and battle-tested library.
My
App component will look like this after a change:
class App extends Component {
constructor() {
super();
this.state = { typedWords: [] };
this.emitChangeDebounced = debounce(this.emitChange, 250);
}
componentWillUnmount() {
this.emitChangeDebounced.cancel();
}
handleChange = (event) => {
this.emitChangeDebounced(event.target.value);
};
emitChange = (value) => {
if (value !== "") {
let typedWords = [...this.state.typedWords, value];
this.setState({ typedWords });
}
};
// render method here
}
Let's start here with
handleChange. Right now it calls
emitChangeDebounced. This
emit is
debounced function that lodash will fire every 250ms after the user changes the input. My main logic lays
inside
emitChange where I set my state based on a value from the event. You may ask why do you pass
event.target.value instead of the whole
event?
It is because of how React works. In React all events are wrapped into SyntheticEvent.
This event is reused by all events inside react. To let garbage collector take it after debounce
has ended I have to either provide only
value to my function or call
event.persist() to have my event persisted.
With
event.persist() my
handleChange event will look like this:
handleChange = (event) => {
event.persist();
this.emitChangeDebounced(event);
};
If I wanted to pass entire event without
persist I will get an error:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `type` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
Testing debounce
Ok, I have my component working but how to test it? This is one of the solutions - in my
App.test.js
I have the following test:
it("should set state when input has changed", () => {
const wrapper = mount(<App />);
const searchInputWrapper = wrapper.find("#search");
searchInputWrapper.simulate("change", {
target: { value: "Fake Name" },
});
setTimeout(() => {
expect(wrapper.state().typedWords).toEqual(["Fake Name"]);
}, 200);
});
The first few lines are component setup using enzyme. Right after that, I simulate change event on my
search input. Then I use
setTimeout to wait with the assertion - I will be executed when debounce stops.
Adding redux
It may seem like overkill for this simple example but I decided to add redux to show how this debounced form can be used in the more realistic scenario.
So, after adding
redux and
react-redux to my application I started by creating actions & actions
creators under
src/actions/index.js:
export const ADD_WORD = "ADD_WORD";
export const addWord = (word) => ({
type: ADD_WORD,
word,
});
To explain how those two can be used I added a small test in 'actions.test.js`:
import { ADD_WORD, addWord } from "./index";
describe("Actions", () => {
it("should create action to add word", () => {
const expectedAction = {
type: ADD_WORD,
word: "fake",
};
expect(addWord("fake")).toEqual(expectedAction);
});
});
As you can see calling
addWord with some string should dispatch action with
ADD_WORD type and typed
a word.
Next step was to add
src/reducers/index.js:
import { combineReducers } from "redux";
import { ADD_WORD } from "../actions/index";
export const words = (state = [], action) => {
switch (action.type) {
case ADD_WORD:
return [action.word, ...state];
default:
return state;
}
};
const rootReducer = combineReducers({ words });
export default rootReducer;
Where I have my pure function
words which is getting its own piece of state to work with. In this
case, I want my typed words to be first in a state of my application. I also added tests:
import { words } from "./index";
import { ADD_WORD } from "../actions/index";
describe("Words reducer", () => {
it("should return initial state", () => {
expect(words(undefined, {})).toEqual([]);
});
it("should handle ADD_WORD on initial state", () => {
expect(words([], { type: ADD_WORD, word: "tom" })).toEqual(["tom"]);
});
it("should handle ADD_WORD on existing state", () => {
expect(words(["tim"], { type: ADD_WORD, word: "tom" })).toEqual(["tom", "tim"]);
});
});
The last thing is to set up my store and connect it with react application. The first step is happening in
store.js:
import { createStore, compose } from "redux";
import rootReducer from "./reducers";
const store = createStore(
rootReducer,
compose(window.devToolsExtension ? window.devToolsExtension() : (f) => f)
);
export default store;
I create here my store with
rootReducer which in this case is only
words reducer and I also
added redux dev tools which help me debug my redux code.
The second step is to modify my
index.js so redux can be injected into my application:
import { Provider } from "react-redux";
import AppContainer from "./components/App/AppContainer";
import store from "./store";
const root = (
<Provider store={store}>
<AppContainer />
</Provider>
);
ReactDOM.render(root, document.getElementById("root"));
Using redux with react applications
You may notice that
Provider component is wrapping a new one -
AppContainer. This is a nice pattern
to use when using redux & react applications. It boils down to two concepts: component and container.
A component is responsible only for rendering html. A container is a way to get your data from the redux store.
That's why I created
AppContainer:
import React from "react";
import { connect } from "react-redux";
import { addWord } from "../../actions/index";
import App from "./App";
export const AppContainer = (props) => <App addWord={props.addWord} words={props.words} />;
const mapDispatchToProps = (dispatch) => ({
addWord: (word) => dispatch(addWord(word)),
});
const mapStateToProps = (state) => ({
words: state.words,
});
export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
Here I added two typical functions for react applications with redux -
mapDispatchToProps &
mapStateToProps. In the first one, I tell redux that when I call
addWord inside my
App component
it should dispatch an action from
actions/index. The second function is for extracting the data from
the store - it will be the best if my component has only access to this part of a state which it is
concerned about.
That's all for today! To recap: I've added redux to my application and used Presentational and Container Components and I have my debounced input with react & redux!
Github repo can be found here. | https://krzysztofzuraw.com/blog/2018/debouncing-forms-in-react/ | CC-MAIN-2022-21 | refinedweb | 1,376 | 50.63 |
Google Architecture
Update 2: Sorting 1 PB with MapReduce. PB is not peanut-butter-and-jelly misspelled. It's 1 petabyte or 1000 terabytes or 1,000,000 gigabytes. It took six hours and two minutes to sort 1PB (10 trillion 100-byte records) on 4,000 computers and the results were replicated thrice on 48,000 disks.
Update:?
Information Sources
- Video: Building Large Systems at Google
- Google Lab: The Google File System
- Google Lab: MapReduce: Simplified Data Processing on Large Clusters
- Google Lab: BigTable.
- Video: BigTable: A Distributed Structured Storage System.
- Google Lab: The Chubby Lock Service for Loosely-Coupled Distributed Systems.
- How Google Works by David Carr in Baseline Magazine.
- Google Lab: Interpreting the Data: Parallel Analysis with Sawzall.
- Dare Obasonjo's Notes on the scalability conference.
Platform
- Linux
- A large diversity of languages: Python, Java, C++
What's Inside?
The Stats
- Estimated 450,000 low-cost commodity servers in 2006
- In 2005 Google indexed 8 billion web pages. By now, who knows?
- Currently there over 200 GFS clusters at Google. A cluster can have 1000 or even 5000 machines. Pools of tens of thousands of machines retrieve data from GFS clusters that run as large as 5 petabytes of storage. Aggregate read/write throughput can be as high as 40 gigabytes/second across the cluster.
- Currently there are 6000 MapReduce applications at Google and hundreds of new applications are being written each month.
- BigTable scales to store billions of URLs, hundreds of terabytes of satellite imagery, and preferences for hundreds of millions of users.
The Stack
Google visualizes their infrastructure as a three layer stack:
- Products: search, advertising, email, maps, video, chat, blogger
- Distributed Systems Infrastructure: GFS, MapReduce, and BigTable.
- Computing Platforms: a bunch of machines in a bunch of different data centers
- Make sure easy for folks in the company to deploy at a low cost.
- Look at price performance data on a per application basis. Spend more money on hardware to not lose log data, but spend less on other types of data. Having said that, they don't lose data.
Reliable Storage Mechanism with GFS (Google File System)
- Reliable scalable storage is a core need of any application. GFS is their core storage platform.
- Google File System - large distributed log structured file system in which they throw in a lot of data.
- Why build it instead of using something off the shelf? Because they control everything and it's the platform that distinguishes them from everyone else. They required:
- high reliability across data centers
- scalability to thousands of network nodes
- huge read/write bandwidth requirements
- support for large blocks of data which are gigabytes in size.
- efficient distribution of operations across nodes to reduce bottlenecks
- System has master and chunk servers.
- Master servers keep metadata on the various data files. Data are stored in the file system in 64MB chunks. Clients talk to the master servers to perform metadata operations on files and to locate the chunk server that contains the needed they need on disk.
- Chunk servers store the actual data on disk. Each chunk is replicated across three different chunk servers to create redundancy in case of server crashes. Once directed by a master server, a client application retrieves files directly from chunk servers.
- A new application coming on line can use an existing GFS cluster or they can make your own. It would be interesting to understand the provisioning process they use across their data centers.
- Key is enough infrastructure to make sure people have choices for their application. GFS can be tuned to fit individual application needs.
Do Something With the Data Using MapReduce
- Now that you have a good storage system, how do you do anything with so much data? Let's say you have many TBs of data stored across a 1000 machines. Databases don't scale or cost effectively scale to those levels. That's where MapReduce comes.
- Why use MapReduce?
- Nice way to partition tasks across lots of machines.
- Handle machine failure.
- Works across different application types, like search and ads. Almost every application has map reduce type operations. You can precompute useful data, find word counts, sort TBs of data, etc.
- Computation can automatically move closer to the IO source.
- The MapReduce system has three different types of servers.
- The Master server assigns user tasks to map and reduce servers. It also tracks the state of the tasks.
- The Map servers accept user input and performs map operations on them. The results are written to intermediate files
- The Reduce servers accepts intermediate files produced by map servers and performs reduce operation on them.
- For example, you want to count the number of words in all web pages. You would feed all the pages stored on GFS into MapReduce. This would all be happening on 1000s of machines simultaneously and all the coordination, job scheduling, failure handling, and data transport would be done automatically.
- The steps look like: GFS -> Map -> Shuffle -> Reduction -> Store Results back into GFS.
- In MapReduce a map maps one view of data to another, producing a key value pair, which in our example is word and count.
- Shuffling aggregates key types.
- The reductions sums up all the key value pairs and produces the final answer.
- The Google indexing pipeline has about 20 different map reductions. A pipeline looks at data with a whole bunch of records and aggregating keys. A second map-reduce comes a long, takes that result and does something else. And so on.
- Programs can be very small. As little as 20 to 50 lines of code.
- One problem is stragglers. A straggler is a computation that is going slower than others which holds up everyone. Stragglers may happen because of slow IO (say a bad controller) or from a temporary CPU spike. The solution is to run multiple of the same computations and when one is done kill all the rest.
- Data transferred between map and reduce servers is compressed. The idea is that because servers aren't CPU bound it makes sense to spend on data compression and decompression in order to save on bandwidth and I/O.
Storing Structured Data in BigTable
- BigTable is a large scale, fault tolerant, self managing system that includes terabytes of memory and petabytes of storage. It can handle millions of reads/writes per second.
- BigTable is a distributed hash mechanism built on top of GFS. It is not a relational database. It doesn't support joins or SQL type queries.
- It provides lookup mechanism to access structured data by key. GFS stores opaque data and many applications needs has data with structure.
- Commercial databases simply don't scale to this level and they don't work across 1000s machines.
- By controlling their own low level storage system Google gets more control and leverage to improve their system. For example, if they want features that make cross data center operations easier, they can build it in.
- Machines can be added and deleted while the system is running and the whole system just works.
- Each data item is stored in a cell which can be accessed using a row key, column key, or timestamp.
- Each row is stored in one or more tablets. A tablet is a sequence of 64KB blocks in a data format called SSTable.
- BigTable has three different types of servers:
- The Master servers assign tablets to tablet servers. They track where tablets are located and redistributes tasks as needed.
- The Tablet servers process read/write requests for tablets. They split tablets when they exceed size limits (usually 100MB - 200MB). When a tablet server fails, then a 100 tablet servers each pickup 1 new tablet and the system recovers.
- The Lock servers form a distributed lock service. Operations like opening a tablet for writing, Master aribtration, and access control checking require mutual exclusion.
- A locality group can be used to physically store related bits of data together for better locality of reference.
- Tablets are cached in RAM as much as possible.
Hardware
- When you have a lot of machines how do you build them to be cost efficient and use power efficiently?
- Use ultra cheap commodity hardware and built software on top to handle their death.
- A 1,000-fold computer power increase can be had for a 33 times lower cost if you you use a failure-prone infrastructure rather than an infrastructure built on highly reliable components. You must build reliability on top of unreliability for this strategy to work.
- Linux, in-house rack design, PC class mother boards, low end storage.
- Price per wattage on performance basis isn't getting better. Have huge power and cooling issues.
- Use a mix of collocation and their own data centers.
Misc
- Push changes out quickly rather than wait for QA.
- Libraries are the predominant way of building programs.
- Some are applications are provided as services, like crawling.
- An infrastructure handles versioning of applications so they can be release without a fear of breaking things.
Future Directions for Google
- Support geo-distributed clusters.
- Create a single global namespace for all data. Currently data is segregated by cluster.
- More and better automated migration of data and computation.
- Solve consistency issues that happen when you couple wide area replication with network partitioning (e.g. keeping services up even if a cluster goes offline for maintenance or due to some sort of outage).
Lessons Learned
- Infrastructure can be a competitive advantage. It certainly is for Google. They can roll out new internet services faster, cheaper, and at scale at few others can compete with. Many companies take a completely different approach. Many companies treat infrastructure as an expense. Each group will use completely different technologies and their will be little planning and commonality of how to build systems. Google thinks of themselves as a systems engineering company, which is a very refreshing way to look at building software.
- Spanning multiple data centers is still an unsolved problem. Most websites are in one and at most two data centers. How to fully distribute a website across a set of data centers is, shall we say, tricky.
- Take a look at Hadoop if you don't have the time to rebuild all this infrastructure from scratch yourself. Hadoop is an open source implementation of many of the same ideas presented here.
- An under appreciated advantage of a platform approach is junior developers can quickly and confidently create robust applications on top of the platform. If every project needs to create the same distributed infrastructure wheel you'll.
- Build self-managing systems that work without having to take the system down. This allows you to more easily rebalance resources across servers, add more capacity dynamically, bring machines off line, and gracefully handle upgrades.
- Create a Darwinian infrastructure. Perform time consuming operation in parallel and take the winner.
- Don't ignore the Academy. Academia has a lot of good ideas that don't get translated into production environments. Most of what Google has done has prior art, just not prior large scale deployment.
- Consider compression. Compression is a good option when you have a lot of CPU to throw around and limited IO.
Reader Comments (72)
good article. really good article. really really good article. really really really good article.
Amazon has "Computing in Cloud" which can give you better price/performance at this scale.
really good article.. /SG)
Thanks for sharing these info....
Quite informative but lacks the nity grity details. I do agree to the fellow above that they only shine in search they need to pitch hard in other areas to milk :)
Awesome content. Really useful. Cheers!
thanks for sharing this info, it was very informative
Awesome post!!
I guess in a way Google has created the Google OS.
Its just a collection of servers and clusters that live in the cloud and that we can use. :-)
As a side effect of my deep studies of your article I translated it into German:
Google can afford all this structure ^)
I'm going to have to save this and re-read again later. There is quite a bit of detail here that could help explain some of G's quirks. just thinking about the massive architecture behind it all just makes my mind melt..
Exceptionnaly interesting and informative article!
I've found it a great source for cogitation about architecture of some projects I'm working on.
really good !
Perfect article, thanks. Google becomes something much more then just Search Engine
Excellent article
Where description Google LAB : GWS - Google Web Server ?
Google was just the first among searchers! for exmple whaat's the difference between or ">rapidshare search and google.com? this both sites are searching the right information! advertisement management is a really good thing!
good. thanks. :)
Quite informative but lacks the nity grity details. I do agree to the fellow above that they only shine in search they need to pitch hard in other areas to milk :)
The best article I have ever read on MapReduce architecture.
it's always interesting to know how such great company like Google works..
thank you ..
To the "what a load of crap" person. How transparent. Won't we look intelligent if we diverse from the mainstream as if we have some inside, superior knowledge about a subject? This article doesn't position Google as being the end all software company. They're a search engine and they do it well. It's about how they do it well. Geez. And if they're "not as bad as Microsoft" - ??? Microsoft employs 60,000 employees in 200 countries. How many do you employ? I get so sick of these negative, ignorant people attempting to look intelligent at the expense of someone else's work product...
Thats a nice collection of information you have gathered, all in one page. | http://highscalability.com/google-architecture | CC-MAIN-2019-18 | refinedweb | 2,300 | 66.94 |
Mutiple timers in a task node problemTal N Apr 24, 2009 9:43 AM
Hello,
I'm adding a timer on a task node, and attaching the timer to an action with an expression,
Then I'm adding another timer (with another action as an expression) to the same node,
When I'm creating an instance of the deployed process, and looking on the task node, two jobs are created in the jbpm_job table,
yet only one of them contains a value for GRAPHELEMENTTYPE_ and GRAPHELEMENT_ and the other contains nulls in both fields,
When the due date of the first has arrived, the action is executed and the job is deleted from the table as expected,
When the due date of the second arrives, it is deleted from the table yet the action not being executed,
What could be the reason for that? do I have any configuration problem or it is a bug?
I tried using the latest jbpm-jpdl snapshot, same behavior,
Many thanks,
Tal.
1. Re: Mutiple timers in a task node problemasaf sh Apr 29, 2009 11:38 AM (in response to Tal N)
Hello,
I had exactly the same problem with multiple timers in the same task node,
Is there a solution for that problem? is it a known bug?
Thanks,
Asaf.
2. Re: Mutiple timers in a task node problemRonald van Kuijk Apr 29, 2009 3:02 PM (in response to Tal N)
Guys (I think),
As stated many times before, it is better in these kinds of situations to not describe your problem, but to make a unit test with EVERYTHING embedded (processdefinition as a string, actionhandlers as innerclasses etc....) that way we can better see what you do and try to reproduce etc...
3. Re: Mutiple timers in a task node problemTal N Apr 30, 2009 8:05 AM (in response to Tal N)
Hi,
I've created an example process, one task node, two timers on it which represents two sla timers (i.e. should invoke an action that will send a reminder to the task actor if not acting on time), what happens is the same, first one is executed, second one is not, still the same differences in the database:
<?xml version="1.0" encoding="UTF-8"?>
<process-definition
example_process
<start-state
</start-state>
<task-node
<assignment actor-
<action name="action1" expression="#{wfAction.write('Action #1 invoked')}
">
<action name="Action2" expression="#{wfAction.write('Action #2 invoked')}
">
</task-node>
<end-state</end-state>
</process-definition>
***************
The WfAction class:
@Name("wfAction")
public class WfAction {
public void write(String s) {
System.out.println(s);
}
}
4. Re: Mutiple timers in a task node problemTal N May 5, 2009 9:27 AM (in response to Tal N)
Anyone tried to run the example process and know of a solution?
I'm kinda stucked here...
5. Re: Mutiple timers in a task node problemSwati S May 11, 2009 1:53 AM (in response to Tal N)
hmm.. did u put any log messages in your second timer task's action handler class? | https://developer.jboss.org/thread/118479 | CC-MAIN-2018-17 | refinedweb | 508 | 50.2 |
Let's Get it Rooling Guys.
First of all I apologies for not mentioning / referring about your idea in this thread.
Will appreciate if you start a Long Post for 287 also.
Will appreciate if you start a Long Post for 287 also.
Question 7. (1 Ans.) Which object CANNOT be retrieved from a JNDI namespace by an Application Client? A. EJBHome (stub) B. EJBLocalHome C. QueueConnectionFactory D. TopicConnectionFactory
Can you verify. I think the correct answer should be A. Even a local home you retrieve from JNDI.
Originally posted by Edy Yu: Got 93% (52 out of 56) Still can't get everything tight
Originally posted by Larry Lecomte: For Question 39. (1 Ans.) JAAS CallbackHandlers are used by what object? A. AuthPermssion B. Policy C. LoginModule D. Credential Answer should be C, because LoginModule has the initialize method with a callback handler for parameter. | http://www.coderanch.com/t/144318/po/certification/Test-LONG-POST | CC-MAIN-2014-52 | refinedweb | 146 | 59.3 |
Type: Posts; User: brad145473
simply put a class to the slideshow pictures. im assuming the pictures you are refering to are the ones you view once you click "also chair" "buttons tool" etc
this will make all pictures in the...
are you sure? it disables whatever input it is attached to, to disable submit on pressing enter key.
no i shortened the code to what was neccesary.
heres the full website
<script type="text/javascript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode;
else
key = e.which;
return (key != 13);
easy, add this to your head.
<style type="text/css">
img:hover {cursor: pointer;}
</style>
basically the script below has a form, and when the user submits, the javascript checks the value of the form and removes everything but the file name, makes a fake loading page, and then shows the... | http://www.webdeveloper.com/forum/search.php?s=7660bcc32d42faa8392e021e78cfee99&searchid=2425885 | CC-MAIN-2013-48 | refinedweb | 145 | 76.01 |
Data - Replay
The time is gone and testing a strategy against a fully formed and closed bar is good, but it could be better.
This is where Data Replay comes in to help. If:
- The strategy operates on data with a timeframe X (example: daily)
and
- Data for a smaller timeframe Y (example: 1 minute) is available
Data replay does exactly what the name implies:
- Replay a daily bar using the 1 minute data
This is of course not exactly how the market developed, but it is far better than looking at the daily fully formed and closed bar in isolation:
If the strategy operates in realtime during the formation of the daily bar, the approximation of the formation of the bar gives a chance to replicate the actual behavior of the strategy under real conditions
Putting Data Replay into action follows the regular usage patterns of
backtrader
Load a data feed
Pass the data to cerebro with
replaydata
Add a strategy
Note
Preloading is not supported when data is being replayed because each bar
is actually built in real-time. It will automatically disabled in any
Cerebro instance.
Parameters which can be passed to
replaydata:
timeframe(default: bt.TimeFrame.Days)
Destination timeframe which to be useful has to be equal or larger than the source
compression(default: 1)
Compress the selected value “n” to 1 bar
Extended parameters (do not touch if not really needed):
bar2edge(default: True)
replays using time boundaries as the target of the closed bar. For example with a “ticks -> 5 seconds” the resulting 5 seconds bars will be aligned to xx:00, xx:05, xx:10 …
adjbartime(default: False))
For the sake of working with a example the standard 2006 daily data will be replayed on a weekly basis. Which means:
There will finally be 52 bars, one for each week
Cerebro will call
prenextand
nexta total of 255 times, which is the original count of daily bars
The trick:
When a weekly bar is forming, the length (
len(self)) of the strategy will remain unchanged.
With each new week the length will increase by one
Some examples below, but first the sauce of the test script in which the data is
loaded and passed to cerebro with
replaydata … and then
run.
#)
Example - Replay Daily to Weekly
The invocation of the script:
$ ./replay-example.py --timeframe weekly --compression 1
The chart cannot unfortunately show us the real thing happening in the background, so let’s have a look at the console output:
prenext len 1 - counter 1 prenext len 1 - counter 2 prenext len 1 - counter 3 prenext len 1 - counter 4 prenext len 1 - counter 5 prenext len 2 - counter 6 ... ... prenext len 9 - counter 44 prenext len 9 - counter 45 ---next len 10 - counter 46 ---next len 10 - counter 47 ---next len 10 - counter 48 ---next len 10 - counter 49 ---next len 10 - counter 50 ---next len 11 - counter 51 ---next len 11 - counter 52 ---next len 11 - counter 53 ... ... ---next len 51 - counter 248 ---next len 51 - counter 249 ---next len 51 - counter 250 ---next len 51 - counter 251 ---next len 51 - counter 252 ---next len 52 - counter 253 ---next len 52 - counter 254 ---next len 52 - counter 255
As we see the internal
self.counter variable is keeping track of each call
to either
prenext or
next. The former being called before the applied
Simple Moving Average produces a value. The latter called when the Simple Moving
Average is producing values.
The key:
- The length (len(self)) of the strategy changes every 5 bars (5 trading days in the week)
The strategy is effectively seeing:
How the weekly bar developed in 5 shots.
This, again, doesn’t replicate the actual tick-by-tick (and not even minute, hour) development of the market, but it is better than actually seeing a bar.
The visual output is that of the weekly chart which is the final outcome the system is being tested again.
Example 2 - Daily to Daily with Compression
Of course “Replaying” can be applied to the same timeframe but with a compression.
The console:
$ ./replay-example.py --timeframe daily --compression 2 prenext len 1 - counter 1 prenext len 1 - counter 2 prenext len 2 - counter 3 prenext len 2 - counter 4 prenext len 3 - counter 5 prenext len 3 - counter 6 prenext len 4 - counter 7 ... ... ---next len 125 - counter 250 ---next len 126 - counter 251 ---next len 126 - counter 252 ---next len 127 - counter 253 ---next len 127 - counter 254 ---next len 128 - counter 255
This time we got half the bars as expected because of the factor 2 requested compression.
The chart:
Conclusion
A reconstruction of the market development is possible. Usually a smaller timeframe set of data is available and can be used to discretely replay the timeframe which the system operates on.
The test script.
from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import backtrader as bt import backtrader.feeds as btfeeds import backtrader.indicators as btind class SMAStrategy(bt.Strategy): params = ( ('period', 10), ('onlydaily', False), ) def __init__(self): self.sma = btind.SMA(self.data, period=self.p.period) def start(self): self.counter = 0 def prenext(self): self.counter += 1 print('prenext len %d - counter %d' % (len(self), self.counter)) def next(self): self.counter += 1 print('---next len %d - counter %d' % (len(self), self.counter)) def runstrat(): args = parse_args() # Create a cerebro entity cerebro = bt.Cerebro(stdstats=False) cerebro.addstrategy( SMAStrategy, # args for the strategy period=args.period, ) #') parser.add_argument('--period', default=10, required=False, type=int, help='Period to apply to indicator') return parser.parse_args() if __name__ == '__main__': runstrat() | https://www.backtrader.com/docu/data-replay/data-replay/ | CC-MAIN-2019-26 | refinedweb | 937 | 56.49 |
Greetings,
I was given the task to create a program that:
1. Lets you input grades from only 10 students.
2. Prints a report with the number of students who got A, B, C, and Ds.
I've been trying my hardest to figure it out, I think I'm onto something but I just need a little push in the right direction, specially with the part where "grade" gets saved into the memory and then it is supposed to add to the counters of the grades A, B, C, and D respectively according to what the user has input.
If you can help me a little I'll appreciate it.
Thanks in advance.
Code:
#include <stdio.h>#include <stdlib.h>
#include <conio.h>
int main()
{
//initialize variables
int grade;
int A = 0;
int B = 0;
int C = 0;
int D = 0;
int count = 0;
printf( "Enter 10 student's grades:\n");
while ( count < 10 ) {
scanf("%i", &grade);
grade = getchar();
if ( grade >= 90){
A = A + 1;
}
else if ((grade >= 80) && (grade < 90)) {
B = B + 1;
}
else if ((grade >= 70) && (grade < 80)) {
C = C + 1;
}
else ((grade >= 1) && (grade < 70)); {
D = D + 1;
}
count = count+1;
}
printf( "%i students got A\n", &A);
printf( "%i students got B\n", &B);
printf( "%i students got C\n", &C);
printf( "%i students got D\n", &D);
return 0;
} | https://cboard.cprogramming.com/c-programming/150677-input-student-grades-report-sharp-students-b-c-d-printable-thread.html | CC-MAIN-2017-13 | refinedweb | 225 | 73.21 |
LOGIN_TIMES(3) BSD Library Functions Manual LOGIN_TIMES(3) NAME
parse_lt, in_lt, in_ltm, in_ltms, in_lts -- functions for parsing and checking login time periods LIBRARY
System Utilities Library (libutil, -lutil) SYNOPSIS
#include <sys/types.h> #include <time.h> #include <login_cap.h> login_time_t parse_lt(const char *str); int in_lt(const login_time_t *lt, time_t *ends); int in_ltm(const login_time_t *lt, struct tm *t, time_t *ends); int in_ltms(const login_time_t *lt, struct tm *t, time_t *ends); int in_lts(const login_time_t *lt, time_t *ends); DESCRIPTION
This set of functions may be used for parsing and checking login and session times against a predefined list of allowed login times as used in login.conf(5). The format of allowed and disallowed session times specified in the times.allow and times.deny capability fields in a login class are com- prised of a prefix which specifies one or more 2- or 3-character day codes, followed by a start and end time in 24 hour format separated by a hyphen. Day codes may be concatenated together to select specific days, or the special mnemonics "Any" and "All" (for any/all days of the week), "Wk" for any day of the week (excluding Saturdays and Sundays) and "Wd" for any weekend day may be used. For example, the following time period: MoThFrSa1400-2200 is interpreted as Monday, Thursday through Saturday between the hours of 2pm and 10pm. Wd0600-1800 means Saturday and Sunday, between the hours of 6am through 6pm, and Any0400-1600 means any day of the week, between 4am and 4pm. Note that all time periods reference system local time. The parse_lt() function converts the ASCII representation of a time period into a structure of type login_time_t. This is defined as: typedef struct login_time { u_short lt_start; /* Start time */ u_short lt_end; /* End time */ u_char lt_dow; /* Days of week */ } login_time_t; The lt_start and lt_end fields contain the number of minutes past midnight at which the described period begins and ends. The lt_dow field is a bit field, containing one bit for each day of the week and one bit unused. A series LTM_* macros may be used for testing bits individu- ally and in combination. If no bits are set in this field - i.e., it contains the value LTM_NONE - then the entire period is assumed invalid. This is used as a convention to mark the termination of an array of login_time_t values. If parse_lt() returns a login_time_t with lt_dow equal to LTM_NONE then a parsing error was encountered. The remaining functions provide the ability to test a given time_t or struct tm value against a specific time period or array of time peri- ods. The in_ltm() function determines whether the given time described by the struct tm passed as the second parameter falls within the period described by the first parameter. A boolean value is returned, indicating whether or not the time specified falls within the period. If the time does fall within the time period, and the third parameter to the function is not NULL, the time at which the period ends relative to the time passed is returned. The in_ltms() function is similar to in_ltm() except that the first parameter must be a pointer to an array of login_time_t objects, which is up to LC_MAXTIMES (64) elements in length, and terminated by an element with its lt_dow field set to LTM_NONE. The in_lt() and in_lts() functions are equivalent to in_ltm() and in_ltms(), respectively, with the second argument set to the current time as returned by localtime(3). RETURN VALUES
The parse_lt() function returns a filled in structure of type login_time_t containing the parsed time period. If a parsing error occurs, the lt_dow field is set to LTM_NONE (i.e., 0). The in_ltm() function returns non-zero if the given time falls within the period described by the login_time_t passed as the first parameter. The in_ltms() function returns the index of the first time period found in which the given time falls, or -1 if none of them apply. SEE ALSO
getcap(3), login_cap(3), login_class(3), login.conf(5), termcap(5) BSD
October 20, 2008 BSD | https://www.unix.com/man-page/freebsd/3/in_ltm/ | CC-MAIN-2019-47 | refinedweb | 680 | 58.62 |
MSP is the minimum cost price of a crop at which government agency FCI procures the crop from farmers. MSP is only given on wheat and rice, however it is declared for all 23 crops.
For the analysis we will only consider MSP of wheat and the farmers of Punjab because Punjab and Haryana farmers are main beneficiaries of MSP.
No, govt is not doing any extra favor to farmers of Punjab, MSP was started only for green revolution states and MSP was one way to encourage farmers to grow more wheat when India used to take wheat in donation…
We started with IPL analysis in the first part. Now we can build up from there and move ahead to delve deeper into the batsman stats.
While we can analyze all batsmen using the same code, I will pick V. Kohli as a batsman to analyze.
In the Sukma district of Chattisgarh state, 22 Indian soldiers were ambushed by PLGA. According to reports, Maoists were trying to disrupt a road construction near Silger-Jagargunda, Sukma district. The road jeopardizes their existence. The attack was lead by PLGA chief Madvi Hidma.
I wanted to analyze terrorism trends in India over the last 5 decades. So I have downloaded the global terrorism data(1972–2017) from Kaggle.
Let us start by importing the CSV data to a data frame and display the top 5 records.
import pyforest
terror_data=pd.read_csv("terror.csv")
terror_data.head()
April is a festive time in India. IPL will kick off in less than a week, Being an avid IPL follower and Dream11 player, I wanted to analyze some of the historic data of IPL available on the internet.
This will be an introductory analysis and we will look into the basic IPL stats. Building up from here, in the next parts, we will find our best fit for the Dream11 team and win a lot of money.
Ever since Indian PM’s visit was announced, protests started in Bangladesh. Bangladesh parliament alleged that Pakistan was fuelling protests in Bangladesh by funding radical groups. Protests eventually turned violent when PM reached Bangladesh. More than 15 people have died in police firing, and 100s injured. Indian media has not covered it and Indians have no idea what’s happening. Most Indians think that India and Bangladesh are best friends.
I saw a lot of activity on social media therefore decided to track what’s happening. I downloaded Tweets with 2 hashtags “#WHATSHAPPENINGBANGLADESH” first and “#BANGLADESHREJECTMODI” later. …
We have a Sunday morning and I have no idea how to waste my day, I should probably Netflix and chill. I’m not sure which one to watch, usually, I watch the first 5 minutes of the movie/series and then decide whether to continue or not. My conversion rate is below 5%. So I have decided to use the Kaggle Netflix dataset, analyze it and build a recommender system to find a movie suitable for me. Click here to download the Netflix dataset from Kaggle.
I have downloaded the Dataset and I will start analyzing the dataset. …
Last night I was startled when I learned that 10 people were killed in what was another shooting incident in the USA. It was 2nd deadly shooting within a week. The world has hardly moved on from the brutal killing of 8 Asian workers in Atlanta. I opened my Twitter and read this,
Looking at the vaccine hesitancy which is prevalent in all parts of the world, I wanted to study the conspiracy theories floating around. what better place than Reddit to find the data.
Download the data from here.
This article will be mostly code, I am trying to cover the most important libraries required for text data analysis and this code as it is can be used for multiple text-related analysis.
My major motivation for the analysis is to find out the common conspiracy theories used by Anti-Vaxxers so as to raise some awareness. …
I had a discussion with my friends regarding Covid 2nd wave, we were discussing if age limits set by govt should be removed or not. I learned that a lot of vaccines are getting wasted and people are not showing up at hospitals. With the 2nd wave impending upon us, we all agreed we need to mass vaccinate.
I decided to look up how states are doing with vaccination in India. I downloaded statewide data from the Ministry of Health, India website.
I will be using Tableau for the visualization.
The darker states are reeling behind in the vaccination drive…
A few days Back 14-year-old was beaten for allegedly entering into temple and drinking water. The perpetrator was rightly arrested immediately however, what followed on Twitter was disturbing which included a barrage of hateful hashtags against 14-year-old Asif and support for Yadav who was seen beating 14 years old in the video. So I decided to see who were the people behind this.
If you are not interested in the coding you can go straight to visualization part at the bottom, section 1.2 and see the analysis. However, if you are a data enthusiast you can stay.
I downloaded the…
Geopolitics and Data Science enthusiast. | https://anmolcrazy2.medium.com/?source=post_internal_links---------1---------------------------- | CC-MAIN-2021-17 | refinedweb | 874 | 63.9 |
The QgsFieldComboBox is a combo box which displays the list of fields of a given layer. More...
#include <qgsfieldcombobox.h>
The QgsFieldComboBox is a combo box which displays the list of fields of a given layer.
It might be combined with a QgsMapLayerComboBox to automatically update fields according to a chosen layer. If expression must be used, QgsFieldExpressionWidget shall be used instead.
Definition at line 38 of file qgsfieldcombobox.h.
QgsFieldComboBox creates a combo box to display the fields of a layer.
The layer can be either manually given or dynamically set by connecting the signal QgsMapLayerComboBox::layerChanged to the slot setLayer.
Definition at line 22 of file qgsfieldcombobox.cpp.
Returns
true if the combo box allows the empty field ("not set") choice.
Definition at line 41 of file qgsfieldcombobox.cpp.
Returns the currently selected field.
Definition at line 92 of file qgsfieldcombobox.cpp.
Emitted when the currently selected field changes.
Returns the fields currently shown in the combobox.
This will either be fields from the associated layer() or the fields manually set by a call to setFields().
Definition at line 62 of file qgsfieldcombobox.cpp.
currently used filter on list of fields
Definition at line 56 of file qgsfieldcombobox.h.
Definition at line 106 of file qgsfieldcombobox.cpp.
Returns the layer currently associated with the combobox.
Definition at line 52 of file qgsfieldcombobox.cpp.
Sets whether an optional empty field ("not set") option is shown in the combo box.
Definition at line 36 of file qgsfieldcombobox.cpp.
setField sets the currently selected field
Definition at line 67 of file qgsfieldcombobox.cpp.
Manually sets the fields to use for the combo box.
This method should only be used when the combo box ISN'T associated with a layer() and needs to show the fields from an arbitrary field collection instead. Calling setFields() will automatically clear any existing layer().
Definition at line 57 of file qgsfieldcombobox.cpp.
setFilters allows filtering according to the type of field
Definition at line 31 of file qgsfieldcombobox.cpp.
Sets the layer for which fields are listed in the combobox.
If no layer is set or a non-vector layer is set then the combobox will be empty.
Definition at line 46 of file qgsfieldcombobox.cpp. | https://api.qgis.org/api/classQgsFieldComboBox.html | CC-MAIN-2022-33 | refinedweb | 370 | 51.44 |
add Userdata - incorrect
On 04/05/2015 at 22:08, xxxxxxxx wrote:
Hello,
I try to add User Data by getting from one Object and add them to an other.
This Code run without error - but I need to open the User Data Manager to see the User Data in my Object.
newuserdata = None if fix != None: for id, bc in fix.GetUserDataContainer() : if id == foundid: newuserdata = bc if newuserdata != None: node = c4d.BaseObject(1030625) node.SetName(newuserdata[c4d.DESC_NAME]) node.InsertUnder(opc) doc.AddUndo(c4d.UNDOTYPE_NEW,node) newud = node.AddUserData(newuserdata) node[newud] = fix[foundid] c4d.EventAdd()
On 06/05/2015 at 02:17, xxxxxxxx wrote:
Hi,
You can simply call c4d.gui.ActiveObjectManager_SetObject() with ACTIVEOBJECTMODE_OBJECT flag, the object and its new user data ID (pass 0 for flags parameter).
On 06/05/2015 at 02:56, xxxxxxxx wrote:
Hi Yannick,
that not solve the problem - the user data is still not visible until i click into the user data manager
Thanks
On 06/05/2015 at 07:54, xxxxxxxx wrote:
Hi,
ActiveObjectManager_SetObject() should show the Object+User Data tabs in the attribute manager.
Are you sure it is called with the complete added user data ID? A user data ID has a first level of ID ID_USERDATA then a second level with the ID beginning at 1.
On 06/05/2015 at 15:53, xxxxxxxx wrote:
i tried this
newud = node.AddUserData(newuserdata) node[newud] = fix[foundid] c4d.gui.ActiveObjectManager_SetObject(c4d.ACTIVEOBJECTMODE_OBJECT,node,0,newud)
On 06/05/2015 at 23:04, xxxxxxxx wrote:
It seems ActiveObjectManager_SetObject() doesn't work well with child objects. You can simply call doc.SetActiveObject(node) instead.
On 07/05/2015 at 02:20, xxxxxxxx wrote:
Hi Yannick,
doc.SetActiveObject(node) will select the object but it don`t change anything to the user data - I need to open the User Data Manager to see the User Data in my Object.
On 07/05/2015 at 02:30, xxxxxxxx wrote:
Sorry, I had not read well your first post. I'm afraid there's no way to open the Manage User Data dialog.
On 07/05/2015 at 02:42, xxxxxxxx wrote:
There is no need if the user data will show up by adding them :)
On 07/05/2015 at 07:39, xxxxxxxx wrote:
Hi guys,
I was interested in this task, that´s why I decided to take part...
With this snippet you can port multiple userdata and it works as expected.
The if clause with the desc id depends on you, for sure.
One question; what kind of object is this : node = c4d.BaseObject(1030625) ?
import c4d from c4d import gui def main() : newUserData = [] if op != None: userData = op.GetUserDataContainer() if userData!=[]: for i in xrange(len(userData)) : desc_id = userData[i][0] if desc_id: con = userData[i][1] print i,desc_id,con newUserData.append((desc_id,con)) if newUserData != None: node = c4d.BaseObject(c4d.Onull) node.InsertUnder(op) doc.AddUndo(c4d.UNDOTYPE_NEW,node) for i in xrange(len(newUserData)) : newud = node.AddUserData(newUserData[i][1]) node[newud] = op[newUserData[i][0]] c4d.EventAdd() doc.SetActiveObject(node)
Best wishes
Martin
On 14/05/2015 at 08:21, xxxxxxxx wrote:
Hey Martin,
thanks for the code - but even with that I see the same behavior - only after opening the user data dialog - i see the user data.
may the problem is not in this code - its in the object - the 1030625 is an own object.
On 14/05/2015 at 11:13, xxxxxxxx wrote:
Hello,
I'm a ghost without internet access and will not be able to reply back to you.
But there's a common problem with adding User Data that isn't documented.
If you create your UD gizmo. And it doesn't show up right way in the AM.
Try usng this code at the end to force the AM to redraw itself. And show the new UD you added:
c4d.SendCoreMessage(c4d.COREMSG_CINEMA, c4d.BaseContainer(c4d.COREMSG_CINEMA_FORCE_AM_UPDATE))
-The Ghost | https://plugincafe.maxon.net/topic/8695/11383_add-userdata--incorrect | CC-MAIN-2020-16 | refinedweb | 661 | 58.48 |
Recent:
Archives:
RMIClassLoadersucceeded with Java 1.0 applets but failed with Java 1.1 programs.
For his "Java In Depth" column in the October '96 issue of JavaWorld, Chuck McManis discussed in "The basics of Java class loaders." Based on that column, this Java Tip demonstrates how to successfully use the Java 1.1 class loader and goes a lot further.
Let's first examine our requirements for a class loader. We'd like one that:
testing or simulating an Internet server on a client.
The most flexible approach to the above requirements is these three classes:
public abstract class MultiClassLoader extends ClassLoader public class URLClassLoader extends MultiClassLoader public class FileClassLoader extends MultiClassLoader
This allows the type of class loader to be determined at runtime and the rest of the application is unaffected.
Hmmmm, fulfilling the above requirements doesn't sound too hard. Let's start with a "Use Case," namely a code example of how
we'll use
MultiClassLoader. This is best done by designing our test class, called
TestLoader. Now, let's write the TestLoader unit test class. This shows how to set the class loader type at runtime, and then uses it
in a variety of ways to illustrate how to use a class loader effectively. Here is the source code for
TestLoader.java.
Let's examine the heart of the test code:
// Init the preferred class loader MultiClassLoader loader = null; if (args.length == 0) { String root = ""; loader = new URLClassLoader(root); } else { loader = new FileClassLoader("store\\"); } loader.setClassNameReplacementChar('_'); // A series of tests: Class testClass = null; try { testClass = loader.loadClass("Hello"); } catch(Exception ex) { print("Load failed"); ex.printStackTrace(); return; } print("Loaded class " + testClass.getName() ); try { Runnable hello = (Runnable)testClass.newInstance(); hello.run(); } catch(Exception ex) { print("Failed to instantiate"); ex.printStackTrace(); }
Good tests are understandable and short. The test first creates an instance of class loader called "loader". Then it uses an optional feature to translate periods to "_".
Next we decide whether to load from the Internet or from a local file, depending on whether any command-line argument was
entered. Note that you will need to set the root or
filePrefix to whatever source URL you're using as a base. We have subclassed
MultiClassLoader, providing a clean way to provide different specific class sources. | http://www.javaworld.com/javaworld/javatips/jw-javatip39.html | crawl-002 | refinedweb | 381 | 58.28 |
This is part
None of the existing JSON libraries can serialize F# unions in a way that is easy to use in TypeScript. Therefore, we changed the library Thoth so that the serialized JSON matches our needs.
Why Thoth?
We used Thoth as a starting point because it is a JSON serialization/deserialization library written in F# for F#. It handles F# records and unions out of the box – just not exactly how we need it so that it is easy to use together with TypeScript.
The problem is how discriminated unions are serialized. Normally, a discriminated union like
type DU = A of int | B of string*int is serialized like
["B","hello",17]. An array containing the case as the first element, followed by the values for the case fields. As we have seen in the post about how we generate TypeScript types, we generate a type for
DU that looks like this:
export type DU = { "A"?: number "B"?: [string, number] };
That means, we need a JSON that looks like this:
{"B":["the answer",42]}. An object containing the case as a property and the values in an array.
There are some other things we changed as well. They are explained below when I show all the changes that we made to the code. Please note that Thoth’s code on Github has changed a bit in the meantime.
To achieve our desired behaviour, we copied the source code of Thoth and made the following changes.
Changes to record encoding
In the function
autoEncodeRecordsAndUnions we changed the handling of records from original to
if FSharpType.IsRecord(t, allowAccessToPrivateRepresentation=true) then let setters = FSharpType.GetRecordFields(t, allowAccessToPrivateRepresentation=true) |> Array.map (fun fi -> let targetKey = Util.Casing.convert caseStrategy fi.Name let encoder = autoEncoder extra caseStrategy skipNullField fi.PropertyType fun (source: obj) (target: JObject) -> let value = FSharpValue.GetRecordField(source, fi) if not skipNullField || (skipNullField && not (isNull value)) then // Discard null fields target.[targetKey] <- encoder.Encode value target) boxEncoder(fun (source: obj) -> //--> changed let getInitialJObject () = let cutGenericType typeName = let index = typeName |> FSharpx.String.indexOfChar '`' if index > 0 then typeName |> FSharpx.String.substring' 0 index else typeName let o = JObject() o.["$type"] <- JValue.CreateString(cutGenericType t.Name) o (getInitialJObject (), setters) ||> Seq.fold (fun target set -> set source target) :> JsonValue) //--> end changed
Line 13-26: We add a property named
$type for every record that holds the name of the type (without generic type parts, if any). We need that for records that implement interfaces to have a discriminator to be used in a switch statement in TypeScript.
A record like
type R = { A : int } is serialized as
{"$type":"R","a":42}.
It is simpler to do that for all records, not just the ones that actually implement an interface.
Changes to discriminated union encoding
We changed the original to this:
elif FSharpType.IsUnion(t, allowAccessToPrivateRepresentation=true) then boxEncoder(fun (value: obj) -> //--> changed let unionCasesInfo = FSharpType.GetUnionCases(t, allowAccessToPrivateRepresentation = true) let info, fields = FSharpValue.GetUnionFields(value, t, allowAccessToPrivateRepresentation=true) let isEnumDU = unionCasesInfo |> Seq.forall (fun x -> x.GetFields().Length = 0) if isEnumDU then string info.Name else match unionCasesInfo.Length with | 1 -> match fields.Length with | 0 -> string info.Name | 1 -> let fieldTypes = info.GetFields() let encoder = autoEncoder extra caseStrategy skipNullField fieldTypes.[0].PropertyType encoder.Encode(fields.[0]) | len -> let fieldTypes = info.GetFields() let target = Array.zeroCreate<JsonValue> len for i = 0 to len-1 do let encoder = autoEncoder extra caseStrategy skipNullField fieldTypes.[i].PropertyType target.[i] <- encoder.Encode(fields.[i]) array target | _ -> match fields.Length with | 0 -> let typeName = info.Name let result = JObject() result.Add(typeName, (bool true)) result :> JsonValue | length -> let result = let fieldTypeInfos = info.GetFields() if fields.Length = 1 then // wert let fieldInfo = fieldTypeInfos.[0] let field = fields.[0] let fieldEncoder = autoEncoder extra caseStrategy skipNullField fieldInfo.PropertyType fieldEncoder.Encode field else // array let result = JArray() for i in 0..(length-1) do let fieldInfo = fieldTypeInfos.[i] let field = fields.[i] let fieldEncoder = autoEncoder extra caseStrategy skipNullField fieldInfo.PropertyType let fieldValue = fieldEncoder.Encode field result.Add(fieldValue) result :> JsonValue let wrapper = JObject() wrapper.Add(info.Name, result) wrapper :> JsonValue) //--> end changed
Line 4, 5: We get all cases of this union and their fields.
Line 7-13: We check whether it is a DU that is used as a “simple” enum. If so, we just write the case name to JSON.
Line 15: Depending on the number of cases, we deal differently with this DU. Single case DUs are handled specially. If a case is later added to this DU, then we would serialize it differently. This is, however, not a problem for us because the JSON we generate with this pimped Thoth version is never persisted. For persisted JSON, we use the normal version of Thoth.
Line 18: A single case DU without a field is serialized by writing the case’s name. E.g.
type A = A results in
A.
Line 20: A single case DU with a single field is serialized by encoding the field’s value. The DU itself is erased. E.g.
type A = A of int result in
42.
Line 24: A single case DU with multiple fields is serialized by putting all the serialized fields’ values into an array. E.g.
type A = A of int*string results in
[42,"hello"].
Line 33: For a value of a multi-case DU without any fields like
A in
type D = A | B of int, we create an object with a property
A of type
bool. The
bool is irrelevant, but this is a way to match the type that we generate for such a DU:
export type D = { A?: bool; B?:int }. We just don’t want to use
null or
0 because that could lead to trouble when comparing with
== in TypeScript. And it’s a nicer JSON 😉
Line 39: Here we handle a multi case DU and the value has at least one field. If there is only one field then we serialize that, otherwise we serialize all the fields and put them into an array.
Line 60: We put the serialized values for the content of the DU into an object with the case name as a property. If we have for example the following types:
type R = { A : int } type DU = A of R | B
And we serialize the value
let value = DU.A { A = 42 }, we get
{"A":{"$type":"R","a":42}}. And that matches our generated TypeScript type.
Changes to record deserialization
We didn’t have to change anything in record deserialization.
Changes to discriminated union deserialization
We changed the original to this:
Changes to elif FSharpType.IsUnion(t, allowAccessToPrivateRepresentation=true) then boxDecoder(fun path (value: JsonValue) -> //--> added let unionCasesInfo = FSharpType.GetUnionCases(t, allowAccessToPrivateRepresentation = true) match unionCasesInfo.Length with | 1 -> let unionCaseInfo = unionCasesInfo.[0] let fields = unionCaseInfo.GetFields() match fields.Length with | 0 -> let name = unionCaseInfo.Name makeUnion extra caseStrategy t name path [||] | 1 -> let name = unionCaseInfo.Name makeUnion extra caseStrategy t name path [| value |] | _ -> let jsons = value.AsJEnumerable() let values = fields |> Seq.zip jsons |> Seq.map (fun (v, p) -> let decoder = autoDecoder extra caseStrategy false p.PropertyType decoder.Decode (path, v)) |> Seq.toList |> FsToolkit.ErrorHandling.List.sequenceResultM values |> Result.map(fun v -> FSharpValue.MakeUnion(unionCaseInfo, v |> List.toArray, allowAccessToPrivateRepresentation = true)) //--> added ended (including the following | _ -> | _ -> if Helpers.isString(value) then let name = Helpers.asString value makeUnion extra caseStrategy t name path [||] elif Helpers.isArray(value) then let values = Helpers.asArray value let name = Helpers.asString values.[0] makeUnion extra caseStrategy t name path values.[1..] //--> added elif Helpers.isObject(value) then let dict = value.Value<JObject>() :> System.Collections.Generic.IDictionary<string, JToken> let uciOption = unionCasesInfo |> Array.tryFind (fun uci -> dict.ContainsKey uci.Name) match uciOption with | Some uci -> let content = dict.[uci.Name] if Helpers.isBool content then makeUnion extra caseStrategy uci.DeclaringType uci.Name path [||] else if Helpers.isArray content then let contentArray = Helpers.asArray content makeUnion extra caseStrategy uci.DeclaringType uci.Name path contentArray else makeUnion extra caseStrategy uci.DeclaringType uci.Name path [| content |] | None -> ("", BadPrimitive("Type not found in Union Cases", value)) |> Error //--> added end else (path, BadPrimitive("a string or array", value)) |> Error)record deserialization
We check the same cases as when encoding. Then we inverse the process. I think most is self-explanatory at this stage. Just some quick hints:
Line 19-28: We decode the values from they array and if there is an error we stop.
Line 43: We deserialize the
JObject and try to find the corresponding union case. Remember that the
bool property is a trick for cases without any fields.
The rest
The rest of Thoth’s code is unchanged. We only put it into a different namespace so that we can use this pimped version for serialization and deserialization when we send data to the client or receive data from the client; and the normal version for all cases when we want to persist JSON. As already written above, the pimped version cannot be used in cases when the JSON is persisted because when a discriminated unions is changed from being single case to multi case, the JSON cannot be deserialized anymore. The normal version of Thoth can handle that because the JSON does not handle single case DUs in a special way.
So now that we can serialize and deserialize F# records and discriminated unions in a way that matches out generated TypeScript types, it is time to show you, how we test that our types are serialized correctly. Stay tuned for the next post.
This blog post is made possible with the support of Time Rocket, the product this blog post is about. Take a look (German only).
[…] TypeScript-friendly JSON serialization of F# types […]
[…] TypeScript-friendly JSON serialization of F# types […]
[…] code on the client-side. I wrote about our approach to get type-safety across .Net and TypeScript here. So we got that working. But one problem remained, how to serialize a mix of C# and F# classes with […]
[…] TypeScript-friendly JSON serialization of F# types […] | https://www.planetgeek.ch/2021/04/07/type-safety-across-net-and-typescript-typescript-friendly-json-serialization-of-f-types/ | CC-MAIN-2021-43 | refinedweb | 1,667 | 51.85 |
DataAccessErrorType
Since: BlackBerry 10.0.0
#include <bb/data/DataAccessErrorType>
To link against this class, add the following line to your .pro file: LIBS += -lbbdata
Represents types of data access errors.
The DataAccessErrorType class enumerates the types of data access errors that can occur during a data load or save operation.
Classes which use this include DataAccessError and DataAccessReply.
Overview
Public Types Index
Public Types
Represents types of data access errors.
BlackBerry 10.0.0
- None 0
No error occurred.
- SourceNotFound 1
The source url or file was not defined, was not found or (for databases) could not be created.
- ConnectionFailure 2
An error occurred with a remote connection or connecting to an existing database.
- OperationFailure 3
An error occurred performing the data operation.
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/cascades/bb__data__dataaccesserrortype.html | CC-MAIN-2019-35 | refinedweb | 140 | 52.66 |
If Java was a Haskell - The Type System
In my previous article If Java was a Haskell I tried to explain the pure functional paradigm offered by Haskell through the words of a Java developer. In this post I will focus on the other strength of Haskell, a strong type system.
Types
What would a Java Class become in the Haskell world?
In my previous post, we ended with static methods working against immutable data structures. In this context, there is no room for Objects as Java developers know them. The first thing which appears clearly is that these static methods are not tied to the data structure they work on. So they don’t need to be in a class. They only need some sort of namespace, a file to keep our code organized. So imagine you can create a method directly at the root of a file. Is there anything left to make a class? Yes, the data. That’s why Haskell uses the keyword data instead of class.
Since the data structures are immutable, they need to be initialized with constructors. Here is an example of a basic class:
class Animal { String name; Color color; Animal(String name, Color color) { this.name = name; this.color = color; } String getName() { return name; } Color getColor() { return color; } }
Oops … a problem with the getters above is that they’re instance methods. There is not such thing in a functional language. That’s easy to fix, by extracting these methods from the class and making them static like we discussed in the previous article:
class Animal { String name; Color color; Animal(String name, Color color) { this.name = name; this.color = color; } } String getName(Animal a) { return a.name; } Color getColor(Animal a) { return a.color; }
A lot of boilerplate can be removed. When you have named parameters, all the information you may need about an object is available in the constructor. So the language can leverage that and our class becomes simply:
class Animal { Animal(String name, Color color); }The parameter names are used by the compiler to generate the “getters” functions. This type of constructor is called record syntax in Haskell. Here is an example of how it could be used in a function which tells us if an animal is dangerous:
boolean isDangerous(Animal a) { if (getColor(a) == Color.PINK) { return false; } return true; }
There can be many constructors with different parameters, but also, and that’s a bit more surprising, different names. In Java, we can’t have 2 constructors with the same number and type of parameters, only because they must have the same name. When you remove this limitation, you can do something like:
class Animal { Cat(String name, Color color); Dog(String name, Color color); }
The name of the constructor used is a bit like an additional field, used as a discriminator. With a little bit of destructuring, we can use this information. Here is a method which makes an animal speak its language:
String speak(Animal a) { switch a { case (Cat name _) : return name + " says Miaow!"; case (Dog name _) : return name + " says Woof!"; } }
Notice how destructuring also gives us the field name, so we don’t need to access the generated getter. We use “_” for the color parameter which means we don’t care about it. For a simple class like Animal, we don’t even need to give names to the constructor parameters, we will not have getters but that’s fine thanks to destructuring. So we can simplify Animal into:
class Animal { Cat(String, Color); Dog(String, Color); }
In Haskell, the signature of the function is separated from the implementation which brings the benefit of having multiple implementations driven by pattern matching. That removes completely the need of the boilerplate switch statement. While we’re at removing boilerplate, the return statement can go too, the last statement is automatically returned. Our speak function becomes:
String speak(Animal a) speak(Cat name _) { name + " says Miaow!" } speak(Dog name _) { name + " says Woof!" }
One last note on types. What happens when the constructors of a class don’t have any parameter? We obtain something very familiar to Java developers: enums. But we don’t need a different name for it, they’re just classes. We can even mix enum constants and parameterized constructors. For instance the class Color could have
Pink and
Color(int int int) as constructors.
Interfaces (Typeclasses)
When types are not used to define behaviors, the concept of inheritance goes away. However polymorphism is still useful and is provided in Haskell by typeclasses, which is something similar to Java interfaces, except it defines a set of functions which can be applied to a data structure. Let’s keep the keyword interface, here is an example:
interface Showable { String toString(Showable s); }
Then, for each concrete type implementing this interface, you define the desired behavior:
class Animal { Cat(String, Color); Dog(String, Color); } Animal implements Showable { String toString(Animal a) { speak(a); // see function speak above } }
After this, any function requiring a Showable argument can be called with an Animal.
Type Inference
Once we have data types and interfaces, we should be able to rely on the language to deduce the type of variables as much as possible. This is an area where Haskell shines while Java clearly sucks. Here is a trivial example:
myCat = Cat("Puss", ORANGE); message = speak(myCat);
There is no need to say that myCat is of type Animal, the compiler already knows that Cat is a constructor for Animal. The compiler also infers that message is of type String because that’s what the function speak returns.
The joy of type inference becomes more obvious with higher-order functions. For instance, imagine we have a list of Animal named myPets and we want to transform this list into a list ofString containing the names of the animals. In Java, using Guava collections API, we get the following:
List<String> names = transform(myPets, new Function<Animal, String>() { @Override public String apply(Animal a) { return a.getName(); } });
In the Haskellized version, we can do:
names = transform(getName, myPets);
That’s it! The compiler knows that myPets is a list of Animal and that map transforms a list into another list by applying the given function to all the elements. If we pass a function that doesn’t take an animal as argument, the compiler will complain. When passing getName, not only the compiler doesn’t complain, it also deduces that the output will be a list of String.
The Java version needed 3 String, 2 Animal and 1 List. Type inference allowed the haskellized version to get rid of these 6 declarations without losing any type safety.
Some special types
Haskell offers a few standard types which are made special by syntactic sugars. Just like any language, there is of course the support for boolean, character and various numbers. More interesting and worth mentioning are:
- List which is much closer to Java array than Java list and can be defined with square brackets syntax like [1, 2, 3]. A list can even be infinite since it is evaluated lazily (like everything in Haskell). For instance an infinite list of even numbers can be defined as [2, 4, ..].
- String which is simply a list of characters, so “hello” is the same as ['h', 'e', 'l', 'l', 'o']
- Tuple which is a special small list containing values of different types. It’s basically a container for simple data structure which are not worth creating a type. An example would be (42, “Mo”, “Molybdenum”)
A very special interface: Monad
Monads are not specific to Haskell, there is even a monad implementation in Java. However monads are one of Haskell most famous signatures because Haskell offers syntactic sugar that makes them natural to use, it’s called the “do” notation.
A monad is a typeclass (interface in our world). It basically defines a container which can hold a value and be chained with other containers of the same type according to a specified mechanism. To make something useful with this, we don’t chain directly those containers but computations which return them.
A typical example of a monads is the Maybe monad, which can contain either a value or nothing. The Maybe container is parameterized and has 2 constructors. In our haskellized Java, a Maybe ofString would be:
class Maybe<String> { Just(String); Nothing; }
The chaining mechanism for Maybe ensures that an input of nothing always yields an output of nothing. In other words, as soon as a nothing happens somewhere in the chain, the output of the chain is nothing.
When the language is not designed for monads, this mechanism gets very clunky. But with the do notation, the invocations of the chaining method are generated by the compiler, making the whole thing feel a bit magical.
// utility function which returns a Maybe Maybe<String> changeSex(String sex) { switch sex { case "XX" : Just("XY"); case "XY" : Just("XX"); default: Nothing } } changeSexFiveTimes() { do { s1 <- changeSex("ZY"); // the "<-" is used to extract the value // from a monad (we say bind) // but oops ... bad input yields Nothing s2 <- changeSex(s1); // this method is not called because the // chaining mechanism of Maybe yields Nothing s3 <- changeSex(s2); // this one is skipped too s4 <- changeSex(s3); // and so is this one changeSex(s4); // returns Nothing as the result of the whole block } }
The magical chaining behavior is defined in the Maybe class. Type inference is used by the compiler to guess what type of chaining mechanism to apply (i.e. the first value is a Maybe so the compiler knows the chaining of Maybe applies).
There is a lot more to say about monads, and a lot of literature on the web. Let’s just mention that Haskell uses monads for things which would otherwise be impossible in a pure functional world, namely I/O and state management.
Conclusion
Those two articles were scratching the surface of Haskell with the eyes and the words of a Java developer. If you know nothing about Haskell, I hope I was able to whet your appetite and I recommend you take a look at Learn You a Haskell for Great Good to discover the wonders this other world has to offer.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) | http://java.dzone.com/articles/if-java-was-haskell-type | CC-MAIN-2013-48 | refinedweb | 1,736 | 60.95 |
Expressions
The most common expressions in Python are numerical, string and boolean. All of them are considered as data items or d-item. For example, this is a numerical expression:
1
or another more complex math expression should be like this:
1/2+10-500*4
Apart from numerical expression, there are also string expressions:
Hello world
the same stands for concatenation strings, like:
"H" + "e" + "l" + "l" + "o" + " world"
and of course another type of expression might be the boolean expression (derived from Boolean algebra, true/false situations), like:
20>30
that returns a false value for example.
Statements and Variables
There are many kinds of statements, like assignments, for-loops, if statements etc. Now let’s start with assignment statements (and thus introduce variables in the same way).
number = 1
In this example, I am putting the numerical value 1 into a variable called number. The data type of this variable is probably integer.
There is no need to provide a data type for a variable because Python automatically assigns data types based on the values that are assigned into them.
So, here’s another one
number = "one"
Now, I am assigning a string into a variable called number. The data type of this variable is probably string. So, you can see that variables in Python are very flexible. Just assign a value into them and that’s it. Also, you can combine expressions, statements and variables, like this:
num1 = 1 num2 = 2 result = num1 + num2
num1 has the value 1 and num2 has the value 2, so if you add them together you’ll get 3 value which is stored into result variable.
Working with numbers
There are several types of numbers you can work within Python. The most common is the integer numbers
300
or the floating-point numbers:
3.14159
or can also work with hexadecimal, octal and binary numbers.
Standard math operations
Addition
2 + 2
Subtraction
10 - 5
Multiplication
2 * 5
Division
100/10
Modulus (remainder of the division)
4 % 2
in this case, 4 mod 2 return no remainder, 0.
3 % 2
in this case, 3 mod 2 returns 1.
Power
There is an exponent operator (like a^b)
2 ** 10
in this case, 2^10 returns 1024
Alternatively, there is a built-in mathematical function called pow()
pow(2,10)
Python uses the default mathematical order of operations
- exponents and roots
- multiplication and division
- addition and subtraction
if you want to change the order, then use parentheses
Mixed Types
When you are working with integers and floating-point, Python always converts them to be all the same (in this case Python converts integer to floating-point). For example:
6.12 + 5
it returns 11.12 because it actually converts 5 (integer) into 5.0 (floating-point) before doing the addition with 6.12. So every time, Python converts up your data so you never gonna lose anything. This is great and it saves you from type casting.
Built-in functions
pow(number,power)
pow(2,10)
This is identical with 2^10 or 1024.
abs(number)
abs(-10)
It returns the absolute value |-10| = 10
round(number)
round(3.9)
It returns 4
Import math functions
Before using these function you have to import math library. So please add this line:
import math
Notice the math. notation. This shows that these functions are members of the math class
math.sqrt()
math.sqrt(100)
It return the square root of 100, which is 10.
math.floor()
math.floor(5.3452)
Return the floor of 5.3452 as a float, the largest integer value less than or equal to 5.3452. So, it returns 5.0
Python Math Documentation
Working with String
A string is any set of characters. To be more precise, it is a sequence of characters inside single or double quotes. So we can write a string using either single quotes or doubles quotes. FYI, single quotes are more of a standard for Python as they are used more often, while double quotes are more of a standard across other programming languages.
string = 'hello world!'
or
string = "hello world!"
In both ways, the string variable called string holds the string value hello world.
Many time you’re going to see double quotes instead of single quotes. This is due to the fact that most programmers do it out of habit. It isn’t wrong or anything like that, both type of quotes work equally fine, so no prob. Just pick one.
String Operations
Concatenation
One of the most common operations we can perform on strings is concatenation. This means you can combine strings together by adding (using the concatenation operator which is the plus (+) sign) them like if they were numbers (but they are strings instead).
>>> str = string + string + string >>> str 'hello worldhello worldhello world'
Similarly, you can use multiplication, like this
>>> str = string * 3 >>> str 'hello worldhello worldhello world'
let’s see another example of concatenation:
>>> str = string + ' Goodbye world!' >>> str 'hello world Goodbye world!'
Concatenation is very important because you are going to need very often to combine data into one variable.
String Length
One of the basic built-in function we can operate for strings is len(). It tells you how many characters are inside a string.
>>>>> len(str) 4
Character position
As I told you before, strings in Python are sequence of characters and each character has a unique position. So if you want to see the n-th position of a string you are going to use array notation ( string[n+1] )
- First character –> [0] position
- Seconds character –> [1] position
- Third character –> [2] position
- and so on. . . . .
For example, if I want to see the first character of the string:
>>>>> str[0] 'p'
Notice I use str[0] because the first character is located at position zero
For example, if you want to see the seconds character:
>>>>> str[1] 'a'
Slice notation
If you want a portion of a string, you can use slice.
For example if you want the first 2 characters:
>>> str[0:2] 'pa'
or if you want to get all characters before a specified number:
>>> str[:2] 'pa'
or if you want to get all the characters after a specified number:
>>> str[2:] 'ok'
if you want to see the last character:
>>> str[-1] 'k'[/cc]
The split operator
It takes a single argument — the delimiter — and give you back the string converted into a list based on the delimiter.
>>>>> str.split(',') ['Hey', ' you', ' come here!']
So each word/phrase separated by comma is going to be on its own on a list.
Strip ’em all \m/
It’s often for many but unknown reason, programmers want to remove certain characters from start or end or both of strings. For example let’s say you have unnecessary whitespace in a string which looks ugly. Let’s strip (remove) the whitespace.
>>>>> str.strip() 'This is a string!!!'
or you can just strip the right end of the string using rstrip() method.
str.rstrip() ' This is a string!!!'
Notice that strip method remove characters only from the beginning and end of strings, not from inside the string.
Working with Boolean Data Type
Boolean data types are either True or False and they are usually generated by comparisons. For example 1 > 2 this indicates a false boolean value. Another way of representation is the binary one: 1 (True), False (0).
Let’s see some examples:
>>> 1 == 1 True
Notice that the ‘==’ is the equality check, not the assign ‘=’ operator. It simply checks if both sides are equal and returns True (1) if they are, or False (0) if they are not.
You can also store a boolean type into a variable and use this variable later as a flag.
>>> is_greater = 10 > 2 >>> is_greater True
Working with List data structure
The most simple kind of list is the empty one. This is a plain set of brackets (open and close) and it represents the empty list.
>>> [] []
If you actually want to create a list with items in it (non-empty), you simply put items in the list separating each item with a comma.
>>> list_of_numbers = [1,2,3,4,5,6,7,8,9,10] >>> list_of_numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you want to access in each item you have to use index notation (aka array notation).
- First element would be —-> list_of_numbers[0] —-> 1
- Second element would be —-> list_of_numbers[1] —-> 2
- and so on . . . . . .
For example, if you want to add the first element with the last element ( I reming you that you can simply use the recursive way for the last item, which is simpler to do than looking for the last one )
>>> list_of_numbers[0] + list_of_numbers[-1] 11
which is similar to
>>> list_of_numbers[0] + list_of_numbers[9] 11
Slice notation
You can also work with slice notation and grab a portion of the list. Let’s say you want only the first 5 items, there are several ways to do it:
>>> list_of_numbers[0:5] [1, 2, 3, 4, 5]
or
>>> list_of_numbers[:5] [1, 2, 3, 4, 5]
or recursively
>>> list_of_numbers[:-5] [1, 2, 3, 4, 5]
Slice with step
The third argument in slice notation is the step
>>> list_of_numbers[0:9:3] [1, 4, 7]
Length of list
You can have the length of list (how many items it contains) by using the len method
>>> len(list_of_numbers) 10
String Lists
You can also have a list which contains strings as items separated by comma.
>>> strlist = ['emeis', 'mazi', 'gia', 'mia', 'zoi'] >>> strlist ['emeis', 'mazi', 'gia', 'mia', 'zoi']
Combine lists (concatenate)
You can simply combine lists together by using the concatenation operator which is the plus sign (+). Take a look here:
>>> strlist = ['emeis', 'mazi', 'gia', 'mia', 'zoi'] >>> strlist ['emeis', 'mazi', 'gia', 'mia', 'zoi'] >>> strlist2 = ['aete', 'aete', 'dikefale'] >>> combined_list = strlist + strlist2 >>> combined_list ['emeis', 'mazi', 'gia', 'mia', 'zoi', 'aete', 'aete', 'dikefale']
Replicate a list
Just use the multiplication operator and point the number of times you want to do the repetition.
>>> message = ['warning! '] >>> message * 5 ['warning! ', 'warning! ', 'warning! ', 'warning! ', 'warning! ']
Nested Lists
You can also have lists inside lists:
>>> names = ['Peter', 'Bruce', ['Clark','Kent'], 'Thor', 'Loki'] >>> names ['Peter', 'Bruce', ['Clark', 'Kent'], 'Thor', 'Loki'] >>> names[0] 'Peter' >>> names[2] ['Clark', 'Kent'] >>> names[2][1] 'Kent'
Working with Dictionary data structure
Dictionary in Python is a way to look up a value based on a key, just like any other dictionary. The simpler dictionary is an empty one, which is created by two curly braces {}
{}
That’s not of much use, so let’s create a dictionary that actually has some data in it. The pattern is similar to this:
{key:value, key2:value2, key3,value3}
>>> iphone = {'Antonis':68424252, 'Orestis':6978833231, 'Mom':2310666999} >>> iphone {'Antonis': 68424252, 'Mom': 2310666999, 'Orestis': 6978833231}
How to retrieve a value
You simply call the key and then its value is automatically retrieved by default
>>> iphone['Mom'] 2310666999
Notice that retrieval is implemented using normal brackets [] instead of curly ones {}.
>>> iphone{'Mom'} File "<stdin>", line 1 iphone{'Mom'} ^ SyntaxError: invalid syntax
How am I supposed to know the keys of the dictionary ?
Right! You can use the keys() function in order to get all the keys of a dictionary.
>>> iphone.keys() ['Antonis', 'Mom', 'Orestis']
and of course you can have access to all their values too, using the values() function.
>>> iphone.values() [68424252, 2310666999, 6978833231]
Working with Tuple data structure
First of all you need to know that a Tuple is very very … very similar to a List data structure. Syntax-wise, Tuples use a different delimiter and make use of parentheses instead of brackets. The major difference is that Tuples cannot be modified after their creation. So every time you modify a tuple’s item, another copy of tuple is created. It basically copies itself and doesn’t change the prototype. So, Tuples are little less efficient that Lists. That’s the difference between tuples and lists, because in lists you can change items “in-place”.
Let me create an empty Tuple:
>>> empty = () >>> empty ()
Let’s create an non-empty tuple:
>>> tuple = (1,2,3,4,5) >>> tuple (1, 2, 3, 4, 5)
If you want to access in each Tuple’s item individually, you have to use the index notation just like lists. For example:
>>> tuple[1] 2
Sure, you can concatenate:
>>> tuple[1] + tuple[2] * 12 38
We can return the length of the Tuple by using len() method:
>>> len(tuple) 5
and yes sir, slices work too and you can concatenate them in order to combine tuples together:
>>> num1= tuple[:2] >>> num1 (1, 2) >>> num2 = tuple[2:] >>> num2 (3, 4, 5) >>> numbers = num1 + num2 >>> numbers (1, 2, 3, 4, 5)
as you can see, all the operation that work on Lists, apply in Tuples too. But there is one thing you can do with Tuples that you can’t do with Lists. A tuple can be used as a key in a dictionary! | http://www.unixmen.com/expressions-statements-variables-data-types-python-must-read/ | CC-MAIN-2016-26 | refinedweb | 2,154 | 67.49 |
Hello,
My plan is to have a ruby class with a variety of functions in it and I
want to be able to call functions from this class using AJAX. I think
the easiest way to do this then is to pass a cgi parameter named
function or soemthing with the value being the def I wish to call.
So something like this
// this contained in test.rb
def test(x)
print x
end
from .js file
url = test.rb?action=test(‘help’);
xmlObject.open(“get”,url,true)
xmlObject.send
anyway something like that and then in test.rb I want to have something
like
if params.has_key?(“action”)
eval(params[“action”])
end
and hopefully it would return “help”. Please let me know if this is the
best way to do this and also if I am being unclear I am more than happy
to clarify.
I have tried something like the above technique and nothing is being
returned to the XmlObject.
Thank you | https://www.ruby-forum.com/t/pass-def-to-eval/151921 | CC-MAIN-2022-05 | refinedweb | 164 | 73.37 |
Introduction to Iterators in Python
In python, an Iterator can be defined as an object for holding a set of values, which can be used in iteration operations in the program. For performing an iteration operation using the iterator object, python had two special methods such as iter() and next(). Python allows Iteration to be performed in both numbers and strings, where the data is represented as an iterator object. This functional method helps in reducing redundancy and improving stability in the source code, without increasing the length of the code.
For Example:
newlist = ("soap", "knife", "handkerchief")
newiter= iter(newList)
print(next(newiter)) # soap
print(next(newiter)) # knife
print(next(newer)) # handkerchief
Strings in Python are also Iterable objects as we can get an iterator from it to traverse every character in it.
For Example:
newstr = "apple"
newiter = iter(newstr)
print(next(newiter)) # a
print(next(newiter)) # p
print(next(newiter)) # p
print(next(newiter)) # l
print(next(newiter)) # e
How to Work with Iterators in Python?
Now, let’s dive into iterators…
1. Looping through an Iterator
Loop can be used to iterate through the iterable objects in python. Loops also use the same procedure as above i.e. it creates an iterable object and keeps using the next method in each loop.
Example:
newlist = ("soap", "knife", "handkerchief")
for an in newlist:
print(a)
Output:
The basic advantage of for in loop or for each loop in python means less work than normal for loop in other languages.
Example:
newstr = "apple"
for an in newstr:
print(a)
Output:
2. Iterating an iterable object (List) using an iterator
An iterable object is something from which we can get an iterator like some pre-built iterable object are – list, dict, string, tuple, etc.
Example:
# define a list
mylist = [7,2, 5, 3] # retrieving an iterator using iter()
myiter = iter(mylist)
# iterate through it using next()
print(next(myiter))
print(next(myiter))
## next(object) is same as object.__next__()
#print(my_iter.__next__())
#print(my_iter.__next__())
Output:
3. Creating an Iterator
To create an object or class as an iterator, we have to implement the iterator protocol methods __iter__() and __next__() to the object.
Both of these methods are needed to get the necessary help to make the object iterable.
- Iter – The iter method is always called on the initialization of an Iterator object. This method always returns an __iter__object and used to fetch iterable form any object.
- Next – The next method of an iterable will return the next values of the object. Whenever an iterator is used within a ‘for in’ loop, the next() method is implicitly called by the iterator object. To end the endless iteration in python, a stopiteration condition is also added in this method.
Example:
In the below example we will create an iterator that will return odd numbers, starting from 1 like 1, 3, 5, and so on.
class OddSeries:
def __iter__(x):
x.a = 1
return x
def __next__(x):
i = x.a
x.a += 2
return i
newclass = OddSeries()
newiter = iter(newclass)
print(next(newiter)) # 1
print(next(newiter)) # 3
print(next(newiter)) # 5
print(next(newiter)) # 7
print(next(newiter)) # 9
4. StopIteration
The example which is stated above will continue as many numbers of times as we can print the next method with the object, or if it was used inside a for loop it will iterate infinitely without any break statement to stop the loop. To stop the iteration to go on forever, we have to use the StopIteration statement inside the Iterable object definition while creating it. The StopIteration statement should be written inside the __next__() method, to add a termination condition to raise an error whenever the iteration crosses a specified number of iterations.
Example:
class OddSeries:
def __iter__(x):
x.a = 1
return x
def __next__(x):
if x.a <= 10:
i = x.a
x.a += 2
return i
else:
raise StopIteration
newclass = OddSeries()
newiter = iter(newclass)
for j in newiter:
print(j):
Understanding the Implementation of for-loop
As we have seen in the above example that for-loop can iterate automatically the list.
Let’s see how the for-loop is implemented in Python:
for element in iterableObject:
#do something with the element
In-depth implementation:
#create an iterator object from iterableObject
iterObject = iter(iterableObject)
while True:
try:
#retrieve the next element
Element = next(iterObject)
#do something with element
except StopIteration:
break
So technically, for-loop is creating an iterator object, iterObject by calling iter() on the iterable object. For-Loop is the same as an infinite while-loop.
Inside the while-loop, it calls next()to retrieve the next element and then executes the body of for loop, After all the elements have been retrieved, then StopIteration is called which internally ends the loop.
Example:
The below example is to create an iterator in Python and print the output pattern.
Code:
class PatternPrint:
def __init__(x, mx = 10):
x.mx = mx
def __iter__(x):
x.a = 1
return x
def __next__(x):
if x.a <= x.mx:
i = x.a*'1'
x.a += 1
return i
else:
raise StopIteration
newiter = PatternPrint(12)
for j in newiter:
print(j)
Output:
Benefits of python Loops
- The key advantages of iterators are as below,
- Code reduction
- Code redundancy is greatly resolved
- Reduces code complexity
- Brings in more stability into coding
Conclusion – Iterators in Python
Iterators in Python are pretty useful stuff whenever we are dealing with any list, tuple, string, etc. as it allows us to traverse through the entire components and helpful when the need is to be based on an entry in the array, or character of a string, etc. Always we have to keep in my mind while declaring iterators that give the starting value of iteration i.e initialize it via iter and the sequence logic should be given in the next method in order to print a sequence and also try giving StopIteration always since it resists your for loop to give an array out of bound error.
Recommended Articles
This is a guide to Iterators in Python. Here we discuss how to work with Iterators in Python through various examples and Outputs. You may also have a look at the following articles to learn more – | https://www.educba.com/iterators-in-python/?source=leftnav | CC-MAIN-2020-45 | refinedweb | 1,042 | 51.18 |
Python 3.0 Review
morgan_greywolf (835522) writes | more than 5 years ago
.
Good: The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement (PEP 3105).
Maybe I just spent too many years writing C and Borland Pascal/Delphi code, but when I first started coding in Python, I often made the mistake of writing
print('Hello world')
rather than
print 'Hello world'
Now it's the way it should have been all along. Things are more consistent this way.
Additionally, the sep= keyword argument makes life easier. No longer do you have put the separator repeatedly in your quoted string especially if the separator is not a space!
Bad: The dict methods dict.keys(), dict.items() and dict.values() return "views" instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).
Why did they change this? I make use of dict.keys() rather a lot. *sniff*
Ugly: range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.
It seems like they changed this just to be pedantic. Tell me what the improvement is in making range work like xrange and then removing xrange? Why not just keep both?
Bad: The ordering comparison operators (=, >) raise a TypeError exception when the operands don't have a meaningful natural ordering. Thus, expressions like 1 None or len are no longer valid, and e.g..
Some of my favorite stupid Python tricks rely on the fact 'None' in fact does not raise a TypeError and instead causes an expression to return False. Oh well. Guess I'll be using a ton more exceptions.
Ugly: PEP 0237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
So if you're going to only have one type, instead of no longer accepting 'long', make 'long' an alias for 'int'. Now that wasn't too hard was it?
Good: PEP 0238: An expression like 1/2 returns a float
About fscking time. Damn, you have no idea how many times I looked at expressions like 1/2 and went "Huh? Whadya mean 0?"
Good, Bad and Ugly:. This value-specific behavior has caused numerous sad faces over the years.
I agree, but changing it is going to be a real pain for a WHOLE lot of programs. Specifically 2to3 and -3 isn't able to fix a lot of these differences.
Meh:.
Okay, but we're already doing this throw DOC strings. Why change it now?
Good:.
Okay, this is more consistent with how arguments work...
Meh: PEP 3104: nonlocal statement. Using nonlocal x you can now assign directly to a variable in an outer (but non-global) scope. nonlocal is a new reserved word.
If you're going to explicitly change the scope of a variable, you might as well make it global, huh? Some people are just too pedantical.
Good:].
Oh, goody! No more writing a, b, dummy1, dummy2 = function()
Good: Dictionary comprehensions: {k: v for k, v in stuff} means the same thing as dict(stuff) but is more flexible. (This is PEP 0274 vindicated.
and
Set literals, e.g. {1, 2}. Note that {} is an empty dictionary; use set() for an empty set. Set comprehensions are also supported; e.g., {x for x in stuff} means the same thing as set(stuff) but is more flexible.
I always thought there should be a way to do this...
Ugly: New octal literals, e.g. 0o720 (already in 2.6). The old octal literals (0720) are gone.
But the old way was consistent with Unix...
Good: Change from except exc, var to except exc as var. See PEP 3110.
I hated the old way. To me, there isn't a lot of difference between except (exc, exc): and except exc, var: so I was always getting confused.
Ugly: PEP 3113: Tuple parameter unpacking removed. You can no longer write def foo(a, (b, c)):
Why? I mean, I read the PEP and understand the introspection issues, but um, if you don't like it, just don't use it.
This and the rest of the removed syntax: These seem like silly, pedantic political issues.
Bad: Library changes: why change the names of libraries without leaving aliases to the old names? You're just being pedantical again. Stop it.
Ugly: String template changes and the '%' string operator
I never saw anything wrong with the '%' operator.
The Rest
'file' is already an alias for 'open'. Again, why rename something in a destructive way? What's wrong with just leaving the damn alias there?
(*) More accurately, I hate programming purism. I tend to mix and match various techniques and metaphors and 'use what works' rather than get all uppity about things like how a function should never modify a global variable. Sometimes that's just the best way to do it.
Some good and some bad (1)
MikeBabcock (65886) | more than 5 years ago | (#25989965)
Looking at the list myself the other day I just sat back and thought "woah."
The new string stuff is going to make maintenance a real pain, between the new formatting and the new Unicode handling. The octal thing is also weird, not quite sure about that syntax myself either.
A lot of the changes I'm pretty happy about, and I see how the new formatting stuff is more flexible, but honestly, I can see it getting ugly.
Things like "User {0{1{4}}} wrote this" are now possible and hideous.
Re:Some good and some bad (1)
morgan_greywolf (835522) | more than 5 years ago | (#26001975)
I dunno about the string formatting. There's already the Template class in the string module:
import string
s=string.Template('User $user ($uid) wrote this')
s.substitute(user="MikeBabcock", uid=65886, email='mtb-slashdot@mikebabcock.ca')
print s
what's wrong with that? Why do we need yet another way to do template strings?
Re:Some good and some bad (1)
MikeBabcock (65886) | more than 5 years ago | (#26003885)
The problem we have of course is the Guido "one right way
..." thinking, which means having two ways to format strings was bad, and they should all be merged into one way.
Unfortunately, string formatting has an awful lot of issues that I don't believe should all be dealt with in a single syntax.
And I'll miss "%(name)s" to be honest. | http://beta.slashdot.org/journal/218709 | CC-MAIN-2014-35 | refinedweb | 1,112 | 76.01 |
PhpStorm 2017.1 EAP 171.3224 : Improvements in PHP Debug, Auto-import and FQN inspection
The new PhpStorm 2017.1 EAP build (171.3224) is now available! You can download it here or via JetBrains Toolbox App. Or, if you have the previous PhpStorm 2017.1 EAP build (171.3019) installed, you should soon get a notification in the IDE about a patch update.
This build delivers new features, bug fixes and improvements for PHP and the Web, and takes on the latest improvements in IntelliJ Platform.
Use namespace and imports from execution point in Watches, Evaluate Expression and Debug Console
Now PhpStorm is aware of a current namespace and all imports at execution point during debugging. It uses this information in Watches pane, Evaluate Expression dialog and Debug Console to make sure that an identical code produces identical results during PHP execution and PhpStorm debug evaluations.
This functionality can be disabled in Settings| PHP | Debug | Import namespace and use statement from evaluation context.
Better User Experience for PHP Debug Settings
We know that setting up a debugger might be a challenge and want to make it easier for you. In this build, we’ve reorganized the Debug Settings and added a guided instruction on how to set up Debug directly at the Settings page, so you don’t have to search anymore. Also, all the important settings are brought on top and advanced are hidden in a separate category. Take a look and let us know what you think!
Improved Auto-import and Fully Qualified Name inspection
We’ve significantly improved PhpStorm understanding of PHP imports including detection of conflicts. That improves Auto-import functionality, Unnecessary Fully Qualified Name inspection and detection of Fatal Errors. So now you won’t get unexpected imports during completion or false positives inspection warnings.
Apart from new features, this build brings many bug fixes, including these:
- Allow opening commit window when only unversioned files present: IDEA-162845
- ES6 import resolve error: WEB-17483.3224 for your platform from the project EAP page or click “Update” in your JetBrains Toolbox App and please do report any bugs and feature request to our Issue Tracker.
Your JetBrains PhpStorm Team
The Drive to Develop | https://blog.jetbrains.com/phpstorm/2017/02/phpstorm-2017-1-eap-171-3224/ | CC-MAIN-2021-10 | refinedweb | 368 | 55.24 |
: module
Not sure if import <module_Name>; is supported right now. When I try to run a program including modules it stats note: c++20 ‘import’ only available with ‘-fmodules-ts’ is that a compiler flag like -std=c++20 or are modules not currently supported. Here is an example program using modules: #include<iostream> import <numbers>; import <format>; int main() { ..
everything is in the title, I’m willing to use some script from a C++ file in my python main program. the problem is that I don’t how to do this. I looked for a solution for the whole day, but I didnt really find anything interesting. To more describe my issue, I actually want to ..
I am trying to use c++20 modules in my project, on Visual Studio 2017 and MSVC. I followed this tutorial to enable experimental modules with c++17 in my project. My problem is that, when I try to compile my project I get some errors like the following: boost.1.77.0.0libnativeincludeboostinterprocessdetailwin32_api.hpp(926): error C2143: syntax error: missing ‘)’ before ..
I’m trying to modify an existing module for Azerothcore, to remove certain buffs from the player after leaving a raid instance. This is an example what should happen (pseudo code): PlayerLeavesRaid () { if (Player is Priest) { RemoveBuff (Buff1); RemoveBuff (Buff2); RemoveBuff (Buff3); } if (Player is Mage) { RemoveBuff (Buff4); RemoveBuff (Buff5); RemoveBuff ..
I need to get D3D9.dll exports, how i get this ? I tried to use EnumProcessModules BOOL EnumProcessModules( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded ); for lphModule, GetModuleBaseNameDWORD GetModuleBaseNameA( HANDLE hProcess, HMODULE hModule, LPSTR lpBaseName, DWORD nSize ); for hModule but no result, i should get Name and VA. This is what i ..
All the things noted above can be used to split the code into parts, and then integrating them back to work together. But how should I use them all together? As far as I know, the "best practice" is to use namespaces along with modules, because they are meant for two different things. Using multiple ..
I have a vector class inside a module: // other_library.cpp module; #include <iostream> export module mylibrary.other; export template<class T> class Vector { private: T x, y; public: Vector(T _x, T _y) : x(_x), y(_y) {} void Write() { std::cout << "Vector{" << x << ", " << y << "}n"; } }; And inside main, ..
// module A export module A; import <type_traits>; namespace test { export{ template<typename T, std::size_t N> class Foo; template<typename T> using Foo1 = Foo<T, 1>; template<typename T> struct is_Foo : std::false_type {}; template<typename T, std::size_t N> struct is_Foo<Foo<T, N>> : std::true_type {}; template<typename T> constexpr static bool is_Foo_v = is_Foo<T>::value; template<typename T> concept Foo_t = ..
In C++20, for each module M there must be exactly one source file that starts: export module M; (This is called the primary module interface unit.) Optionally, each module M may have additional source files: (1) Zero or more source files starting: module M; (These are called module implementation units.) (2) Zero or more source ..
Recent Comments | https://windowsquestions.com/category/module/ | CC-MAIN-2021-43 | refinedweb | 505 | 54.02 |
Websites are all about hyperlinks and being able to explore more. As such it's important to be able to provide a good navigation experience for your users. Templating in Lektor makes it very easy to make automatic navigation that keeps up to date with your pages. Most of this involves generating links with the help of the URL Filter.
The most basic form of navigation is a semi automatic one. It's one of the most flexible ones while still being easy to maintain. It requires knowledge of which pages to show and what the link title should be:
<nav> <ul class="nav navbar-nav"> <li{% if this._path == '/' %}Welcome</a></li> {% for href, title in [ ['/blog', 'Blog'], ['/projects', 'Projects'], ['/about', 'About'] ] %} <li{% if this.is_child_of(href) %}{{ title }}</a></li> {% endfor %} </ul> </nav>
In this case we use a list of pages (href and title) to automatically
generate some list items and we ask the current page (
this) if it is
a child of the given path. Based on that information we automatically
add a class to the link.
The index page requires a bit of special casing as we do not want it to be active if any of its children are active. So we just check if the path of the current page is actually the path of the index page.
Sometimes all we want is to show navigation links for all sub-pages of a page. This is easy to accomplish as well:
<nav> <ul class="nav"> {% for project in site.get('/projects').children %} <li{% if this == project %}{{ project.name }}</a></li> {% endfor %} </ul> </nav>
In some situations you want to show a tree like navigation. This is for instance something that comes up when building site maps. In that situation the recursive Jinja loop system really comes in handy.
<ul class="tree-nav"> {% set root = site.get('/') %} {% for child in root.children recursive %} <li{% if this._path == child._path %}{{ child.title }}</a> {% if this.is_child_of(child) %} <ul>{{ loop(child.children) }}</ul> {% endif %} </li> {% endfor %} </ul>
This above template recursively renders out a part of the tree based navigation around the current active page. For a concrete example for this: this is how the navigation of this documentation is rendered. | http://www.getlektor.com/docs/templates/navigation/ | CC-MAIN-2022-40 | refinedweb | 374 | 74.39 |
Help:Draft
RationalWiki allows you to create new articles in the Draft namespace. This allows people to work on articles which are not ready to "go live" or "air" in the main RationalWiki namespace.
Anyone can edit a draft article, so if you want to work on an article by yourself, you should create it in your sandbox instead.
Creating[edit]
To create a draft article, you can do a search for "Draft:Article name". If no article exists with that title, it will show up as a redlink (like this: redlink), and you can create a new article.
Moving to draft[edit]
An article can be moved to draft namespace if it is considered not ready for mainspace, for example if it is lacking references, is badly formatted, or is very incomplete. It should be moved using the relocate option, also used to change page titles, as described at Help:Page title.
Once properly edited it can be moved back to mainspace in the same way. If you are unsure if an article is good enough for mainspace, consult a moderator or other experienced user or ask in the Saloon bar.
Existing draft articles[edit]
There are some draft articles kicking around in a state of limbo (like dead babies floating around the Pope's head). Here is a list of all of them. You can search for one using the site search facility.
Warning[edit]
Even though draft articles have a lower standard than regular RationalWiki articles, they should still have the potential of being turned into proper articles. They should not be hopelessly off-topic, and should not be libellous or otherwise naughty articles. | https://rationalwiki.org/wiki/Help:Draft | CC-MAIN-2021-04 | refinedweb | 277 | 60.55 |
Failure to import cv2 in python : DLL load failed.
Two weeks ago, I built openCV-3.0.0, using Visual Studio 2013 x64 on Windows 7, with Python 3.4.3. I've copied cv2.pyd into the
Python34\Lib\site-packages folder. It was working.
Today, when I typed
import cv2, I was given this error message:
ImportError: DLL load failed: The specified module could not be found.
I couldn't remember everything I did to my computer in the past two weeks, but I did remember I installed openSSH for windows. When I checked my path variable, surprisingly, there is only one entry left for this software. Apparently this software erase previously existing path variable entries. While I suspect this could be the cause of the problem, I couldn't solve it. I added the path to opencv binaries, and Windows\System32, Windows\SysWow64 back but they didn't help.
When I use dependency walker, I saw the same list of missing dlls as reported [here]. (...), which, according to the original poster, was misleading.
Then I'm wondering : 1) Is it indeed the path variable that gave me problem? If so, how can I restore it? 2) Could it be something other than path variable? How then can I troubleshoot?
if you built the cv2.pyd yourself, it's probably a good idea, to make a second attempt with
this should result in a (fat ~10mb) cv2.pyd, that does no more depend on opencv dlls (if you don't count opencv_ffmpeg.dll)
Thanks! That's a very good suggestion !
how does one execute that command? I tried while in the CMake\bin folder and it told me that it "does not appear to contain CMakeLists.txt". I then tried to do it in opencv-master/include where I found the file CmakeLists.txt but cmake is not a valid command there. Any help would be appreaciated | https://answers.opencv.org/question/69587/failure-to-import-cv2-in-python-dll-load-failed/ | CC-MAIN-2019-35 | refinedweb | 319 | 77.43 |
Episode #22: PYTHONPATH considered harmful directory of a typical Python project: it contains
setup.py-- and so, if it were added to the current search path,
import setupwould become possible. (This is one reason to have
src/directories.) Often, directories added unwisely to the Python search path cause files to be imported from paths they do not expect to, and surprisingly conflict.”
#2 Michael: keon/algorithms
- Minimal examples of data structures and algorithms in Python
- Topics include
- Array
- circular_counter
- flatten
- garage
- merge_intervals
- graphs
- clone_graph
- find_path
- traversal
- trees
- etc.
#3 Brian: Glyph on attrs
- We talked about
attrsin episode 11, and pointed to the project and the docs.
- I came across good article introducing why you should use
attrs, by glyph, from 2016.
- The one Python library everyone needs:
- Discusses
- problems with using lists and tuples as data structures.
- creating your own classes properly.
- possible problems with
namedtuple(-ish. I still love
namedtuple).
Sponsored by ADVANCE DIGITAL
- A small team of developers who work in an agile/devops environment– you will make an impact with your work quickly
- Are mostly a python shop, but there is an opportunity to introduce and run other technologies at scale
- Fund employee development and conference attendance
- Are located in beautiful Jersey City, one stop from Manhattan on the PATH
- Are one of the 10 largest news sites by traffic in the US
- Apply at
#4 Michael: Curio for Python 3.5+ concurrency
- Curio is a library for performing concurrent I/O and common system programming tasks such as launching subprocesses and farming work out to thread and process pools.
- Curio is solely concerned with the execution of coroutines. A coroutine is a function defined using async def.
- It uses Python coroutines and the explicit
async/
awaitsyntax introduced in Python 3.5.
- Its programming model is based on cooperative multitasking and existing programming abstractions such as threads, sockets, files, subprocesses, locks, and queues.
- All sorts of cool constructs:
AsyncThreads,
UniversalQueues, async file I/O,
Tasks, and more.
#5 Brian: Python Package src-ery
- "Use the src, Luke"
- "To src, or not to src, that is the question"
Answering a listener question about Python packaging. In episode 15: Digging into Python Packaging, we mentioned to articles about getting started with packaging. In the comments, Kristof Claes noted that these references were in conflict with a couple of other references:
- pytest “Good Integration Practices”,
- ionel’s “Packaging a Python library”,
Both of these strongly encourage the use of a “src” directory when setting up a package for distribution. There seems to be good reasons to use “src”. Many of the reasons are around the idea that during testing, you should be testing an installed version of the code. I have no reason to disagree with Ionel’s arguments and the pytest documentation recommendation.
However:
- The pypa doesn’t bring this up when discussing distribution:
- The pypa sample project doesn’t use “src”:
- Many popular packages don’t:
- requests:
- pytest itself:
Why not?
- The pytest recommendation is subtle. It recommends using “src” if you need to include a dunder init file in the tests directory. Otherwise, the local code will be tested instead of the installed code, in part to test the installation and to test a library from the perspective of a user.
- pytest also recommends against having a top level dunder init in the tests directory. And this is a stronger recommendation.
- But Ionel’s points are not just around the use of pytest.
- So this is still really an open question to the Python community.
- If it’s great to use “src” instead of top level packages, why aren’t more projects doing this?
- Why doesn’t the PyPA mention it?
# 6 Michael: Intel Pulls Funding from OpenStack Effort It Founded With Rackspace
- Intel and Rackspace were collaborating on a project called OpenStack Innovation Center
- Launched in July 2015.
- A source close to the effort said initial funding was supposed to last through 2018, but Intel pulled it early.
- A Rackspace spokeswoman said “OSIC’s objective was to create the world’s largest OpenStack developer cloud and develop enterprise capabilities within OpenStack. It quickly accomplished the first goal, and has made great progress toward the second.”
- Some 30 Rackspace employees who had been working at the innovation center have been given two weeks to find new jobs at the San Antonio-based company.
- Story here is we all need to think about funding projects and diversification.
Our news:
Michael: Hurry up and register for EuroPython: Earlybird sold out. | https://pythonbytes.fm/episodes/show/22/pythonpath-considered-harmful | CC-MAIN-2018-30 | refinedweb | 752 | 53.41 |
Telerik UI for Blazor 0.2.0 Free Preview Available
Telerik UI for Blazor 0.2.0 Free Preview Available
A look into how one dev team is working tying the latest update for Blazor and ASP.NET Core into their products and code.
Join the DZone community and get the full member experience.Join For Free
Telerik UI for Blazor 0.2.0 is available for download today. This release makes Telerik UI for Blazor compatible with Visual Studio 2019 preview 2, and ASP.NET Core 3.0 preview 2.
A few weeks ago we released an early preview of Telerik UI for Blazor. The early preview is intended to give developers a peek into the development process while giving everyone a chance to share their feedback on the product. We are working closely to align our goals with those of Microsoft's ASP.NET Core team, which is why we're happy to announce Telerik UI for Blazor 0.2.0. This new version aligns our UI components with the ASP.NET Core 3.0 preview 2 and Blazor 0.8.0 release.
What's New
In this release, you may not see a lot of changes on the surface, but we've diligently kept up with things that are happening beneath the surface of the framework. ASP.NET Core 3.0 preview 2 marks a milestone for Razor Components, the underlying component model for Blazor. In preview 2, Razor Components have been decoupled from Blazor, making the component model much more flexible (for more about this see the preview 2 announcements). The change shifted some dependencies and namespaces used to power Telerik UI for Blazor, prompting us to add compatibility with the new release.
Telerik UI for Blazor is now compatible with:
- Visual Studio 2019 Preview 2
- ASP.NET Core 3.0 Preview 2
- Blazor 0.8.0
Going forward, Telerik UI for Blazor 0.1.0 is only compatible with Visual Studio 2017. You will need to migrate your experiments along with your tooling to Visual Studio 2019 to utilize 0.2.0.
Besides supporting the new, latest bits, some small changes were made to the Grid component:
- Grid columns are now better defined. In this version, Grid columns have improved semantics through nesting. The
KendoGridColumnscontainer clearly defines where columns begin in the Grid and gives us a framework to build upon. In the example below the columns are clearly defined and have different nesting from the
RowTemplate.
<KendoGrid Data=@GridData> <RowTemplate ... /> <KendoGridColumns> <KendoGridColumn Field=@nameof(Product.ProductName)/> <KendoGridColumn Field=@nameof(Product.UnitPrice)/> </KendoGridColumns> </KendoGrid>
HTML
- Grid Height is now a supported parameter, which allows the grid height to be defined programmatically.
<KendoGrid Data=@GridData Height=@Height>
HTML
- Code samples are here! We really wanted to help you hit the ground running. With the ecosystem changing rapidly, it's best to show solid examples of how to get things done. This is why we have released a new GitHub repository showing of our components doing cool things like templates, editing, and swapping themes. You can clone the samples here:
Stay Tuned
We're committed to Telerik UI for Blazor and plan to release more content in the form of video, blogs, and samples on GitHub. If you're watching with anticipation for what's coming next, make sure to visit our blogs frequently for news and announcements. For more insight into all things Blazor, you can watch me (Ed Charbeneau, Progress developer advocate), each week Friday at 12:00 pm EST on Twitch.
Join the Early Preview legacy JavaScript dependencies (there's no jQuery this time folks). Throughout the year Microsoft will be working on Blazor (a.k.a..
A Special Installation Note
For the Telerik UI for Blazor version 0.2.0 to show in your NuGet feed, you must visit the download page and create an account, or sign in. You will need to repeat this process even if you already have early preview 0.1.0. Visiting this page will activate your NuGet feed. For more information about adding the Telerik NuGet feed please see our documentation.
Published at DZone with permission of Ed Charbeneau , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/telerik-ui-for-blazor-020-free-preview-available?fromrel=true | CC-MAIN-2019-43 | refinedweb | 719 | 67.25 |
How to edit a kubernetes resource from a shell script
kubectl edit file in pod
kubectl default editor
kubectl cp
kubectl commands
kubectl exec
kubectl can-i
kubectl restart pod
I went through the documentation to edit kubernetes resource using
kubectl edit command. Once I execute the command, the file in YAML-format is opened in the editor where I can change the values as per requirement and save it. I am trying to execute these steps by means of
sed. How can the following steps be achieved?
- Execute
kubectl editfor a deployment resource
- Set a value from
trueto
false(using sed)
- Save the changes
I tried to achieve this in the following way :
$ kubectl edit deployment tiller-deploy -n kube-system | \ sed -i "s/\(automountServiceAccountToken:.*$\)/automountServiceAccountToken: true/g"`
Your command is missing a backtick. But even though you put it there, it won't work. The reason is because when you do
kubectl edit ..., it edits the file on vim. I am not sure sed would work on vim though. Even though if it does, the output goes to a file, so you get the
Vim: Warning: Output is not to a terminal error, which I don't know how to solve.
I would recommend you to get the file and save it. Replace the desired parameters and run it again:
kubectl get deploy tiller-deploy -n kube-system -o yaml > tiller.yaml && sed -i "s/automountServiceAccountToken:.*$/automountServiceAccountToken: true/g" tiller.yaml && kubectl replace -f tiller.yaml
I tried the command above and it worked.
Note: no need to add
-n kube-system as the yaml file already contains the namespace.
Managing Resources, This page is an overview of the kubectl command. kubectl - Cheat Sheet Kubectl completion bash) # setup autocomplete in bash into the current shell, bash-completion Edit any API resource in your preferred editor. Often times you need to inject a configuration file into a container in Kubernetes. This is really easy to do using the ConfigMap resource. But once in a while you might need to inject an executable script into a container. There are any number of reasons why you might need to do so. In my case, I needed to alter the default behaviour of a
I automate through piping the commands through
sed command without creating a temporary file. Take the below example, where I am replacing nameserver
8.8.8.8 with
1.1.1.1
$ kubectl -n kube-system get configmap/kube-dns -o yaml | sed "s/8.8.8.8/1.1.1.1/" | kubectl replace -f -
kubectl Cheat Sheet, The edit command allows you to directly edit any API resource you can or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows.
I don't know kubectl but doc seems to explain that it extract data, edit from an editor than send back, not sure sed pipe work in this case
if piping wokrs Don't use -i, you don't change a file in a pipe
kubectl edit deployment tiller-deploy -n kube-system | \ sed 's/automountServiceAccountToken:.*$/automountServiceAccountToken: true/g'
if editing a file (and using group in sed)
kubectl edit deployment tiller-deploy -n kube-system > YourCOnfigFile && \ sed -i 's/\(automountServiceAccountToken:\).*$/\1 true/g' YourConfigFile \ && Some kubectl to send back YourConfigFile
kubectl edit, The edit command allows you to directly edit any API resource you can or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. In the Azure portal, select All resources in the left menu to see the resources created for your new Kubernetes cluster. Recover from a Cloud Shell timeout If the Cloud Shell session times out, you can do the following steps to recover:
kubectl-edit(1) — kubernetes-client, Editing Resources. The edit any API resource in an editor. $ kubectl edit svc/docker-registry # Edit the service named docker Note: Cluster Turndown is currently in ALPHA. GKE Setup. We have provided a shell script capable of performing the required steps in setting up a service account for use with cluster-turndown. More info. Running the Setup Script. To use this setup script supply the following parameters:
Kubectl cheatsheet, The edit command allows you to directly edit any API resource you can or EDITOR environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. Edit This Page. Define a Command and Arguments for a Container. This page shows how to define commands and arguments when you run a container in a Pod A Pod represents a set of running containers in your cluster.. Before you begin. You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with
kubectl-edit - Edit a resource on the server - man page, Get, create, edit, and delete resources with kubectl When using the exec command, the end of the line must always provide which shell you Edit This Page. Configure Pod Initialization. This page shows how to use an Init Container to initialize a Pod before an application Container runs. Before you begin. You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster.
- Please post samples of the Input and expected output in your post too.
- How should that command ever work?
kubectl edit deployment tiller-deploy -n kube-system > YourCOnfigFilewould throw an error | http://thetopsites.net/article/53904028.shtml | CC-MAIN-2020-45 | refinedweb | 897 | 63.29 |
We are going to exclusively use the
csv module built into Python for this task. But first, we will have to import the module as :
import csv
We have already covered the basics of how to use the
csv module to read and write into CSV files. If you don't have any idea on using the
csv module, check out our tutorial on Python CSV: Read and Write CSV files
Basic Usage of csv.writer()
Let's look at a basic example of using
csv.
writer
() to refresh your existing knowledge.
Example 1: Write into CSV files with csv.writer()
Suppose we want to write a CSV file with the following entries:
SN,Name,Contribution 1,Linus Torvalds,Linux Kernel 2,Tim Berners-Lee,World Wide Web 3,Guido van Rossum,Python Programming
Here's how we do it.
import csv with open('innovators.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(["SN", "Name", "Contribution"]) writer.writerow([1, "Linus Torvalds", "Linux Kernel"]) writer.writerow([2, "Tim Berners-Lee", "World Wide Web"]) writer.writerow([3, "Guido van Rossum", "Python Programming"]). The
writer.writerow() function is then used to write single rows to the CSV file.
Example 2: Writing Multiple Rows with writerows()
If we need to write the contents of the 2-dimensional list to a CSV file, here's how we can do it.
import csv row_list = [["SN", "Name", "Contribution"], [1, "Linus Torvalds", "Linux Kernel"], [2, "Tim Berners-Lee", "World Wide Web"], [3, "Guido van Rossum", "Python Programming"]] with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(row_list)
The output of the program is the same as in Example 1.
Here, our 2-dimensional list is passed to the
writer.writerows() function to write the content of the list to the CSV file.
Now let's see how we can write CSV files in different formats. We will then learn how to customize the
csv.writer() function to write them.
CSV Files with Custom Delimiters
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are
| and
\t.
Suppose we want to use
| as a delimiter in the innovators.csv file of Example 1. To write this file, we can pass an additional
delimiter parameter to the
csv.writer() function.
Let's take an example.
Example 3: Write CSV File Having Pipe Delimiter
import csv data_list = [["SN", "Name", "Contribution"], [1, "Linus Torvalds", "Linux Kernel"], [2, "Tim Berners-Lee", "World Wide Web"], [3, "Guido van Rossum", "Python Programming"]] with open('innovators.csv', 'w', newline='') as file: writer = csv.writer(file, delimiter='|') writer.writerows(data_list)
Output
SN|Name|Contribution 1|Linus Torvalds|Linux Kernel 2|Tim Berners-Lee|World Wide Web 3|Guido van Rossum|Python Programming
As we can see, the optional parameter
delimiter = '|' helps specify the
writer object that the CSV file should have
| as a delimiter.
CSV files with Quotes
Some CSV files have quotes around each or some of the entries.
Let's take quotes.csv as an example, with the following entries:
"SN";"Name";"Quotes" 1;"Buddha";"What we think we become" 2;"Mark Twain";"Never regret anything that made you smile" 3;"Oscar Wilde";"Be yourself everyone else is already taken"
Using
csv.writer() by default will not add these quotes to the entries.
In order to add them, we will have to use another optional parameter called
quoting.
Let's take an example of how quoting can be used around the non-numeric values and
; as delimiters.
Example 4: Write CSV files with quotes=';') writer.writerows(row_list)
Output
"SN","Name","Quotes" 1,"Buddha","What we think we become" 2,"Mark Twain","Never regret anything that made you smile" 3,"Oscar Wilde","Be yourself everyone else is already taken"
Here, the quotes.csv file is created in the working directory with the above entries.
As you can see, we have passed
csv.QUOTE_NONNUMERIC to the
quoting parameter. It is a constant defined by the
csv module.
csv.QUOTE_NONNUMERIC specifies the
writer object that quotes should be added around the non-numeric entries.
There are 3 other predefined constants you can pass to the
quoting parameter:
csv.QUOTE_ALL- Specifies the
writerobject to write CSV file with quotes around all the entries.
csv.QUOTE_MINIMAL- Specifies the
writerobject to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)
csv.QUOTE_NONE- Specifies the
writerobject that none of the entries should be quoted. It is the default value.
CSV files with custom quoting character
We can also write CSV files with custom quoting characters. For that, we will have to use an optional parameter called
quotechar.
Let's take an example of writing quotes.csv file in Example 4, but with
* as the quoting character.
Example 5: Writing CSV files with custom quoting character=';', quotechar='*') writer.writerows(row_list)
Output
*SN*;*Name*;*Quotes* 1;*Buddha*;*What we think we become* 2;*Mark Twain*;*Never regret anything that made you smile* 3;*Oscar Wilde*;*Be yourself everyone else is already taken*
Here, we can see that
quotechar='*' parameter instructs the
writer object to use
* as quote for all non-numeric values.
Dialects in CSV module
Notice in Example 5 that we have passed multiple parameters (
quoting,
delimiter and
quotechar) to the
csv.writer() function.
This practice is acceptable when dealing with one or two files. But it will make the code more redundant and ugly once we start working with multiple CSV files with similar formats.
As a solution to this, the
csv module offers
dialect as an optional parameter.
Dialect helps in grouping together many specific formatting patterns like
delimiter,
skipinitialspace,
quoting,
escapechar into a single dialect name.
It can then be passed as a parameter to multiple
writer or
reader instances.
Example 6: Write CSV file using dialect
Suppose we want to write a CSV file (office.csv) with the following content:
"
The CSV file has quotes around each entry and uses
| as a delimiter.
Instead of passing two individual formatting patterns, let's look at how to use dialects to write this file.
import csv row_list = [ ["] ] csv.register_dialect('myDialect', delimiter='|', quoting=csv.QUOTE_ALL) with open('office.csv', 'w', newline='') as file: writer = csv.writer(file, dialect='myDialect') writer.writerows(row_list)
Output
"
Here, office.csv is created in the working directory with the above contents.
From this example, we can see that the
csv.register_dialect() function is used to define a custom dialect. Its syntax is:
csv.register_dialect(name[, dialect[, **fmtparams]])
The custom dialect requires a name in the form of a string. Other specifications can be done either by passing a sub-class of the
Dialect class, or by individual formatting patterns as shown in the example.
While creating the
writer object, we pass
dialect='myDialect' to specify that the writer instance must use that particular dialect.
The advantage of using
dialect is that it makes the program more modular. Notice that we can reuse myDialect to write other CSV files without having to re-specify the CSV format.
Write CSV files with csv.DictWriter()})
Output
CSV files with lineterminator
A
lineterminator is a string used to terminate lines produced by
writer objects. The default value is
\r\n. You can change its value by passing any string as a
lineterminator parameter.
However, the
reader object only recognizes
\n or
\r as
lineterminator values. So using other characters as line terminators is highly discouraged.
doublequote & escapechar in CSV module
In order to separate delimiter characters in the entries, the
csv module by default quotes the entries using quotation marks.
So, if you had an entry: He is a strong, healthy man, it will be written as: "He is a strong, healthy man".
Similarly, the
csv module uses double quotes in order to escape the quote character present in the entries by default.
If you had an entry: Go to "programiz.com", it would be written as: "Go to ""programiz.com""".
Here, we can see that each
" is followed by a
" to escape the previous one.
doublequote
It handles how
quotechar present in the entry themselves are quoted. When
True, the quoting character is doubled and when
False, the
escapechar is used as a prefix to the
quotechar. By default its value is
True.
escapechar
escapechar parameter is a string to escape the delimiter if quoting is set to
csv.QUOTE_NONE and quotechar if doublequote is
False. Its default value is None.
Example 8: Using escapechar in csv writer
import csv row_list = [ ['Book', 'Quote'], ['Lord of the Rings', '"All we have to decide is what to do with the time that is given us."'], ['Harry Potter', '"It matters not what someone is born, but what they grow to be."'] ] with open('book.csv', 'w', newline='') as file: writer = csv.writer(file, escapechar='/', quoting=csv.QUOTE_NONE) writer.writerows(row_list)
Output
Book,Quote Lord of the Rings,/"All we have to decide is what to do with the time that is given us./" Harry Potter,/"It matters not what someone is born/, but what they grow to be./"
Here, we can see that
/ is prefix to all the
" and
, because we specified
quoting=csv.QUOTE_NONE.
If it wasn't defined, then, the output would be:
Book,Quote Lord of the Rings,"""All we have to decide is what to do with the time that is given us.""" Harry Potter,"""It matters not what someone is born, but what they grow to be."""
Since we allow quoting, the
quotechar themselves are double-quoted. The entry with
delimiter is enclosed within quote characters.
Note: The csv module can also be used for other file extensions (like: .txt) as long as their contents are in proper structure.
Recommended Reading: Read CSV Files in Python | https://www.programiz.com/python-programming/writing-csv-files | CC-MAIN-2020-16 | refinedweb | 1,630 | 66.74 |
Details
- Type:
Bug
- Status: Patch Available
- Priority:
Critical
- Resolution: Unresolved
- Affects Version/s: 3.0.0
- Fix Version/s: None
- Component/s: master, regionserver
- Labels:None
Description
This was done on a local cluster (non hdfs) and following are the steps
- Start a single node cluster and start an additional RS using local-regionservers.sh
- Through hbase shell add a new rs group
hbase(main):001:0> add_rsgroup 'test_rsgroup' Took 0.5503 seconds hbase(main):002:0> list_rsgroups NAME SERVER / TABLE test_rsgroup default server dob2-r3n13:16020 server dob2-r3n13:16022 table hbase:meta table hbase:acl table hbase:quota table hbase:namespace table hbase:rsgroup 2 row(s) Took 0.0419 seconds
- Move one of the region servers to the new rsgroup
hbase(main):004:0> move_servers_rsgroup 'test_rsgroup',['dob2-r3n13:16020'] Took 6.4894 seconds hbase(main):005:0> exit
- Stop the regionserver which is left in the default rsgroup
local-regionservers.sh stop 2
The cluster becomes unusable even if the region server is restarted or even if all the services were brought down and brought up.
In 1.1.x version, the cluster recovers fine. Looks like meta is assigned to a dummy regionserver and when the regionserver gets restarted it gets assigned. The following is what we can see in master UI when the rs is down
1588230740 hbase:meta,,1.1588230740 state=PENDING_OPEN, ts=Wed May 23 18:24:01 EDT 2018 (1s ago), server=localhost,1,1 | https://issues.apache.org/jira/browse/HBASE-20632 | CC-MAIN-2018-39 | refinedweb | 243 | 53.71 |
In this tutorial you will learn how to append the text when you are writing in a text file.
Appending a text means that the text that are written earlier or can say the old contents of an existing file should be retained when you are trying to write new contents in an existing files.
The example what I am going to give here will demonstrate you how to retain the older text when you are writing again to an existing file. To achieve the solution of this problem at first I have created a text file named "appenToFile.txt" and write some text. And then create a java file named WriteToFileAppend.java where I have used the FileWriter constructor to write a stream of characters. Argument 'true' of FileWriter constructor denotes that the contents of the file will be retained when you will try to write new text in an existing files.
Constructor of the FileWriter class that I have used in this example is as :
FileWriter(String fileName, boolean append);
e.g. FileWriter fw = new FileWriter("appenToFile.txt", true);
Example :
WriteToFileAppend.java
import java.io.*; class WriteToFileAppend { public static void main (String args[]) { WriteToFileAppend wtfa = new WriteToFileAppend(); wtfa.fileWithAppend(); System.out.println("-----*----New text has been written into the existing file successfully----*-----"); } public void fileWithAppend() { FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter("appenToFile.txt", true); bw = new BufferedWriter(fw); bw.write("These text are newly added."); } catch(Exception e) { System.out.println(e); } finally { if (bw != null) try { bw.close(); } catch (IOException ioe) { System.out.println(ioe); } } } }
How to Execute this example :
After doing the basic process to execute a java program write simply on command prompt as :
javac WriteToFileAppend.java to compile the program
And after successfully compilation to run simply type as :
java WriteToFileAppend
Output :
When you will execute this example new contents that you are trying to write using java program in an existing file will be written with retaining the old texts.
1. An existing text file that contains the texts as follows :
2. An existing file into which new texts are written with retaining the old texts as follows :
Advertisements
Posted on: January Append
Post your Comment | http://www.roseindia.net/java/examples/io/writeToFileAppend.shtml | CC-MAIN-2015-35 | refinedweb | 367 | 65.52 |
ID3 is additional information that attaches to mp3 files. This information can be: text, files, images, lyrics and much more.
ID3 Editor � Text information dialog
ID3Info is a class that allows you to manage ID3 of files. My article is about this class.
To learn how ID3 works in detail, look at The ID3 Homepage. This is the best place to help you understand the details of ID3. In this article I won't explain the details of ID3. I'll just explain the basics of ID3 and how the
ID3Info class works.
This class can Read/Write both versions of ID3: ID3v1 and ID3v2. For ID3v2 minor versions this class can read ID3v2.2, ID3v2.3, ID3v2.4 and can write ID3v2.3 and ID3v2.4.
The most popular version of ID3 is 2.3.0 and version 1.
In this article my focus is more on ID3v2 because there are too many other good references for ID3v1.
To understand how this class works you need to know some basics. Classes, inheritance, and some useful .NET classes (like
ArrayList,
FileStream,
MemoryStream, etc.).
I wrote an application with ID3Info. This application doesn't use more than 60% of
ID3Info's power. I just wrote the application to find bugs. In my opinion it's not complete. I will try to make it better using my own time and other user's ideas.
I'll just explain some basics here.
ID3 Editor � General Dialog
ID3v1 usage is so simple. The last 128 bytes of file may contain ID3v1 information. It starts with 'TAG', this is ID3v1 identifier. 'TAG' keyword will follow with Title (30 character), Artist (30 Character), Album (30 Character), Year (4 Character), Comment (28 character), Track Number (1 byte) and Genre (1 byte).
Genre has a table within ID3 definition. All softwares must use that table.
ID3Info returns Genre number not Genre name.
As you can see, there's nothing complex in ID3v1.
ID3v1 class, in ID3.ID3v1Frames namespace handles ID3v1 jobs.
private string _FilePath; private string _Title; private string _Artist; private string _Album; private string _Year; private string _Comment; private byte _TrackNumber; private byte _Genre;
The variables in this class hold ID3v1 data. There are some properties for each variable and they check the limitations of ID3v1. For example,
_Comment does not allow comments to be more than 28 characters.
There's another variable that allows the
ID3Info class to know if the current file must contain ID3v1. This variable name is
_HaveTag.
In the constructor, set the
_FilePath variable to the path of the file. If the programmer wanted to load ID3v1 data in the constructor (With LoadData argument), otherwise load sets information to "".
To load ID3v1 you must use the '
Load()' method. This method first defines a
FileStream to a file and tries to find out if the file contains ID3 data. The
HaveID3 method determines if file contains ID3v1. And if the file contains ID3v1,
HaveID3 tries to load it.
For reading text, I have used the '
Frame.ReadText' method. This method just reads text from a specified
FileStream, according to
TextEncoding and the maximum available length.
public void Load() { FileStream FS = new FileStream(_FilePath, FileMode.Open); if (!HaveID3(FS)) { FS.Close(); _HaveTag = false; return; } _Title = Frame.ReadText(FS, 30, TextEncodings.Ascii); FS.Seek(-95, SeekOrigin.End); //� FS.Seek(-2, SeekOrigin.End); _TrackNumber = Convert.ToByte(FS.ReadByte()); _Genre = Convert.ToByte(FS.ReadByte()); FS.Close(); _HaveTag = true; }
To save ID3v1 we first need to understand if the file currently has ID3. To do so use the '
HaveID3(FilesStream)' function. If the file currently contains ID3 and the user wants to remove ID3 we just delete it. If the file currently doesn't contain ID3 and the user wants to save info we just write ID3 at the end of the file. If you want to change ID3 information you must overwrite it.
GetTagBytes is a property that converts ID3 information to a byte array.
public void Save() { FileStream fs = new FileStream(_FilePath, FileMode.Open); bool HTag = HaveID3(fs); if (HTag && !_HaveTag) // just delete ID3 fs.SetLength(fs.Length - 128); else if (!HTag && _HaveTag) { fs.Seek(0, SeekOrigin.End); fs.Write(GetTagBytes, 0, 128); } else if (HTag && _HaveTag) { fs.Seek(-128, SeekOrigin.End); fs.Write(GetTagBytes, 0, 128); } fs.Close(); }
An Mp3 file with ID3 looks something like this figure:
ID3v2 saves at the beginning of the file. It saves as frames. Each frame contains some information, for example, one contains artist, another, title of song. A frame also contains: release date, composer, pictures related to track, track number and much more information.
Each frame contains two main parts:
FrameIDthat indicates what this frame contains. For example, if a
FrameIDis 'TIT2', this means this frame contains "title of song". Frame header also contains some flags, and length of frame in byte. For more information about ID3 frames look at The ID3 Homepage.
I have classified ID3 frames into 25 classes. All of them inherit the 'Frame' class
ID3v2 has some minor versions which have small differences. The main difference is in version 2.2. In this version,
FrameID is three characters, but in later versions it increased to four characters. And in v2.2 frame headers don't contain a frame flag. Many frames have been added to v2.3 and some added to v2.4. The most popular version is v2.3.
In 'Main.cs' the file is 'Frame' class. This is the main class used for ID3 frames. As you can see, this is an abstract class (must be inherited in Visual Basic) because for any frame there's another class that inherits this class. Some of the most important things are done in this class.
In this class we have some abstract properties and methods.
IsAvailable: Indicates if current information is valid for this frame.
FrameStream: Get a
MemoryStreamthat contains data from frame to save.
Length: Indicates how many bytes this frame needs to save.
These two properties and one method must override all inherited classes. This class also contains some static methods that are used to read/write data from/to
FileStream.
When we want to save a frame first we need to save frame header. The
FrameHeader method creates a
MemoryStream and writes the frame header to it. This method will be used in inherited frames to write their own data after the frame header.
This class reads and writes ID3v2. In the constructor you indicate the file path and must determine whether to load its data or not.
To load data you can use the filter option.
Filter: You can indicate class by opening some special frames. Imagine you have a player application and you want load the ID3 of a file. In your application you just view "Title of song". So why should you load all frames? This makes the application slower and uses more RAM to store useless information.
You can add 'TIT2' to
Filter. And set
FilterType to
LoadFiltersOnly to load the Title of track if it exists. You must always remember: if you use filtering, don't save file info because you might lose some data.
The
Load method checks if file has ID3 (
HaveID3 method). If the file has ID3, then
Load starts reading frames. But first, version information must be read with the
ReadVersion(FileStream) method. This method stores version information in the
_Ver variable which is available with 'VersionInfo' properties. Then with '
ReadFrames' all frames are read.
public void Load() { FileStream ID3File = new FileStream(_FilePath, FileMode.Open); if (!HaveID3(ID3File)) // If file doesn't contain ID3v2 exit function { _HaveTag = false; ID3File.Close(); return; } ReadVersion(ID3File); // Read ID3v2 version _Flags = (ID3v2Flags)ID3File.ReadByte(); // Extended Header Must Read Here ReadFrames(ID3File, ReadSize(ID3File)); ID3File.Close(); _HaveTag = true; }
Note:
FrameID in ID3v2.2 is three characters but in later versions it's four characters.
private void ReadFrames(FileStream Data, int Length) { string FrameID; int FrameLength; FrameFlags Flags = new FrameFlags(); byte Buf; // If ID3v2 is ID3v2.2 FrameID, FrameLength of Frames is 3 byte // otherwise it's 4 character int FrameIDLen = VersionInfo.Minor == 2 ? 3 : 4; // Minimum frame size is 10 because frame header is 10 byte while (Length > 10) { // check for padding( 00 bytes ) Buf = Frame.ReadByte(Data); if (Buf == 0) { Length--; continue; } // if read byte is not zero. it must read as FrameID Data.Seek(-1, SeekOrigin.Current); // ---------- Read Frame Header ----------------------- FrameID = Frame.ReadText(Data, FrameIDLen, TextEncodings.Ascii); if (FrameIDLen == 3) FrameID = FramesList.Get4CharID(FrameID); FrameLength = Convert.ToInt32(Frame.Read(Data, FrameIDLen)); if (FrameIDLen == 4) Flags = (FrameFlags)Frame.Read(Data, 2); else Flags = 0; // must set to default flag long Position = Data.Position; if (Length > 0x10000000) throw (new FileLoadException("This file contain frame that have more than 256MB data")); bool Added = false; if (IsAddable(FrameID)) // Check if frame is not filter Added = AddFrame(Data, FrameID, FrameLength, Flags); if (!Added) { // if don't read this frame // we must go forward to read next frame Data.Position = Position + FrameLength; } Length -= FrameLength + 10; } }
As you can see '
ReadFrames' reads frame header and '
AddFrame' method tries to load the content of the frame. The '
AddFrame' method first checks if the frame is a text frame.
Text frames are frames that contain text only. For example: title, artist, album, etc.. All text frame
FrameIDs start with 'T'; you can see a list of text frames in ID3 documentation. If it was not a text frame, a switch statement is used to try to find out what kind of frame it is.
ID3 Editor � Files Dialog
As I mentioned before there are about 25 classes to store frames. You can find these classes in the 'Frame classes' directory. Switch statement uses
FrameID to select the "true" class. For example, if
FrameID is 'APIC'.
AttachedPictureFrame TempAttachedPictureFrame = new AttachedPictureFrame( FrameID, Flags, Data, Length); if (TempAttachedPictureFrame.IsReadableFrame) { _AttachedPictureFrames.Add(TempAttachedPictureFrame); return true; } else AddError(new ID3Error(TempAttachedPictureFrame.ErrorMessage, FrameID)); break;
As you can see I've created '
AttachedPictureFrame'. This class inherits the
Frame class and reads information from the attached
picture from a frame. After creating an attached picture with '
IsReadable',
properties check if frames data is readable. If data is readable '
AttachedPictureFrame' tries to add this
attached picture to an attached picture array.
Note: you can store more than one piece of information in some frames. For example, in some frames you can save as many pictures as you want. But for other frames this is not possible. In the Relative volume frame, for example, the ID3v2 class just contains a variable for that frame. (To better understand frames that can hold additional information look at references).
If you look more closely at
AttachedPicture's code you'll see the else statement contains an '
AddError' method. If for any reason the
Frame class (that
AttachedPictureFrame inherited) can't read the data of the frame,
IsReadable properties will return false. This means an error occurred while reading, so the program will add an error message to the array of errors.
Adding errors to a collection allows the program to load other frames that have no error. If, when error occurred program throw exception other later frames will not read.
Remember you can clear the Error list, and must do it when required.
As I have said many times, for each type of frame we have a special class. Imagine for an mp3 file, we start reading frames. We find a frame with a 'TIT2'
FrameID. And then find another frame with a 'TIT2'
FrameID. Can we have two frames with a 'TIT2'
FrameID? The answer is no. We must overwrite the first frame with the second one. It means if we find two frames with one
FrameID that they must not be repeated (though some
FrameIDs can repeat) - we must store the last one.
For each frame class there's an
Equal method. It's an inherited method from the object class. To explain the
Equal method I will use the '
TextFrame' class as an example. As you can see, the '
TextFrame' class equality overrides as below ('TextFrames.cs').
public override bool Equals(object obj) { if (obj.GetType() != this.GetType()) return false; // if FrameID of two text frames were equal they are equal // ( the text value is not important ) if (this._FrameID == ((TextFrame)obj)._FrameID) return true; else return false; }
In this method I have checked if the
FrameID of the current frame class is
Equal to another one. They are equal. The text of frame is not important. This is because for text frames we must not have more than one frames with the same
FrameID.
The usage of this override is in the '
ArrayList' class. When we want to add new Frames to the list we can simply remove the previous one with '
ArrayList.Remove' (because this method uses the '
Object.Equal' method).
So always remember frame equality means no two frames have exactly same data.
ID3 Editor � Lyric Editor Dialog
In this part I explain how to use the
ID3Info class. I have used the
ID3Info class in the 'ID3 editor' application. To see samples of how you can use
ID3Info, you can take a look at the 'ID3 Editor' source code.
To load data you can use constructor.
ID3Info File = new ID3Info("Path", true);
Or
ID3Info File = new ID3Info("Path", false); // You can use filter here // ID3File.ID3v2Info.Filter.Add("TIT2"); // ID3File.ID3v2Info.FilterType = FilterTypes.LoadFiltersOnly; File.Load();
After defining the
ID3Info class and loading data, you need to get data from the class. to get text information you can use the
GetTextFrame method as shown below.
ID3Info File = new ID3Info("Path", true); String Title = File.ID3v2Info.GetTextFrame("TIT2"); And to set text information you can use 'SetInformation' method, And below. ID3Info File = new ID3Info("Path", true); File.ID3v2Info.SetTextFrame("TIT2","My Title", TextEncodings.Ascii, ID3File.ID3v2Info.VersionInfo.Minor);
Note: For any text you must set a text encoding, and a minor version of ID3v2. This is because these two parameters are important to text information. In the next version both of them will be automatic.
You can get a list of all text frames related to file from
File.ID3v2Info.TextFrames. To get a list of
FrameIDs look at the
FrameID table.
If the application can't find what the
FrameID means, it will not delete that. That frame will add to an unknown frames array (
File.ID3v2Info.UnKnownFrames). There is also a boolean property indicating if you would like to save unknown frames (
File.ID3v2Info.DropUnknown).
Linked frames are information that is attached from another file. For example, you can attach a picture to one file, and for another file in the same album use a linked frame to add the same picture from that file. In this way you will save memory and consume less memory, saving data.
Linked frames indicate which
FrameID must read from which file. If you set
ID3File.ID3v2Info.LoadLinkedFrames' boolean properties to true the application will automatically load linked frames while loading data.
To save data you can call the '
ID3Info.Save()' method. This will save ID3v1 normally and ID3v2 with a minor version of 3. Or use
ID3Info.Save(MinorVersion of ID3v2). And finally, you can use
ID3Info.Save(ID3v2 minor version, Rename string). Rename string is a string that let you rename a file while saving. In rename string you can use [Title], [Track], [00Track], [000Track], [Album]. These are case sensitive.
ID3Info File = new ID3Info("Path", true); String MyText = File.ID3v2Info.GetTextFrame("TIT2") + " - " + File.ID3v2Info.GetTextFrame("TALB"); // Now my text contain Title � Album
using ID3; using ID3.ID3v2Frames.BinaryFrames // Code: ID3Info File = new ID3Info("Path", true); Image[] ImageArray = new Image[File.ID3v2Info.AttachedPictureFrames.Count]; for(int I = 0; I < File.ID3v2Info.AttachedPictureFrames.Count; i++) ImageArray[I] = Image.FromStream( ID3File.ID3v2Info.AttachedPictureFrames.Items[i]) // now ImageArray contain array of images attached to file
This method returns English lyrics if they exist.
using ID3; using ID3.TextFrames; ID3Info File = new ID3Info("Path", true); foreach(TextWithLanguageFrame TWL in File.ID3v2Info.TextWithLanguageFrames) if(TWL.FrameID == "USLT" && TWL.Language == "ENG") return TWL.Text; return null;
For more examples you can look at 'ID3 Editor' source code. If there are problems contact me.
Note: ID3 editor has a help feature you can use to understand how ID3 editor works. And the source code is available to see how to work with each frame.
I know parts of the ID3Class application need some changes. It can be more powerful. I will try to improve both the
ID3Info class and ID3 Editor. If you have any ideas about how this application can be more amazing contact me. Write comments here.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/Do_Anything_With_ID3.aspx | crawl-002 | refinedweb | 2,768 | 68.77 |
posix 4.0.0
posix: ^4.0.0 copied to clipboard
Provides Dart access to the POSIX api for osx and linux system.
import 'package:posix/posix.dart'; int uid = getuid();
Contributing #
Dart types only #
The api should only expose dart types. Any C types MUST be translated to dart types before being returned.
setters and getters #
One of the first questsion is to whether we should use Dart's settings and getters:
e.g.
// getuid int uid = getuid; or int uid = getuid(); /// setuid uid = myuid; or setuid = uid; or setuid(uid);
My initial thoughts is to make the api identical to the posix api which would mean that we don't use Dart setters and getters.
error returns #
Do we return error no.s or do we throw.
As Dart is a modern language it uses Exception whereas posix returns error codes.
Often posix will return null and then expect you to make a separate call to 'errorno' to get the actual error no.
I'm inclined to bring the api that we expose into the modern world.
So I'm proposing that if an posix api returns an error that we throw a PosixException with a message and error code.
Adding additional functions #
The process of adding additional functions is:
- Install ffigen
dart pub global activate ffigen
- Run the ffigen setup.
The paths may be different on your system. Search for clang-c/Index.h
sudo apt-get install libclang-dev dart pub run ffigen:setup -I/usr/lib/llvm-11/include -L/usr/lib/llvm-11/lib
find the required posix header file
use ffigen to create the initial dart file from the header.
- add your header file to ffigen.yaml
Run ffigen
dart pub run ffigen --config ffigen.yaml
- convert each method to take/return dart types. | https://pub.dev/packages/posix | CC-MAIN-2022-40 | refinedweb | 301 | 65.62 |
note Haarg <p>If you don't clean your imports using something like namespace::autoclean or namespace::clean, then they will remain and be callable as methods on your objects. So something like the following will work and issue a warning with your object stringified:</p> <code> package Foo; use Moose; use Carp; Foo->new->carp; </code> <p>This is usually not harmful, although it can be unexpected or allow people to accidentally call things in unusual ways. Cleaning your imports also allows you to re-use those imported sub names as method, such as for attributes. That means that the following will work:</p> <code> package Foo; use Moose; use namespace::autoclean; has after => (is => 'ro', default => 'yay'); print "It worked " . Foo->new->after; </code> <p>Normally, after would be one of Moose's helpers that creates a method modifier, but cleaning it using namespace::autoclean allows an attribute with the same name to be created.</p> 1229960 1229960 | https://www.perlmonks.org/index.pl/?node_id=1229961;displaytype=xml | CC-MAIN-2020-50 | refinedweb | 160 | 55.78 |
I’ve managed to change the code of Redis-Benchmark to give real results on my computer for the last MarkLogic comparison. Read on for final results! Check out the previous post here.
I forked the Redis code and patched src/redis-benchmark.c to add support for the HSET and HMSET commands! Was actually a lot easier than expected thanks to how well written the benchmark harness is to support random key names and test data.
Below are the results for HSET – setting a single random field on a named hash:-
adamfowbookwork:src adamfowler$ ./redis-benchmark -h 192.168.123.4 -n 100000 -r 100000 -t hset -c 50 ====== HSET ====== 100000 requests completed in 4.60 seconds 50 parallel clients 3 bytes payload keep alive: 1 0.00% <= 1 milliseconds 8.01% <= 2 milliseconds 98.28% <= 3 milliseconds 99.69% <= 4 milliseconds 99.81% <= 5 milliseconds 99.89% <= 6 milliseconds 100.00% <= 6 milliseconds 21739.13 requests per second
And below are the results for HMSET, setting 10 fields in a single call on random fields on a named hash:-
adamfowbookwork:src adamfowler$ ./redis-benchmark -h 192.168.123.4 -n 100000 -r 100000 -t hmset -c 50 ====== HMSET (10 keys) ====== 100000 requests completed in 5.85 seconds 50 parallel clients 3 bytes payload keep alive: 1 0.00% <= 1 milliseconds 0.28% <= 2 milliseconds 71.92% <= 3 milliseconds 97.45% <= 4 milliseconds 99.31% <= 5 milliseconds 99.51% <= 6 milliseconds 99.58% <= 7 milliseconds 99.60% <= 8 milliseconds 99.67% <= 9 milliseconds 99.70% <= 11 milliseconds 99.78% <= 12 milliseconds 99.84% <= 13 milliseconds 99.88% <= 14 milliseconds 99.88% <= 17 milliseconds 99.90% <= 19 milliseconds 99.90% <= 20 milliseconds 99.92% <= 22 milliseconds 99.92% <= 25 milliseconds 99.95% <= 64 milliseconds 99.99% <= 65 milliseconds 100.00% <= 65 milliseconds 17094.02 requests per second
This looks like HMSET is slower, but if you think about it you’re actually saving 10 pieces of data per request, so it’s pretty damn performant! 10x the amount of data for approx a 20% performance hit. Not bad.
I was expecting somewhere between 3.5x and 5x speed over MarkLogic’s saving of documents with 10 fields (XML elements)…
Our results from yesterday for saving 100000, 10-element documents in MarkLogic: 3225.80 per second.
This means for simple aggregates Redis hashes are only 5.3 times faster than MarkLogic. So my guestimate wasn’t far out. I guess the Redis guys and gals have done some performance tuning since the blog post I was basing my performance factors on!
A Different MarkLogic Client
MarkLogic Content Pump (MLCP) has overheads and is likely not that highly tuned as redis-benchmark. I’ve also downloaded and tested the xmlsh application with the MarkLogic extension to xmlsh.
I’m still reading files off disc, so there’s a significant IO penalty that redis-benchmark doesn’t suffer from.
Here’s the ingest.sh file:-
#!/bin/sh export XMLSH=./ export MLCONNECT=xcc://admin:admin@192.168.123.4:7777/Documents export XMODPATH=./ext
date ./unix/xmlsh ./ingest.xh date
And the ingest.xh XMLSH file:-
import module ml=marklogic
ml:put -baseuri /test/ -uri "doc{seq}.xml" -x -repair none -maxthreads 20 -maxfiles 30 -r aggregates
This now takes 28 seconds, which means a total throughput of 3571.43 documents per second. This can probably be improved upon, but it’s sufficient for my tests today.
Using a RamDisk Instead of Spinning Disc
After some tuning, I created a RamDisk on my mac instead of the spinning HDD, and modified ingest.xh to be the following:-
ml:put -baseuri /test/ -uri "doc{seq}.xml" -x -repair none -maxthreads 20 -maxfiles 30 -r aggregates
This gave final execution in 27 seconds repeatedly, giving a throughput of 3703.70 docs / second.
This means that Redis is 4.61 times faster than MarkLogic in storing these very simple aggregates.
NB I also assigned 6 cores (3 cores – 6 hw threads) to the vmware image to see if that helped… it didn’t!
Configuring Memory Caches to Minimize Disc Writes
MarkLogic appends data to in memory stands and journals to disc. This is limited to 16 MB though. My data load is about 35 MB. My changing the list cache and tree cache sizes to 64 MB I should avoid added disc penalties.
Running the same test again gives 39 seconds – so slower! This probably means I’m actually within the margin of error between my tests.
Configuring Two Forests Instead of One
My testing shows I’m CPU bound rather than IO bound on the MarkLogic Server. This is because the app server threads are blocking until the Forest (shard) managing thread completes. Probably ideal for a VMWare disc and network test, as these are not the bottlenecks.
I’ll configuring 2 forests instead of the default 1 to balance out this problem. A slight cheat as Redis was only running on 1 core, and this is equivalent to running 2 cores (2 redis instances), but interesting none the less.
I also changed the vmware image back to 4 hw threads (2 physical cores) so its an apples to apples comparison again.
The results were… still 28 seconds. So it looks like I’m still CPU bound, and that’s where the issue lays in my testing.
What Does This Mean?
A Key-Value store is generally expected to be 50x faster than a document store due to how it works – we see only up to 4.6x a performance difference. That’s a factor of ten less speedy (technical term!). We have shown that the more complex the aggregates operations get, and especially the more paranoid you are about data consistency and durability, the closer the performance of the two databases are.
This is not surprising. Redis is built for blazingly fast read queries. MarkLogic is built for fast but complex query loads – they therefore have different performance characteristics on the writing side of things.
Practically, it shows that a document store like MarkLogic is not fundamentally disadvantaged in pure write performance. Thus if you have complex query loads or data models then use MarkLogic, if not then feel free to use Redis.
How Can the Tests Be Improved?
I would really like to spend time altering redis-benchmark so that both hash, list and field names, and values can all be randomised so you can test update versus create workloads. I’ve done this for HMSET using random hash and field names.
I also suspect that the bigger the aggregates (more fields/elements) then the nearer MarkLogic will get to Redis. Trying 100 elements per hash/document may be a useful test. As would be nested hashes, if indeed Redis supports those?
I’d also like to have a benchmarking app written in C or C++ against MarkLogic’s REST API rather than using Java against the XCC API – as this would give better client performance and test the part of the server most applications would use (REST).
I suspect MarkLogic’s performance would be significantly closer to Redis if using a better client – or simply generated the XML from a variable rather than reading from the file system/RAM disc. I’ll hunt around for an alternative to MLCP (Content Pump) and XMLSH in the meantime.
Actually, I’ll contribute the Redis benchmark code back first, as I’m sure you’ll want to play with those tests!!! Here’s the pull request for my changes. Enjoy!
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/update-hybrid-nosql-marklogic-as-a-key-value-store | CC-MAIN-2017-34 | refinedweb | 1,266 | 68.77 |
One challenge I’ve hit upon when producing multi-page apps is ensuring that component IDs for each page are unique., which is a requirement for Dash apps. This starts to become challenging with even a handful of pages, as callbacks across pages can do very similar things, resulting in the desire to use similar IDs. This also makes re-using/copying pages for new (and similar pages) difficult, as you have to go through and uniquify the IDs.
My current best approach to namespacing layout fragments is to traverse the layout tree, patching each component’s ID (if it has one) with the desired prefix.
Callbacks are a bit uglier though as I currently use f-strings templates in order to to namespace them with a parameter. eg:
ID_PREFIX = "page1_" @app.callback( Output(f"{ID_PREFIX}some_div", "children"), [ Input(f"{ID_PREFIX}text-input", "value"), Input(f"{ID_PREFIX}num-input", "value") ] ) def some_func(text, num): return "output"
Curious to know if anyone has come up with some cleaner strategies than this. | https://community.plotly.com/t/ideas-for-namespacing-component-ids/22446 | CC-MAIN-2022-21 | refinedweb | 170 | 52.29 |
Introduction:
Here I will explain how to export gridview data to PDF using asp.net.
Now if you’re getting any error message like
Here I will explain how to export gridview data to PDF using asp.net.
Description:
In my previous articles I explained clearly how to export gridview data to excel or word and how to export gridview data to CSV file . Now I will explain how to export gridview data to PDF using asp.net. In asp.net we don’t have direct feature to export gridview data to PDF for that reason here I am using third party library ITextSharp reference. The dll is available here ITextSharp first download dll from this site after that create one new website in visual studio and add ITextsharp dll reference to newly created website after these references
After that write the following code in code behind
Demo for PDF
158 comments :
i m using the literal data to convert pdf file and an exception occurs after htmlparser.Parse(sr);
line.Please help me..........
hi tiwari i think this problem with pdf dll you should download my attached code and use existing dll in code for your requirement it will work for you
hey suresh...i am using your above code to export data to pdf, when i debug,the function is called but no pdf is created or downloaded. how do i fix this? i am not getting any errors too.
hey suresh...i am using your above code to export data to pdf, when i debug,the function is called but no pdf is created or downloaded. how do i fix this? i am not getting any errors too. how do i debug to see what's wrong and if the pdf is created or not?
the pdf was created successfully but its shows only two lines in vertical thats it please explain it again
hi sindhu,
have you used my attached code dll or another one download attached code dll and try it will work for you
hi,
i check the code it's working fine please check your code once again i think you are making mistake during binding the gridview
awesome work.please continue with these type of services bro.
thanks raja keep visiting.......
error on opening adobe reader token not recognized.
hi subhash that problem with dll in itextsharp you should download attached code and use my dll in your code it will work for you i already mention same thing in comments check it once.
i get pdf but it shows only single column of the gridview...any idea.
hi,
please check your code once again i think you are making mistake during binding the gridview
my pdf working fine...but on upload to the server giving error..namespace itextsharp could not found...suggest somthing...also without using third party tool.
Hai Suresh..thank for your valuable code.. i got an error when i opened PD F file i,e
THERE WAS AN ERROR OCCURRED.WHEN OPENING FILE. THE FILE COULD NOT BE CREATED...
Please do the needful..
Hi, Suresh.. thanks a lot for your help.. My code is working fine.. Keep this good work up.. Thanks again..
Subhadeep
Hello,Suresh I got this error while using this code
Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.
the pdf was created successfully but its shows only two lines in vertical thats it please explain it again
AND
get pdf but it shows only single column of the gridview...any idea.
ANSWER :
check ur compatibility view settings or browser
Hi Suresh,
Thank you for your code sample.
You code worked beautifully on gridview with siource table with few columns. However, I get parcing error "Illegal characters in path" at line "Dim sr As New StreamReader(sw.ToString())" when I use a table with much more columns.
Any suggestions?
Best regards,
Michael
It shows me this error 'System.IO.IOException: The document has no pages.'
hi Suresh,
i would like to export data to pdf from windows application so can u please help me .
thanks for the article...its very useful...
Hi Suresh...
How can we put a heading to the pdf file before the grid appears...plz help...
Dear, i tried but i found below prob;
Server Error in '/' Application.
Format of the initialization string does not conform to specification starting at index 0.
could you please help me, as i tried multiple time as i have changed connection string many time but prob is not yet resolved :(
convert pdf from gridview problem for fill cs file
Hi..
i got the output pdf but without any colors i got the plain table.how to achieve the colors n styles applied.
hi
this is rekha ,i tried above code bt it showing an error (Illegal characters in path).....:(
can u please help
it's good
what program in gridview to pdf in windows application
System.ArgumentException: Font size too small: 0
when I export the gridview, It's header style backcolor is not getting exported. Can you please, explain me the reason.
when i export the gridview getting error like "System.ArgumentException: Font size too small: 0".
please relpy me sir..
how to convert aspx page to pdf using iTextSharp
and i used gridview to pdf code. but when control reaches pdfDoc.close(), i m getting error message "the document has no pages" y its so
hi, mr.Suresh Dasari
I tried your code.
to export pdf from GridView.
exporting is working but
I cannot change font family and font-size.
please help me.
thanks
Suresh, Thank you for the post.
The PDF produces an outupt, but I get no header row or color. Is there a particular version of iTextSharp.dll that I have to use?
I am using Internet Explorer 6 (old I know) and also FireFox 10.02 with the same results.
Thank you.
how to export only single column ?
Hello boss how to implement StringWriter and StringReader ?? i can't understand this 2 things..
thanks
Hai Sir,I have one query,If am uploading pdf files.i want see that pdf file in own page.its not display any save r open options like in windows we are using adobe reader component na like that i have to display in web pages.it should be displayed in panel like scrolls pls give me solution for this query.its too urgent sir........
loooks good.
hi suresh,
Export Selected GridView Rows to pdf in ASP.NET,i need code can u send me and my mail id msureshbabu15@gmail.com
@sureshbabu......
check below post to export selected rows of gridview
good article suresh
Hi suresh, I downloaded the iText (5 dlls inside it).In which folder i put that dll.I'm using Visual studio 2010 professional ?
Good one
Good one... Helped me a lot...
hello suresh, first of all i admire your work that you have been doing and its amazing how helpful you are, i have a question, i have been able to export the entire grid as a pdf, but what if i want to write some text ontop of the export, like a heading and some description about the data, how will i be able to do that.
The given key was not present in the dictionary. i have this error
i press in the button and does not do anything
please help me
hello suresh,
im gettin an error while opening the pdf file.it says the file may be corrupted.plz help
I got the error when try to have both the PDF and the Excel:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0117: 'iTextSharp.text.Color' does not contain a definition for 'White'
Source Error:
Line 72: foreach (GridViewRow gvrow in gvdetails.Rows)
Line 73: {
Line 74: gvrow.BackColor = Color.White;
Line 75: if (j <= gvdetails.Rows.Count)
Line 76: {
Error 2 Cannot implicitly convert type 'iTextSharp.text.Color' to 'System.Drawing.Color'
Hi guys
I could help but exported to pdf code vb. .net
how to get code from .exe file.if it is there pls tel me
Hey suresh am just a Beginner in c# and you help me out in solving this error
cannot convert from 'System.IO.StringReader' to 'System.IO.StreamReader'
Hi suresh, How to add textbox along with this girdview control which is present outside the gridview. Please help me
Thanks
Naresh
am getting the error as
The document has no pages. please help me...
u r a saviour!!!
Hello, I have learned many things from your post its really nice and also useful for me. Thanks for sharing.
Thank you
Font Converter
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
i am getting problem when i include these namespaces.
please provide solution.
it does not work in online
Dear Sir, your code works well in local. But I upload this in online I got security exception error. how can i fix this. ...
thanks in advance...
Can i export any panel in to pdf??
If yes then plz provide code for it
sir how can i uploaded pdf file data in editing mode....
or how to export gridview data to pdf
superb
your code was useful..only problem i m facing is that when pdf is genrated,griedviw data is shown properly but why not itz header row and style???header row is blank......
at localhost its working fine but on server it is generating error for security
superb man keep up the good work does this work for datalist too?
Hi suresh,
i needed a demo article on "aspx page content(i.e page should contain text boxes, check box, panels, collapsible panels..)and when ever the button is clicked the page data of the server side should be converted into pdf format"
can u plz upload the article which will be useful to others also....
Hi suresh,
How to export images from gridview to word with 150 height and 150 width.
Thank You
hi suresh,
Thanks for your valuable post.I've one requirement like Exporting a dymamic gridview's data....which is inside a Ajax Collapsible panel extender....as it is to a pdf document
hi i am convert to detail view to pdf
but i have error like this please give me a sum idea to this error
The document has no pages.
pdfDoc.Close();
Hi Suresh, your code working fine with Gridview, however, is it possible to change this to DataList? When I'm trying with DataList control with Templatefield columns, it's showing error: "The document has no pages". But databind is fine and same list is successfully getting export to Excel. Can you please help me to tweak this code for DataList, if any? Anirban
Thanks Suresh for your code. When doing databind without templatefield in gridview, it's working fine. However, when there is templatefield with HTML table inside it, PDF file saying corrupt and can't be opened. Is there any special treatment for templatefiled? Please help me. Thanks again, A. Maitra
hi suresh,
Export Selected GridView Rows to pdf in ASP.NET,i need code can u post that code
hello suresh i use ur code in 2010 but no pdf generated.
Hi,
Gridview is exported to pdf. But showing one line in bottom of the pdf file i.e.
//(function() {var fn = function() {$get("ctl00_ToolScriptmgr_HiddenField").value = '';Sys.Application.remove_init(fn);};Sys.Application.add_init(fn);})();//
Please solve my problem
Thanks
Hi Suresh..I want to open this converted pdf file to
browser..is it possible to directly open in browser without downloading ...if it is possible how?
Hi, Thanks a lot. Your coding is working good. But if i merge some cells in grid, i couldn't convert that to PDF file correctly. All rows and columns are not coming in proper way. But the Excel conversion is good. Please help to solve this problem.,
Thank's.,
hi...
i m gettin below error while exporting formview to pdf
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The document has no pages.
Source Error:
Line 82: htmlparser.Parse(sr);
Line 83:
Line 84: pdfDoc.Close();
Line 85:
Line 86: Response.Write(pdfDoc);
Hi,
Your code is working fine for me when am clicking 'btnPDF' for the first time.From second time on wards, it is not working.
Note: If i refresh the page once, then the btnPDF_Click is working. That is also first time after refresh.
Do u have any idea on this?
Thanks in advance!
Thanks a lot suresh finally succeeded after copying your itextsharp dll..
hi suresh im having prblm wid this dll cn u plz give me d solution dis code is not wrking for me
actually i am running with one problem,
ie. my html form contains lables and textboxes
itwork fine to render lables on PDF but textboxes values are not rendering on pdf .
can we have solution for that?how?
Hi Suresh,
After using ur coding and dll, i have below problems
"Could not load file or assembly 'itextsharp, Version=4.1.6.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"
hi suresh......
the code is running sucessfully, but the pdf file which is downloaded is showing an error message in this way "there was an error opening this document.the file is damaged and could not be repaired".
will u plz check it once..
please give the solution
Hi Suresh,
This is Arun from Chennai. Thank you for your post. Export to Excel is working fine with me. While working on the Export to PDF, a blank pdf is getting generated with gridview borders and colors and without text.
There are 7 rows in Gridview and 7 rows are displayed in PDF without any text on it.
Please advise how to solve it.
The document has no pages.
HOW TO REMOVE THIS ERROR
suresh..how to transfer the web application data to pdf format in button click
suresh please help me......how to pass the data to pdf in button click..i don't know how to design the labels & textbox..in pdf..
im getting error on pdfDoc.Close(); the error is:
The document has no pages.
plzz help its urgent... thnx in advance :)
I am getting this error
Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.html.simpleparser.TableWrapper'. please help
Server Error in '/' Application.
Control 'MainContent_gridstorageshow' of type 'GridView' must be placed inside a form tag with runat=server.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Control 'MainContent_gridstorageshow' of type 'GridView' must be placed inside a form tag with runat=server.
Source Error:
Line 49: gridstorageshow.AllowPaging = false;
Line 50: gridstorageshow.DataBind();
Line 51: gridstorageshow.RenderControl(hw);
Line 52: Response.Output.Write(sw.ToString());
Line 53: Response.Flush();
how to create header report?
Hi,
I'm having master page. I want to print the whole page with the values in PDF. Can anyone help me on this. Please its urgent. Thanks
Regards,
Umesh
I see few people added the error error 'System.IO.IOException: The document has no pages.'
Did anyone figure out the prob. If so can someone please update.
Is this ITextSharp dll is free
sir is there any way to store data(using fileupload) in text format or string format rather than using binary format .
Hai suresh,
im exporting ASP.Net Panel control (which is rendered as HTML DIV) to PDF using iTextSharp, but my problem is after exporting it to pdf when i look at that document the labels present in the document are scattered through out the page. may i know the problem !!
thanks in advance
Hi,
Excelent help, it's works but a need to put titles on header of the grid view and i can't do it...someone can tell me how???
thanks in advance
Hi Suresh,
Great job man ... But i do have one doubt ... only changing or replacing my dll with yours provided in your code ... how does it solve the problems ??
I am getting Error like this please help me Suresh The best overloaded method match for
'iTextSharp.text.html.simpleparser.HTMLWorker.Parse(System.IO.StreamReader)' has some invalid arguments
I got this error please help me
Server Error in '/ExportGrid' Application.
The DataSourceID of 'gvdetails' must be the ID of a control of type IDataSource. A control with ID 'dsdetails' could not be found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The DataSourceID of 'gvdetails' must be the ID of a control of type IDataSource. A control with ID 'dsdetails' could not be found.
Source Error:
An unhandled exception was generated during the execu
Hi,
I'm trying to convert the entire page export to pdf
and used the below code to render entire page.
this.Page.RenderControl(hw),But ,below error throws in html parser...Pls help me in this..
The number of columns in PdfPTable constructor must be greater than zero.
hi mr.suresh i used your code. its runing 100% fine with local host, but when i uploaded the application on the server, it gives an error.
server could not find the file from the "Bin" folder. how to fix this problem.
Line 7: using iTextSharp.text;
Compiler Error Message: CS0246: The type or namespace name 'iTextSharp' could not be found (are you missing a using directive or an assembly reference?)
hiii sir
i have a query, if i have two grid view on page and i want to convert one grid view data into pdf please tell me how can i convert it.I am converting in pdf, but the pdf file contain both grid data. Please Reply
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
gvdetails.RenderControl(hw);
gvdetails.HeaderRow.Style.Add("width", "15%");
gvdetails.HeaderRow.Style.Add("font-size", "10px");
gvdetails.Style.Add("text-decoration", "none");
gvdetails.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
gvdetails.Style.Add("font-size", "8px");
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
I have used your code and it works superb, thanks .
However I have another requirement that I have a page which contains some static data likes labels and textbox values, then gridveiw data, then again some labels. How will you export all these details into one pdf? Can you pls help me?
Hie Suresh
Thnax in advance for your excellent codes . I have used above code to export grid view data to adobe file in a neat & presentable manner. It worked well in localhost. But when i uploaded the files in to my domain, its not working . Could you please tell me why ? . I tried many times but in vain...
sir i want to add a new row at the top of pdf file like a header but i don't want to display in our web application when i am running , the header only display when we download gridview data into pdf format
WHICH BUUTON YOU USE FOR WRITTING THIS CODE
Is this Normal button Which You Write a Coding bcoz i found error nesr Response??///
can you send me VB code for same task....
thanks
this article works and convert the gridview into pdf but gridview rows are not converted into pdf only header of grid view columns are coming. Y does it happens any one help me
Nice article, but how would you add a header with image next to it above the gridview in the PDF?
Never mind my previous question, I found the answer:
string imagepath = Server.MapPath("Images");
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imagepath + "/MyImage.jpg");
Paragraph paragraph = new Paragraph(@"Programming is Great Stuff!");
paragraph.Alignment = Element.ALIGN_CENTER;
paragraph.SpacingAfter = 35f;
in my grid view images are there when i am click on print,its getting path error suresh
hello suresh,
I want one solution for pdf file-
I convert my webpage to pdf format, but i want to pass my gridview column widths also in pdf, pdf takes it's own widths.
I want to display same format of gridview in pdf file.plz help me. thanks
Hi,
i have tried the code but but m getting an error
ie.
The document has no pages.
The document has no pages.
After generating pdf only show gridview row...,no any data in gridview...
Hello All,
Who are getting page not found error plz remove following lines from code
gvdetails.AllowPaging = false;
gvdetails.DataBind();
Thanks.
I want SUMMARY TABLE,gridview data,Graph based on data,Page Number,Logo in heading,Minimum 2 graphs per page in Email_Id is Kapilbhati2310@yahoo.com
hi sir......
i have a problem related to pdf .in my gridview have have some tools like label(Which is used to display the data).and no any rows and colon ,
In my gridview basically display the Information about the Proforma Invoice .
like..... name jagat singh yadav Id -1423
programe MCA
and also display picture like logo..........
So please Help me .if you have any solution about this please tell............
hi,
use your converted code in VB but gives me error:
String format INPUT INCORRECT
pdfDoc.Open ()
htmlparser.Parse (sr)
pdfDoc.Close ()
my page is .aspx page containing 2 table, 1 div and some labels with data loaded from SqlDataSource. . . .
can you give me some indication,
thanks
sorry my english . . . . .
Si usan Master Page, se soluciona de esta forma agregando en el web.config esto
"system.web"
"pages buffer="true"
masterPageFile = "~/Site1.master"
enableEventValidation="false""
" /pages"
"/system.web"
I have this error:
"The document has no pages."
please guide me.
Nice work brother,, could you pls put some code how to read content from pdf and display it in gridview..?
The type or namespace name 'iTextSharp' could not be found (are you missing a using directive or an assembly reference?)
After adding reference it still shows the error like above.
hi! how to convert text box value and background image to pdf file using itextsharp
hii suresh, how can we set heading line in pdf
I have bind my datagrid view programatically
when i download i get nothing
I want to display the Header and footer for the pdf with logo. Can please help me...
hii sir ,
sir i want to say that i text dll can be used for editing the pdf documents like draw a cropa ,line sticky notes as .. if possible then pl send some code to neelugupta30@gmail.com. thanks
How i export Grid (Large data more than 1 lac ) data to PDF in .net ?
hi suresh,
i use your code but it's not exporting my gridview data to pdf.
my scenario is like this i have a input form which has text boxes and drop down lists on it after having input from user data is saved in database and bind into grid view. after that i want to export grid view data to pdf.
also that my grid view has multiple pages.
In my case when i click export button focus will go back to first field of the form.
pls help what to do.
thanks.
Dear suresh sir,
iam reading your articals lost couple of months
but now i have a problem
i need to export the a c#.net windows page data to pdf
in that form i don't have datagrid
i have labels and txtboxes but
i need to export the data to pdf..
help me asap
thanks and regards
prasad bhagat
Sir can you explain step by step for clear understanding?
thanx in advance
Hello suresh,
Can you say how to customize the gridview widths in pdf as of in web page as the itextsharp is taking gridview as "table"
sorry , i solved that problem .but i got error on
System.IO.IOException was unhandled by user code
HResult=-2146232800
Message=The document has no pages.
Source=itextsharp
help me.
1.Please upload code for import selected gridview coloumns data into graph
2.please upload code for import slected grid view data into excel or pdf without using check box
Mine does not print the column headings, Please HELLLLP
i have an error "document have no pages"
i m not getting an option of stringwriter in my .net wat to do
inside update panel gridviw data does not get exported
protected void Button4_Click(object sender, EventArgs e)
{
ExportGridToPDF();
}
private void ExportGridToPDF()
{
gvregistration.Visible = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;REGISTRATION1.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvregistration.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
GridView1.AllowPaging = true;
GridView1.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.IO;
using System.Text;
For me it occurs an error as
Unable to cast object of type 'iTextSharp.text.html.simpleparser.IncTable' to type 'iTextSharp.text.IElement'.
I am getting error on hw.Parse(sr);
"Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.
MyCode
public void GeneratePDF()
{
string body;
//Read template file from the App_Data folder
using (var sr = new StreamReader(Server.MapPath("\\PDFTemplate\\") + "test.html"))
{
body = sr.ReadToEnd();
}
if (User.Identity.IsAuthenticated)
{
string filenm = "MyIDCard.pdf";
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline;filename=" + filenm + "");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
ApplicationDbContext db = new Models.ApplicationDbContext();
var userId = User.Identity.GetUserId();
ApplicationUser user = db.Users.Where(x => x.Id == userId).FirstOrDefault();
string pdfBody = string.Format(body,user.FirstName,user.LastName,user.Email,user.PhoneNumber );
StringReader sr = new StringReader(pdfBody.ToString());
Document pdfDoc = new Document(PageSize.A6,1f,1f,1f,1f);
HTMLWorker hw = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
hw.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
}
same problem guys !! is there a solution for HTMLworker is obselete !!
Note: Only a member of this blog may post a comment. | https://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-pdf.html?showComment=1306756475577 | CC-MAIN-2020-16 | refinedweb | 4,569 | 68.57 |
Full file at
CHAPTER 2 THE NATURE OF COSTS P 21:
Solution to Darien Industries (CMA adapted) (10 minutes) [Relevant costs and benefits] Current cafeteria income Sales Variable costs (40% × 12,000) Fixed costs Operating income
$12,000 (4,800) (4,700)
Vending machine income Sales (12,000 × 1.4) Darien's share of sales (.16 × $16,800) Increase in operating income P 22:
$2,500
$16,800 2,688 $ 188
Negative Opportunity Costs (10 minutes) [Opportunity cost]
Yes, when the most valuable alternative to a decision is a net cash outflow that would have occurred is now eliminated. The opportunity cost of that decision is negative (an opportunity benefit). For example, suppose you own a house with an inground swimming pool you no longer use or want. To dig up the pool and fill in the hole costs $3,000. You sell the house instead and the new owner wants the pool. By selling the house, you avoid removing the pool and you save $3,000. The decision to sell the house includes an opportunity benefit (a negative opportunity cost) of $3,000. P 23:
Solution to NPR (10 minutes) [Opportunity cost of radio listeners]
The quoted passage ignores the opportunity cost of listeners’ having to forego normal programming for onair pledges. While such fundraising campaigns may have a low outof pocket cost to NPR, if they were to consider the listeners’ opportunity cost, such campaigns may be quite costly.
2-1
Full file at
P 2–4:
Solution to Silky Smooth Lotions (15 minutes) [Break even with multiple products]
Given that current production and sales are: 2,000, 4,000, and 1,000 cases of 4, 8, and 12 ounce bottles, construct of lotion bundle to consist of 2 cases of 4 ounce bottles, 4 cases of 8 ounce bottles, and 1 case of 12 ounce bottles. The following table calculates the breakeven number of lotion bundles to break even and hence the number of cases of each of the three products required to break even. Per Case Price Variable cost Contribution margin Current production Cases per bundle Contribution margin per bundle
4 ounce $36.00 $13.00 $23.00 2000
8 ounce $66.00 $24.50 $41.50 4000
12 ounce $72.00 $27.00 $45.00 1000
2
4
1
$46.00
$166.00
$45.00
Fixed costs
P 2–5:
$257.00 $771,000
Number of bundles to break even Number of cases to break even
Bundle
3000 6000
12000
3000
Solution to J. P. Max Department Stores (15 minutes) [Opportunity cost of retail space]
Profits after fixed cost allocations Allocated fixed costs Profits before fixed cost allocations Lease Payments Forgone Profits
Home Appliances Televisions $64,000 $82,000 7,000 8,400 71,000 90,400 72,000 86,400 – $1,000 $ 4,000
We would rent out the Home Appliance department, as lease rental receipts are more than the profits in the Home Appliance Department. On the other hand, profits generated by the Television Department are more than the lease rentals if leased out, so we continue running the TV Department. However, neither is being charged inventory holding costs, which could easily change the decision. Also, one should examine externalities. What kind of merchandise is being sold in the leased store and will this increase or decrease overall traffic and hence sales in the other departments? 2-2
Full file at
P 2–6:
Solution to Executive Stock Options (15 minutes) [Opportunity cost of stock options]
The statement that there is “no cost to the company” is wrong. As soon as this stock option is granted, the number of shares having claims on the firm’s future cash flows increases by the expected likelihood that this option will be exercised. Existing shareholders’ claims on the future cash flows have been diluted. Thus, there is an opportunity cost imposed on the existing shareholders by issuing stock options to directors. They are not free. There is no cash outlay to the firm when stock options are issued; accounting earnings are not affected by issuing stock options (as long as they are issued at or above the current stock price), but there is a cost to the shareholders. P 27: a.
Solution to Bidwell Company (CMA adapted) (15 minutes) [Simple breakeven analysis] Breakeven
= =
$210, 000 = 70,000 units ($10 - $7)
b.
[10Q – 7Q – 210,000](1 – .4) = (3Q – 210,000) (.6) = 3Q = Q =
c.
Breakeven
P 28:
=
90,000 90,000 150,000 + 210,000 120,000
$241,500 = 80,500 units $3/unit
Solution to Vintage Cellars (15 minutes) [Average versus marginal cost]
2-3
Full file at
a.
The following tabulates total, marginal and average cost. Quantity 1 2 3 4 5 6 7 8 9 10
Average Cost $12,000 10,000 8,600 7,700 7,100 7,100 7,350 7,850 8,600 9,600
Total Marginal Cost Cost $12,000 20,000 $8,000 25,800 5,800 30,800 5,000 35,500 4,700 42,600 7,100 51,450 8,850 62,800 11,350 77,400 14,600 96,000 18,600
b.
Marginal cost intersects average cost at minimum average cost (MC=AC=$7,100). Or, at between 5 and 6 units AC = MC = $7,100.
c.
At four units, the opportunity cost of producing and selling one more unit is $4,700. At four units, total cost is $30,800. At five units, total cost rises to $35,500. The incremental cost (i.e., the opportunity cost) of producing the fifth unit is $4,700.
d.
Vintage Cellars maximizes profits ($) by producing and selling seven units. Quantit y 1 2 3 4 5 6 7 8 9 10
Average Cost $12,000 10,000 8,600 7,700 7,100 7,100 7,350 7,850 8,600 9,600
Total Cost $12,000 20,000 25,800 30,800 35,500 42,600 51,450 62,800 77,400 96,000
2-4
Total Revenue $9,000 18,000 27,000 36,000 45,000 54,000 63,000 72,000 81,000 90,000
Profit $3,000 2,000 1,200 5,200 9,500 11,400 11,550 9,200 3,600 6,000
Full file at
P 29:
Solution to Sunnybrook Farms (CMA adapted) (15 minutes) [Incremental costs and revenues of extending retail store hours] Annual Sunday incremental costs ÷ 52 weeks Weekly Sunday incremental costs
$24,960 $ 480
Sunday sales to cover incremental costs 480 ÷ (.2)
$ 2,400
Sunday sales to cover lost sales during the week 2,400 ÷ (1 – .6)
$ 6,000
Check: Sunday sales Additional Sales due to Sunday ($6,000 × 40%) Gross Margin on additional sales ($2,400 × 20%) × 52 Weeks P 210: a.
$ 6,000 $ 2,400 $ 480 $24,960
Solution to Taylor Chemicals (15 minutes) [Relation between average, marginal, and total cost]
Marginal cost is the cost of the next unit. So, producing two cases costs an additional $400, whereas to go from producing two cases to producing three cases costs an additional $325, and so forth. So, to compute the total cost of producing say five cases you sum the marginal costs of 1, 2, …, 5 cases and add the fixed costs ($500 + $400 + $325 + $275 + $325 + $1000 = $2825). The following table computes average and total cost given fixed cost and marginal cost.
2-5
Full file at
Quantity
Marginal Cost
Fixed Cost
Total Cost
Average Cost
1
$500
$1000
$1500
$1500.00
2
400
1000
1900
950.00
3
325
1000
2225
741.67
4
275
1000
2500
625.00
5
325
1000
2825
565.00
6
400
1000
3225
537.50
7
500
1000
3725
532.14
8
625
1000
4350
543.75
9
775
1000
5125
569.44
10
950
1000
6075
607.50
b.
Average cost is minimized when seven cases are produced. At seven cases, average cost is $532.14.
c.
Marginal cost always intersects average cost at minimum average cost. If marginal cost is above average cost, average cost is increasing. Likewise, when marginal cost is below average cost, average cost is falling. When marginal cost equals average cost, average cost is neither rising nor falling. This only occurs when average cost is at its lowest level (or at its maximum).
P 211:
Solution to Emrich Processing (15 minutes) [Negative opportunity costs]
Opportunity costs are usually positive. In this case, opportunity costs are negative (opportunity benefits) because the firm can avoid disposal costs if they accept the rush job. The original $1,000 price paid for GX100 is a sunk cost. The opportunity cost of GX100 is $400. That is, Emrich will increase its cash flows by $400 by accepting the rush order because it will avoid having to dispose of the remaining GX100 by paying Environ the $400 disposal fee. How to price the special order is another question. Just because the $400 disposal fee was built into the previous job does not mean it is irrelevant in pricing this job. Clearly, one factor to consider in pricing this job is the reservation price of the customer proposing the rush order. The $400 disposal fee enters the pricing decision in the following way: Emrich should be prepared to pay up to $399 less any outofpocket costs to get this contract.
2-6
Full file at
P 2–12:
Solution to Gas Prices (15 minutes) [“Price gouging” or increased opportunity cost?]
The opportunity cost of the oil in process was higher after the invasion and thus the oil companies were justified in raising prices as quickly as they did. For example, suppose the oil company had one barrel of oil purchased at $15. This barrel was refined and processed for another $5 of cost and then the refined products from the barrel sold for $21. Replacing that barrel requires the oil company to pay another $15 per barrel on top of the $15 per barrel it is already paying. Therefore, in order to replace the old barrel, the prices of the refined products must be raised as soon as the crude oil price rises. However, accounting treats the realized holding gain on the old oil as an accounting profit, not as an opportunity cost. Therefore, the income statement of oil companies with large stocks of inprocess crude will show accounting profits, unless they can somehow defer these profits. Switching to incomedecreasing accounting methods and writing off obsolete equipment will help the oil companies avoid the political embarrassment of reporting the holding gains. In January 1990, the large oil companies received significant adverse media publicity when they reported large increases in fourthquarter profits. It is useful having discussed this problem to ask the following question: What happens to oil companies in the reverse situation when a large, unexpected price drop occurs? Suppose the oil company purchased old barrels for $15 and sold the refined products for $21. New barrels now can be purchased for $10. The company would like to keep selling refined products at $21, but competition from other oil companies will push the price of refined products down. Depending on how quickly the price of refined products fall, the oil companies will report smaller (maybe even negative) accounting earnings as their inventory of $15 oil gets refined and sold, but at lower prices. P 2–13: a.
Solution to Penury Company (15 minutes) [Breakeven analysis with multiple products]
Breakeven when products have separate fixed costs:
Fixed costs Divided by contribution margin Breakeven in units Times sales price Breakeven in sales revenue b.
Line K
Line L
$40,000 $0.60 66,667 units $1.20 $80,000
$20,000 $0.20 100,000 units $0.80 $80,000
Cost sharing of facilities, functions, systems, and management. That is, the existence of economies of scope allows common resources to be shared. For example, a smaller purchasing department is required if K and L are produced in the same plant and share a single purchasing department than if they are produced separately with their own purchasing departments. 2-7
Full file at
2-8
Full file at
c.
Breakeven when products have common fixed costs and are sold in bundles with equal proportions: At breakeven we expect: Contribution from K + Contribution from L = Fixed costs $0.60 Q + $0.20 Q = $50,000 where Q = number of units sold of K = number of units sold of L $0.80 Q Q Product K L
P 214:
= =
$50,000 62,500 units
Breakeven Units 62,500 62,500
Price $1.20 $0.80
Breakeven Sales $75,000 $50,000
Solution to University Tuition Benefits (15 minutes) [Opportunity cost of faculty and staff tuition benefits: tax incentives]
a.
It does not “cost” the University of Pennsylvania $7 million to send employee children to Penn and other schools. By offering this benefit, Penn is able to employ higher quality staff and faculty at a lower cost than if this benefit were not offered. Because this benefit is not taxed, Penn is able to give its employees $1 of benefits (tuition) that would cost the employees $2 (before personal taxes) if they had to pay the tuition themselves (assuming a 50 percent tax rate). Thus, employees are willing to accept up to $2 of lower wages for each $1 of tuition benefit. Also, if the employee’s child attends the parent’s institution, the cost to the institution is not the full amount of the tuition, if there is excess capacity in the classroom. However, given that all higher education is subsidized through either endowment or state aid, then the tuition does not cover the full cost of education. Adding 100 additional students each year, in the long run can cause the institution to forego admitting tuition paying students.
b.
Probably not. Case Western will either have to increase wages or see a reduction in faculty and staff quality. These tuition benefits are tax free. As long as some of the tax benefits are shared between Case Western and its employees (not all the tax savings accrue to the employees), then Case Western is worse off by cutting the tuition benefit. Moreover, cutting its tuition benefit for employee children who attend its graduate schools increases the price of its programs to these students. At the margin, some students will switch to other graduate programs. As with all price increases, fewer students will attend Case Western, and those that do will be of lower quality. 2-9
Full file at
P 2–15:
Solution to Volume and Profits (15 minutes) [Costvolumeprofit]
a.
False.
b.
Write the equation for firm profits: Profits = P × Q (FC VC × Q) = Q(P VC) FC = Q(P VC) (FC ÷ Q)Q Notice that average fixed costs per unit (FC÷Q) falls as Q increases, but with more volume, you have more fixed cost per unit such that (FC÷Q) × Q = FC. That is, the decline in average fixed cost per unit is exactly offset by having more units. Profits will increase with volume even if the firm has no fixed costs, as long as price is greater than variable costs. Suppose price is $3 and variable cost is $1. If there are no fixed costs, profits increase $2 for every unit produced. Now suppose fixed cost is $50. Volume increases from 100 units to 101 units. Profits increase from $150 ($2 ×100 $50) to $152 ($2 × 101 $50). The change in profits ($2) is the contribution margin. It is true that average unit cost declines from $1.50 ([100 × $1 + $50]÷100) to $1.495 ([101 × $1 + $50]÷101). However, this has nothing to do with the increase in profits. The increase in profits is due solely to the fact that the contribution margin is positive. Alternatively, suppose price is $3, variable cost is $3, and fixed cost is $50. Contribution margin in this case is zero. Doubling output from 100 to 200 causes average cost to fall from $3.50 ([100 × $3 + $50]÷100) to $3.25 ([200 × $3 + $50]÷200), but profits are still zero.
P 216: a.
Solution to American Cinema (20 minutes) [Breakeven analysis for an operating decision]
Both movies are expected to have the same ticket sales in weeks one and two, and lower sales in weeks three and four. Let Q1 be the number of tickets sold in the first two weeks, and Q 2 be the number of tickets sold in weeks three and four. Then, profits in the first two weeks, 1, and in weeks three and four, 2, are: 1 = .1(6.5Q1) – $2,000 2 = .2(6.5Q2) – $2,000 “I Do” should replace “Paris” if 2-10
Full file at
1 > 2, or
2-11
Full file at
.65Q1 – 2,000 > 1.3Q2 – 2,000, or Q1 > 2Q2. In other words, they should keep “Paris” for four weeks unless they expect ticket sales in weeks one and two of “I Do” to be twice the expected ticket sales in weeks three and four of “Paris.” b.
Taxes of 30 percent do not affect the answer in part (a).
c.
With average concession profits of $2 per ticket sold, 1 = .65Q1 + 2Q1 – 2,000 2 = 1.30Q2 + 2Q2 – 2,000 1 > 2 if 2.65Q1 > 3.3Q2 Q1 > 1.245Q2 Now, ticket sales in the first two weeks need only be about 25 percent higher than in weeks three and four to replace “Paris” with “I Do.”
P 217: a.
Solution to Home Auto Parts (20 minutes) [Opportunity cost of retail display space]
The question involves computing the opportunity cost of the special promotions being considered. If the car wax is substituted, what is the forgone profit from the dropped promotion? And which special promotion is dropped? Answering this question involves calculating the contribution of each planned promotion. The opportunity cost of dropping a planned promotion is its forgone contribution: (retail price less unit cost) × volume. The table below calculates the expected contribution of each of the three planned promotions.
2-12
Full file at
Planned Promotion Displays For Next Week Endof Aisle Texcan Oil
Front Door Wiper blades
Cash Register Floor mats
5,000
200
70
69¢/can
$9.99
$22.99
Unit cost
62¢
$7.99
$17.49
Contribution margin
7¢
$2.00
$5.50
$350
$400
$385
Item Projected volume (week) Sales price
Contribution (margin × volume)
Texcan oil is the promotion yielding the lowest contribution and therefore is the one Armadillo must beat out. The contribution of Armadillo car wax is: Selling price less: Unit cost Contribution margin × expected volume Contribution
$2.90 $2.50 $0.40 800 $ 320
Clearly, since the Armadillo car wax yields a lower contribution margin than all three of the existing planned promotions, management should not change their planned promotions and should reject the Armadillo offer. b.
With 50 free units of car wax, Armadillo’s contribution is: Contribution from 50 free units (50 × $2.90) Contribution from remaining 750 units: Selling price $2.90 less: Unit cost $2.50 Contribution margin $0.40 × expected volume 750 Contribution
$145
300 $445
With 50 free units of car wax, it is now profitable to replace the oil display area with the car wax. The opportunity cost of replacing the oil display is its forgone contribution ($350), whereas the benefits provided by the car wax are $445.
2-13
Full file at
Additional discussion points raised (i)
This problem introduces the concept of the opportunity cost of retail shelf space. With the proliferation of consumer products, supermarkets’ valuable scarce commodity is shelf space. Consumers often learn about a product for the first time by seeing it on the grocery shelf. To induce the store to stock an item, food companies often give the store a number of free cases. Such a giveaway compensates the store for allocating scarce shelf space to the item.
(ii)
This problem also illustrates that retail stores track contribution margins and volumes very closely in deciding which items to stock and where to display them.
(iii)
One of the simplifying assumptions made early in the problem was that the sale of the special display items did not affect the unit sales of competitive items in the store. Suppose that some of the Texcan oil sales came at the expense of other oil sales in the store. Discuss how this would alter the analysis.
P 2–18:
Solution to Measer (20 minutes) [Average versus variable cost]
"Beware of unit costs." If you focus solely on the unit cost numbers in the problem, you are likely to be misled. In the long run, the firm should shut down because it cannot cover fixed costs. However, if the firm has already incurred or is liable for fixed factory and administration costs, then it should continue to operate if it can cover variable costs. Notice the assumption regarding timing. Fixed costs are assumed to have been incurred whereas variable costs are assumed not to have been incurred yet. Given these assumptions, the lossminimizing rate of output is 11 million units: Rate of Production and Sale (000's units) Sales @ $4.50/unit Total Costs Profit (Loss)
10,000 $45,000 58,000 ($13,000)
11,000 $49,500 62,400 ($12,900)
12,000 $54,000 67,000 ($13,000)
13,000 $58,500 71,600 ($13,100)
Notice, minimizing average unit costs is not the basis for choosing output levels. Average unit costs are minimized at 13 million units. An alternative way to solve the problem is to calculate contribution margin, as below:
2-14
Full file at
Output Levels Variable Cost Average Variable Cost/unit Contribution margin/unit Contribution margin (units × output level)
10,000 $43,000 $4.30 $.20
11,000 $47,400 $4.31 $.19
12,000 $52,000 $4.33 $.17
13,000 $56,600 $4.35 $.15
$2,000
$2,090
$2,040
$1,950
The preceding table indicates that maximizing contribution margin (not contribution margin per unit) also gives the right answer. At 11 million units $2,090 is being generated towards covering fixed costs. Minimizing average variable cost gives the wrong answer. P 219: a.
Solution to Affording a Hybrid (20 minutes) [Breakeven analysis]
The $1,500 upfront payment is irrelevant since it applies to both alternatives. To find the breakeven mileage, M, set the monthly cost of both vehicles equal: $3.00 $3.00 $499 M $399 M 50 25
$100
= M(.12 .06)
M = $100/.06 = 1,666.66 miles per month Miles per year = 1,666.66 × 12 = 20,000 b.
$4.00 $4.00 $499 M 399 M 50 25
$100 = M(.16 .08) M = $100/.08 = 1,250 miles per month Miles per year = 1,250 × 12 = 15,000 miles per year
2-15
Full file at
P 2–20:
Solution to Fast Photo (20 minutes) [Cost behavior]
Matt's intuition is correct regarding the behavior of fixed costs. As the table below shows, average fixed costs per unit falls from $6 per unit in Plant A to $4.62 in plant D. However, unlike the usual textbook assumption that variable costs per unit are constant, these plants exhibit increasing variable costs per unit. Plant A has average variable costs per roll of $3.90 and this rises to $5.42 per roll in plant D. The increase in variable costs per unit more than offsets the lower fixed costs per roll. Thus, profits fall as volume increases in plants B through D. One likely reason for the increasing variable cost per roll is higher labor costs due to overtime. If the highvolume plants add extra work shifts and if there are wage shift differentials between day and night work, average variable costs will increase. Finally, average variable costs per unit will increase with volume if plant congestion forces the firm to hire workers whose sole job is managing the congestion (i.e., searching for misplaced orders, expediting work flows, etc.)
P 221: a.
Number of rolls processed Variable costs (000s) Fixed costs (000s)
Plant A 50,000 195 300
Plant B 55,000 242 300
Plant C 60,000 298 300
Plant D 65,000 352 300
Average fixed cost per unit
$6.00
$5.45
$5.00
$4.62
Average variable cost per unit
$3.90
$4.40
$4.97
$5.42
Solution to MedView (20 minutes) [Breakeven Analysis]
The brochure gives the breakeven point and the question asks us to calculate variable cost per unit. Or, BE =
Fixed Cost Price - Variable Cost
Substituting in the known quantities yields: 45 =
$18,000 $475 - Variable Cost
2-16
Full file at
Solving for the unknown variable cost per unit gives Variable cost = $75/scan b.
The brochure is overlooking the additional fixed costs of office space and additional variable (or fixed) costs of the operator, utilities, maintenance, insurance and litigation, etc. Also overlooked is the required rate of return (cost of capital). Calculating the breakeven point for the machine rental fee is very misleading.
P 2–22:
Solution to Manufacturing Cost Classification (20 minutes) [Period versus product costs]
Advertising expenses for DVD Depreciation on PCs in marketing dept. Fire insurance on corporate headquarters Fire insurance on plant Leather carrying case for the DVD Motor drive (externally sourced) Overtime premium paid assembly workers Plant building maintenance department Plant security guards Plastic case for the DVD Property taxes paid on corporate office Salaries of public relations staff Salary of corporate controller Wages of engineers in quality control dept. Wages paid assembly line employees Wages paid employees in finished goods warehouse
Period Cost x x x
Product Cost
Direct Labor
x x x x x x x
Direct Material
Over head
x x x x x x x
x x x x x x
2-17
x x
Full file at
P 2–23: a.
Solution to Australian Shipping (20 minutes) [Negative transportation costs]
Recommendation: The ship captain should be indifferent (at least financially) between using stone or wrought iron as ballast. The total cost (£550) is the same. Stone as ballast Cost of purchasing and loading stone Cost of unloading and disposing of stone Ton required Total cost Wrought iron as ballast Number of bars required: 10 tons of ballast × 2,000 pounds/ton Weight of bar Loss per bar (£1.20 – £0.90) × number of bars Cost of loading bars (£15 ×10) Cost of unloading bars (£10 ×10) Total cost
b.
£40 15 £55 × 10 £550
20,000 pounds ÷ 20 pounds/bar 1,000 bars £0.30 1,000 £300 150 100 £550
The price is lower in Sydney because the supply of wrought iron relative to demand is greater in Sydney because of wrought iron’s use as ballast. In fact, in equilibrium, ships will continue to import wrought iron as ballast as long as the relative price of wrought iron in London and Sydney make it cheaper (net of loading and unloading costs) than stone.
2-18
Full file at
P 2-24:Solution to iGen3 (20 minutes) [Cost-volume-profit and breakeven on a lease contract] a and b. Breakeven number of impressions under Options A and B: Option A $10,000 5,000 $15,000
Monthly fixed lease cost Labor/month Total fixed cost/month Variable lease cost/impression Ink/impression Total variable cost
$0.01 0.02 $0.03
$0.03 0.02 $0.05
Price/impression
$0.08
$0.08
$0.05 300,000
$0.03 166,667
Contribution margin/impression Breakeven number of impressions c.
Option B $0 5,000 $5,000 $10,000 Q
= = =
$5,000 + $0.05 Q $0.02 Ă— 520,000), whereas Option B costs $31,000 ($5,000 + .05 Ă—.
2-19
Full file at
P 2-25:Solution to Adapt, Inc. (20 minutes) [Cost-volume-profit and operating leverage] a.
NIAT = (PQ – VQ –F)(1-T)
and
(PQ – VQ) / PQ = 70%
Where: NIAT = Net income after taxes P = Price Q= Quantity V= variable cost per unit F = Fixed cost T= Tax rate $1.700 2.833 (PQ – VQ) / PQ 1- VQ / PQ VQ / PQ VQ 2.833 F b.
($6.200 – VQ – F) (1 – 0.4) 6.200 – VQ – F 70% .70 .30 .30 PQ = .30(6.200) = 1.860 6.200 – 1.860 – F 1.507
Knowing DigiMem’s fixed costs informs Adapt, Inc. about DigiMem’s operating leverage. Knowing DigiMem’s operating leverage helps Adapt design pricing strategies in terms of how DigiMem is likely to respond to price cuts. The higher DigiMem’s operating leverage, the more sensitive DigiMem’s cash flows are to downturns. If DigiMem has a lot of operating leverage, they will not be able to withstand a long price war. Also, knowing DigiMem’s fixed costs is informative about how much capacity they have and hence what types of strategies they may be pursuing in the future.
P 226:
a.
= = = = = = = =
Solution to Exotic Roses (25 minutes) [Breakeven analysis]
Fixed costs total $27,000 per year and variable costs are $1.50 per plant. The breakeven number of potted roses is found by solving the following equation for Q: Profits = $15 Q $1.50 Q $27,000 = 0 Or Q = $27,000 / ($15 $1.50) = $27,000 / $13.50 = 2,000 plants
b.
Q:
To make $10,000 of profits before taxes per year, solve the following equation for Profits = $15 Q $1.50 Q $27,000 = $10,000 Or Q = $37,000 / ($15 $1.50) = $37,000 / $13.50 = 2,740.74 plants
2-20
Full file at
c.
for Q:
To make $10,000 of profits AFTER taxes per year, solve the following equation Profits = [$15 Q $1.50 Q $27,000] × (1 0.35) = $10,000 = [$15 Q $1.50 Q $27,000] = $10,000 / 0.65 = $15,384.62 Or Q = $42,384.62 / $13.50 = 3,139.60 plants
P 227: a.
Solution to Oppenheimer Visuals (25 minutes) [Choosing the optimum technology and “all costs are variable in the long run”]
The following table shows that Technology 2 yields the highest firm value:
Q 60 65 70 75 80 85 90 95 100 105 110
Price $760 740 720 700 680 660 640 620 600 580 560
Revenue $45600 48100 50400 52500 54400 56100 57600 58900 60000 60900 61600
Technology 1 Total cost Profit $46000 $-400 47000 1100 48000 2400 49000 3500 50000 4400 51000 5100 52000 5600 53000 5900 54000 6000 55000 5900 56000 5600
Technology 2 Total cost Profit $40000 $5600 42000 6100 44000 6400 46000 6500 48000 6400 50000 6100 52000 5600 54000 4900 56000 4000 58000 2900 60000 1600
b.
They should set the price at $700 per panel and sell 75 panels per day.
c.
The fixed cost of technology 2 of $16,000 per day was chosen as part of the profit maximizing production technology. Oppenheimer could have chosen technology 1 and had a higher fixed cost and lower variable cost. But given the demand curve the firm faces, they chose technology 2. So, at the time they selected technology 2, the choice of fixed costs had not yet been determined and was hence “variable” at that point in time.
2-21
Full file at
P 2–28:
Solution to Eastern University Parking (25 minutes) [Opportunity cost of land]
The University's analysis of parking ignores the opportunity cost of the land on which the surface space or parking building sits. The $12,000 cost of an enclosed parking space is the cost of the structure only. The $900 cost of the surface space is the cost of the paving only. These two numbers do not include the opportunity cost of the land which is being consumed by the parking. The land is assumed to be free. Surface spaces appear cheaper because they consume a lot more “free” land. A parking garage allows cars to be stacked on top of each other, thereby allowing less land to be consumed. The correct analysis would impute an opportunity cost to each potential parcel of land on campus, and then build this cost into both the analysis and parking fees. The differential cost of each parcel would take into account the additional walking time to the center of campus. Remote lots would have a lower opportunity cost of land and would provide less expensive parking spaces. Another major problem with the University's analysis is that parking prices should be set to allocate a scarce resource to those who value it the highest. If there is an excess demand for parking (i.e., queues exist), then prices should be raised to manage the queue and thereby allocate the scarce resource. Basing prices solely on costs does not guarantee that any excess supply or demand is eliminated. Other relevant considerations in the decision to build a parking garage include: 1. 2.
The analysis ignores the effect of poor/inconvenient parking on tuition revenues. Snow removal costs are likely lower, but other maintenance costs are likely to be higher with a parking garage.
The most interesting aspect of this question is "Why have University officials systematically overlooked the opportunity cost of the land in their decisionmaking process?" One implication of past University officials’ failure to correctly analyze the parking situation is the "dumbadministrator" hypothesis. Under this scenario, one concludes that all past University presidents were ignorant of the concept of opportunity cost and therefore failed to assign the "right" cost to the land. The way to understand why administrators will not build a parking garage is to ask what will happen if a garage is built and priced to recover cost. The cost of the covered space will be in excess of $1,200 per year. Those students, faculty, and staff with a high opportunity cost of their time (who tend to be those with higher incomes) will opt to pay the significantly higher parking fee for the garage. Lowerpaid faculty will argue the inequity of allowing the "rich" the convenience of covered parking while the “poor” are relegated to surface lots. Arguments will undoubtedly be made by some constituents that parking spots should not be allocated using a price system which discriminates against the poor but rather parking should be allocated based on "merit" to be determined by a faculty committee. Presidents of universities have risen to their positions by developing a keen sense of how faculty, students, and staff will react to various proposals. An alternative to the "dumbadministrator" hypothesis is the "rational selfinterested administrator" hypothesis. Under this hypothesis, the parking garage is not built because the administrators are unwilling to bear the internal political ramifications of such a decision.
2-22
Full file at
Finally, taxes play an important role in the University's decision not to build a parking garage. If faculty are to pay the full cost of the garage, equilibrium wage rates will have to rise to make the faculty member as well off at Eastern University paying for parking than at another university where parking is cheaper. Because employees are unable to deduct parking fees from their taxes, the University will have to increase salaries by the amount of the parking fees plus the taxes on the fees to keep the faculty indifferent about staying or leaving the University. Therefore, a parking garage paid for by the faculty (which means paid by the University) causes the government to raise more in taxes. The question then comes down to: is the parking garage the best use of the University's resources? P 229:
a.
Solution to William Company (CMA adapted) (25 minutes) [Using Costvolumeprofit as a decision rule]
Model Economy Regular Difference
Variable Cost per Box $.43 .35 $.08
Total Fixed Cost $ 8,000 11,000 $ 3,000
Volume at which both machines produce the same profit
b.
=
Fixed cost differential Variable cost differential
=
$3,000 $.08
=
37,500 boxes
A decision rule would have to include the Super Model: Regular Super
Variable Cost per Box $.35 .26 $.09
Volume at which Regular and Super produce the same profit
=
$9,000 $.09
= 100,000 boxes
2-23
Total Fixed Cost $11,000 20,000 $ 9,000
Full file at
Therefore, the decision rule is as shown below. Anticipated Annual Sales Between ————————— 0–37,500 37,500–100,000 100,000 and above
Use Model ————— Economy Regular Super
The decision rule places volume well within the capacity of each model. c.
No, management cannot use theater capacity or average boxes sold because the number of seats per theater does not indicate the number of patrons attending, nor the popcorn buying habits in different geographic locations. Each theater likely has a different average "boxes sold per seat" with significant variations. The decision rule does not take into account variations in demand that could affect model choice.
P 230:
Solution to Mastich Counters (25 minutes) [Opportunity cost to the firm of workers deferring vacation time]
At the core of this question is the opportunity cost of workers deferring vacation. The new policy was implemented because management believed it was costing the firm too much money when workers left with accumulated vacation and were paid. However, these workers had given Mastich in effect a loan. By not taking their vacation time as accrued, they stayed in their jobs and worked, allowing Mastich to increase its output without hiring additional workers, and without reducing output or quality. Mastich was able to produce more and higher quality output with fewer workers. Suppose a worker is paid $20 per hour this year and $20.60 next year. By deferring one vacation hour one year, the worker receives $20.60 when the vacation hour is taken next year. As long as average worker salary increases are less than the firm’s cost of capital, the firm is better off by workers accumulating vacation time. The firm receives a loan from its workers at less than the firm’s cost of capital. Under the new policy, and especially during the phasein period, Mastich has difficulty meeting production schedules and quality standards as more workers are now on vacation at any given time. To overcome these problems, the size of the work force will have to increase to meet the same production/quality standards. If the size of the work force stays the same, but more vacation time is taken, output/quality will fall. Manager A remarked that workers were refreshed after being forced to take vacation. This is certainly an unintended benefit. But it also is a comment about how some supervisors are managing their people. If workers are burned out, why aren’t their supervisors detecting this and changing job assignments to prevent it? Moreover, how is burnout going to be resolved after the phasein period is over and workers don’t have excess accumulated vacation time? The new policy reduces the workers’ flexibility to accumulate vacation time, thereby reducing the attractiveness of Mastich as an employer. Everything else equal, workers will demand some offsetting form of compensation or else the quality of Mastich’s work force will fall. 2-24
Full file at
Many of the proposed benefits, namely reducing costs, appear illusory. The opportunity costs of the new policy are reduced output, schedule delays, and possible quality problems. If workers under the new policy were forfeiting a significant number of vacation hours, these lost hours “profit” the firm. But, as expected from rational workers, very few vacation hours are being forfeited (as mentioned by Manager C). However, there is one very real benefit of the new policy – less fraud and embezzlement. One key indicator of fraud used by auditors is an employee who never takes a vacation. Forced vacations mean other people have to cover the person’s job. During these periods, fraud and embezzlement often are discovered. Another benefit of this new policy is it reduces the time employees will spend lobbying their supervisors for extended vacations (in excess of three to four weeks). Finally, under the existing policy, employees tend to take longer average vacations (because workers have more accumulated vacation time). When a worker takes a long vacation, it is more likely the employee’s department will hire a temporary or “float” person to fill in. With shorter vacations, the work of the person on vacation is performed by the remaining employees. Thus, the new policy reduces the slack (free time) of the work force and results in higher productivity. P 231:
Solution to Optometry Practice (25 minutes) [Breakeven analysis]
Hiring the optometrist generates two income streams, examination revenue and eyeglass and contact sales. Each exam is expected to produce the following additional revenue: Frequency (1) Eyeglasses 60% Contact lens 20% Expected Profits from sales per exam
Profits (2) $90 $65
Expected Profits (1) × (2) $54 $13 $67
The breakeven point is calculated as follows: Contribution margin per exam: Exam fee Expected gross margin on sales Contribution margin
$ 45 $ 67 $112
Fixed costs: Optometrist Occupancy costs Equipment Office staff Total fixed costs
$63,000 1,200 330 23,000 $87,530
2-25
Full file at
Break even volume of exams =
Total fixed costs Contribution margin
2-26
Full file at
=
$87,530 $112
= 781.5 exams Break even volume as a fraction of capacity =
781.5 exams 2 ´ 40 ´ 48
= 20.3% P 2–32:
Solution to JLE Electronics (25 minutes) [Maximize contribution margin per unit of scarce resource]
Notice that the new line has a maximum capacity of 25,200 minutes (21 ×20 × 60) which is less than the time required to process all four orders. The profit maximizing production schedule occurs when JLE selects those boards that have the largest contribution margin per minute of assembly time. The following table provides the calculations:
Price Variable cost per unit Contribution margin Number of machine minutes Contribution margin/minute
A $38 23 $15 3 5
CUSTOMERS B C $42 $45 25 27 $17 $18
D $50 30 $20
4 4.25
6 3.33
5 3.6
Customers A, B, and C provide the highest contribution margins per minute and should be scheduled ahead of customer D.
Number of boards requested Number of boards scheduled to be produced in the next 21 days
A 2500
CUSTOMERS B C 2300 1800
2500
2300
* 1700 [25,200 – (2,500 × 3) – (2,300 × 40]/5
2-27
1700*
D 1400 0
Full file at
P 2–33:
Solution to News.com (25 minutes) [Breakeven and operating leverage increases risk]
a. and b.
Breakeven number of hits: NetCom $0.05 0.01 $0.04 $3,000 75,000
Price Variable cost Contribution margin Fixed cost Breakeven number of hits c.
Globalink $0.05 0.02 $0.03 $2,000 66,667
The choice among ISPs depends on the expected number of hits. The two ISP’s have the same cost at 100,000 hits per month: $3,000 + $0.01Q = $2,000 + $0.02Q Q = 100,000 If the number of hits exceeds 100,000 per month, NetCom is cheaper. If the number of hits is less than 100,000, Globalink is cheaper.
d.
If demand fluctuates with general economywide factors, then the risk of News.com is not diversifiable and the variance (and covariance) of the two ISP’s will affect News.com’s risk. For example, the table below calculates News.com’s profits if they use NetCom or Globalink and demand is either high or low. Notice that News.com has the same expected profits ($1,000 per month) from using either ISP. However, the variance of profits (and hence risk) is higher under Net.Com than under Globalink. Therefore, News.com should hire Globalink. Basically, with lower fixed costs, but higher variable costs per hit, News.com’s profits don’t fluctuate as much with Globalink as they do with Net.Com. Hits Revenue Fixed Cost Variable Cost Profits Expected profits
NetCom NetCom 50,000 150,000 $2,500 $7,500 3,000 3,000 500 1,500 $1,000 $3,000 $1,000
2-28
Globalink Globalink 50,000 150,000 $2,500 $7,500 2,000 2,000 1,000 3,000 $500 $2,500 $1,000
Full file at
P 2–34: a.
Solution to Kinsley & Sons (25 minutes) [Opportunity cost of cannibalized sales]
The decision to undertake the additional advertising and marketing campaign depends on how one considers the cannibalized sales from catalog. Additional web profits from the program will be $4 million. But half of these will be from existing catalog purchases. Thus, the net new profits are only $2 million. In this case, undertaking the project is not profitable as documented by the following calculations: Net new incremental web profits Incremental catalog profits Cost of ad campaign Lost profits from catalog sales Net Loss
$4.0 0.6 (2.8) (2 .0) ($0 .2)
However, if we do not undertake the marketing campaign, we have no assurance that our competitors will not pursue an aggressive web campaign for their web sites. Thus, we may lose the $2 million of catalog sales profits whether we undertake this campaign or not. If this is the case, we should undertake the campaign because we will lose the $2 million anyway. In this case, the calculation becomes: Net new incremental web profits Incremental catalog profits Cost of ad program Net Gain b.
$4.0 0.6 (2 .8) $1 .8
The critical assumption involves whether the $2.0 million of lost catalog sales is an opportunity cost of this campaign. If we believe that our competitors will not expand their web marketing, and hence we will not lose these $2 million profits from catalog, then this $2 million is an opportunity cost of the web marketing campaign. On the other hand, if we expect our competitors to launch web marketing campaigns and this $2 million profits from catalog would have been lost whether or not we undertake the campaign, the $2 million is not an opportunity cost of our campaign.
2-29
Full file at
P 235: a.
Solution to Littleton Imaging (25 minutes) [Breakeven analysis]
Breakeven: Fee Film Lease Contribution margin
$250 55 45 $150
Fixed costs per month: Office rent Receptionist 2 technicians CAT scanner lease Office furniture, telephone & equipment Radiologist Total Breakeven (fixed cost/contribution margin)
b.
180
To calculate the number of sessions required to yield an aftertax profit of $5,000 (with a 40 percent tax rate), solve the following equation for Q (number of sessions):
Or,
c.
$1,400 2,400 6,400 1,200 600 15,000 $27,000
$5,000 = (CM × Q – FC) × (1T) $5,000 / 0.60 + FC = CM × Q Q = ($5,000 / .060 + FC) / CM Q = ($8,333.33 + $27,000) / $150 Q = $35,333.33 / $150 Q = 235.56 sessions
To calculate the breakeven price, given Dr. Gu expects to conduct 200 sessions per month, solve the following equation for F (fee per session): 200 × F = $55 × 200 + $45 × 200 + $27,000 200 × F = $100 × 200 + $27,000 200 × F = $20,000 + $27,000 F = $47,000 / 200 F = $235
2-30
Full file at
P 236: a.
Solution to Candice Company (CMA adapted) (30 minutes) [Breakeven analysis of new technologies]
Breakeven units =
Selling price Variable costs: Raw materials Direct labor Variable overhead Variable selling Contribution margin
Method A Method B —————————— —————————— $30.00 $30.00 $5.00 6.00 3.00 2.00
Traceable fixed manufacturing costs Incremental selling expenses Total fixed costs
16.00 $14.00
19.60 $10.40
$2,440,000 500,000 $2,940,000
$1,320,000 500,000 $1,820,000
$ 14.00 210,000
$ 10.40 175,000
Divided by: Contribution margin Breakeven units b.
$5.60 7.20 4.80 2.00
The choice of production methods depends on the level of expected sales. Candice Company would be indifferent between the two manufacturing methods at the volume (x) for which total costs are equal. $16x + $2,940,000 = $19.60x + $1,820,000 $3.60x = $1,120,000 x = 311,111 units In a world of certainty, if management expects to produce fewer than 311,111 units it would choose method B. Above 311,111 units they would prefer method A. The figure below illustrates this situation. The two breakeven points for the two manufacturing methods occur at 210,000 and 175,000 units. However, it is the point where the two cost curves intersect (311,111 units) that is relevant. Method B has lower total costs up to 311,111 units and then method A has lower costs beyond this volume.
2-31
Full file at
With uncertainty, the problem becomes more complicated because the two methods affect operating leverage differently. Operating leverage affects risk, cost of capital, and expected tax payments (to the extent that marginal tax rates vary with profits). Basically, the production method with the lower breakeven volume has the lower systematic risk and thus the lower discount rate. 1
P 2–37:
Solution to Mat Machinery (30 minutes) [Determining the best alternative use of a special order]
Contribution of each alternative:
Sales price Less discount Net sales price
Sell to Raytell Corp. $68,000 $68,000
Sell as a Standard Model $64,500 1,290 $63,210
Sell As Is $55,000 $55,000
1P. Lederer and V. Singhal, “Effect of Cost Structure and Demand Risk in Justification of New Technologies,”
Journal of Manufacturing and Operations Management 1 (1988), pp. 339371. 2-32
Full file at
Less
Less
Additional costs Materials $5,000 Labor 6,000 Overhead (50% DL) 3,000 Commissions Contribution
$6,500 2,000 1,000
14,000 $54,000 1,360 $52,640
9,500 $53,710 632 $53,078
— — ____
— $55,000 550 $54,450
Therefore, the “sell as is” for $55,000 is the best alternative. Notice that fixed factory overhead does not enter the analysis, as these costs are not relevant to any of the alternatives. P 2–38:
Solution to Internal Support Services (30 minutes) [Opportunity cost of an internal service department and pricing it]
Internal Support Systems illustrates the important connection between how informal, internal contracts (in this case for consulting services) affect incentives and ultimately the cost and sourcing of resource allocation decisions. This problem involves addressing the question: Is $50 an hour the opportunity cost to the firm of providing internal services? This problem illustrates that “adverse selection” results if the internal price ($50) is not set at opportunity cost. By using a blended rate of $50, the clients are cream skimming. Clients are using T.Q. for complicated jobs (where the existing market price exceeds $50) and then going outside for the bulk of the work. Users should be charged actual rates, not blended rates. T.Q. should assess how competitive his department is compared with the outside. What is causing the disparity between his rate of $50.00 and a rate of $30.00 on the outside? Are any of these costs controllable? On the other hand, maybe the firm is overpaying T.Q.’s people for what they are getting. Due to widely fluctuating demands from internal clients, T.Q.’s department is staffed for the peak demand periods. This will cause a high charge rate due to inefficient operation at other times. Unless T.Q. wishes to trim his staffing levels, he may never be competitive. A solution may be for T.Q. to perform work outside the corporation. This will force his department to come facetoface with competitive realities. It would also help T.Q.’s department maintain a steady flow of design work. A major issue to be addressed with this approach is the drastic change in incentives given to department personnel. The corporation may wish to subsidize T.Q.’s department so that it is more attractive to use. The rationale for this is that the subsidy represents fixed costs that will not disappear even if T.Q.’s department is eliminated. Another rationale is that T.Q.’s department provides the corporation some strategic advantage (i.e., positive externalities) in the marketplace that is not readily apparent to some internal clients. Ultimately, the firm must address the central question of whether the internal support services provided by T.Q.’s department is better secured internally or externally. What are the benefits to the firm of having these services provided inhouse relative to the cost of securing these services from outside vendors?
2-33
Full file at
P 239:
Solution to G. Demopoulos & Son Inc. (30 minutes) [Opportunity cost of a backup delivery truck]
There are three mutually exclusive uses of the truck: (a) use it to expand the fleet, (b) sell it, or (c) use it as a replacement vehicle. Each alternative is evaluated below. All calculations assume that the ninth truck will not break down. a.
If the truck is used for expansion the net cash flow is: Additional annual contribution (see below) less: additional truck rental ($90/day × 20 days × 8 trucks) Annual cash flow of expansion
$29,400 $14,400 $15,000
If the truck is used in expansion: Revenues Cost: Driver's Comp. Gasoline Expense Truck Maintenance Expected Rental Cost Total Costs Profit
$59,8001 $21,000 $ 3,6002 $ 6,0003 $ 1,8004
$30,400 $29,400 per year
1 $2.00/item ×115 items ×5 days ×52 weeks = $59,800 per year 2 $2,400/8 trucks ×12 months
3 $4,000/8 trucks ×12 months 4 20 days × $90/day
Only variable costs are considered, as fixed costs are irrelevant in this incremental analysis. b.
If the truck is sold: Interest on the proceeds = 12% ×$10,000 less: additional truck rentals Decline in cash flow
c.
$ 1,200 ($14,400) ($13,200)
If the truck is used as a replacement vehicle: Assume the probability that any given truck breaks down in any given day is independent of other trucks breaking down. Furthermore, assume 260 working days per year (52 ×5). Probability that any truck breaks down in a day = 20/260 = 1/13 2-34
Full file at
Next, calculate the expected frequency of days when 0, 1, 2, 3, ..., 8 trucks break down and additional rental trucks are required. This requires estimating the probability that N trucks are broken down in any given day, which is a standard probability theory problem: P(N broken) =
8! 1 N 12 8–N N !(8 - N )! 13 13
The following table computes the probabilities and expected frequencies: (1) # of Trucks Broken ––––––––– 0 1 2 3 4 5 6 7 8
(2) Probability N Broken ––––––––– .527 .351 .102 .017 .002 .000 .000 .000 .000 1.000
(3) Expected # of Trucks Broken (1 × 2) –––––––––––– 0 .351 .205 .051 .007 .001 .000 .000 .000
(4) Expected # of Broken Truck Days (3 × 260) –––––––––––– 0 91.366 53.297 13.324 1.851 .154 .008 .000 .000 160.000
(5) Expected Cost of Renting Outside Extra Trucks* –––––––––––– 0 0 $2,398 799 125 11 1 0 0 $3,334
* (# of trucks broken –1) × Prob(# broken trucks) × 260 days × $90/day. If GDS keeps the truck, the expected rental is $3,334 instead of $14,400, or a savings of about $11,000. Therefore, do not sell the truck but rather use it to add a new route.
2-35
Full file at
P 240: a.
b.
Solution to Cost Behavior Patterns (30 minutes) [Graphing cost behavior patterns]
1000 cans 100 cans 1 can Marginal cost/can
= ten cubic feet of gas = one cubic foot of gas = 0.01 cu.ft = 0.01cu.ft/can × $0.175/cu.ft = $0.00175
c.
The question does not specify whether to plot marginal gas cost per can or average gas cost per can. Therefore, there are two possible answers.
2-36
Full file at
Marginal gas cost per can is:
2-37
Full file at
P 241: a.
Solution to Royal Holland Line (30 minutes) [Breakeven analysis]
Before the breakeven point can be calculated, the variable cost per passenger is computed as: Variable cost per passenger
=
$324, 000 1, 200
= $270 Contribution margin per passenger
= $1,620 – $270 = $1,350
Breakeven number of passengers
=
Fixed cost Contribution margin
=
$607,500 1,350
= 450 passengers b.
The cost of the ship itself is not included. The weekly opportunity cost of the Mediterranean cruise is not using the ship elsewhere. One alternative use is to sell the ship and invest the proceeds. Since no other information is provided regarding alternative uses of the ship and assuming there are no capital gains taxes on the sale proceeds, the weekly opportunity cost of the ship is: Sales proceeds × Interest rate
$371,250,000 10% $37,125,000 50 $ 742,500
÷ number of weeks/year Weekly opportunity cost c.
The revised breakeven including the cost of the ship: Total fixed costs
Breakeven
=
= =
$607,500 + 742,500 $1,350,000
$1, 350, 000 1,350
= 1,000 passengers 2-38
Full file at
d.
Let C = contribution margin from additional sales 900
=
1,350, 000 1,350 C
900(1,350 + C)
=
1,350,000
900C
=
1,350,000 – 1,350 × 900
C
=
1,350, 000 - 1,350 900
C
=
$150
Additional purchases per passenger = = $300. P 242: a.
Solution to Cards Unlimited (30 minutes) [Calculating opportunity costs of international alternatives]
The following table first summarizes the data presented in the problem and then calculates the contribution margin of the international alternatives. After converting the sales prices and selling and distribution costs to U.S. dollars, selling the 100,000 cards in Italy yields the highest contribution margin. Notice fixed costs do not enter the analysis since they do not vary with the number of cards processed.
Currency Exchange rate Selling price Selling & distribution costs
U.S. dollar 1.00 0.31 0.09
Australia dollar 1.34 0.43 0.14
England pound 0.65 0.21 0.06
Italy euro 1.60 .550 .160
Dollar Amounts Selling price $0.310 $0.321 $0.323 $0.344 Cards 0.080 0.080 0.080 0.080 Variable packaging cost 0.040 0.040 0.040 0.040 Selling & distribution costs 0.090 0.104 0.092 0.100 Contribution margin per card $0.100 $0.096 $0.111 $0.124 b. The following table indicates it is better to keep the price at $0.31 and let the WalMart sales drop to 800,000 cards. The contribution from the lost 100,000 cards that would have been sold to WalMart is replaced by selling cards to the next best foreign chain, England. 2-39
Full file at
P 2–43: a.
Price
Reject Proposal $ 0.310
Accept Proposal $ 0.30
WalMart sales (cards) Contribution margin per card WalMart contribution Plus English contribution Total contribution
800,000 × 0.100 $ 80,000 1,110 $ 91,110
900,000 × 0.090 $ 81,000 0 $ 81,000
Solution to Roberts Machining (30 minutes) [Describing the opportunity set and determining opportunity costs]
The opportunity set consists of: 1. Use die to produce #1160 racks and then scrap the die. 2. Use die to produce #1160 racks, but do not scrap the die. 3. Do not produce #1160 racks. Scrap the die immediately. 4. Sell the die to Easton. 5. Do not produce and do not scrap die.
b.
Cash flows of each alternative (assuming GTE does not sue Roberts for breaching contract and ignoring discounting): 1. Use die to produce #1160 racks and then scrap the die Accounting profit Add back cost of die Scrap Net cash flow
$358,000 49,000 6,800 $413,800
2. Use die to produce #1160 racks, but do not scrap the die Accounting profit Add back cost of die Net cash flow
$358,000 49,000 $407,000
3. Do not produce #1160 racks. Scrap the die immediately Net cash flow
$6,800
4. Sell the die to Easton
Payment from Easton Less lost future profits Net cash flow
5. Do not produce and do not scrap die Net cash flow 2-40
$588,000 192,000 $396,000 $0
Full file at
c.
d.
Opportunity cost of each alternative: 1. Use die to produce #1160 racks and then scrap the die
$407,000
2. Use die to produce #1160 racks, but do not scrap the die
$413,800
3. Do not produce $1160 racks. Scrap the die immediately
$413,800
4. Sell the die to Easton
$413,800
5. Do not produce and do not scrap die
$413,800
Roberts should reject Easton’s offer and produce the #1160 rack as specified in its contract. This alternative has the lowest opportunity cost (or equivalently, it has the greatest net cash flow).
P 244: a.
Solution to Doral Rentals (30 minutes) [All costs are variable in the long run, breakeven, and profit maximization]
The fraction of sprayers Amos has to rent each week to breakeven: Weekly lease cost per sprayer
$27 .00
Rental price Cleaning cost Contribution margin per rental
$38.00 2 .00 $36 .00
Fraction of rentals per week to break even ($27/$36)
75%
Suppose Doral leases 10 units and rents 75% of them each week. Then he has: Rental income: (75% × 10 × $38) Less: Lease cost (10 × $27) Cleaning cost on rented sprayers (75% × 10 × $2) Profit b.
$285.00 (270.00) (15 .00) $0 .00
No, Amos is ignoring the opportunity cost of his time spent leasing and renting the sprayers. He could be spending this time marketing his other rentals. He should also consider the additional rentals of his other items (punch bowls) from customers coming into his store to rent sprayers as a potential benefit of the sprayers.
2-41
Full file at
c.
With fixed costs of advertising and labor, the breakeven number of rentals is: Fixed costs per week (advertising and labor)
$65 .00
Rental price per sprayer $38.00 Less: cleaning cost 2 .00 Contribution margin per sprayer rented $36.00 Likelihood of rental × 0 .90 Expected cash flow from each sprayer leased Less: lease cost per sprayer Expected contribution margin per rental Breakeven number of rentals per month ($65/$5.40) d.
$32.40 ($27 .00) $5 .40 12 .04
Amos wants to maximize profits, so Profits
= P × Q – V × Q – FC = (69 – Q)Q – 29Q $65 = 69Q – Q2 –29Q 65 = 40Q – Q2 –65
Taking the derivative and setting it to zero to find the maximum profits : 40 – 2Q = 0 Or,
Q* = 20 sprayers
An alternative way to solve for the maximum profits is by using a table and searching for the maximum profits: Number of Sprayers 10 15 16 17 18 19
Price $59 54 53 52 51 50
Revenue $590 810 848 884 918 950
Lease Cost $270 405 432 459 486 513
Cleaning Cost $20 30 32 34 36 38
Fixed Cost $65 65 65 65 65 65
Total Cost $355 500 529 558 587 616
Profit $235 310 319 326 331 334
20
49
980
540
40
65
645
335
21 22 23 24 25
48 47 46 45 44
1008 1034 1058 1080 1100
567 594 621 648 675 2-42
42 44 46 48 50
65 65 65 65 65
674 703 732 761 790
334 331 326 319 310
Full file at
2-43
Full file at
The profit maximizing number of sprayers is 20. P 245: a.
Solution to Fuller Aerosols (30 minutes) [Breakeven and production planning with capacity constraints]
Breakeven volumes
Fixed cost Price Variable cost Contribution margin Breakeven volume
b.
AA143 $900 $37.00 28.00 $9.00 100
Fuller Aerosols Breakeven Volumes AC747 CD887 FX881 $240 $560 $600 $54.00 $62.00 $21.00 50.00 48.00 17.00 $4.00 $14.00 $4.00 60
40
HF324 $1,800 $34.00 28.00 $6.00
KY662 $600 $42.00 40.00 $2.00
300
300
150
With 70 hours (or 4200 minutes) of capacity per week, all the products can be manufactured. Fuller Aerosols Minutes on the Fill Line to Produce All Products
Fill time per case (minutes) Cases ordered Minutes
AA143 3 300 900
AC747 4 100 400
CD887 5 50 250
FX881 2 200 400
HF324 3 400 1200
Total KY662 Minutes 4 200 800 3950
An aerosol product should only be produced if its contribution margin times the number of units sold exceeds its fixed costs.
Contribution margin Cases ordered Contribution Fixed cost Profit (loss)
c.
AA143 $9.00 300 $2,700 900 $1,800
Fuller Aerosols Breakeven Volumes AC747 CD887 $4.00 $14.00 100 50 $400 $700 240 560 $160 $140
FX881 $4.00 200 $800 600 $200
HF324 $6.00 400 $2400 1,800 $600
KY662 $2.00 200 $400 600 $200
Given a capacity constraint on the aerosol fill line, products should be produced that maximize the contribution margin per minute of fill time. The following table lists the order in which the products should be produced and the quantity of each produced. Products AA143, CD887, FX881, and HF324 are produced to meet demand. After producing these four products to meet demand this leaves 250 minutes of fill line time to produce 62 cases out of the 100 ordered AC747. Making 62 cases of AC747 generates contribution of $248 (62 x $4) which just barely covers its fixed costs of $240. And KY662 is not produced because it has the lowest contribution margin per minute of fill time and even if meeting all orders, it does not cover fixed costs. 2-44
Full file at
Fuller Aerosols Production Schedule with Only 3,000 Minutes (50 hours × 60 minutes/hour) of Fill Line Time Minutes AA143 AC747 CD887 FX881 HF324 KY662 Available Fill time per case (minutes) 3 4 5 2 3 4 Cases ordered 300 100 50 200 400 200 Minutes 900 400 250 400 1200 800 Contribution margin $9.00 $4.00 $14.00 $4.00 $6.00 $2.00 Contribution margin/min $3.00 $1.00 $2.80 $2.00 $2.00 $0.50 Most to least profitable Product per minute 1 5 2 3 3 6 Total minutes available 3,000 Minutes used to meet demand for AA143 900 2,100 Minutes used to meet demand for CD887 250 1,850 Minutes used to meet demand for FX881 and HF324 400 1200 250 Minutes used to meet demand for AC747 250 0 Cases manufactured 300 62.5 50 200 400 0
P 246:
Solution to Amy’s Boards (35 minutes) [Breakeven analysis — shortrun versus longrun]
The major goals of this problem are to demonstrate how fixed costs first become fixed and second to illustrate the relation between fixed costs and capacity. Before the snow boards are purchased in part (a), they are a variable cost. (In the long run, all costs are variable.) However, once purchased, the boards are a fixed cost. The number of boards purchased determines the shop’s total capacity, which is fixed, until she either buys more boards or sells used boards.
2-45
Full file at
a.
Number of boards to breakeven: Fixed Costs Store rent (net of sublet, $7,200 $1,600) Salaries, advertising, office expense Contribution margin per board per year: Revenue per week Refurbishing cost Contribution margin per board per week ×number of weeks Seasonal contribution margin from 100% rental × likelihood of rental Expected seasonal contribution margin per board Net cost per board ($550 – $250) Net contribution per board per year Breakeven number of boards ($31,600 ÷ $788)
b.
$ 5,600 26,000 $31,600 $75 7 $68 20 $1,360 80% $1,088 300
Expected profit with 50 boards:
$ 1,088 50 $54,400
Expected seasonal contribution margin per board (from part a)
× number of boards Expected contribution margin Less: Cost of boards ($300 × 50) Fixed costs Expected profit c.
(15,000) (31,600) $ 7,800
Breakeven number of rentals with 50 boards: Total fixed costs Store rent Salaries, advertising, and office expense Boards and boots (net of resale, $300 × 50) Contribution margin per board per week Breakeven number of rentals
$ 788 40 .10
$46, 600 $68
Total possible number of rentals (50 boards × 20 weeks) Breakeven fraction of boards rented each week
2-46
$ 5,600 26,000 15,000 $46,600 $68 685.29 1,000 68.5%
Full file at
d.
In the long run, all costs are variable. However, once purchased, the boards are a fixed cost. The reason for the difference is Amy has about ten more boards than the break even number calculated in part (a). In part (a), before the boards are purchased, they are a variable cost. She can buy any number of boards she wants and pay a proportionately higher cost for them and rent them all 80 percent of the time. Therefore the cost of the boards is a variable cost with respect to the number of rentals. It is subtracted from the revenue in calculating the contribution margin per board. Once you buy the boards, their cost becomes fixed. Instead of being included in calculating contribution margin, it is included in the fixed cost (numerator of the breakeven volume).
P 247: a.
Solution to Blue Sage Mountain (35 minutes) [Costs and pricing decisionsAppendix A]
Table of prices, quantities, revenues, costs, and profits:-47
Total Cost $79,000 88,000 97,000 106,000 115,000 124,000 133,000 142,000 151,000 160,000 169,000 178,000 187,000 196,000 205,000 214,000 223,000 232,000 241,000 250,000
Total Profit -$28,000 10,000 44,000 74,000 100,000 122,000 140,000 154,000 164,000 170,000 172,000 170,000 164,000 154,000 140,000 122,000 100,000 74,000 44,000 10,000
Full file at
b.
Profits are maximized when the price is set at $310 and 1,100 boards are sold.
c.
If fixed costs fall from $70,000 to $50,000, prices should not be changed because a price of $310 and 1,100 boards continue to maximize profits as illustrated below:-48
Total Cost $59,000 68,000 77,000 86,000 95,000 104,000 113,000 122,000 131,000 140,000 149,000 158,000 167,000 176,000 185,000 194,000 203,000 212,000 221,000 230,000
Total Profit -$8,000 30,000 64,000 94,000 120,000 142,000 160,000 174,000 184,000 190,000 192,000 190,000 184,000 174,000 160,000 142,000 120,000 94,000 64,000 30,000
Full file at
d.
If variable costs fall from $90 to $50 per board, prices should be lowered to $290 per board to maximize profits as illustrated below: Quantity 100 200 300 400 500 600 700 800 900 1,000 1,100 1,200 1,300 1,400 1,500 1,600 1,700 1,800 1,900 2,000
P 2–48: a.
Total Cost $75,000 80,000 85,000 90,000 95,000 100,000 105,000 110,000 115,000 120,000 125,000 130,000 135,000 140,000 145,000 150,000 155,000 160,000 165,000 170,000
Total Profit -$24,000 18,000 56,000 90,000 120,000 146,000 168,000 186,000 200,000 210,000 216,000 218,000 216,000 210,000 200,000 186,000 168,000 146,000 120,000 90,000
Solution to Gold Mountain Ski Resort (45 minutes) [Analyze reasonableness of an investment using breakeven]
Recommendation: Reject immediately. Given the fixed and variable cost structure provided by the client, I calculate that breakeven volume of the venture is 82 percent of the chair lift’s annual capacity (see analysis below). Each daily pass generates $58 of contribution margin. With total fixed cost of $12.4 million ($8.3 million of financing cost plus $4.1 million of operating cost), they must sell 213,793 daily passes to break even. This number of passes requires 427,586 lifts. But their tripleperson chair lift, if operating full, can only produce 518,400 lifts per year. It is likely that during weekends and holidays there will be long lift lines, uncharacteristic of a highend ski resort, further reducing demand. Early in the morning and late afternoons and at the beginning and end of the season, they are unlikely to have sufficient demand to operate the lift at the 82 percent of capacity necessary to breakeven, let alone generate a profit.
2-49
Full file at
Number of skiers per chair Chairs per hour Hours per day Daily pass Annual fixed cost of the ski resort Financing costs Operating costs Variable costs per skierday Additional cost per 100 skierdays Skier days Contribution margin per skierday Breakeven number of skier days Fixed cost ÷ Contribution margin Breakeven skier days b.
3 180 8 $60 $ 8,300,000 $ 4,100,000 $12,400,000 $ 200 ÷100 $ 2.00 $58.00 $12,400,000 $58.00 213,793 213,793 2 427,586 8 540 4,320 120 518,400 427,586 518,400 82%
Based on the revised facts, I would change my recommendation to, Gather additional information. With the fourperson chair lift, the number of daily passes to break even rises slightly (see below). However, the capacity of the chair lift increases more, thereby reducing the breakeven capacity to 62 percent. The resort has more capacity at peak times. However, while this additional capacity reduces lift lines at peak load periods, it also causes the slopes to be more congested, making the ski resort less attractive. I suggest we gather more data from competitive highend resorts regarding the number of skiers per run per hour at peak times. 2-50
Full file at
Total fixed cost Contribution margin Breakeven number of skiers
$ 12,475,000 ÷ $58 215,086
Case 2–1: a.
215,086 2 430,172 8 720 5,760 120 691,200 430,172 691,200 62%
Solution to Old Turkey Mash (50 minutes) [Period versus Product Costs]
This question involves whether the costs incurred in the aging process (oak barrels and warehousing costs) are period costs (and written off) or product costs (and capitalized as part of the inventory value). The table below shows the effect on income of capitalizing all the warehousing costs and then writing them off when the whiskey is sold.
Revenues less: Cost of Goods Sold: bbls distilled @ $100/bbl Oak barrels Warehouse rental Warehouse direct costs Net Income before taxes Income taxes (30%) Net Income after taxes Increase in income from capitalizing aging costs
Base Year
Year 1
Year 2
Year 3
$6,000,000
$6,000,000
$6,000,000
$6,000
$000
$203,000
$504,000
$903,000
2-51
Full file at
Since all the additional expansion costs are now being capitalized into inventory, profits are higher by the amount of the capitalized costs less the increase in taxes. b.
The present financial statements based on treating aging cost as period costs show an operating loss. This loss more closely represents the operating cash flows of the firm. Unless the bank is dumb, the bank will want to see a statement of cash flows in addition to the income statement. If the firm computes net income with the aging costs treated as product costs, net income is higher. But is the banker really fooled? If the firm is able to sell the additional production as it emerges from the aging process, then the following income statements will result for years 3 to 10: Year 3 Revenues $6,000,000 less: Cost of Goods Sold: (gallons sold × $2.50) 1,000,000 Oak barrels 1,200,000 Warehouse rental 1,240,000 Warehouse direct costs 3,100,000 Net Income before taxes (540,000) Income taxes (30%) 162,000 Net Income after taxes ($ 378,000 )
Revenues less: Cost of Goods Sold: (gallons sold × $2.50) Oak barrels Warehouse rental Warehouse direct costs Net Income before taxes Income taxes (30%) Net Income after taxes
Year 4
Year 5
Year 6
Year 7
$6,000,000
$6,000,000
$7,200,000
$8,400,000
1,000,000 1,350,000 1,400,000 3,500,000 (1,250,000) 375,000 ($ 875,000 )
1,000,000 1,200,000 1,500,000 1,500,000 1,600,000 1,760,000 4,000,000 4,400,000 (2,100,000) (1,660,000) 630,000 498,000 ($1,470,000 ) ($1,162,000 )
Year 8
Year 9
$9,600,000
$10,800,000
1,600,000 1,500,000 1,960,000 4,900,000 (360,000) 108,000 ($ 252,000 )
1,800,000 1,500,000 2,000,000 5,000,000 500,000 (150,000 ) $ 350,000
1,400,000 1,500,000 1,880,000 4,700,000 (1,080,000) 324,000 ($ 756,000 )
Year 10 $12,000,000 2,000,000 1,500,000 2,000,000 5,000,000 1,500,000 (450,000 ) $1,050,000
Notice that by year 10, the firm’s profits are twice what the old base profits were. Ultimately, the decision by the banker to continue lending to Old Turkey will depend on the banker’s expectation that the additional production will be sold, not on how the accounting profits are recognized on the books. The decision to report aging costs as product costs depends on the following questions: • Will taxes be affected? If the treatment of aging costs is changed for reporting purposes, will the IRS require the firm to use the same method for taxes? If so, this will increase the firm’s tax liability and further increase the cash drain the firm faces. Therefore, expert tax advice is needed. 2-52
Full file at
• Will the bank be fooled by the positive income numbers even though a cash drain is occurring? The bank’s decision to continue to lend to the firm depends on its assessment of the firm’s ultimate ability to sell the increased quantities produced at the same or higher prices. Independent of how the firm reports its current earnings, the wisdom of the decision to double production depends on whether the overseas markets for the product exist. • The bank may in fact want the firm to treat aging costs as product costs and thereby increase reported profits to satisfy bank regulatory reviews. Regulators look closely at outstanding loans and the documentation provided by the borrowers to their banks. Submitting income statements with reported losses may cause the regulators to question this loan, thereby imposing costs on the bank. Advice: First, find out if the firm can continue to write off aging costs as period expenses for taxes while capitalizing these costs for financial reporting purposes. If the tax rules are such that the firm can keep separate books, then take both sets of income statements and the cash flow statements to the bank and find out which set of statements they feel more accurately reflects the firm’s financial condition. Case 22:
Solution to Mowerson Division (CMA adapted) (60 minutes) [Opportunity cost of make/buy decisions]
In this problem, specific identification of opportunity costs is required. a.
Joseph Wright should have analyzed the costs and savings that Mowerson would realize for a period greater than one year (2007). For instance, Wright should have considered the fact that Mowerson expects production volume to steadily increase over the next three years. Under these circumstances, the difference between Mowerson's standard cost for manufacturing PCBs and TriStar's price for PCBs becomes increasingly important. A decision of this type is dependent on events in the future, i.e., differing income streams, production plans, and production capabilities. Furthermore, this is a longterm decision, which means that more than one year should be considered. Once Mowerson dismisses the assembly technicians, it would not be able to rehire them immediately. By incorporating more than 2007 costs and revenues, Mowerson should also use discounted cash flow techniques to recognize the time value of money.
2-53
Full file at
b.
2-54
Full file at
1.
(i) Appropriate/Inappropriate Appropriate. Mowerson will no longer have to pay these wages.
1.
2.
Inappropriate. The Assembly Supervisor will 2. continue to be employed by Mowerson for two years.
3.
Appropriate but only to the extent of the outside rental space. The cost associated with the main plant floor space is inappropriate because Mowerson is still using this space. Inappropriate. Although the purchasing clerk is on temporary assignment to a special project, the clerk's employment at Mowerson will continue. Appropriate. Mowerson will realize this savings from the reduction in purchase orders issued. Inappropriate. Mowerson has included the cost of incoming freight in direct material cost and TriStar has included the cost of delivery in its price. Therefore, any differential in freight expense is accounted for in Item 7. Appropriate. Any differential between the inhouse cost to manufacture and the purchase cost should be accounted for in Wright's analysis.
4.
5.
6.
7.
8. 9. 10.
3.
4.
5.
(ii) Correct/Incorrect Correct. This is the cost associated with the 40 technicians who will no longer work at Mowerson. Incorrect. Cost will continue to be incurred by Mowerson and only the amount should be included in Wright's analysis, that is salary less the benefits provided by the supervisor. Incorrect. Only the amount related to the outside rental space (1,000 × $9.50 = $9,500) should be included. The cost associated with the floor space in the main plant will continue. Incorrect. There will be no savings associated with the purchasing clerk, except for any value added by the clerk to the special project. Correct based on the information provided.
6.
Incorrect. Any savings or additional costs associated with freight expense will be included in Item 7.
7.
Incorrect. The correct amount should be $2,975,000 [($60.00–30.25) × 100,000]. The only relevant manufacturing costs are direct material ($24.00) and variable overhead ($6.25) as fixed overhead will continue to be incurred irrespective of the decision and direct labor costs have already been considered as a savings in Item 1. Correct based on the information provided.
Appropriate. The junior engineer represents 8. an addition to the staff. Appropriate. The quality control inspector 9. represents an addition to the staff. Appropriate. The increase in the safety stock 10. represents additional cost to Mowerson.
2-55
Correct based on the information provided. Incorrect. Mowerson currently maintains a safety stock of 1,800 boards so a more correct amount is $4,800 as calculated below. However, the correct safety stock level really cannot be determined without knowing the consequences of a stockout, i.e., the cost of a stockout must be compared to the additional storage cost.
Full file at
2-56
Full file at
Percentage of Time TriStar Deliveries Will be Late ————————
Probability (1) —————
4% 6% 8% 10%
.30 .40 .25 .05
Safety Stock of PCBs (2) ————— 2,500 4,000 6,000 7,000
New safety stock level Current level Increase in safety stock Cost per unit Additional cost c.
Expected Value (1) × (2) ————— 750 1,600 1,500 350 4,200 1,800 2,400 $2 $4,800
In evaluating its manufacturing decision, Mowerson should consider information about TriStar's: • • • • • •
Case 2–3:
financial stability credit rating reputation for product quality and ability to meet quoted deliveries potential price increases in the future capacity levels competition, i.e., other potential sources of supply besides TriStar. Solution to Puttmaster (60 minutes) [Opportunity cost of lost sales]
The profitmaximizing number of infomercials requires trading off the additional sales of Puttmasters sold via infomercials against the cost of the infomercials and the cost of the lost sales from retail outlets. Each Puttmaster sold via the infomercial yields the following contribution margin: Selling price Shipping and handling fee Total revenue Less: Manufacturing cost Shipping Answering fee Contribution margin
2-57
$69.95 15 .95 $85.90 9.55 5.80 2 .00 $68 .55
Full file at
Innovative Sports’ contribution margin for each unit sold to the distributor is: Selling price $30.85 Less: Manufacturing cost 9 .55 Contribution margin $21 .30 Since every 10 Puttmasters sold via infomercials reduces retail store sales by two units, 10 infomercials cause $42.60 (2 × $21.30) of lost contribution margin from retail sales. Therefore, each infomercial sale has an opportunity cost of $4.26 ($42.60 ÷ 10). Hence, the net contribution margin of each infomercial sale is: Contribution margin Less: Contribution margin (retail sale) Net contribution margin
$68.55 4 .26 $64 .29
To breakeven on each infomercial, Innovative Sports must sell 13,143 Puttmasters ($845,000 ÷ $64.29). The following table calculates the expected number of Puttmasters to be sold from repeated showings of the infomercial assuming that each showing generates 90 percent of unit sales as the previous showing. Showing Number 1 2 3 4 5 6
Units Sold 22,000 19,800 17,820 16,038 14,434 12,990
Innovative Sports will want to continue to purchase infomercial TV spots as long as each 30minute spot continues to produce total contribution margin in excess of the infomercial’s cost ($845,000) after taking into account the affect of the infomercial on reducing retail sales. From the above table, we see that five infomercials produce sales in excess of the 13,143 breakeven point. Therefore, the profitmaximizing number of infomercials is five.
2-58
Full file at
The following table confirms this conclusion. Infomercial Number 1 2 3 4 5 6 7 8 9
Units Sold 22,000 19,800 17,820 16,038 14,434 12,991 11,692 10,523 9,470
Total Contribution $1,414,380 1,272,942 1,145,648 1,031,083 927,975 835,177 751,660 676,494 608,844
Cost of Infomercial $845,000 845,000 845,000 845,000 845,000 845,000 845,000 845,000 845,000
Cumulative profits reach a maximum at five infomercials.
2-59
Profit from Infomercial $569,380 427,942 300,648 186,083 82,975 9,823 93,340 168,506 236,156
Cumulative Profit $569,380 997,322 1,297,970 1,484,053 1,567,028 1,557,205 1,463,864 1,295,358 1,059,202 | https://issuu.com/eric410/docs/test-bank-accounting-for-decision-m | CC-MAIN-2017-34 | refinedweb | 14,385 | 61.77 |
- Designing the Active Directory Infrastructure to Meet Business and Technical Requirements
- Designing the Network Services Infrastructure to Meet Business and Technical Requirements
- Analyzing the Effect of the Infrastructure Design on the Existing Technical Environment
- Exam Prep Questions
- Need to Know More?
Designing the Network Services Infrastructure to Meet Business and Technical Requirements
When all the required information has been gathered, you're ready to begin designing the network infrastructure. This includes designing how the various network services, such as WINS, DHCP, and DNS, will be used in the new infrastructure.
Creating the Conceptual Design of the DNS Infrastructure
When creating the conceptual design, consider things such as the DNS namespace, DNS server placement, as well as any interoperability issues.
DNS Namespace
One of the most important points when designing a DNS infrastructure is the DNS namespace that will be used. This is essentially the foundation of the Active Directory hierarchy. When the DNS name has been chosen, it should be registered on the Internet, regardless of whether the company has an Internet presence. That way, if the company decides to implement an Internet presence in the future, you won't have to reorganize the current Active Directory hierarchy.
NOTE
The internal and external namespaces are frequently different, so you would not have to change the internal namespace when implementing an Internet presence or presences.
Server Placement
When you design a DNS infrastructure, you need to consider where on the network your DNS servers should be located. The main goal is to provide clients with optimal response time when resolving hostnames (of course, you also want to consider network traffic as well).
In a network that's routed, you have two options. Ideally, you want to be able to place a DNS server on each subnet. Or, if the subnets are connected via high-speed links, you can place all the DNS servers in a central location (which might be more ideal for administrators). However, in choosing the second option, the loss of a connection could mean that clients are temporarily without name resolution services.
If zones aren't integrated within Active Directory, secondary servers should be used for fault tolerance and increased availability. The primary DNS servers should ideally be located near those who are responsible for administering them. Consider placing the secondary servers on subnets that contain the most hosts or on those that generate the most name resolution traffic. For those subnets that generate a large amount of traffic, you might want to place both a primary and secondary server for load balancing purposes.
You also need to consider whether any remote sites are connected to the main sites via slow WAN connections. In these situations, caching-only servers are ideal. When the cache is built up, there will not be as much need to resolve queries over the WAN connection. The WAN link will also not be used for zone transfers (which can generate a large amount of network traffic) because the server does not store any zone information. On the other hand, if the remote location has enough clients, it would be prudent to have a domain controller placed locally, therefore using a full DNS implementation.
Interoperability Issues
When planning a DNS infrastructure, one of the important things to consider is that the version of DNS included with Windows Server 2003 will integrate with other DNS servers. In some cases, a network will already have a DNS implementation and you might be required to add a Windows Server 2003 DNS server to the infrastructure. Before you do, it's critical that you know how DNS will integrate with these existing versions. For example, if you were installing a Windows Server 2003 domain, how would an existing BIND DNS server function within the domain? Identifying any interoperability issues during the design phase can help ensure that any interoperability issues are corrected before the plan is rolled out.
You also need to consider the existing name service used for resolution. Many networks today still implement WINS servers to support legacy clients such as Windows NT 4.0 or clients that still use NetBIOS names. Because Active Directory requires the use of DNS, you must be aware how Windows Server 2003 DNS can integrate with WINS servers.
Many networks already have a DNS infrastructure in place. As the old saying goes, "If it ain't broke, don't fix it." So, many administrators may be reluctant to switch over to another DNS server when the infrastructure currently in place is fine. In such cases, you should be aware of how Windows Server 2003 DNS will interoperate with other versions of DNS.
Creating the Conceptual Design of the WINS Infrastructure
In a network environment that supports only Windows 2000, Windows XP, and Windows Server 2003 clients, WINS is not required because the primary namespace used is DNS. When NetBIOS over TCP/IP is enabled, traditional name resolution techniques are still used depending on the manner is which a request is made.
PreWindows 2000 clients require NetBIOS for such things as locating domain controllers. If any legacy clients such as Windows NT 4.0, Windows 95, and Windows 98 are on the network, WINS might be required for NetBIOS name resolution services. Otherwise, if all workstations can support DNS, WINS does not have to be implemented.
You also need to look at the physical network. If there is a single subnet with a small number of clients, WINS might not be necessary and you can rely on LMHOSTS files or broadcasts for name resolution. However, if there are a large number of hosts on the subnet or if there are multiple subnets, WINS should be implemented. In terms of the number of clients, the performance of a physical network can suffer if broadcasts are relied on for name resolution. Implementing WINS can reduce the number of broadcasts on a subnet. Also, because routers do not forward broadcasts between subnets, WINS should be used to facilitate network access between different subnets. WINS servers on different subnets can be configured for replication so that clients on one subnet can resolve the names of clients on other subnets.
A single WINS server is capable of handling a large number of requests. The number of WINS servers you implement on a network is dependent on several things, such as the hardware installed on the WINS server, whether or not the network is routed, as well as the number of clients on each subnet. When determining the number of WINS servers required, keep the following points in mind:
The number of NetBIOS names typically registered by a WINS client
The frequency of name registrations and releases due to workstations being rebooted
The speed and availability of the physical links connecting the various networks
A single WINS server is capable of handling approximately 10,000 clients; of course, this is dependent on the amount of NetBIOS traffic that is generated. It is always recommended that two WINS servers be configured for fault tolerance. So, when you're planning the number of WINS servers, a good guideline is to install two WINS servers for every 10,000 WINS clients. You can then configure the two WINS servers as replication partners.
When implementing multiple WINS servers, you also need to decide where they should be located. The speed and available bandwidth of the existing network connections have a major effect on where WINS servers are placed.
Creating the Conceptual Design of the DHCP Infrastructure
Certain factors will affect your DHCP implementation. When designing a DHCP infrastructure, you need to consider the following points:
The number of DHCP servers
The placement of DHCP servers
DHCP in a routed network
Number of DHCP Servers
There really is no limit to the number of clients that a single DHCP server can service. Therefore, the main factors that will influence the number of servers you implement will be the existing network infrastructure and the server hardware. If your network consists of a single subnet, a single DHCP server is sufficient, although you might choose to implement more than one for a high level of availability. Implementing a single DHCP server creates a single point of failure, although clients can use APIPA in the event that the DHCP server is unavailable. You can also use the Alternate Configuration option, and manually specify the IP address parameters that a client should use if a DHCP server is not available.
In terms of the network infrastructure, if the network consists of multiple subnets, routers can be configured to forward DHCP broadcasts between subnets. Or you might choose to place DHCP servers on each of the subnets. Another option is to configure a DHCP relay agent on those subnets that do not host DHCP servers (see Figure 3.4). The DHCP relay agent can forward IP address requests to DHCP servers on other subnets on behalf of clients.
In any case, before you implement any DHCP servers on the network, consider the following points:
DHCP servers should be configured with fast disk subsystems and as much RAM as possible. If your DHCP server lacks the hardware (and depending on the number of clients), you might need to implement more than one DHCP server to improve response time for clients.
Implementing a single DHCP server creates a single point of failure.
If there are multiple subnets, you can extend the functionality of a DHCP server across subnets using the DHCP relay agent. Other solutions include placing a DHCP server on each subnet or enabling forwarding of DHCP requests via the routers.
Consider the speed of the links connecting various networks and segments. If a DHCP server is on the far side of a slow WAN link or a dial-up connection, you might choose to place DHCP servers on either side for increased performance. Because DHCP servers do not share any information, there would be no increase in network traffic. Network traffic on the slow link would actually be reduced because clients can obtain leases locally as opposed to using a remote DHCP server.
Placement of DHCP Servers
When it comes time to determine where on the network DHCP servers should be placed, keep in mind that your overall goals are to provide high levels of client performance and server availability. Placement of the DHCP servers depends on the routing configuration, how the network is configured, and the hardware installed on the DHCP servers.
If you're implementing a single DHCP server, it should be placed on the subnet that contains the highest number of clients. All other subnets will have a DHCP relay agent installed or the routers will be configured to forward DHCP broadcasts. Also keep in mind that with a single-server implementation, the network connections should be high speed and the server should be configured with the appropriate hardware.
There are a number of reasons why you might choose to use multiple DHCP servers. Some obvious reasons are high availability and redundancy. When you're determining where to place the DHCP servers, remember that they should be located on the subnets that contain the most clients. Also assess the connections between networks: If certain subnets or segments are connected with slow WAN links, such as a dial-up connection, a DHCP server should be placed at these locations so that clients do not have to use the slow connection when attempting to lease or renew an IP address. Having clients obtain IP addresses across slow unreliable links creates another point of failure if the link becomes unavailable.
Routed Networks
Networks can be subdivided into smaller networks known as subnets. Those subnets are connected using routers. To reduce network traffic, most routers do not forward broadcasts from one subnet to another. This poses a problem with DHCP because clients initially send out a broadcast when leasing an IP addressthe client does not yet have an IP address. One solution to this problem is to use DHCP relay agents.
A relay agent is responsible for relaying DHCP messages between DHCP clients and DHCP servers that are located on different subnets. If routers are RFC 1542compliant, they can forward the DHCP-related messages between subnets. If not, a computer running Windows Server 2003 (Windows NT 4.0 and Windows 2000 as well) can be configured as a relay agent by installing the DHCP relay agent component. Configuring a DHCP relay agent is done through the Routing and Remote Access console.
Centralized Versus Decentralized
Another aspect you need to consider when planning for DHCP is whether you will implement a centralized or a decentralized model in a subnetted environment. For example, you could choose to have all the DHCP servers in a single location servicing requests from clients on different subnets. Or you might choose to place the DHCP servers on each of the different subnets instead. Before you make your decision, you should be aware of the advantages and disadvantages associated with each option.
A decentralized approach would result in DHCP servers being placed in each of the different subnets. Doing so offers the following advantages and disadvantages:
Local administrators can administer their own DHCP servers and configure them in a way that meets their own needs.
Clients do not have to rely on WAN links to obtain an IP address.
Placing a DHCP server at each location will obviously result in an increase in cost due to the fact that multiple servers are required.
A centralized approach would result in all DHCP servers being located in a specific location. This approach offers the following advantages and disadvantages:
Administration of DHCP might be simpler because there will be fewer servers and having them in a single location where technical support is on-hand makes problems easier to troubleshoot.
If fewer DHCP servers are required, the cost associated with implementing DHCP will obviously be reduced.
Clients in remote sites might have to rely on WAN links to obtain an IP address. That means if the WAN link is down, clients will not be able to contact a DHCP server. This creates a single point of failure.
Administration could be more difficult because it is hard for an administrator to know the configuration requirements of a remote site.
Creating the Conceptual Design of the Remote Access Infrastructure
When creating the conceptual design for remote access, you need to determine the remote access method. Windows Server 2003 supports two different remote access methods, dial-up and VPN. You need to evaluate the advantages and disadvantages of each remote access method to determine which one best suits your needs.
With a dial-up solution, remote access clients connect to a remote access server using a telephone line. The remote access server requires at least one modem or multi-port adapter as well as a telephone line or another form of connectivity. If the remote access clients require access to resources on the private network, the remote access server must also be configured with a LAN connection. The remote access client simply requires a modem and telephone connection.
The second option for remote access connectivity is to implement a VPN remote access solution. To provide users with remote access via the Internet, the remote access VPN server is normally configured with a permanent Internet connection. Again, if users require access to the private network, the server must also have a LAN connection. The VPN client must have a modem or network adapter as well as Internet connectivity using the phone line or another WAN connectivity method. A VPN solution also requires the use of a tunneling protocol. The remote access client and the remote access server must be configured to use PPTP or L2TP (keeping in mind that the client and the server must be configured to use the same tunneling protocol). | https://www.informit.com/articles/article.aspx?p=102280&seqNum=2 | CC-MAIN-2022-05 | refinedweb | 2,630 | 50.36 |
pthread_kill - send a signal to a thread
#include <signal.h> int pthread_kill(pthread_t thread, int sig);
The pthread_kill() function is used to request that a signal be delivered to the specified thread.
As in kill(), if sig is zero, error checking is performed but no signal is actually sent.
Upon successful completion, the function returns a value of zero. Otherwise the function returns an error number. If the pthread_kill() function fails, no signal is sent.
The pthread_kill() function will fail if:
- [ESRCH]
- No thread could be found corresponding to that specified by the given thread ID.
- [EINVAL]
- The value of the sig argument is an invalid or unsupported signal number.
The pthread_kill() function will not return an error code of [EINTR].
None.
None.
None.
kill(), pthread_self(), raise(), <signal.h>.
Derived from the POSIX Threads Extension (1003.1c-1995) | http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_kill.html | CC-MAIN-2015-48 | refinedweb | 138 | 67.65 |
Source Network Address Translation (SNAT)
Overview
Source Network Address Translation (source-nat or SNAT) allows traffic from a private network to go out to the internet. Virtual machines launched on a private network can get to the internet by going through a gateway capable of performing SNAT. The gateway has one arm on the public network and as part of SNAT, it replaces the source IP of the originating packet with its own public side IP. As part of SNAT, the source port is also updated so that multiple VMs can reach the public network through a single gateway public IP.
The following diagram shows a virtual network with the private subnet of 10.1.1.0/24. The default route for the virtual network points to the SNAT gateway. The gateway replaces the source-ip from 10.1.1.0/24 and uses its public address 172.21.1.1 for outgoing packets. To maintain unique NAT sessions the source port of the traffic also needs to be replaced.
Neutron APIs for Routers
OpenStack supports SNAT gateway implementation through its Neutron APIs for routers. The SNAT flag can be enabled or disabled on the external gateway of the router. The default is True (enabled).
The OpenContrail plugin supports the Neutron APIs for routers and creates the relevant service-template and service-instance objects in the API server. The service scheduler in OpenContrail instantiates the gateway on a randomly-selected virtual router. OpenContrail uses network namespace to support this feature.
Example Configuration: SNAT for Contrail
The SNAT feature is enabled on OpenContrail through Neutron API calls.
The following configuration example shows how to create a test network and a public network, allowing the test network to reach the public domain through the SNAT gateway.
- Create the public network and set the router external flag.
neutron net-create public
neutron subnet-create public 172.21.1.0/24
neutron net-update public -- --router:external=True
- Create the test network.
neutron net-create test
neutron subnet-create --name test-subnet test 10.1.1.0/24
- Create the router with one interface in test.
neutron router-create r1
neutron router-interface-add r1 test-subnet
- Set the external gateway for the router.
neutron router-gateway-set r1 public
Network Namespace
Setting the external gateway is the trigger for OpenContrail to set up the Linux network namespace for SNAT.
The network namespace can be cleared by issuing the following Neutron command:
neutron router-gateway-clear r1
SNAT and Security Groups
When a logical router is enabled to support SNAT, the default security group is automatically applied to the left SNAT interface. This automatic application of the default security group allows the virtual machine to send and receive traffic without additional user configuration when the default security group is used by interconnected virtual machines. Additional configuration is required to send and receive traffic, however, when your virtual machine is connected to virtual machines that are not using the default security group.
If you are connecting your virtual machine to a virtual machine that is not using the default security group, you must make one of the following configuration updates to allow your virtual machine to pass traffic:
update the default security group to add rules that allow the VM traffic.
update the rules to the VM security group to allow traffic from the default security group.
apply the same security group to the VM and the SNAT left interface.
For information on configuring security groups in environments using Contrail Networking, see Using Security Groups with Virtual Machines Instances.
Using the Web UI to Configure Routers with SNAT
You can use the Contrail user interface to configure routers for SNAT and to check the SNAT status of routers.
To enable SNAT for a router, go to Configure > Networking > Routers. In the list of routers, select the router for which SNAT should be enabled. Click the Edit cog to reveal the Edit Routers window. Click the check box for SNAT to enable SNAT on the router.
The following shows a router for which SNAT has been Enabled.
When a router has been Enabled for SNAT, the configuration can be seen by selecting Configure > Networking > Routers. In the list of routers, click open the router of interest. In the list of features for that router, the status of SNAT is listed. The following shows a router that has been opened in the list. The status of the router shows that SNAT is Enabled.
You can view the real time status of a router with SNAT by viewing the instance console, as in the following.
Using the Web UI to Configure Distributed SNAT
The distributed SNAT feature allows virtual machines to communicate with the IP fabric network using the existing forwarding infrastructure for compute node connectivity. This functionality is achieved through port address translation of virtual machine traffic using the IP address of the compute node as the public address.
The following distributed SNAT use case is supported:
Virtual networks with distributed SNAT enabled can communicate with the IP fabric network. The session must be initiated from a virtual machine. Sessions initiated from the external network are not supported.
Distributed SNAT is supported only for TCP and UDP, and you can configure discrete port ranges for both protocols.
A pool of ports is used for distributed SNAT. To create a pool of ports, go to Configure > Infrastructure > Global Config. The following shows an example of a port range used for port address translation.
To use distributed SNAT, you must enable SNAT on the virtual network. To enable SNAT on the virtual network, go to Configure > Networking > Networks. The following shows a virtual network for which SNAT has been enabled under Advanced Options. | https://www.juniper.net/documentation/en_US/contrail19/topics/task/configuration/snat-vnc.html | CC-MAIN-2022-21 | refinedweb | 954 | 54.93 |
Parser and analytics tools for WhatsApp group chats
Project description
whatstk
whatstk is a Python module for WhatsApp chat group analysis and distributed under the GPL-3.0 license.
The project was started in December 2016 by lucasrodes and albertaparicio.
:star: Please star our project if you found it interesting to keep us motivated :smiley:!
Installation
git clone pip install .
Getting Started
Cumulative messages sent by day
from whatstk.core import WhatsAppChat, interventions from whatstk.plot import vis from plotly.offline import plot filename = 'chats/example.txt' hformat = '%d.%m.%y, %H:%M - %name:' chat = WhatsAppChat.from_txt(filename, hformat) counts = interventions(chat, 'date', msg_length=False) counts_cumsum = counts.cumsum() plot(vis(counts_cumsum, 'cummulative characters sent per day'))
Note: More examples to come soon.
Contribute
We are very open to have collaborators. You can freely fork and issue a pull request with your updates! For other issues/bugs/suggestions, please report it as an issue or text me.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/whatstk/0.1.4/ | CC-MAIN-2019-51 | refinedweb | 179 | 53.47 |
In order to debug Rails applications using the fast Cylon debugger, you should need to use the FastTPD server. This is because the current version of Cylon is single-threaded and does not work with a multi-threaded server such as WEBrick. A multi-threaded version of Cylon is in development and will be available as a free upgrade to registered users of Ruby In Steel Developer.
First, Get Everything Installed...
The steps below explain how to install all the components required in order to run LightTPD with SCGI (which is needed in order that LightTPD can interface with Rails):
1. If you haven't got Rails installed, then the first step is to install it. From a command prompt type:
gem install rails
…and answer ‘Y’ to any questions about required dependencies.
2. Install the cmdparse gem:
gem install cmdparse
3. Install the highline gem
gem install highline
Download Zed Shaw’s SCGI gem from (at the time of writing this is version 0.4.3) and the gem file name is scgi_rails-0.4.3.gem) to a temporary directory. Change to the directory where you downloaded the scgi gem and install it. This time, you will have to do this from the command prompt rather than the Gem dialog, as you are not installing this gem from an online repository:
gem install scgi_rails-0.4.3.gem
Download LightTPD for Windows from..
Now Create Your Project, your new Rails project will be created. You are now ready to set the web server script to LightTPD. To do this, select Tools|Options|Projects and Solutions and select Ruby In Steel. Set Web server script to lighttpd_server.bat. (You can click the browse button [...] in order to select this file from an Open dialog…
In the Options dialog, set the Rails debug script to scgi_service.rb (once again you can browse and select this file).
Also in Options, ensure Use the fast Cylon Debugger is checked. The server port shown in this dialog is only used when running a server script (for example, with WEBrick) and this option is not relevant to LightTPD.
Click OK to close the Options dialog.
Start The Server
You are now ready to start LightTPD. Select Ruby|Start Server. You should see a command window appear confirming that the LightTPD server is running…
Click and Debug!
We are now going to check that all is well by starting Rails and displaying its welcome page. To do this, select One-click Rails Debugger from the Ruby menu. You should see the Visual Studio Ruby console displayed a mesaage stating that the LightTPD service is running.
Check that Rails is running by entering the following URL in a browser (Note: if you edited the port number in the config file, remember to substitute 81 – i.e. - or whatever port number you specified, in the address entered) :
You should now see the Rails intro page:
Stop Rails
To stop Rails, go back into Visual Studio and select Debug|Stop Debugging.
Generate A Controller
To generate a controller, select Ruby|Generate and ensure the Controller radio button is selected. Enter in the Value textbox:
helloworld
Then click OK.
Open /app/controllers branch of the Solution Explorer and open the file helloworld_controller.rb. Add the following code between the class declaration and its end keyword:
def index
render :text => “hello world”
end
Save the file.
Set a breakpoint on the line:
render :text => “hello world”
Start the Rails debugger again by selecting Ruby|One-click Rails Debugger.
In your web browser enter:
(remember to use the actual port number if this is not 80)
The Rails program should now hit the breakpoint and you should see…
When stopped at a breakpoint you can use all the usual Ruby In Steel debugging features to trace through the code and monitor variables and expressions in the various debugging windows.
Continue by pressing F5. you should now see the "hello world" page displayed in your web browser…
And that's it!
See Also
Tutorials
Debugging Rails With WEBrick
Ruby On Rails Debugging
Debugging Rails
Debugging
The Debugger
Customization
Configure Debug and Server Scripts
Select Debugger | http://www.sapphiresteel.com/onlinehelp/Debugging%20Rails%20With%20Cylon.html | CC-MAIN-2017-17 | refinedweb | 693 | 63.49 |
README
Js FacadeJs Facade
Static interface to concrete classes via an IoC Service Container.
Before you continue reading, you should know that this package is heavily inspired by Taylor Otwell's Facades in Laravel. Please go read the documentation, to gain a better understanding of what facades are and how they are intended to work.
ContentsContents
- How to install
- Quick start
- Contribution
- Acknowledgement
- Versioning
- License
How to installHow to install
npm install @aedart/js-facade
Quick startQuick start
Set the IoC instanceSet the IoC instance
The Facade requires an IoC Service Container instance, so that it can resolve the facade's accessor (a string identifier) and obtain a concrete class instance.
There is no check of kind of IoC implementation you should use. But, your IoC is required to have a
make method;
Required Make method
/** * Resolve the registered abstract from the container * * @param {string} abstract * @param {Array.<*>} [parameters] * * @return {Object} * * @throw {Error} */ function make(abstract, parameters = []){ // ... not shown ... // };
Whenever the make method is invoked, the facade assumes that the IoC is able to return a concrete instance or fail.
As long as your desired IoC has such a method, you can use this facade. Alternatively, you can use my
@aedart/js-ioc package.
Setting IoC instance on Facade
import Facade from '@aedart/js-facade'; import IoC from '@aedart/js-ioc'; // Somewhere in you bootstrap / setup logic, set the IoC on the Facade Facade.ioc = IoC;
Create a facadeCreate a facade
Given that you have a concrete class, and that you somehow have registered (bound) an instance to it in your IoC;
A simple Box class
'use strict'; class Box { set width(value){ // ... not shown .../ } get width(){ // ... not shown .../ } set height(value){ // ... not shown .../ } get height(){ // ... not shown .../ } } export default Box;
A facade for the Box class
'use strict'; import Facade from '@aedart/js-facade'; class BoxFacade extends Facade { constructor(){ // Accessor - MUST match the identifier you used to // register your Box with, in your IoC. super('my-box-identifier'); } } // You MUST export a initialised instance of this facade. export default new BoxFacade();
Behind the scene, a Proxy is used by the facade to trap method calls. Those traps ensure to invoke the correct methods on the concrete class, via the IoC Service Container.
Using your facadeUsing your facade
Whenever you need to use your concrete class, via a facade, you simply just import it and invoke the methods or properties that you require from it.
Using BoxFacade
'use strict'; // Import you facade from where you stored it... import BoxFacade from './src/Facades/BoxFacade'; // ... somewhere in your application or inside a component ... // BoxFacade.width = 25; BoxFacade.height = 50; console.log(BoxFacade.width, BoxFacade.height); // Output 25, 50
ContributionContributionBugFork,.
AcknowledgementAcknowledgement
- Taylor Otwell, for his Facade implementation
VersioningVersioning
This package follows Semantic Versioning 2.0.0
LicenseLicense
BSD-3-Clause, Read the LICENSE file included in this package | https://www.skypack.dev/view/@aedart/js-facade | CC-MAIN-2021-39 | refinedweb | 475 | 53.41 |
The previous chapter described the basics of how to use ‘--create’ (‘-c’) to create an archive from a set of files. See section How to Create Archives. This section described advanced options to be used with ‘- File permissions in GNU file utilities. This reference
also has useful information for those not being overly familiar with
the UNIX permission system). Using latter syntax allows for
more flexibility. For example, the value ‘a+rw’ adds read and write
permissions for everybody, while retaining executable bits on directories
or on any other file already marked as executable:
$ tar -c -f archive.tar --mode='a+rw' . ‘/’ or ‘.’. In the latter case, the modification time
of that file will be used.
The following example will set the modification date to 00:00:00, January 1, 1970:
$ tar -c -f archive.tar --mtime='1970-01-01' .:
$ tar -c -f archive.tar -v --mtime=yesterday . tar: Option --mtime: Treating date 'yesterday' as 2006-06-20 13:06:29.152478 …
When used with ‘-.
$ tar -c -f archive.tar --clamp-mtime --mtime=@$SOURCE_DATE_EPOCH . ‘0’ usually means
root. Some people like to force ‘0’ as the value to offer in
their distributions for the owner of files, because the
root user is
anonymous anyway, so that might as well be the owner of anonymous
archives. For example:
$ tar -c -f archive.tar --owner=0 .
or:
$ tar -c -f archive.tar --owner=root .
Files added to the
tar archive will have a group ID of group,
rather than the group from the source file. As with ‘--owner’,
the argument group can be an existing group symbolic name, or a
decimal numeric group ID, or name:id.
The ‘--owner’ and ‘--group’ options affect all files
added to the archive. GNU
tar provides also two options that allow
for more detailed control over owner translation:
Read UID translation map from file.
When reading, empty lines are ignored. The ‘#’:
+10 bin smith root:0
Given this file, each input file that is owner by UID 10 will be stored in archive with owner name ‘bin’ and owner UID corresponding to ‘bin’. Each file owned by user ‘smith’ will be stored with owner name ‘root’ and owner ID 0. Other files will remain unchanged.
When used together with ‘--owner-map’, the ‘--owner’ option affects only files whose owner is not listed in the map file.
Read GID translation map from file.
The format of file is the same as for ‘- ‘--group-map’, the ‘- ‘--create’,
this option instructs GNU
tar to store extended file attribute in the
created archive. This implies POSIX.1-2001 archive format
(‘--format=pax’).
When used with ‘--extract’, this option tells
tar,
for each file extracted, to read stored attributes from the archive
and to apply them to the file.
Disable extended attributes support. This is the default.
Attribute names are strings prefixed by a namespace name and a dot. Currently, four namespaces exist: ‘user’, ‘trusted’, ‘security’ and ‘system’. By default, when ‘--xattr’ is used, all names are stored in the archive (or extracted, if using ‘--extract’). This can be controlled using the following options:
Specify exclude pattern for extended attributes.
Specify include pattern for extended attributes.
Here, the pattern is a globbing pattern. For example, the following command:
$ tar --xattrs --xattrs-exclude='user.*' -c a.tar .
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’ and don’t match any of the regexps from ‘--xattrs-exclude’.
When listing the archive, if both ‘--xattrs’ and ‘--verbose’ options are given, files that have extended attributes are marked with an asterisk following their permission mask. For example:
-rw-r--r--* smith/users 110 2016-03-16 16:07 file
When two or more ‘--verbose’ options are given, a detailed listing of extended attributes is printed after each file entry. Each attribute is listed on a separate line, which begins with two spaces and the letter ‘x’ indicating extended attribute. It is followed by a colon, length of the attribute and its name, e.g.:
-rw-r--r--* smith/users 110 2016-03-16 16:07 file x: 7 user.mime_type x: 32 trusted.md5sum ‘--create’,
this option instructs GNU
tar to store ACLs in the
created archive. This implies POSIX.1-2001 archive format
(‘--format=pax’).
When used with ‘--extract’, this option tells
tar,
to restore ACLs for each file extracted (provided they are present
in the archive).
Disable POSIX ACLs support. This is the default.
When listing the archive, if both ‘--acls’ and ‘--verbose’ options are given, files that have ACLs are marked with a plus sign following their permission mask. For example:
-rw-r--r--+ smith/users 110 2016-03-16 16:07 file
When two or more ‘--verbose’ options are given, a detailed listing of ACL is printed after each file entry:
-rw-r--r--+ smith/users 110 2016-03-16 16:07 file a: user::rw-,user:gray:-w-,group::r--,mask::rw-,other::r--.
This option has effect only during creation. It instructs tar to treat as mild conditions any missing or unreadable files (directories). Such failures don’t affect the program exit code, and the corresponding diagnostic messages are marked as warnings, not errors. These warnings can be suppressed using the ‘--warning=failed-read’ option (see section Controlling Warning Messages).
This document was generated on March 24, 2021 using texi2html 5.0. | http://www.gnu.org/software/tar/manual/html_section/create-options.html | CC-MAIN-2021-49 | refinedweb | 954 | 66.33 |
Mean shift clustering is one of my favorite algorithms. It’s a simple and flexible clustering technique that has several nice advantages over other approaches.
In this post I’ll provide an overview of mean shift and discuss some of its strengths and weaknesses. All of the code used in this blog post can be found on github.
Kernel Density Estimation
The first step when applying mean shift (and all clustering algorithms) is representing your data in a mathematical manner. For mean shift, this means representing your data as points, such as the set below.
Mean shift builds upon the concept of kernel density estimation (KDE). Imagine that the above data was sampled from a probability distribution. KDE is a method to estimate the underlying distribution (also called the probability density function) for a set of data.
It works by placing a kernel on each point in the data set. A kernel is a fancy mathematical word for a weighting function. There are many different types of kernels, but the most popular one is the Gaussian kernel. Adding all of the individual kernels up generates a probability surface (e.g., density function). Depending on the kernel bandwidth parameter used, the resultant density function will vary.
Below is the KDE surface for our points above using a Gaussian kernel with a kernel bandwidth of 2. The first image is a surface plot, and the second image is a contour plot of the surface.
Mean Shift
So how does mean shift come into the picture? Mean shift exploits this KDE idea by imagining what the points would do if they all climbed up hill to the nearest peak on the KDE surface. It does so by iteratively shifting each point uphill until it reaches a peak.
Depending on the kernel bandwidth used, the KDE surface (and end clustering) will be different. As an extreme case, imagine that we use extremely tall skinny kernels (e.g., a small kernel bandwidth). The resultant KDE surface will have a peak for each point. This will result in each point being placed into its own cluster. On the other hand, imagine that we use an extremely short fat kernels (e.g., a large kernel bandwidth). This will result in a wide smooth KDE surface with one peak that all of the points will climb up to, resulting in one cluster. Kernels in between these two extremes will result in nicer clusterings. Below are two animations of mean shift running for different kernel bandwidth values.
The top animation results in three KDE surface peaks, and thus three clusters. The second animation uses a smaller kernel bandwidth, and results in more than three clusters. As with all clustering problems, there is no correct clustering. Rather, correct is usually defined by what seems reasonable given the problem domain and application. Mean shift provides one nice knob (the kernel bandwidth parameter) that can easily be tuned appropriately for different applications.
The Mean Shift Algorithm
As described previously, the mean shift algorithm iteratively shifts each point in the data set until it the top of its nearest KDE surface peak. The algorithm starts by making a copy of the original data set and freezing the original points. The copied points are shifted against the original frozen points.
The general algorithm outline is:
for p in copied_points:
while not at_kde_peak:
p = shift(p, original_points)
The shift function looks like this:
def shift(p, original_points):
shift_x = float(0)
shift_y = float(0)
scale_factor = float(0)
for p_temp in original_points:
# numerator
dist = euclidean_dist(p, p_temp)
weight = kernel(dist, kernel_bandwidth)
shift_x += p_temp[0] * weight
shift_y += p_temp[1] * weight
# denominator
scale_factor += weight
shift_x = shift_x / scale_factor
shift_y = shift_y / scale_factor
return [shift_x, shift_y]
The shift function is called iteratively for each point, until the point it not shifted by much distance any longer. Each iteration, the point will move more closer to the nearest KDE surface peak.
Image Segmentation Application
A nice visual application of mean shift is image segmentation. The general goal of image segmentation is to partition an image into semantically meaningful regions. This can be accomplished by clustering the pixels in the image. Consider the following photo that I took recently (largely because the nice color variation makes it a nice example image for image segmentation).
The first step is to represent this image as points in a space. There are several ways to do this, but one easy way is to map each pixel to a point in a three dimensional RGB space using its red, green, and blue pixel values. Doing so for the image above results in the following set of points.
We can then run mean shift on the above points. The following animation shows how each point shifts as the algorithm runs, using a Gaussian kernel with a kernel bandwidth value of 25. Note that I clustered scaled down version of the image (160×120) to allow it run in a reasonable amount of time.
Each point (e.g., pixel) eventually shifted to one of seven modes (e.g., KDE surface peaks). Showing the image using the color of these seven modes produces the following.
Comparison to Other Approaches
As I mentioned above, I really like mean shift because of its simplicity. The entire end result is controlled by one parameter—the kernel bandwidth value. Other clustering approaches, such as k-means, require a number of clusters to be specified as an input. This is acceptable for certain scenarios, but most of the time the number of clusters is not known.
Mean shift cleverly exploits the density of the points in an attempt to generate a reasonable number of clusters. The kernel bandwidth value can often times be chosen based on some domain-specific knowledge. For example, in the above image segmentation example, the bandwidth value can be viewed as how close colors need to be in the RGB color space to be considered related to each other.
Mean shift, however, does come with some disadvantages. The most glaring disadvantage is its slowness. More specifically, it is an N squared algorithm. For problems with many points, it can take a long time to execute. The one silver lining is that, while it is slow, it is also embarrassingly parallelizable, as each point could be shifted in parallel with every other point.
By commenting below, you agree to the terms and conditions outlined in our (linked) Privacy Policy27 Comments
Thanks for the well written post, very useful.
I’m curious about the preference over using a kernel bandwidth over using a specified number of clusters. While it is true that you won’t know the number of clusters before hand, you also don’t know the bandwidth to use, and so you are essentially leaving the number of clusters up to luck – you could just generate random numbers?
I intuitively like the approach better too, but am curious as to your take on the distinction.
Thanks for the comment. Unfortunately, there is no easy answer to your question, it really depends on the situation.
There are situations where you know the number of clusters a priori. For those, using a clustering approach where the number of clusters is specified makes the most sense.
When you don’t know the number of clusters up front, you need some method to compare different clusterings (to determine which one is the best). There are several ways to do this – ranging from qualitative inspection (e.g., just looking at the results and choosing the one that looks the most reasonable), to various cluster scoring metrics [1]. If you have an idea of how “close” observations need to be to be similar mean shift can work really well, as the kernel bandwidth represents this “neighborhood distance”.
With respect to k-means specifically, mean shift has some nice advantages. A significant limitation of k-means is that it can only find spherical clusters. Mean shift uses density to discover clusters, so each cluster can be any shape (e.g., even concave). On the other hand, k-means is significantly faster than mean shift.
[1]
Thanks for your reply. I hadn’t really appreciated the fact that K-Means has the spherical limitation. Also, it occurs to me that choosing a bandwidth lets you see how the clusters change continuously against the bandwidth, rather than just trying a few random numbers.
Interesting stuff either way!
Very good article to make it easy to understand what mean shift is and how it can be used.
Thank you for the post. It helped me a lot understand the mean shift algorithm.
I would like to make the same animations as you did in the post (those that the points result at the KDE peaks for different kernel bandwidth values). Which dependencies have you used? It would be helpful if you could upload some sample code for these animations.
Thanks in advance.
Hi John, I used Matplotlib to generate the plots and Seaborn to add some nicer styling to them. The central idea is to create a plot for each iteration of the algorithm, and save it as an image. Then, take the sequence of images and turn them into an animation.
The code I have on github has this method in mean_shift.py
def cluster(self, points, kernel_bandwidth, iteration_callback = None)If you pass in an iteration_callback function, the mean shift code will call it after each iteration with the current state of the algorithm. You can plot the state inside of the callback.
thank u so much.great written post
Thank you so much for writing this post. The visualizations and clear examples really worked to cement some of the concepts I’ve been reading through in the peer-reviewed literature. Hopefully journals start to update their requirements along these lines for methods papers. Also very thankful for the pytjon code provided, it allows me to play around with my own data.
Thanks Nick, I’m glad you found it helpful and I appreciate the nice words.
Dear Matt, thank you for this very practical and useful post related to Mean Shift Clustering. It has been quite difficult to encounter intelligible material about this algorithm. I converted your code in Python to Matlab and added KNN to adapt the bandwidth for each point (Adaptive Mean Shift). I have a question related to the first and second figures (KDE surface and contour plot of this surface, respectively). How did you generate these figures with Matplotlib? In Matlab, I used surf() and contour() function, but the result seems to be not correct (maybe I have forgotten something regarding to points [-10:20,-10:20] on Gaussian kernel with bandwidth = 2). Have you established any mean vector and covariance matrix from the points in each cluster (after mean shift process with bandwidth = 2)?
Hi Adam, thanks for the comment.
I used matplotlib’s
plot_surfaceto generate the blue KDE surface plots.
For the contour plot, I used Seaborn:
I haven’t used Matlab in a while, so I’m not sure what the Matlab equivalents would be. In general though, your approach of discretizing the space into a 2D grid, applying the KDE function over each grid cell, and plotting that as a surface has been how I’ve always done it.
Adam, do you have this Matlab code available anywhere? I’m interested in trying Adaptive Mean Shift but haven’t been able to find code in a language I understand.
Hi Matt, great article by the way. It helped me a lot.
I am trying to generate like you did, the KDE surface plots and the contour plots of a dataset on which later I am going to apply your mean shift algorithm. I want to do that in order to have an idea of the expected number of clusters that mean shift will generate. If I am not mistaken, your version of the algorithm uses a gaussian kernel. So, I want to apply via scipy’s gaussian_kde the same bandwidth value for a gaussian kernel on the dataset and with matplotlib’s plot_surface and seaborn’s kdeplot to generate the KDE surface plot and contour plots respectively. My problem is that although the contour plots seem to generate similar results to the mean shift algorithm, the gaussian_kde does not. For bandwidth values larger than 1 or 2, I get a huge cone for the whole dataset. Did you use scipy’s gaussian_kde as well?
Hi Matt, I am trying to generate the KDE surface plots and contour plots as you did. Since, your version of the mean shift algorithm is based on a gaussian kernel, I am trying to get an indincation of the number of the clusters the algorithm yields for each bandwidth value, by applying the same bandwidth value to scipy’s gaussian_kde and seaborn’s kdeplot. Although, seaborn seems to generate a contour plot that seems to be in agreement with the number of clusters the mean shift algorithm generates, scipy’s gaussian_kde does not. For bandwidth values larger than one, I get surface plots looking like a cone for the whole dataset, which theoritically would lead to one cluster. But, the mean shift algorithm generates different number of clusters.
I am using scipy’s gaussian_kde for the kernel density estimation and matplotlib’s surface_plot in order to plot is as surface. Have you also used the same functions for these plots? Do you have an idea what might be going wrong?
Thanks in advance.
Hi John,
I’ve never used the scipy gaussian_kde function. I just skimmed through the docs for it (). It says that the bandwidth is determined automatically unless you provide a scalar value. I imagine you are providing a scalar. It’s not clear to me though, if the scalar is used directly as the bandwidth, or if it’s used as an input to another function. I tried finding where it’s used in the source code (), but couldn’t quickly find it. I may take another look later if I have some time.
Another thought I had is that although “gaussian” has a concrete meaning, people often approximate a gaussian function by using different constants and such. It’s possible the “gaussian” calculation could be slightly different between different implementations.
Hope this helps.
Yes, I provide a scalar value. With the same value I feed the mean shift algorithm as well. Mmm, I see. What procedure did you follow for the generation of the KDE surface plot? My data is 2D, as yours.
Hi Matt,
According to what I understood KDEs are estimated probability distribution functions based on an assumed underlying distribution like guassian or epanechnikov distributions, is that right?
The function ‘kernel’ in your code, is it the KDE. If it is then shouldn’t x and y coordinates be the arguments of the function, if not is the underlying kernel distribution – in that case why give bandwidth as argument , isn’t bandwidth an argument to KDE but not the underlying assumed distribution.
Hi Dhanush,
In this example the KDE concept is used to conceptualize a probability function that could have generated the data that we have.
In other words, we start with some data (2D points). You can imagine that if we randomly sampled some probability distribution, we may have ended up with those points. What would such a probability function look like? Constructing a KDE helps us to answer this question. The KDE is constructed by placing a kernel (weighting function, or conceptually a little hill or bump) on each point. Adding all of those kernels up gives us the overall KDE function.
Depending on the size of the kernel (defined by the bandwidth value), the shape of the overall KDE surface will vary. The points could have been sampled from any one of these surfaces with similar likelihood (there is no “one” surface that could have generated the points better than another).
Mean shift works by exploiting this KDE concept, and marching each point up to the nearest peak on the KDE surface. We don’t actually know what the formula for the KDE surface is, but since we’re constructing it using the points we are able to evaluate it at any given (x,y) location.
Does this help?
Hi Matt,
I tried to make function of mean shift clustering on C#. But I did not find any hint(source code of C, C++) yet. If you don’t mind, can you help to me??
Hi Matt, I’m new to python and mean shift clustering. Thank you for your post, this was very helpful especially to a non-technical like me. I may have a basic question here, hope you can help. I ran your code and saw that your data.csv (125×2) file neatly forms into 3 clusters. My question is, what if my data has three or more dimensions (i.e. 125X3) like in your RGB example? How do I set up the data? and will your mean_shift.py work?
Hi Carla,
My implementation should work for data of any dimension. Instead of having 1×2 vectors (2D points, or 1×3 vectors (3D points), you’ll just pass in an array 1xN vectors (i.e, an array of 1xN arrays) where N is the dimensionality of your data. Have you tried running it with higher dimensional data?
– Matt
Hi Matt, I also read your post, your post is helpful for me. As you know, in mean shift clustering, window-size is very important. If this value is small, computational time is very long, and this value is big, the quality of clustering is low. Can I ask to you your good comment about window-size??
Hi Matt,
Thanks for the blog! It is wonderfully written :)
I understand that the bandwidth value for the kernel is the most important parameter that decides the cluster means.
You have said that the Gaussian kernel is the most commonly used one. But does the type of kernel we use influence the output? If we know that our clusters have a specific shape in space, then would it make sense to use a kernel function that approximates that shape?
Hi Kaaviya,
The type of kernel used can certainly influence the output.
However, Gaussian kernels should allow most shapes to be recognized in clustering results. One of the nice aspects of Mean Shift is that it is able to cluster arbitrary (e.g., non spherical) shapes.
I don’t think it necessarily makes sense to use specialized kernel shapes in most situations. The kernel defines the shape of importance around each point. Gaussian kernels allow you to give equal importance in every direction from a given point, but as you get further away from the point the importance decays in an gaussian way.
The importance doesn’t have to decay in a gaussian manner though. For example, you could use a flat (also called uniform) kernel, which usually defines a circular (or spherical) region around each point, and gives equal weight to all points within the region, and zero weight to points outside. Alternatively, you could use a linear kernel that allows the weight to decay in a linear manner as you get further away from each point. Often times these kernels are used to improve performance, as you can ignore points that fall outside of the kernel during each iteration of the algorithm (if you can figure out what point those are efficiently).
See the “Kernel Functions in Common Use” section –
The goal of the kernel is to help understand the probability function that may have generated the data. I have seen adaptive kernel approaches that vary the kernel bandwidth depending on the density of points in a local area, in an attempt to better estimate the underlying probability function.
Hi Matt,
Thanks for the reply!
I am trying to extract ellipsoidal objects from lidar data and I have some promising first results from mean-shift. I am using Gaussian kernel with band-widhts X = Y << Z which looks for clusters within a cylinder.
Your answer helped me understand better what I am doing. And I feel that Gaussian kernel is a better choice compared to the ones available.
Have a nice day!
Hi Matt,
Thanks for your information.
As I understood, mean shift algorithm needs input value of band width like K value in k-means algorithm.
If input K value is disadvantage in k-means then input band width is also one of the disadvantage. If so, how to overcome this?
And also, how to overcome is its slowness? Because slowness of any algorithm is main disadvantage. With this slowness how to consider this algorithm rather than k-means, Fuzzy c-means algorithms.?
Hi, Matt, thank you so much for your post. It helped me a lot to understand Mean Shift.
By the way, I created MeanShift_js nodejs module based on your work. Here is the link:
I added your name into the license file(MIT), thanks again! | https://spin.atomicobject.com/2015/05/26/mean-shift-clustering/ | CC-MAIN-2019-30 | refinedweb | 3,502 | 64.2 |
So here is my problem.
I want to retrieve a string stored in a model and at runtime change a part of it using a variable from the rails application. Here is an example:
I have a Message model, which I use to store several unique messages. So different users have the same message, but I want to be able to show their name in the middle of the message, e.g.,
"Hi #{user.name}, ...."
If you want
"Hi #{user.name}, ...."
in your database, use single quotes or escape the
# with a backslash to keep Ruby from interpolating the
#{} stuff right away:
s = 'Hi #{user.name}, ....' s = "Hi \#{user.name}, ...."
Then, later when you want to do the interpolation you could, if you were daring or trusted yourself, use
eval:
s = pull_the_string_from_the_database msg = eval '"' + s + '"'
Note that you'll have to turn
s into a double quoted string in order for the
eval to work. This will work but it isn't the nicest approach and leaves you open to all sorts of strange and confusing errors but it should be okay as long as you (or other trusted people) are writing the strings; I think you'd be better off with a simple micro-templating system, even something as simple as this:
def fill_in(template, data) template.gsub(/\{\{(\w+)\}\}/) { data[$1.to_sym] } end #... fill_in('Hi {{user_name}}, ....', :user_name => 'Pancakes')
You could use whatever delimiters you wanted of course, I went with
{{...}} because I've been using Mustache.js and Handlebars.js lately. This naive implementation has issues (no in-template formatting options, no delimiter escaping, ...) but it might be enough; if your templates get more complicated then you might want to just store bits of
ERB in the database and use the ERB processor in the standard library deal with it. | https://codedump.io/share/m6DiiEww0dPC/1/rails-string-interpolation-in-a-string-from-a-database | CC-MAIN-2018-26 | refinedweb | 301 | 67.99 |
#include <math.h> double ceil(double x);
float ceilf(float x);
long double ceill(long double x);
Link with -lm.
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
ceilf(), ceill():
For example, ceil(0.5) is 1.0, and ceil(-0.5) is 0.0.
If x is integral, +0, -0, NaN, or infinite, x itself is returned.
The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type. | http://www.makelinux.net/man/3/C/ceil | CC-MAIN-2016-30 | refinedweb | 106 | 67.86 |
Note Input 212: Voice
Voice input gives us another way to interact with our holograms. Voice commands work in a very natural and easy way. Design your voice commands so that they are:
- Natural
- Easy to remember
- Context appropriate
- Sufficiently distinct from other options within the same context
In MR Basics 101, we used the KeywordRecognizer to build two simple voice commands. In MR Input 212, we'll dive deeper and learn how to:
- Design voice commands that are optimized for the HoloLens speech engine.
- Make the user aware of what voice commands are available.
- Acknowledge that we've heard the user's voice command.
- Understand what the user is saying, using a Dictation Recognizer.
- Use a Grammar Recognizer to listen for commands based on an SRGS, or Speech Recognition Grammar Specification, file.
In this course, we'll revisit Model Explorer, which we built in MR Input 210 and MR Input 211.
Important
The videos embedded in each of the chapters below were recorded using an older version of Unity and the Mixed Reality Toolkit. While the step-by-step instructions are accurate and current, you may see scripts and visuals in the corresponding videos that are out-of-date. The videos remain included for posterity and because the concepts covered still apply.
Device support
Before you start
Prerequisites
- A Windows 10 PC configured with the correct tools installed.
- Some basic C# programming ability.
- You should have completed MR Basics 101.
- You should have completed MR Input 210.
- You should have completed MR Input 211.
- A HoloLens device configured for development.
Project files
- Download the files required by the project. Requires Unity 2017.2 or later.
- Un-archive the files to your desktop or other easy to reach location.
Note
If you want to look through the source code before downloading, it's available on GitHub.
Errata and Notes
- "Enable Just My Code" needs to be disabled (unchecked) in Visual Studio under Tools->Options->Debugging in order to hit breakpoints in your code.
Unity Setup
Instructions
- Start Unity.
- Select Open.
- Navigate to the HolographicAcademy-Holograms-212-Voice folder you previously un-archived.
- Find and select the Starting/Model Explorer folder.
- Click the Select Folder button.
- In the Project panel, expand the Scenes folder.
- Double-click ModelExplorer scene to load it in Unity.
Building
- In Unity, select File > Build Settings.
- If Scenes/ModelExplorer is not listed in Scenes In Build, click Add Open Scenes to add the scene.
- If you're specifically developing for HoloLens, set Target device to HoloLens. Otherwise, leave it on Any device.
- Ensure Build Type is set to D3D and SDK is set to Latest installed (which should be SDK 16299 or newer).
- Click Build.
- Create a New Folder named "App".
- Single click the App folder.
- Press Select Folder and Unity will start building the project for Visual Studio.
When Unity is done, a File Explorer window will appear.
- Open the App folder.
- Open the ModelExplorer Visual Studio Solution.
If deploying to HoloLens:
- Using the top toolbar in Visual Studio, change the target from Debug to Release and from ARM to x86.
- Click on the drop down arrow next to the Local Machine button, and select Remote Machine.
- Enter your HoloLens device IP address and set Authentication Mode to Universal (Unencrypted Protocol). Click Select. If you do not know your device IP address, look in Settings > Network & Internet > Advanced Options.
- In the top menu bar, click Debug -> Start Without debugging or press Ctrl + F5. If this is the first time deploying to your device, you will need to pair it with Visual Studio.
- When the app has deployed, dismiss the Fitbox with a select gesture.
If deploying to an immersive headset:
- Using the top toolbar in Visual Studio, change the target from Debug to Release and from ARM to x64.
- Make sure the deployment target is set to Local Machine.
- In the top menu bar, click Debug -> Start Without debugging or press Ctrl + F5.
- When the app has deployed, dismiss the Fitbox by pulling the trigger on a motion controller.
Note
You might notice some red errors in the Visual Studio Errors panel. It is safe to ignore them. Switch to the Output panel to view actual build progress. Errors in the Output panel will require you to make a fix (most often they are caused by a mistake in a script).
Chapter 1 - Awareness
Objectives
- Learn the Dos and Don'ts of voice command design.
- Use KeywordRecognizer to add gaze based voice commands.
- Make users aware of voice commands using cursor feedback.
Voice Command Design
In this chapter, you'll learn about designing voice commands. When creating voice commands:
DO
- Create concise commands. You don't want to use "Play the currently selected video", because that command is not concise and would easily be forgotten by the user. Instead, you should use: "Play Video", because it is concise and has multiple syllables.
- Use a simple vocabulary. Always try to use common words and phrases that are easy for the user to discover and remember. For example, if your application had a note object that could be displayed or hidden from view, you would not use the command "Show Placard", because "placard" is a rarely used term. Instead, you would use the command: "Show Note", to reveal the note in your application.
- Be consistent. Voice commands should be kept consistent across your application. Imagine that you have two scenes in your application and both scenes contain a button for closing the application. If the first scene used the command "Exit" to trigger the button, but the second scene used the command "Close App", then the user is going to get very confused. If the same functionality persists across multiple scenes, then the same voice command should be used to trigger it.
DON'T
- Use single syllable commands. As an example, if you were creating a voice command to play a video, you should avoid using the simple command "Play", as it is only a single syllable and could easily be missed by the system. Instead, you should use: "Play Video", because it is concise and has multiple syllables.
- Use system commands. The "Select" command is reserved by the system to trigger a Tap event for the currently focused object. Do not re-use the "Select" command in a keyword or phrase, as it might not work as you expect. For example, if the voice command for selecting a cube in your application was "Select cube", but the user was looking at a sphere when they uttered the command, then the sphere would be selected instead. Similarly app bar commands are voice enabled. Don't use the following speech commands in your CoreWindow View:
- Go Back
- Scroll Tool
- Zoom Tool
- Drag Tool
- Adjust
- Remove
- Use similar sounds. Try to avoid using voice commands that rhyme. If you had a shopping application which supported "Show Store" and "Show More" as voice commands, then you would want to disable one of the commands while the other was in use. For example, you could use the "Show Store" button to open the store, and then disable that command when the store was displayed so that the "Show More" command could be used for browsing.
Instructions
- In Unity's Hierarchy panel, use the search tool to find the holoComm_screen_mesh object.
- Double-click on the holoComm_screen_mesh object to view it in the Scene. This is the astronaut's watch, which will respond to our voice commands.
- In the Inspector panel, locate the Speech Input Source (Script) component.
- Expand the Keywords section to see the supported voice command: Open Communicator.
- Click the cog to the right side, then select Edit Script.
- Explore SpeechInputSource.cs to understand how it uses the KeywordRecognizer to add voice commands.
Build and Deploy
- In Unity, use File > Build Settings to rebuild the application.
- Open the App folder.
- Open the ModelExplorer Visual Studio Solution.
(If you already built/deployed this project in Visual Studio during set-up, then you can open that instance of VS and click 'Reload All' when prompted).
- In Visual Studio, click Debug -> Start Without debugging or press Ctrl + F5.
- After the application deploys to the HoloLens, dismiss the fit box using the air-tap gesture.
- Gaze at the astronaut's watch.
- When the watch has focus, verify that the cursor changes to a microphone. This provides feedback that the application is listening for voice commands.
- Verify that a tooltip appears on the watch. This helps users discover the "Open Communicator" command.
- While gazing at the watch, say "Open Communicator" to open the communicator panel.
Chapter 2 - Acknowledgement
Objectives
- Record a message using the Microphone input.
- Give feedback to the user that the application is listening to their voice. Unity's Hierarchy panel, verify that the holoComm_screen_mesh object is selected.
- In the Inspector panel, find the Astronaut Watch (Script) component.
- Click on the small, blue cube which is set as the value of the Communicator Prefab property.
- In the Project panel, the Communicator prefab should now have focus.
- Click on the Communicator prefab in the Project panel to view its components in the Inspector.
- Look at the Microphone Manager (Script) component, this will allow us to record the user's voice.
- Notice that the Communicator object has a Speech Input Handler (Script) component for responding to the Send Message command.
- Look at the Communicator (Script) component and double-click on the script to open it in Visual Studio.
Communicator.cs is responsible for setting the proper button states on the communicator device. This will allow our users to record a message, play it back, and send the message to the astronaut. It will also start and stop an animated wave form, to acknowledge to the user that their voice was heard.
- In Communicator.cs, delete the following lines (81 and 82) from the Start method. This will enable the 'Record' button on the communicator.
// TODO: 2.a Delete the following two lines: RecordButton.SetActive(false); MessageUIRenderer.gameObject.SetActive(false);
Build and Deploy
- In Visual Studio, rebuild your application and deploy to the device.
- Gaze at the astronaut's watch and say "Open Communicator" to show the communicator.
- Press the Record button (microphone) to start recording a verbal message for the astronaut.
- Start speaking, and verify that the wave animation plays on the communicator, which provides feedback to the user that their voice is heard.
- Press the Stop button (left square), and verify that the wave animation stops running.
- Press the Play button (right triangle) to play back the recorded message and hear it on the device.
- Press the Stop button (right square) to stop playback of the recorded message.
- Say "Send Message" to close the communicator and receive a 'Message Received' response from the astronaut.
Chapter 3 - Understanding and the Dictation Recognizer
Objectives
- Use the Dictation Recognizer to convert the user's speech to text.
- Show the Dictation Recognizer's hypothesized and final results in the communicator.
In this chapter, we'll use the Dictation Recognizer to create a message for the astronaut. When using the Dictation Recognizer, keep in mind that:
- You must be connected to WiFi for the Dictation Recognizer to work.
- Timeouts occur after a set period of time. There are two timeouts to be aware of:
- If the recognizer starts and doesn't hear any audio for the first five seconds, it will timeout.
- If the recognizer has given a result but then hears silence for twenty seconds, it will timeout.
- Only one type of recognizer (Keyword or Dictation) can run at a time.
We're going to edit MicrophoneManager.cs to use the Dictation Recognizer. This is what we'll add:
- When the Record button is pressed, we'll start the DictationRecognizer.
- Show the hypothesis of what the DictationRecognizer understood.
- Lock in the results of what the DictationRecognizer understood.
- Check for timeouts from the DictationRecognizer.
- When the Stop button is pressed, or the mic session times out, stop the DictationRecognizer.
- Restart the KeywordRecognizer, which will listen for the Send Message command.
Let's get started. Complete all coding exercises for 3.a in MicrophoneManager.cs, or copy and paste the finished code found below:
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections; using System.Text; using UnityEngine; using UnityEngine.UI; using UnityEngine.Windows.Speech; namespace Academy { public class MicrophoneManager : MonoBehaviour { [Tooltip("A text area for the recognizer to display the recognized strings.")] [SerializeField] private Text dictationDisplay; private DictationRecognizer dictationRecognizer; // Use this string to cache the text currently displayed in the text box. private StringBuilder textSoFar; // Using an empty string specifies the default microphone. private static string deviceName = string.Empty; private int samplingRate; private const int messageLength = 10; // Use this to reset the UI once the Microphone is done recording after it was started. private bool hasRecordingStarted; void Awake() { /* TODO: DEVELOPER CODING EXERCISE 3.a */ // 3.a: Create a new DictationRecognizer and assign it to dictationRecognizer variable. dictationRecognizer = new DictationRecognizer(); // 3.a: Register for dictationRecognizer.DictationHypothesis and implement DictationHypothesis below // This event is fired while the user is talking. As the recognizer listens, it provides text of what it's heard so far. dictationRecognizer.DictationHypothesis += DictationRecognizer_DictationHypothesis; // 3.a: Register for dictationRecognizer.DictationResult and implement DictationResult below // This event is fired after the user pauses, typically at the end of a sentence. The full recognized string is returned here. dictationRecognizer.DictationResult += DictationRecognizer_DictationResult; // 3.a: Register for dictationRecognizer.DictationComplete and implement DictationComplete below // This event is fired when the recognizer stops, whether from Stop() being called, a timeout occurring, or some other error. dictationRecognizer.DictationComplete += DictationRecognizer_DictationComplete; // 3.a: Register for dictationRecognizer.DictationError and implement DictationError below // This event is fired when an error occurs. dictationRecognizer.DictationError += DictationRecognizer_DictationError; // Query the maximum frequency of the default microphone. Use 'unused' to ignore the minimum frequency. int unused; Microphone.GetDeviceCaps(deviceName, out unused, out samplingRate); // Use this string to cache the text currently displayed in the text box. textSoFar = new StringBuilder(); // Use this to reset the UI once the Microphone is done recording after it was started. hasRecordingStarted = false; } void Update() { // 3.a: Add condition to check if dictationRecognizer.Status is Running if (hasRecordingStarted && !Microphone.IsRecording(deviceName) && dictationRecognizer.Status == SpeechSystemStatus.Running) { // Reset the flag now that we're cleaning up the UI. hasRecordingStarted = false; // This acts like pressing the Stop button and sends the message to the Communicator. // If the microphone stops as a result of timing out, make sure to manually stop the dictation recognizer. // Look at the StopRecording function. SendMessage("RecordStop"); } } /// <summary> /// Turns on the dictation recognizer and begins recording audio from the default microphone. /// </summary> /// <returns>The audio clip recorded from the microphone.</returns> public AudioClip StartRecording() { // 3.a Shutdown the PhraseRecognitionSystem. This controls the KeywordRecognizers PhraseRecognitionSystem.Shutdown(); // 3.a: Start dictationRecognizer dictationRecognizer.Start(); // 3.a Uncomment this line dictationDisplay.The currently hypothesized recognition.</param> private void DictationRecognizer_DictationHypothesis(string text) { // 3.a: Set DictationDisplay text to be textSoFar and new hypothesized text // We don't want to append to textSoFar yet, because the hypothesis may have changed on the next event dictationDisplay.text = textSoFar.ToString() + " " + text + "..."; } /// <summary> /// This event is fired after the user pauses, typically at the end of a sentence. The full recognized string is returned here. /// </summary> /// <param name="text">The text that was heard by the recognizer.</param> /// <param name="confidence">A representation of how confident (rejected, low, medium, high) the recognizer is of this recognition.</param> private void DictationRecognizer_DictationResult(string text, ConfidenceLevel confidence) { // 3.a: Append textSoFar with latest text textSoFar.Append(text + ". "); // 3.a: Set DictationDisplay text to be textSoFar dictationDisplay.text = textSoFar.ToString(); } /// <summary> /// This event is fired when the recognizer stops, whether from Stop() being called, a timeout occurring, or some other error. /// Typically, this will simply return "Complete". In this case, we check to see if the recognizer timed out. /// </summary> /// <param name="cause">An enumerated reason for the session completing.</param> private void DictationRecognizer_DictationComplete(DictationCompletionCause cause) { // If Timeout occurs, the user has been silent for too long. // With dictation, the default timeout after a recognition is 20 seconds. // The default timeout with initial silence is 5 seconds. if (cause == DictationCompletionCause.TimeoutExceeded) { Microphone.End(deviceName); dictationDisplay.The string representation of the error reason.</param> /// <param name="hresult">The int representation of the hresult.</param> private void DictationRecognizer_DictationError(string error, int hresult) { // 3.a: Set DictationDisplay text to be the error string dictationDisplay.text = error + "\nHRESULT: " + hresult; } /// <summary> /// The dictation recognizer may not turn off immediately, so this call blocks on /// the recognizer reporting that it has actually stopped. /// </summary> public IEnumerator WaitForDictationToStop() { while (dictationRecognizer != null && dictationRecognizer.Status == SpeechSystemStatus.Running) { yield return null; } } } }
Build and Deploy
- Rebuild in Visual Studio and deploy to your device.
- Dismiss the fit box with an air-tap gesture.
- Gaze at the astronaut's watch and say "Open Communicator".
- Select the Record button (microphone) to record your message.
- Start speaking. The Dictation Recognizer will interpret your speech and show the hypothesized text in the communicator.
- Try saying "Send Message" while you are recording a message. Notice that the Keyword Recognizer does not respond because the Dictation Recognizer is still active.
- Stop speaking for a few seconds. Watch as the Dictation Recognizer completes its hypothesis and shows the final result.
- Begin speaking and then pause for 20 seconds. This will cause the Dictation Recognizer to timeout.
- Notice that the Keyword Recognizer is re-enabled after the above timeout. The communicator will now respond to voice commands.
- Say "Send Message" to send the message to the astronaut.
Chapter 4 - Grammar Recognizer
Objectives
- Use the Grammar Recognizer to recognize the user's speech according to an SRGS, or Speech Recognition Grammar Specification, file. the Hierarchy panel, search for Jetpack_Center and select it.
- Look for the Tagalong Action script in the Inspector panel.
- Click the little circle to the right of the Object To Tag Along field.
- In the window that pops up, search for SRGSToolbox and select it from the list.
- Take a look at the SRGSColor.xml file in the StreamingAssets folder.
- The SRGS design spec can be found on the W3C website here.
- In our SRGS file, we have three types of rules:
- A rule which lets you say one color from a list of twelve colors.
- Three rules which listen for a combination of the color rule and one of the three shapes.
- The root rule, colorChooser, which listens for any combination of the three "color + shape" rules. The shapes can be said in any order and in any amount from just one to all three. This is the only rule that is listened for, as it's specified as the root rule at the top of the file in the initial <grammar> tag.
Build and Deploy
- Rebuild the application in Unity, then build and deploy from Visual Studio to experience the app on HoloLens.
- Dismiss the fit box with an air-tap gesture.
- Gaze at the astronaut's jetpack and perform an air-tap gesture.
- Start speaking. The Grammar Recognizer will interpret your speech and change the colors of the shapes based on the recognition. An example command is "blue circle, yellow square".
- Perform another air-tap gesture to dismiss the toolbox.
The End
Congratulations! You have now completed MR Input 212: Voice.
- You know the Dos and Don'ts of voice commands.
- You saw how tooltips were employed to make users aware of voice commands.
- You saw several types of feedback used to acknowledge that the user's voice was heard.
- You know how to switch between the Keyword Recognizer and the Dictation Recognizer, and how these two features understand and interpret your voice.
- You learned how to use an SRGS file and the Grammar Recognizer for speech recognition in your application.
Opinia
Prześlij opinię dotyczącą:
Trwa ładowanie opinii... | https://docs.microsoft.com/pl-pl/windows/mixed-reality/holograms-212 | CC-MAIN-2019-18 | refinedweb | 3,294 | 50.63 |
Hi Volker, Volker Wysk <post@volker-wysk.de> writes: > On Mit, 2002-03-20 at 07:00, Jens Petersen wrote: > > J: > > > > > > > > POpen-1.0.0 contains the same bug which I made. It doesn't ensure that > the values which are needed after the call of forkProcess, before that > of executeFile, are fully evaluated. So, if they are read lazily from a > stream, the newly spawned child process reads data from a stream which > it shares with its parent, making it disappear from the parent's input. > In this situation, this sure isn't intended. Perhaps you could give an explicit example? > Inserting the following lines just before the line "pid <- forkProcess", > in POpen.hs, would force the corresponding values to be evaluated, so no > data will be lost. > > seq (length path) $ seq (sum (map length args)) $ return () > when (isJust env) $ seq (sum (map (\(a,b) -> length a + length b) > (fromJust env))) $ return () > when (isJust dir) $ seq (length (fromJust dir)) $ return (). > I'm also not sure what this part is supposed to do: > > inr <- if (isJust inpt) then > do > (inr', inw) <- createPipe > hin <- fdToHandle inw > hPutStr hin $ fromJust inpt > hClose hin > return $ Just inr' > else > return Nothing | http://www.haskell.org/pipermail/haskell/2002-March/009263.html | CC-MAIN-2014-35 | refinedweb | 197 | 71.65 |
#include <TIL_PixelFilter.h>
Definition at line 282 of file TIL_PixelFilter.h.
Definition at line 286 of file TIL_PixelFilter.h.
When vetsSamples() returns true, this should be called so that the pixel filter can decide how to combine samples, instead of just summing. NOTE: nnew_samples is 1 when adding a new sample, but may be more than 1 when combining pixels into higher levels of the TIL_AdaptiveImage.
Reimplemented from TIL_PixelFilter.
Definition at line 296 of file TIL_PixelFilter.h.
Returns false iff TIL_AdaptiveImage needs to create/delete it. true means that it's owned globally, so will be deleted when the process exits.
Reimplemented from TIL_PixelFilter.
Definition at line 334 of file TIL_PixelFilter.h.
Definition at line 339 of file TIL_PixelFilter.h. | http://www.sidefx.com/docs/hdk/class_t_i_l___pixel_filter_min_max.html | CC-MAIN-2018-30 | refinedweb | 120 | 61.12 |
Measure devel notes
From OLPC
Development notes. For the official page, please see Measure
Metadata file associated with Logs
Measure Activity logs metadata file Filename Filename Filename Logname Logname Logname
Log file format
FIXME: There is no reliable way for the "file" command to identify this data format. It is not clear what parts of this description are to be actually in the file; for example if the first line has 4 "/" characters or if that notation indicates alternatives. It is not clear if "minute" is a 6-character word that should appear in the file or if it is supposed to be a number, etc. The word "stop" at the end will mildly complicate both generators and consumers of this file format. Future extensions are neither prohibited nor defined; it is anyone's guess what might be valid in the future. If I guess the format right, it appears that the three discrete rate choices (a limitation of the current Measure activity) have been enshrined into the data file format. The y_mag and g values, both undocumented, appear to be display-related rather than data-related and thus do not belong in the file.
sec/minute/hour/snapshot time/freq y_mag g freq_range ( l / m /h) 2232 3445 ... ... stop
Draw dotted log
context.move_to(x,y) context.arc(x,y,r,0,2*pi)
Convert #RRGGBB to an (R, G, B) tuple
colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:] r, g, b = [int(n, 16) for n in (r, g, b)] return (r, g, b)
Get the XO colors
from sugar import profile color=profile.get_color() fill = color.get_fill_color() stroke = color.get_stroke_color()
DSP
Filtering using sinc
-
- I will precompute h[i] for all the three ranges and apply it to all the three ranges
- See [[1]]
Scaling - for scale display, and RMS values
- I get a buffer of 16bit values (-32768 to 32768). I need to calculate the corresponding rms value of the voltage
- The correspondence between digital domain values and physical values has been found out experimentally as
v = (m/g)*(s) + 1180 millivolts
where s is a sample value ranging from -32768 to +32768 where m = .0238(i.e. slope when all capture gains are 0dB i.e. g=1) where g is the gain introduced by capture gains. There are two such gains Mic Boost +20dB and Capture Gain. Note that g IS NOT in dB.
- Also let k = m/g and c = 1180
- One option is to scale each sample in voltage domain (which would come out to be a float value) to get rms voltage, Rv = sqrt(sigma(Vi^2)) / N
- The other option is to calculate RMS of all samples s and then convert result to equivalent voltage
- For calculating RMS of samples s and then converting to Rv
- sigma(Vi^2) = (k^2)*(sigma(Xi^2)) + N*c^2 + 2*k*c*sigma(Xi)
- Once we have sigma(Vi^2) we can take square root of that and divide by N
- The big question is which one would be better suited in terms of performance overheads on the XO ? <-- profiling is the answer ?
- You can get rid of the floating point and the division if Python does OK with 64-bit numbers. You do something like this...
G = 1000/g V = s*238*G + 1180*10000000 v = V/10000000
- ...except that you don't immediately divide to get v, and you don't use 10000000. Use 2**32 instead, allowing a 32-bit right shift (free) instead of the division. (so the 1000 has to change, and you don't do .0238*10000 but rather something else appropriate) You may also delay that right shift, adding up the numbers first.
Profiling
import os import cProfile import lsprofcalltree self._profiler = cProfile.Profile() self._profiler.enable() #code to profile# self._profiler.disable() k = lsprofcalltree.KCacheGrind(self._profiler) data = open(os.path.expanduser('/tmp/measure.kgrind'), 'w+') k.output(data) data.close() | http://wiki.laptop.org/go/Measure_devel_notes | CC-MAIN-2014-41 | refinedweb | 669 | 62.48 |
Hi Daniel, That'd be great. I will use that 'probe' method. Is it included in the latest libvirt 0.4.2 release? Thanks, Eunice Daniel P. Berrange wrote:
On Thu, Apr 10, 2008 at 06:34:31PM -0500, Eunice Moon wrote:Hi, The following was not included in the ldom patch, but I would appreciate your advice. Xen is the default hypervisor for virsh and if the user doesn't specify in the command line option, the virsh connects to xen. But, for the SPARC platforms, xen is not supported. So I would like to add the #ifdef WITH_LDOMS block in do_open() (in src/libvirt.c) to default to ldoms if the user doesn't specify with --connect when running virsh on the SPARC platforms. static virConnectPtr do_open (const char *name, virConnectAuthPtr auth, int flags) { int i, res; virConnectPtr ret = NULL; xmlURIPtr uri; #ifdef WITH_LDOMS =====> /* Convert NULL or "" to ldoms:/// */ =====> if (!name || name[0] == '\0') name = "ldoms:///"; =====> #else =====> /* Convert NULL or "" to xen:/// for back compat */ if (!name || name[0] == '\0') name = "xen:///"; #endif .. Would this kind of branching in the common code be acceptable?This particularly area of code has changed since the LDoms code was first written. There is now a 'probe' method in all the internal driver APIs. If you implement the probe driver method for LDoms it will automatically translate NULL / "" into ldoms:/// getting the effect you desire without needing the #ifdefs Regards, Dan. | https://www.redhat.com/archives/libvir-list/2008-April/msg00221.html | CC-MAIN-2015-27 | refinedweb | 239 | 74.08 |
This document is aimed at developers who wish to create their own applications that incorporate Blockly as a code editor. It is assumed that one is generally familiar with Blockly's usage, and one has a basic understanding of HTML and JavaScript.
After reading this document, you may wish to try the Getting Started codelab. another language.
Blockly is 100% client side, requiring no support from the server (unless one wants to use the cloud-storage feature). There are no 3rd party dependencies (unless one wants to recompile the core). Everything is open source.
Get the Code
Recommended: npm
Blockly is published on the npm registry and yarn registry. We recommend accessing Blockly through a package manager because:
- It is easier to stay up to date with changes in Blockly
- It encourages using plugins instead of monkeypatching Blockly
If you need more convincing you can watch our 2021 Blockly on npm talk. If you are already using a package manager, you can install Blockly with
npm install --save blockly
You can reference Blockly in your application code with:
import Blockly from 'blockly';
This will import the default packages. For more information, see the package readme, and the examples for using Blockly with Node and webpack.
Unpkg
If you aren't using a package manager for your project, but don't want to have to copy the code yourself, you can use unpkg.
<script src=""></script>
Unpkg grabs the latest version of the published code, so there won't be any version control with this method. It is great for demos or quick experiments, and we use it in many codelabs.
GitHub
You can also copy the entire source code from GitHub. However, you will have to manually sync to our repository at regular intervals in order to receive the latest updates and fixes to Blockly..
In your application code, you can load Blockly with:
<script src="blockly_compressed.js"></script>
You may need to include other files as well, which are explained in the "Injecting Blockly" guides linked in the next section.
Blockly is highly configurable. For instance, you may set the theme or renderer on a workspace, set a workspace to RTL mode, or select from a variety of zoom and scroll modes.
Configuration is done per-workspace, by passing a configuration struct when injecting a Blockly workspace.
→ More info on configuring a workspace...
Defining Blocks... | https://developers.google.cn/blockly/guides/get-started/web | CC-MAIN-2021-39 | refinedweb | 396 | 61.26 |
I am a beginner and am having problem with a form, when i refresh page with the form and the data, all my error messages are still there...
is there a way to stop the form repeating the same action when a page is refreshed, e.g. just going back to being empty...?
But what I do normally is, the form is submitted in the same page (generally in case of single entry system) checking whether the request method was posted or not. Validate entries and if there are any errors remain in the same page. If successfully done the processing form then redirect to the same page or another page as required:form.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$errors = array();
if(empty($email) || !validateEmail($email)){
$errors['email'] = 'Invalid E-mail';
}
if(empty($errors)){
// do some actions
// and redirect to the requried page or the same page form.php
header("Location: form.php");
exit();
}
}
// if there are validations errors then the $error variable will have your messsages
// which you can print out in your form
// put your rest of the form and/or other HTML tags here under.
Edit:The form will look something like this:
<form name="frm1" id="frm1" method="post" action="">
E-mail: <input type="text" name="email" id="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>" />
<?php if(isset($errors['email'])): ?><span style="color: red;"><?php echo $errors['email']?></span> <?php endif; ?>
</form>
hey thanks.. is there any sample code you think could work for the PRG pattern?
Post/Redirect/Get pattern.
form.php:
<input id="email" name="email" value="<?php echo isset($_SESSION['email']) ? htmlspecialchars($_SESSION['formdata']['email']) : "default value" />
<?php if (isset($_SESSION['formerror']['email'])): ?>
<strong>Please enter your email</strong>
<?php endif ?>
<?php unset($_SESSION['formerror'], $_SESSION['formdata']) ?>
process.php:
if (!isset($_POST['email']) or !validateEmail($_POST['email'])) {
$_SESSION['formerror']['email'] = TRUE;
$_SESSION['formdata']['email'] = isset($_POST['email']) ? $_POST['email'] : "";
header("Location: /form.php");
exit;
}
// do stuff
header("Location: /success.php");
That's about it. This is a very simplified example to get you going. There's a lot of manual work going on in this example which can be automated.
Bear in mind I've ommited a lot of stuff (session starting, declaring variables, etc.) for clarity. | https://www.sitepoint.com/community/t/page-resubmission-simple-problem/59534 | CC-MAIN-2016-18 | refinedweb | 376 | 60.92 |
Improving SD Card performance
It's been over a year since I looked at this and @evanh came up with a test program that I thought I would try out. It turns out it didn't work for me at first. I quickly discovered I was running out of memory and needed to make some changes to the code.
It also uncovered a bug in my SD card file support functions. I rewrote the flexspin file system functions to make some improvements and added a bug in the conversion process. It's one of those if the function returns 0 is that true and if it's not true is it really true bug.
It turns out that one of the nice things about the way flexspin implements SD card support is you can completely rewrite that whole thing and not mess with any of the existing code that is there. Kind of like a plug and play deal.
I also tried to add multi volume or drive support as well. This turns out to add a little bit of overhead with passing around the volume number, but I know somebody is going to want to attach more than one SD card to the P2 and want that function.
I also moved this code over to P2LLVM so that it would have SD card support. The low-level code is about the same but the upper level not so much.
In addition it looks like FatFs came out with a small update that removed a lot of custom memory code and went back to using the standard library functions. For P2LLVM it was a cut and past and Flexspin needed a few more tweaks.
From the diagram the filesystem program is the high level C library functions that are hooked by virtual function pointers except for the mount and directory functions. This system then uses FatFs to convert these library functions into calls to the diskio code that uses the sd_mmc low level code to actually read and write data to the SD card. So one code replace the sd_mmc code with say flash or a usb drive code.
So all the performance functions lie in the low level driver sd_mmc.
Now back to running some performance test and see how we did.
Here is a copy of the performance program that I used:
#include <stdio.h> #include <propeller.h> #include <sys/vfs.h>", _clockfreq(), _clockmode() ); printf( " Randfill ticks = %d\n", randfill( data1, sizeof(data1) ) ); printf( " Mounting: " ); mount( "/sd", _vfs_open_sdcardx(PIN_CLK, PIN_SS, PIN_MOSI, PIN_MISO) ); if( fh = fopen( "/sd/speed2.bin", "w" ) ) {/speed2.bin", "r" ) ) {ms(500); } } uint32_t randfill( uint32_t *addr, size_t size ) { uint32_t ticks; size >>= 2; ticks = _cnt(); do { *(addr++) = _rnd(); } while( --size ); return( _cnt() - ticks ); } int compare( uint32_t *addr1, uint32_t *addr2, size_t size ) { uint32_t pass = 1; size >>= 2; do { if( *(addr1++) != *(addr2++) ) pass = 0; } while( --size ); return( pass ); }
For these tests I used a standard Parallax SD card Adapter and some loose wires.
First test with the standard flexspin driver:
Entering terminal mode. Press Ctrl-] to exit. clkfreq = 200000000 clkmode = 0x10009fb Randfill ticks = 225062 Mounting: Writing 100000 bytes at 136 kB/s Reading 100000 bytes at 314 kB/s Matches! :)
Second test using my SD card functions changing one line of code:
mount( "/sd", _vfs_open_sd(PIN_SS, PIN_CLK, PIN_MOSI, PIN_MISO) ); Entering terminal mode. Press Ctrl-] to exit. clkfreq = 200000000 clkmode = 0x10009fb Randfill ticks = 225070 Mounting: Writing 100000 bytes at 164 kB/s Reading 100000 bytes at 718 kB/s Matches! :)
Third test using P2LLVM. This required a few more changes:", _clkfreq, _clkmode); printf( " Randfill ticks = %d\n", randfill( data1, sizeof(data1) ) ); printf( " Mounting: " ); sd_mount(0, PIN_SS, PIN_CLK, PIN_MOSI, PIN_MISO); if( (fh = fopen( "SD0:/speed2.bin", "w" )) > 0 ) {0:/speed2.bin", "r" )) > 0 ) {(500); } } uint32_t randfill( uint32_t *addr, size_t size ) { uint32_t ticks; size >>= 2; ticks = _cnt(); do { *(addr++) = rand(); } while( --size ); return( _cnt() - ticks ); } int compare( uint32_t *addr1, uint32_t *addr2, size_t size ) { uint32_t pass = 1; size >>= 2; do { if( *(addr1++) != *(addr2++) ) pass = 0; } while( --size ); return( pass ); }
P2LLVM was setup to do multi volume support so the 0 is the volume number used. This also slowed performance some:
Entering terminal mode. Press Ctrl-] to exit. clkfreq = 200000000 clkmode = 0x14cc8fb Randfill ticks = 6574977 Mounting: Writing 100000 bytes at 149 kB/s Reading 100000 bytes at 794 kB/s Matches! :)
Here is the assembly code used to read the SD card and the internal assembly code:
void ReceiveSD(char *buff, unsigned int bc) { char *b = buff; unsigned int c = bc; int m = Pins.MOSI; int n = Pins.MISO; int x = Pins.CLK; int i; int j; int v; __asm { drvh m waitx #8 mov i, c loopi mov v, #0 mov j, #8 loopj testp n wc drvh x rcl v, #1 drvl x waitx #6 djnz j, #loopj wrbyte v, b add b, #1 djnz i, #loopi } } /***********************/ _ReceiveSD add ptr__dat__, ##201926 rdbyte _var01, ptr__dat__ add ptr__dat__, #1 rdbyte _var02, ptr__dat__ sub ptr__dat__, #2 rdbyte _var03, ptr__dat__ sub ptr__dat__, ##201925 zerox _var03, #7 drvh _var01 waitx #8 LR__0687 mov _var04, #0 loc pa, #(@LR__0690-@LR__0688) call #FCACHE_LOAD_ LR__0688 rep @LR__0691, #8 LR__0689 testp _var02 wc drvh _var03 rcl _var04, #1 drvl _var03 waitx #6 LR__0690 LR__0691 wrbyte _var04, arg01 add arg01, #1 djnz arg02, #LR__0687 _ReceiveSD_ret ret
And this is P2LLVM code for the same:
void ReceiveSD(int drive, BYTE *buff, unsigned int bc) { BYTE *b = buff; unsigned int c = bc; int m = (Pins[drive] >> 16) & 0xff; int n = (Pins[drive] >> 24) & 0xff; int x = (Pins[drive] >> 8) & 0xff; int i = 0; int j = 0; int v = 0; asm volatile ("drvh %[m]\n" "waitx #8\n" "mov %[i], %[c]\n" ".li: mov %[v], #0\n" "mov %[j], #8\n" ".lj: testp %[n] wc\n" "drvh %[x]\n" "rcl %[v], #1\n" "drvl %[x]\n" "djnz %[j], #.lj\n" "wrbyte %[v], %[b]\n" "add %[b], #1\n" "djnz %[i], #.li\n" :[i]"+r"(i), [j]"+r"(j), [v]"+r"(v), [b]"+r"(b) :[x]"r"(x), [n]"r"(n), [m]"r"(m), [c]"r"(c)); } /***********************/ 00007468 <ReceiveSD>: 7468: 28 02 64 fd setq #1 746c: 61 a1 67 fc wrlong r0, ptra++ 7470: 28 08 64 fd setq #4 7474: 61 a7 67 fc wrlong r3, ptra++ 7478: 02 a0 67 f0 shl r0, #2 747c: 4f 02 00 ff augs #591 7480: 34 a7 07 f6 mov r3, #308 7484: d0 a7 03 f1 add r3, r0 7488: d3 a1 03 fb rdlong r0, r3 748c: d0 a7 03 f6 mov r3, r0 7490: 08 a6 47 f0 shr r3, #8 7494: ff a6 07 f5 and r3, #255 7498: d0 a9 03 f6 mov r4, r0 749c: 18 a8 47 f0 shr r4, #24 74a0: 10 a0 47 f0 shr r0, #16 74a4: ff a0 07 f5 and r0, #255 74a8: 00 aa 07 f6 mov r5, #0 74ac: d5 ad 03 f6 mov r6, r5 74b0: d5 af 03 f6 mov r7, r5 74b4: 59 a0 63 fd drvh r0 74b8: 1f 10 64 fd waitx #8 74bc: d2 ab 03 f6 mov r5, r2 000074c0 <.li>: 74c0: 00 ae 07 f6 mov r7, #0 74c4: 08 ac 07 f6 mov r6, #8 000074c8 <.lj>: 74c8: 40 a8 73 fd testp r4 wc 74cc: 59 a6 63 fd drvh r3 74d0: 01 ae a7 f0 rcl r7, #1 74d4: 58 a6 63 fd drvl r3 74d8: fb ad 6f fb djnz r6, #-5 74dc: d1 af 43 fc wrbyte r7, r1 74e0: 01 a2 07 f1 add r1, #1 74e4: f6 ab 6f fb djnz r5, #-10 74e8: 28 08 64 fd setq #4 74ec: 5f a7 07 fb rdlong r3, --ptra 74f0: 28 02 64 fd setq #1 74f4: 5f a1 07 fb rdlong r0, --ptra 74f8: 2e 00 64 fd reta
It looks like from the assembled code that flexspin is using FCACHE where as P2LLVM is not yet the speed number is higher for P2LLVM which questions is there is any performance gain by using it. Also my DJNZ loop was converted to a repeat instruction in flexspin.
Hopefully I didn't make to many mistakes in putting this together.
Mike
Ha, didn't notice you post this last night. Cool looking Edge Card carrier, BTW. I want to make something similar.
That
WAITX #6is basically negating the cogexec advantage. Have you tried my code again?
Your speeds are a little slow for the original FlexC code. I'm getting around 340 kB/s reading at 200 MHz sysclock.
Try this sdmm.cc with it's debug code turned on. It might tell us a little more why.
@evanh ,
Those test were done using a old 16Mb SD card I had laying around. Kind of worse case test.
Here is with a new 32Gb SanDisk card rated at 130Mb per second:
And here is with the new code:
And here is with P2LLVM:
Mike
PS: most of the slow downs in flexc is because of too long a delay before checking ready state.
Where is that in the source? Found it
wait_ready()in sdmm.cc.
select()hits it a lot!
EDIT: Testing that ... while there is some select() delays for block writes, for the block reading, select() is returning on first pass. 100% no pausing for wait_ready() through the whole file. And only one select() per file cluster too. So I don't see that as really impacting read performance.
Oh, now I see it. There's a duplicate of wait_ready()'s code inside of
rcvr_datablock()... which is used for every block read, one by one ... yep, that repeats ... at least one delay of 100 us preceding each block. More at cluster start.
Wow, you're totally right. Knocked the set 100 us delay down to 10 us which bumped me from 1560 kB/s up to 2250 kB/s, at 200 MHz sysclock.
EDIT: And 1 us delays at 360 MHz:
Read averaging 10.8 sysclock ticks per bit. 45 MHz SPI clock.
And the 200 MHz report using 1 us delays:
That delay is totally pointless, you can just read dummy bytes until you get a block start, no delay needed at all. Also, the only reason for a timeout IME is to handle sudden disconnect of the SD card or bung commands from higher up. A valid command will never time out.
Hmm, I hadn't really thought about why it was there. I see Eric comments 500 ms and 100 ms timeouts. Which are now wildly missed with the much smaller 1 us delays.
Okay, reverted the delays back to 100 us for the old code ... but, in new code, replaced the ready loop with an actual timeout and no delays. eg:
@evanh ,
That's amazing. By using RDFAST and WRFAST you can double the input/output speed to the SD card. How can this be.
It doesn't work with my old 16Meg memory card though:
This can also mean that byte reads and writes are slow to hub memory.
So if I switch to writing 32 bits at a time I will see a speed increase?
Mike
Not just using the FIFO. It's tricky to figure out the I/O pin latencies and work with them so as to remove that WAITX from the inner loop.
There also needs to be enough lead time to allow for external latencies too. I make use of the fact that there is 8 sysclock ticks per bit to give me slack for this without needing to calculate a compensation based on sysclock frequency.
That's your slow card still working isn't it. That's normal. Slow SD cards are slow. EDIT: BTW, run it a second time and the write speed might be faster the second time.
I tried that at one stage but it failed badly. Didn't try to sort out why though.
You have to take care of the bit order - just shifting bits into a long does not suffice, you'll end up with the first byte received in the last byte of the long (a single MOVBYTS can fix this)
Cool. Should try it again I guess ... yep, that worked. Gained another 10% extra read speed at 200 MHz. Maybe 7% gain for write speed.
Ada,
My quick hack there for 32-bit inner loop is split into two separate blobs of assembly with a simple logic decision as to which one gets used. I've now got a more robust logic solution that can use both paths but it also merges the two blobs into one. So I have my doubts as to its benefit because of the larger all-in-one blob size.
Do you know if Fcache always reloads into cogRAM/lutRAM or is there some smarts to reuse an already loaded blob?
EDIT: So far, testing isn't revealing any advantage either way. Larger blob doesn't seem to be any hindrance ...
EDIT2: Here's what I've got now:
As is it always reloads, yes. But each additional instruction beyond the initial overhead just costs one cycle and you're saving some by doing the branch inside the FCACHE, so yeah, difference is minor.
Also, to make it not explode with FCACHE disabled, I think an FCACHE_SIZE preprocessor symbol could be introduced...
Thanks, hehe, I'm on to smartpins now. If this works out then it won't even need Fcache at all. Maybe all done in C too.
Oh, wow, SD's SPI protocol is sensitive to, even unclocked, post-command trailing level of DI. Not very SPI compliant at all. Makes it tricky to keep the tx smartpin doing the right thing.
The good news is it's now good enough to read and write blocks. Bad news is it corrupts the filesystem ...
EDIT: Huh, I may have found a bug in the disk_write() function. The optimiser maybe reordering the multiple functions within an if() condition. Namely this:
I split them up to work out which one was giving an error and it started working ... err, well, still not getting 100% valid data read back yet but it is writing a complete file now without destroying the filesystem ... Update: One of my three uSD cards is passing the speed test with matching data ...
Well, I have created a PR to define
__HAVE_FCACHE__when FCACHE is available. That should solve the issue of making stuff work at -O0
Thanks, that was a little hairy.
I think I've solved the smartpins implementation too. I changed it from SPI clock mode 0 to mode 3. The clock pin now idles high. All three cards are passing the speed test - only tested at 10 MHz sysclock ...
Aaaand it's on master. That was quick.
Got a problem detecting SPI mode on one card at high clock rate. It switches/detects and works first run, but rebooting the Prop2 with that SD card still powered in SPI mode then fails to detect. Amusingly it's the one that was happy in mode 0.
EDIT: Oh, I guess it should be doing those steps at a low clock rate ...
EDIT2: hmm, might be a latencies thing ... hmm, yeah, I guess I'm pushing the limits now ...
EDIT3: Grrr, there's a missing pull-up on the Eval Board. DO is meant to have one according to SD specs. Important for idle detection. Good news is I can substitute with the rx pin's drive controls ... doesn't seem to make it any faster though.
EDIT4: Oh, I wasn't expecting this:
EDIT5: Ah, here we go:
PS: Those results are 200 MHz and sysclock/4, ie: 50 MHz SPI clock. I was surprised it worked at all at sysclock/4. The SPI clock config to prevent glitches on the DI pin means I can't setup the rx smartpin to change phase like I would with a regular SPI memory.
Soldered up some wires for powering and programming an Edge Card. Plugged it all together and slotted a uSD card to see if the tests were any better there ... Nope.
First thing I managed to do was supply 24 Volts to the Edge Card. Didn't seem to hurt it luckily.
That's surprising. The Eval Board is faster than the Edge Card. Something is messing with data out from the SD card. Maybe reflections. Dunno, way too fast for the scope.
Ouch! And it's bad enough to mess with the optimised bit-bashed code I posted earlier too. Bugger, 200 MHz sysclock is all it can do on the Edge.
I'll be damned! The Sandisk Extreme is fine all the way up to max test frequency of 360 MHz! Drive strength clearly makes a difference.
I better try reading the SD standard to see what queries can be made for speed limits ...
PS: On the current state of the smartpins development: I've mostly solved the card detection issue on reboot. Just needed a small delay added after the first CMD0 to wait for switching out of transfer mode. It was of those it-never-happened-with-debug-enabled situations. Because the time required to report status was enough to make the SD card happy.
There still is occasional issue after I've had massive errors due to bad timings and then need to power down to recover.
Doing some more clean up today ... and after discovering the above bit-bashing issue I figured it'd also be worth bringing that method up to speed with the other fixes I'd done while developing the smartpins method. And voila, it works fully on the Edge Card. I had to adjust rx phase to suit clock idle high instead of low, but not much else other than remove the smartpin init code.
So both methods are getting pretty robust. Oops, spoke too soon. Timings too tight in the new smartpins method ...
Update: Here's the latest code. It's set to bit-bashed. I'd like to get others testing the revised bit-bashed method.
Eliminated the need for Fcache - without clock stretching within a block transfer. And in the process found out I'd wrongly assumed SD was sensitive to trailing DI level when it's not.
So now there is a possibility of adjusting rx phase at faster clock rates and solidly hitting 50 MHz SPI clock. Or maybe not. It's way overkill for the size of RAM.
EDIT: Scratching my head lots on this tight timings issue. It looks like the main factor is actually the smartB clock input for both tx and rx smartpins. It seems that registering just the clock pin irons out a lot of inconsistencies. It also ups the lag effect out to +5 sysclock ticks on the tx smartpin. I'd previously avoided even trying it because of the extra lag.
Okay, this time. Smartpin solution is enabled again.
EDIT: Oops, left debug enabled. Fixed now.
Updated sdmm.cc: Some minor tweaks and comments added.
Updated speedtest.c: Removed the spin2 library code.
@evanh ,
Looking at the code I think it would be better to have two sets of code. There is a block read and write section that could have there own block read/write.
Leave the simple 1, 2 byte send/receive functions simple as not much speed can be gained there and build block read/write functions into the block code.
In the above code use block function to read N number of blocks.
Mike
@ersmith ,
I have made a lot of changes to your vfs_sdcard functions and move 99% of the code you put into FatFs out. They have come out with a newer version and to update it only required coping in the new files and changing two or three lines of code in the FatFs system.
Along with Evans changes we could have a very efficient SD card support.
The only thing is the vfs_sdcard parameters seems to be a sticking point. On the P1 we always had to provide them and don't see a problem with passing them in. I know the P2 has the SD card mounted and would use the same pins but passing them in seems to be simple enough.
I also added long file name support and date/time, file size, and entry type to the directory functions which aids in finding files on the SD card.
Let me know what you think.
Mike
I've not tried to redesign how Eric's done the SD protocol verses block level functionality. In fact, you're more than welcome to work on that side of the code.
BTW, Eric supports SDv1/MMC variable length blocks.
EDIT: On that note, I'm procrastinating on a project I started with the Prop1. Time to get back to it. I'm much more comfortable with the Prop2 but the Prop1 is more than capable for the job and the DIP40 package is surprisingly convenient for the layout.
I'd certainly be interested to see what you've done. The SD card driver can definitely use some improvements (and I hope to incorporate @evanh 's changes when they're ready, as well).
There's a vfs_sdcardx where the pin parameters are provided. Are there other parameters that we need? If so, we may also be able to provide them via mount() (I've recently changed the vfs code so the mount() parameter gets passed to an initialization routine in the VFS layer).
I think we'll want to leave the long file name support as optional (I think it can be enabled by a compile time define). Extending the directory functions is probably a good idea in principle, but we'll need to make sure the other file systems can support it.
Thanks,
Eric
Oh, that'd be useful indeed. readdir is a bit silly as-is because AFAICT you have to separately stat each file to figure out what the entry actually is.
Also, there's a weird issue I had to work around to get scanning subdirectories to work in megayume: The SD root directory can only be read if a trailing slash is given, but subdirectories only if it is not given.
/can not be enumerated at all?
Relatedly, I think the true root directory | https://forums.parallax.com/discussion/174513/improving-sd-card-performance | CC-MAIN-2022-21 | refinedweb | 3,709 | 81.12 |
(For more resources on Web Development, see here.)
What's a module?
Modules are the basic building block of constructing Node applications. We have already seen modules in action; every JavaScript file we use in Node is itself a module. It's time to see what they are and how they work.
The following code to pull in the fs module, gives us access to its functions:
var fs = require('fs');
The require function searches for modules, and loads the module definition into the Node runtime, making its functions available. The fs object (in this case) contains the code (and data) exported by the fs module.
Let's look at a brief example of this before we start diving into the details. Ponder over this module, simple.js:
var count = 0;
exports.next = function() { return count++; }
This defines an exported function and a local variable. Now let's use it:
The object returned from require('./simple') is the same object, exports, we assigned a function to inside simple.js. Each call to s.next calls the function next in simple.js, which returns (and increments) the value of the count variable, explaining why s.next returns progressively bigger numbers.
The rule is that, anything (functions, objects) assigned as a field of exports is exported from the module, and objects inside the module but not assigned to exports are not visible to any code outside the module. This is an example of encapsulation.
Now that we've got a taste of modules, let's take a deeper look.
Node modules
Node's module implementation is strongly inspired by, but not identical to, the CommonJS module specification. The differences between them might only be important if you need to share code between Node and other CommonJS systems. A quick scan of the Modules/1.1.1 spec indicates that the differences are minor, and for our purposes it's enough to just get on with the task of learning to use Node without dwelling too long on the differences.
How does Node resolve require('module')?
In Node, modules are stored in files, one module per file. There are several ways to specify module names, and several ways to organize the deployment of modules in the file system. It's quite flexible, especially when used with npm, the de-facto standard package manager for Node.
Module identifiers and path names
Generally speaking the module name is a path name, but with the file extension removed. That is, when we write require('./simple'), Node knows to add .js to the file name and load in simple.js.
Modules whose file names end in .js are of course expected to be written in JavaScript. Node also supports binary code native libraries as Node modules. In this case the file name extension to use is .node. It's outside our scope to discuss implementation of a native code Node module, but this gives you enough knowledge to recognize them when you come across them.
Some Node modules are not files in the file system, but are baked into the Node executable. These are the Core modules, the ones documented on nodejs.org. Their original existence is as files in the Node source tree but the build process compiles them into the binary Node executable.
There are three types of module identifiers: relative, absolute, and top-level.
Relative module identifiers begin with "./" or "../" and absolute identifiers begin with "/". These are identical with POSIX file system semantics with path names being relative to the file being executed.
Absolute module identifiers obviously are relative to the root of the file system. Top-level module identifiers do not begin with "." , "..", or "/" and instead are simply the module name. These modules are stored in one of several directories, such as a node_modules directory, or those directories listed in the array require.paths, designated by Node to hold these modules.
Local modules within your application
The universe of all possible modules is split neatly into two kinds, those modules that are part of a specific application, and those modules that aren't. Hopefully the modules that aren't part of a specific application were written to serve a generalized purpose. Let's begin with implementation of modules used within your application.
Typically your application will have a directory structure of module files sitting next to each other in the source control system, and then deployed to servers. These modules will know the relative path to their sibling modules within the application, and should use that knowledge to refer to each other using relative module identifiers.
For example, to help us understand this, let's look at the structure of an existing Node package, the Express web application framework. It includes several modules structured in a hierarchy that the Express developers found to be useful. You can imagine creating a similar hierarchy for applications reaching a certain level of complexity, subdividing the application into chunks larger than a module but smaller than an application. Unfortunately there isn't a word to describe this, in Node, so we're left with a clumsy phrase like "subdivide into chunks larger than a module". Each subdivided chunk would be implemented as a directory with a few modules in it.
In this example, the most likely relative module reference is to utils.js. Depending on the source file which wants to use utils.js it would use one of the following require statements:
var utils = require('./lib/utils');
var utils = require('./utils');
var utils = require('../utils');
(For more resources on Web Development, see here.)
Bundling external dependencies with your application
Modules placed in a node_modules directory are required using a top-level module identifier such as:
var express = require('express');
Node searches the node_modules directories to find modules. There is not just one node_modules directory, but several that are searched for by Node. Node starts at the directory of the current module, appends node_modules, and searches there for the module being requested. If not found in that node_modules directory it moves to the parent directory and tries again, repeatedly moving to parent directories until reaching the root of the file system.
In the previous example, you'll notice a node_modules directory within which is a directory named qs. By being situated in that location, the qs module is available to any module inside Express with this code utterance:
var qs = require('qs');
What if you want to use the Express framework in your application? That's simple, make a node_modules directory inside the directory structure of your application, and install the Express framework there:
We can see this in a hypothetical application shown here, drawapp. With the node_modules directory situated where it is any module within drawapp can access express with the code:
var express = require('express');
But those same modules cannot access the qs module stashed inside the node_modules directory within the express module. The search for node_modules directories containing the desired module goes upward in the filesystem hierarchy, and not into child directories.
Likewise a module could be installed in lib/node_modules and be accessible from draw.js or svg.js and not accessible from index.js. The search for node_modules directories goes upward, and not into child directories.
Node searches upward for node_modules directories, stopping at the first place it finds the module it's searching for. A module reference from draw.js or svg.js would search this list of directories:
- /home/david/projects/drawapp/lib/node_modules
- /home/david/projects/drawapp/node_modules
- /home/david/projects/node_modules
- /home/david/node_modules
- /home/node_modules
- /node_modules
The node_modules directory plays a key role in keeping the Node package management from disappearing into a maze of conflicting package versions. Rather than having one place to put modules, and descend into confusion as dependencies on conflicting module versions slowly drive you nuts, multiple node_modules directories let you have specific versions of modules in specific places, if needed. Different versions of the same module can live in different node_modules directories, and they won't conflict with each other, so long as the node_modules directories are situated correctly.
For example, if you've written an application using the forms module () to help build the forms in your application and after writing hundreds of different forms, the authors of the forms module make incompatible changes. With hundreds of forms to convert and test on their new API you might not want to do it all at once, but spread out the effort. To do so would require two directories within your application, each with its own node_modules directory, with a different version of the forms module in each. Then as you convert a form to the new forms module, move its code into the directory where the new forms module lives.
System-wide modules in the require.paths directories
The algorithm Node uses to find the node_modules directories extends beyond your application source tree. It goes to the root of the file system, and you could have a /node_modules directory with a global module repository to satisfy any search for modules.
Node provides an additional mechanism with the require.paths variable. This is an array of directory names where we can search for modules.
An example is:
$ node
> require.paths;
["/home/david/.node_modules","/home/david/.node_libraries","/usr/
local/lib/node"]
The NODE_PATH environment variable can add directories to the require.paths array:
$ export NODE_PATH=/usr/lib/node
$ node
> require.paths;
["/usr/lib/node","/home/david/.node_libraries","/usr/local/lib/node
"]>
It used to be a common idiom for Node programs to add directories into require.paths variable as follows: require.paths.push(__dirname). However, this is no longer recommended because in practice it was found to be a troublesome source of confusion. While you can still do this, and while there are still modules in existence using this idiom, it's sternly frowned upon. The results are unpredictable when multiple modules push directories into require.paths.
The recommended practice is, in most cases, to install modules in node_modules directories.
Complex modules—modules as directories
A complex module might include several internal modules, data files, template files, documentation, tests, or more. These can be stashed inside a carefully constructed directory structure,which Node will treat as a module satisfying a require('moduleName') request. To do so, you place one of the two files in a directory, either a module file named index.js, or a file named package.json. The package.json file will contain data describing the module, in a format nearly identical to the package.json format defined by the npm package manager. The two are compatible with Node using a very small subset of the tags that npm recognizes.
Specifically, Node recognizes these fields in package.json:
{ name: "myAwesomeLibrary",
main: "./lib/awesome.js" }
With that package.json, the code require('myAwesomeLibrary') would find this directory, and load the file:
/path/to/node_modules/myAwesomeLibrary/lib/awesome.js
If there were no package.json file then Node will instead look for index.js, which would load the file:
/path/to/node_modules/myAwesomeLibrary/index.js
Under either scenario (index.js or package.json), the complex module with internal modules and other assets is easy to implement. Some of the modules will use relative module identifiers to reference other modules inside the package, and you can use a node_modules directory to integrate modules developed elsewhere.
CommonJS modules
Node's module system is based on the the CommonJS module system (). While JavaScript is a powerful language with several advanced modern features (such as objects and closures), it lacks a standard object library to facilitate building applications. CommonJS aims to fill that gap with both a convention for implementing modules in JavaScript, and a set of standard modules.
The require function takes a module identifier and returns the API exported by the module. If a module requires other modules they are loaded as well. Modules are contained in one JavaScript file, and CommonJS doesn't specify how the module identifier is mapped into a filename.
Modules provide a simple mechanism for encapsulation to hide implementation details while exposing an API. Module content is JavaScript code which is treated as if it were written as follows:
(function() { ... contents of module file ... })();
This encapsulates (hides) every top-level object in the module within a private namespace that other code cannot access. This is how the Global Object problem is resolved.
The exported module API is the object returned by the require function. Inside the module it's implemented with a top-level object named exports whose fields contain the exported API. To expose a function or object from the module, simply assign it into the exports object.
Demonstrating module encapsulation
That was a lot of words, so let's do a quick example. Create a file named module1.js containing this:
var A = "value A";
var B = "value B";
exports.values = function() {
return { A: A, B: B };
}
Then create a file named module2.js containing the following:
var util = require('util');
var A = "a different value A";
var B = "a different value B";
var m1 = require('./module1');
util.log('A='+A+' B='+B+' values='+util.inspect(m1.values()));
Then run it as follows (you must have already installed Node):
$ node module2.js
19 May 21:36:30 - A=a different value A B=a different value B
values={ A: 'value A', B: 'value B' }
This artificial example demonstrates encapsulation of the values in module1.js from those in module2.js. The A and B values in module1.js don't overwrite A and B in module2.js, because they're encapsulated within module1.js. Values encapsulated within a module can be exported, such as the .values function in module1.js.
The Global Object problem has to do with those variables which are outside the functions, putting them in the global context. In web browsers there is a single global context, and it causes a lot of problems if one JavaScript script steps on the global variables used in another script. With CommonJS modules each module has its own private global context, making it safe to share variables between functions within a module without danger of interfering with global variables in other modules.
Summary
We learned a lot about modules and packages for Node. In this article we covered implementing modules and packages for Node. We also saw how Node locates modules.
Further resources on this subject:
- An Overview of the Node Package Manager [Article]
- MODx Web Development: Creating Lists [Article]
- Creating Web Templates in Inkscape [Article]
- MODx 2.0: Web Development Basics [Article]
- An Overview of Web Services in Sakai [Article] | https://www.packtpub.com/books/content/understanding-and-developing-node-modules | CC-MAIN-2016-30 | refinedweb | 2,433 | 56.66 |
We will build a deep neural network that functions as part of an end-to-end machine translation pipeline. The completed pipeline will accept English text as input and return the French translation. For our model, we will use an English and French sample of sentences. We will load the following libraries:
import collectionsimport helper
import numpy as npfrom keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model
from keras.layers import GRU, Input, Dense, TimeDistributed, Activation, RepeatVector, Bidirectional
from keras.layers.embeddings import Embedding
from keras.optimizers import Adam
from keras.losses import sparse_categorical_crossentropy
Where
helper.py is:
import osdef load_data(path)…
Folium provides a python interface for leaflet.js. Leaflet.js is a Javascript library for interactive maps and can be useful to know on its own. The benefit of using this library via Folium is that Folium makes it very easy to use from within a Jupyter Notebook and to access your python data structures (e.g. Pandas DataFrames). The documentation for Folium can be found on its official website. For this tutorial, we will work with the Baltimore Arrest Data.
The map will include the following dimensions:
isAdultwhere will be a
pop-upin every observation
In this tutorial, we will provide you an example of how you can build a powerful neural network model to classify images of cats and dogs using transfer learning by considering as base model a pre-trained model trained on ImageNet, and then we will train additional new layers for our cats and dogs classification model.
We will work with a sample of 600 images from the Dogs vs Cats dataset, which was used for a 2013 Kaggle competition.
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dense, Flatten, Dropout
import numpy as np
import os
import…
Today, when I visited the “Medium Partner Program” to see my traffic and revenues, I saw this message:
In the cryptocurrency market, the big whales play a key role. These movements affect significantly the market. Take for example a well-known big whale, Elon Musk. Whenever he trades a big amount of Bitcoins, the market follows him. In this post, we will try to build an algorithmic trading strategy that takes an advantage of big whales' movements.
We can detect the whales from the per-minute volume. When there is a significant spike in the volumes, it means that there is an anomaly and most probably is due to the trades of a big investor, the so-called “whale”. Usually, the…
It is common to be asked to build some functions in Python (or any other programming language) during interviews in order to assess your coding style, your skills and your way of thinking. Let’s provide some examples:
Assume that we have a sequence of N rolling Die results, taking values from 1 to 6. Assuming that your input will be a sequence of results like “56611166626634416” build the following functions:
How many times did it occur in the trial, that exactly two 6s were rolled after each other? …
We have started a series of articles on tips and tricks for data scientists (in Python and R). In case you have missed:
When we build predictive models, we use to remove the high correlated variables (multi-collinearity). The point is to keep on of the two correlated variables. Let’s see how we can do it in R by taking as an example the independent variables of the
iris dataset.
Get the correlation matrix of the IVs of iris dataset:
df<-iris[, c(1:4)] cor(df)
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 1.0000000 -0.1175698…
We have provided an example of how to get a sentiment score for words in Python based on ratio frequency. For this example, we will work with the Naive Bayes approach taking into consideration a Twitter dataset that comes with NLTK which has been manually annotated. The sample dataset from NLTK is separated into positive and negative tweets. It contains 5000 positive tweets and 5000 negative tweets exactly.
We have provided an example of Naive Bayes Classification where we explain the theory. …
In this tutorial, we will get the Bayesian Score of each word as well as of the whole Subject Line. The score will indicate the chance of a Subject Line and/or token being “spam”. You can find the dataset here. We have used the same dataset, in the Email Spam Detector Tutorial, so feel free to compare the Bayesian approach with the Logistic Regression.
Load the libraries
import pandas as pd
import numpy as np
import re from collections
import Counter import string
So how do you train a Naive Bayes classifier?
We have provided a tutorial of Market Basket Analysis in Python working with the
mlxtend library. Today, we will provide an example of how you can get the association rules from scratch. Let's recall the 3 most common:
It calculates…
Data Scientist @ Persado | Co-founder of the Data Science blog: | https://jorgepit-14189.medium.com/?source=post_internal_links---------6---------------------------- | CC-MAIN-2021-25 | refinedweb | 854 | 54.32 |
!
Multi-threading with the BackgroundWorker
By default, each time your application executes a piece of code, this code is run on the same thread as the application itself. This means that while this code is running, nothing else happens inside of your application, including the updating of your UI..
The solution to all of this is the use of multiple threads, and while C# makes this quite easy to do, multi-threading comes with a LOT of pitfalls, and for a lot of people, they are just not that comprehensible. This is where the BackgroundWorker comes into play - it makes it simple, easy and fast to work with an extra thread in your application.
How the BackgroundWorker works. This is all a bit cumbersome, but not when you use the BackgroundWorker.
When performing a task on a different thread, you usually have to communicate with the rest of the application in two situations: When you want to update it to show how far you are in the process, and then of course when the task is done and you want to show the result. The BackgroundWorker is built around this idea, and therefore comes with the two events ProgressChanged and RunWorkerCompleted.
The third event is called DoWork and the general rule is that you can't touch anything in the UI from this event. Instead, you call the ReportProgress() method, which in turn raises the ProgressChanged event, from where you can update the UI. Once you're done, you assign a result to the worker and then the RunWorkerCompleted event is raised.
So, to sum up, the DoWork event takes care of all the hard work. All of the code in there is executed on a different thread and for that reason you are not allowed to touch the UI from it. Instead, you bring data (from the UI or elsewhere) into the event by using the argument on the RunWorkerAsync() method, and the resulting data out of it by assigning it to the e.Result property.
The ProgressChanged and RunWorkerCompleted events, on the other hand, are executed on the same thread as the BackgroundWorker is created on, which will usually be the main/UI thread and therefore you are allowed to update the UI from them. Therefore, the only communication that can be performed between your running background task and the UI is through the ReportProgress() method.
That was a lot of theory, but even though the BackgroundWorker is easy to use, it's important to understand how and what it does, so you don't accidentally do something wrong - as already stated, errors in multi-threading can lead to some nasty problems.
A BackgroundWorker example
Enough with the theory - let's see what it's all about. In this first example, we want a pretty simply but time consuming job performed. Each number between 0 and 10.000 gets tested to see if it's divisible with the number 7. This is actually a piece of cake for today's fast computers, so to make it more time consuming and thereby easier to prove our point, I've added a one millisecond delay in each of the iterations.
Our sample application has two buttons: One that will perform the task synchronously (on the same thread) and one that will perform the task with a BackgroundWorker and thereby on a different thread. This should make it very easy to see the need for an extra thread when doing time consuming tasks. The code looks like this:
<Window x: <DockPanel Margin="10"> <DockPanel DockPanel. <Button Name="btnDoSynchronousCalculation" Click="btnDoSynchronousCalculation_Click" DockPanel.Synchronous (same thread)</Button> <Button Name="btnDoAsynchronousCalculation" Click="btnDoAsynchronousCalculation_Click" DockPanel.Asynchronous (worker thread)</Button> </DockPanel> <ProgressBar DockPanel. <ListBox Name="lbResults" Margin="0,10" /> </DockPanel> </Window>
using System; using System.ComponentModel; using System.Windows; namespace WpfTutorialSamples.Misc { public partial class BackgroundWorkerSample : Window { public BackgroundWorkerSample() { InitializeComponent(); } private void btnDoSynchronousCalculation_Click(object sender, RoutedEventArgs e) { int max = 10000; pbCalculationProgress.Value = 0; lbResults.Items.Clear(); int result = 0; for(int i = 0; i < max; i++) { if(i % 42 == 0) { lbResults.Items.Add(i); result++; } System.Threading.Thread.Sleep(1); pbCalculationProgress.Value = Convert.ToInt32(((double)i / max) * 100); } MessageBox.Show("Numbers between 0 and 10000 divisible by 7: " + result); } private void btnDoAsynchronousCalculation_Click(object sender, RoutedEventArgs e) { pbCalculationProgress.Value = 0; lbResults.Items.Clear(); BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += worker_DoWork; worker.ProgressChanged += worker_ProgressChanged; worker.RunWorkerCompleted += worker_RunWorkerCompleted; worker.RunWorkerAsync(10000); } void worker_DoWork(object sender, DoWorkEventArgs e) { int max = (int)e.Argument; int result = 0; for(int i = 0; i < max; i++) { int progressPercentage = Convert.ToInt32(((double)i / max) * 100); if(i % 42 == 0) { result++; (sender as BackgroundWorker).ReportProgress(progressPercentage, i); } else (sender as BackgroundWorker).ReportProgress(progressPercentage); System.Threading.Thread.Sleep(1); } e.Result = result; } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { pbCalculationProgress.Value = e.ProgressPercentage; if(e.UserState != null) lbResults.Items.Add(e.UserState); } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("Numbers between 0 and 10000 divisible by 7: " + e.Result); } } }
The XAML part consists of a couple of buttons, one for running the process synchronously (on the UI thread) and one for running it asynchronously (on a background thread), a ListBox control for showing all the calculated numbers and then a ProgressBar control in the bottom of the window to show... well, the progress!
In Code-behind, we start off with the synchronous event handler. As mentioned, it loops from 0 to 10.000 with a small delay in each iteration, and if the number is divisible with the number 7, then we add it to the list. In each iteration we also update the ProgressBar, and once we're all done, we show a message to the user about how many numbers were found.
If you run the application and press the first button, it will look like this, no matter how far you are in the process:
No items on the list and, no progress on the ProgressBar, and the button hasn't even been released, which proves that there hasn't been a single update to the UI ever since the mouse was pressed down over the button.
Pressing the second button instead will use the BackgroundWorker approach. As you can see from the code, we do pretty much the same, but in a slightly different way. All the hard work is now placed in the DoWork event, which the worker calls after you run the RunWorkerAsync() method. This method takes input from your application which can be used by the worker, as we'll talk about later.
As already mentioned, we're not allowed to update the UI from the DoWork event. Instead, we call the ReportProgress method on the worker. If the current number is divisible with 7, we include it to be added on the list - otherwise we only report the current progress percentage, so that the ProgressBar may be updated.
Once all the numbers have been tested, we assign the result to the e.Result property. This will then be carried to the RunWorkerCompleted event, where we show it to the user. This might seem a bit cumbersome, instead of just showing it to the user as soon as the work is done, but once again, it ensures that we don't communicate with the UI from the DoWork event, which is not allowed.
The result is, as you can see, much more user friendly:
The window no longer hangs, the button is clicked but not suppressed, the list of possible numbers is updated on the fly and the ProgressBar is going steadily up - the interface just got a whole lot more responsive.
Input and output
Notice that both the input, in form of the argument passed to the RunWorkerAsync() method,as well as the output, in form of the value assigned to the e.Result property of the DoWork event, are of the object type. This means that you can assign any kind of value to them. Our example was basic, since both input and output could be contained in a single integer value, but it's normal to have more complex input and output.
This is accomplished by using a more complex type, in many cases a struct or even a class which you create yourself and pass along. By doing this, the possibilities are pretty much endless and you can transport as much and complex data as you want between your BackgroundWorker and your application/UI.
The same is actually true for the ReportProgress method. Its secondary argument is called userState and is an object type, meaning that you can pass whatever you want to the ProgressChanged method.
Summary
The BackgroundWorker is an excellent tool when you want multi-threading in your application, mainly because it's so easy to use. In this chapter we looked at one of the things made very easy by the BackgroundWorker, which is progress reporting, but support for cancelling the running task is very handy as well. We'll look into that in the next chapter. | https://wpf-tutorial.com/da/97/misc-/multi-threading-with-the-backgroundworker/ | CC-MAIN-2019-43 | refinedweb | 1,498 | 53.61 |
Using?
But In the other hand the jira API through the postman works fine.
So can you define how it has to be configured in data3sixty analyze?
The following works for calling JIRA REST API's:
1. Get your Jira API Token ()
2. Base64 Encode your email address:api_token The following example is using python.
Python example:
import base64
out1.Base64EncodedString = base64.b64encode("email:api_token".encode('utf-8'))
3. In the HTTP Node, put the following in the header property:
Authorization: Basic <value from step #2 above>
4. Run the HTTP node with your URL and then connect a JSON node to read the response
It should look like this when you are done:
-
-
Please sign in to leave a comment. | https://support.infogix.com/hc/en-us/community/posts/360028940693-Using-Data3sixty-to-GET-JIRA-API-jSON-information | CC-MAIN-2020-29 | refinedweb | 121 | 65.73 |
First Steps in Unit Testing
- |
-
-
-
-
-
-
Read later
Reading List
In addition to being a software industry best practice, unit testing is promoted by agile methodologies as a pillar for sustainable software production. According to the most recent annual Agile survey, 70% of the participants said they unit test their code.
Unit testing goes hand in hand with other agile practices, so starting to write tests is a stepping-stone for organizations wanting to go agile. The road is long, but is worth taking. In this article, I’ll cover tips on what to expect, and steps to take when starting out in order to make unit testing a part of development life.
There’s an implicit notion about effective unit tests - they are automated. Without automation, productivity tumbles. Making unit testing a habit cannot be sustained long term without it. Relying on manual testing (done by either testers or developers) doesn’t stick; under pressure, no one remembers to run all the tests, or to cover all the scenarios. Automation is our friend, and all unit test frameworks have embraced automation, as well as integration with other automated systems.
Unit testing is crucial for modern development
With tests around our code, we have a built-in safety net. If we change our code and break something, the tests let us know. The bigger the safety net, the more confident we are in knowing the code works and our own ability to change it when needed.
The major benefit of unit tests over other types of tests is quick feedback. Running suites of hundreds of tests in a matter of seconds helps the development flow. We’re forming a cadence of adding some code, adding a test, seeing the tests pass and moving forward. Moving in small steps, knowing everything is working, also means debugging time drops immensely. It’s no wonder we feel more productive with tests - there’s less time spent on bugs, while a lot more time is spent on pushing features out.
The wall of dependencies
Adding tests to a greenfield project is considerably easier - after all, the code is not there to get in the way. However, this situation is definitely not the norm. Most of us work on legacy code, which is not easily testable. Sometimes we can’t even run the code - it may require data or configuration existing only on production servers. We may need to create different setups for different scenarios, and this may require a lot of effort. In many cases, we may need to change the code in order to test it. This doesn’t make sense: we’re writing tests to have the confidence to change our code without breaking it - how can we do it safely without tests?
Code testability is a function of language and tools. With dynamic languages, like Ruby, code is considered testable as is. We can change behavior of dependencies of the code inside tests, without touching the production code. Statically-typed languages like C# or Java are more difficult.
Here’s an example: An expiration checker method (C#), that checks for expiration against a constant date:
public class ExpirationChecker { private readonly DateTime expirationDate = new DateTime(2012, 1, 1); public bool IsExpired() { if (DateTime.Now > expirationDate) { return true; } return false; } }
In this example, there is a hard dependency in the method IsExpired on when the test runs, since the property DateTime. Now returns the actual time. The method has two cases, returning a different value based on that date. Changing the computer clock is out of the question - we want to tests scenarios on any computer, whenever we can, and without any side effects.
A possible solution to test both cases is to change the code. For example, we can modify our code to this:
public bool IsExpired(DateTime now) { if (now > expirationDate) { return true; } return false; }
Here the test can inject a different, controllable DateTime value than the one in the production code. If we can’t change the code, we can use a mocking framework, like Typemock Isolator, that can mock static properties and methods. This allows writing the following test for the original code:
[TestMethod] public void IsExpired_BeforeExpirationDate_ReturnFalse() { Isolate.WhenCalled(() => DateTime.Now) .WillReturn(new DateTime(2000, 1, 1)); ExpirationChecker checker = new ExpirationChecker(); var result = checker.IsExpired(); Assert.IsFalse(result); }
Existing legacy code is not as simple to change, since we don’t have tests for it. Starting out with testing legacy code, the truth is revealed: the uglier our code, the harder it is to test. Tools can alleviate some of the pain, but we need to work hard for our safety net.
And it’s not just dependencies...
Another issue we quickly encounter is test maintenance: Tests are coupled to tested code. With coupling, there’s a chance changing production code will break the tests. When tests break due to code changes, we need to go back and fix them. The fear of maintaining two code bases discourage many developers from even starting out unit testing. The real maintenance work depends on both tooling and skill.
Writing good tests is a skill acquired through practice. The more tests we write, the better we become at it, while the tests improve and require less maintenance. With tests around, we’ll have the opportunity to refactor our code, which, in turn, will make for shorter, more readable and robust tests.
Tools can greatly affect how easy or hard the experience is. At the basic level we’ll need a test framework and a mocking framework. In the .NET space, there is a wide selection of both.
Guidelines for writing our first tests
When we start out, we usually experiment with different tools to understand how they work. We usually do not do this on our real work code. But, the moment soon arrives when we need to write actual tests for our code. When that time comes, here are a few tips:
- Where to start: As a rule of thumb, we write tests for code we’re working on, whether it is a bug fix or a new feature. For bug fixes, write a test that checks for the fix. For features, check the correct behavior.
- Scaffoldings: It is prudent to first add tests that make sure the current implementation is working according to our knowledge or expectation. We do this prior to adding new code, because we want a safety net around our existing code before we change it. These tests are called "characterization tests", a term from Michael Feathers’ excellent book, Working Effectively with Legacy Code.
- Naming: The most important property of a test is its name. Usually once a test passes, we don’t look at it again. But when it fails, what we’ll see is the name. So pick a good one, describing the scenario and the expected result from the code. A good name will help us identify bugs in the test as well!
- Reviewing: To increase our chances of successful adoption, we should partner with a co-worker when writing our first tests. Both will learn from the experience, and as with any code, we’ll get instant review on the test. It’s better to have agreement on what to test, and how to name it, since this will be the base template for the rest of the team.
- AAA: Modern tests are structured in the AAA pattern- Arrange (the test setup), Act (calling the code under test) and Assert (test pass criteria). If we use Test Driven Development (TDD), we write the test first completely, and then add the code. For legacy code, we might need another option. Once we have a scenario and a name to test, write the Act and Assert part first. We’ll need to keep building the Arrange part, as we know more about dependencies we’ll need to prepare or fake. Then we’ll continue until we have a passing test.
- Refactoring: Once we have tests in place we can refactor the code. Refactoring, as with testing, is an acquired skill. We’ll refactor not just the tested code, but also the tests themselves. We don’t apply the DRY (Don’t Repeat Yourself) principle to tests though. When tests break, we want to fix the problem as quickly as possible, and it’s better to have all the test code in one place, rather than scattered around in different files.
- Readability: Tests should be readable, preferably by a human. Review the test code with a partner to see if he can make sense of the purpose of the test. Review other tests to see how well their names and content differentiate themselves from their neighbors. Once tests fail, they will need fixing, and it is better to review them before that happens.
- Organization: Once we have more tests, organization will come in handy. Tests can differ in many ways, but the one most apparent is how quickly they run. Some can run within milliseconds, others require seconds or minutes. As we work, we want to the quickest feedback possible. This is how we can progress in the cadence I talked about earlier. To do this, you should separate the tests in a way so you can run the quick ones separately from the slow tests. This can be done manually (and diligently), however in .NET, Typemock Isolator also includes a runner that does the separation automatically.
Summary
Taking the first steps in unit testing is challenging. The experience depends on so many things - language, tools, existing code, and dependencies and skill. With a little bit of thinking, a lot of discipline, and practice you’ll get to unit testing nirvana. I did.
About the Author
Gil Zilberfeld is the Product Manager DRY?
by
Rafał Wicha
Re: Why not DRY?
by
Jonathan Allen
Perils of Not Unit Testing
by
Ilias Tsagklis
I question Unit test utility
by
Serge Bureau
For compiled languages and in particular for strongly typed one, it seems much less useful.
Don't get me wrong, I am for automatic tests but mostly functional tests.
When did a Unit test showed me an error the last time ? Maybe once in 3 years.
Just about all the bugs are functional or multi-threading issue, ...
So the return on investment for truely Unit tests is not good at all. (except for dynamic languages)
In fact the popularity of Unit tests came with the popularity of dynamic languages ?
Refactoring code should not imply refactoring tests
by
Alex Worden
If tests break (due to false-negatives) when I refactor, they are more of a hinderance than a help. This is why mock frameworks are largely a broken paradigm because they assume too much about the implementation being tested. Good tests should only verify the external expression of a 'unit'.
TDD
by
Olivier Gourment
Re: I question Unit test utility
by
Alan Felice
> Just about all the bugs are functional or multi-threading issue, ...
A unit test that never fails is not a good unit test. And if you really saw your last failing unit test 3 years ago.. consider the option that you are writing too weak unit tests.
I've just developed a 10k multi-threaded Java application in 5 months that seems (till now) to be stable; it was up for 20 days.
The only bug found (till now) was caused by an openJDK bug on the ARM board, that killed my Java application with no possibility to recover, and the serial modem I use was left in an unexpected (for my implementation) state the next time the application was started -by a watchdog-. I have over 250 unit tests that runs in less than 10 seconds (3 times slower on the ARM board):
- I can't enumerate the times a unit-test revealed that I made in a conditional if the opposite of what I intended to;
- I can't enumerate the times I extended something in one point, and the unit tests for some other component (that I forgot was indirectly using the same thing) suddenly failed, and so prevented me to put that (broken, not safe) extension on production code;
- I can't enumerate the times I heavenly modified a class hierarchy, and the unit-tests revealed me where the new implementation was lacking.
I'm really sure I wouldn't be able to develop (and deliver) that application without the unit-test. And not in that time.
Re: Why not DRY?
by
Alan Felice
> Especially for unit tests where you are going to see the same setup over and over again.
For my experience, readability should be in first place. So, isolate what differs from what is always the same. If something is always the same, put it in a proper method [JUnit has a setUp() method, automatically invoked for all the test-cases in a unit-test]. But when two test cases have different 'arrangement', has to be evident in what them differs. You should not navigate 5 level of methods to discover that.
Mocking framework helps a lot in that. You quite 'declaratively' say what each 'arrangement' is:
when(theMock.myMethod(X)).thenReturn(Y)
Re: Why not DRY?
by
Assaf Stone
So in short, keeping your test code self-evident is important both for learning (understanding how to use your code) and keeping it error free.
Another point to consider - if you feel the need to apply DRY to your test, could it be that your test is too big?
Assaf
Where to start and naming
by
Darrell Grainger
I would add that for Where to start, for bug fixes I'd write a test which would have caught the bug. I'd run it against the existing code and see it fail. I'd then fix the bug and see my test go green.
For Naming I like to have the test method name tell me what it is testing. The expected results should be in the assert statement. If the method passes I assume I got the expected result. No need to clutter up the results with expected results for every test. You really only need the expected results for when it failed. I'd make sure we are looking for the correct expected results during the Reviewing stage.
Re: I question Unit test utility
by
Serge Bureau
But I submit to you that Unit tests themselves are too low level.
Anything a little bit complex is much more testing the Mocks than the code.
I think only fonctional tests have real value. (in the form of story testing)
Most of todays issue are related to distribution, transaction, deadlocks, muti-threading timing issue: all of which are not to be tested with Unit tests.
That adding two numbers give a wrong value will be apparent on any functional tests, Unit tests are redondant and loosing precious development time. | https://www.infoq.com/articles/First-Steps-Unit-Testing | CC-MAIN-2017-47 | refinedweb | 2,480 | 71.44 |
I'm a little confused on how the program reads the math operations for this line:
It seems to me that the way the code is set up it can only add two point objects at a time.It seems to me that the way the code is set up it can only add two point objects at a time.Code:Point point4 = point1 + point2 + point3
How does the operator function know how to add the sum of point1 and point2 to point3. Is this where the inline functionHow does the operator function know how to add the sum of point1 and point2 to point3. Is this where the inline functionCode:Point operator+(const Point &pt) {return add(pt);}comes in?comes in?Code:{return add(pt)}
I know this is very basic to some. I'm having a hard time understanding this.
Complete code is below:
Code://this program sets three Point objects to non-negative, then adds them creating //the 4th Point object. #include <iostream> using namespace std; class Point { private: // Data members (private) int x, y; public: // Constructors Point() {}; Point(int new_x, int new_y) {set(new_x, new_y);} Point(const Point &src) {set(src.x, src.y);} // Operations Point add(const Point &pt); Point operator+(const Point &pt) {return add(pt);} // Other member functions void set(int new_x, int new_y); int get_x() const {return x;} int get_y() const {return y;} }; int main() { Point point1(20, 20); Point point2(0, 5); Point point3(-10, 25); Point point4 = point1 + point2 + point3; cout << "The point is " << point4.get_x(); cout << ", " << point4.get_y() << "." << endl; system("PAUSE"); return 0; } void Point::set(int new_x, int new_y) { if (new_x < 0) new_x *= -1; if (new_y < 0) new_y *= -1; x = new_x; y = new_y; } Point Point::add(const Point &pt) { Point new_pt; new_pt.x = x + pt.x; new_pt.y = y + pt.y; return new_pt; } | http://cboard.cprogramming.com/cplusplus-programming/140470-operator-function-i%27m-not-following-flow.html | CC-MAIN-2015-40 | refinedweb | 306 | 70.33 |
In Chapter 1, we claimed that one way Scala is a scalable language is that you can use the same techniques to construct small as well as large programs. Up to now in this book we've focused primarily on programming in the small: designing and implementing the smaller program pieces out of which you can construct a larger program.[1] The other side of the story is programming in the large: organizing and assembling the smaller pieces into larger programs, applications, or systems. We touched on this subject when we discussed packages and access modifiers in Chapter 13. In short, packages and access modifiers enable you to organize a large program using packages as modules, where a module is a "smaller program piece" with a well defined interface and a hidden implementation.
While the division of programs into packages is already quite helpful, it is limited because it provides no way to abstract. You cannot reconfigure a package two different ways within the same program, and you cannot inherit between packages. A package always includes one precise list of contents, and that list is fixed until you change the code.
In this chapter, we'll discuss how you can use Scala's object-oriented features to make a program more modular. We'll first show how a simple singleton object can be used as a module, and then we'll show how you can use traits and classes as abstractions over modules. These abstractions can be reconfigured into multiple modules, even multiple times within the same program. Finally, we'll show a pragmatic technique for using traits to divide a module across multiple files.
As a program grows in size, it becomes increasingly important to organize it in a modular way. First, being able to compile different modules that make up the system separately helps different teams work independently. In addition, being able to unplug one implementation of a module and plug in another is useful, because it allows different configurations of a system to be used in different contexts, such as unit testing on a developer's desktop, integration testing, staging, and deployment.
For example, you may have an application that uses a database and a message service. As you write code, you may want to run unit tests on your desktop that use mock versions of both the database and message service, which simulate these services sufficiently for testing without needing to talk across the network to a shared resource. During integration testing, you may want to use a mock message service but a live developer database. During staging and certainly during deployment, your organization will likely want to use live versions of both the database and message service.
Any technique that aims to facilitate this kind of modularity needs to provide a few essentials. First, there should be a module construct that provides a good separation of interface and implementation. Second, there should be a way to replace one module with another that has the same interface without changing or recompiling the modules that depend on the replaced one. Lastly, there should be a way to wire modules together. This wiring task can by thought of as configuring the system.
One approach to solving this problem is dependency injection, a technique supported on the Java platform by frameworks such as Spring and Guice, which are popular in the enterprise Java community.[2] Spring, for example, essentially allows you to represent the interface of a module as a Java interface and implementations of the module as Java classes. You can specify dependencies between modules and "wire" an application together via external XML configuration files. Although you can use Spring with Scala and thereby use Spring's approach to achieving system-level modularity of your Scala programs, with Scala you have some alternatives enabled by the language itself. In the remainder of this chapter, we'll show how to use objects as modules to achieve the desired "in the large" modularity without using an external framework.
Imagine you are building an enterprise web application that will allow users to manage recipes. You want to partition the software into layers, including a domain layer and an application layer. In the domain layer, you'll define domain objects, which will capture business concepts and rules and encapsulate state that will be persisted to an external relational database. In the application layer, you'll provide an API organized in terms of the services the application offers to clients (including the user interface layer). The application layer will implement these services by coordinating tasks and delegating the work to the objects of the domain layer.[3]
Imagine also that you want to be able to plug in real or mock versions of certain objects in each of these layers, so that you can more easily write unit tests for your application. To achieve this goal, you can treat the objects you want to mock as modules. In Scala, there is no need for objects to be "small" things, no need to use some other kind of construct for "big" things like modules. One of the ways Scala is a scalable language is that the same constructs are used for structures both small and large. For example, since one of the "things" you want to mock in the domain layer is the object that represents the relational database, you'll make that one of the modules. In the application layer, you'll treat a "database browser" object as a module. The database will hold all of the recipes that a person has collected. The browser will help search and browse that database, for example, to find every recipe that includes an ingredient you have on hand.
The first thing to do is to model foods and recipes. To keep things simple, a food will simply have a name, as shown in Listing 27.1. A recipe will simply have a name, a list of ingredients, and some instructions, as shown in Listing 27.2.
package org.stairwaybook.recipe
abstract class Food(val name: String) { override def toString = name }
package org.stairwaybook.recipe
class Recipe( val name: String, val ingredients: List[Food], val instructions: String ) { override def toString = name }
The Food and Recipe classes shown in Listings 27.1 and 27.2 represent entities that will be persisted in the database.[4] Listing 27.3 shows some singleton instances of these classes, which can be used when writing tests:
package org.stairwaybook.recipe
object Apple extends Food("Apple") object Orange extends Food("Orange") object Cream extends Food("Cream") object Sugar extends Food("Sugar")
object FruitSalad extends Recipe( "fruit salad", List(Apple, Orange, Cream, Sugar), "Stir it all together." )
package org.stairwaybook.recipe
object SimpleDatabase { def allFoods = List(Apple, Orange, Cream, Sugar)
def foodNamed(name: String): Option[Food] = allFoods.find(_.name == name)
def allRecipes: List[Recipe] = List(FruitSalad) }
object SimpleBrowser { def recipesUsing(food: Food) = SimpleDatabase.allRecipes.filter(recipe => recipe.ingredients.contains(food)) }
Scala uses objects for modules, so you can start modularizing your program by making two singleton objects to serve as the mock implementations of the database and browser modules during testing. Because it is a mock, the database module is backed by a simple in-memory list. Implementations of these objects are shown in Listing 27.4. You can use this database and browser as follows:
scala> val apple = SimpleDatabase.foodNamed("Apple").get apple: Food = Apple
scala> SimpleBrowser.recipesUsing(apple) res0: List[Recipe] = List(fruit salad)
To make things a little more interesting, suppose the database sorts foods into categories. To implement this, you can add a FoodCategory class and a list of all categories in the database, as shown in Listing 27.5. Notice in this last example that the private keyword, so useful for implementing classes, is also useful for implementing modules. Items marked private are part of the implementation of a module, and thus are particularly easy to change without affecting other modules.
At this point, many more facilities could be added, but you get the idea. Programs can be divided into singleton objects, which you can think of as modules. This is no big news, but it becomes very useful when you consider abstraction.
package org.stairwaybook.recipe
object SimpleDatabase { def allFoods = List(Apple, Orange, Cream, Sugar)
def foodNamed(name: String): Option[Food] = allFoods.find(_.name == name)
def allRecipes: List[Recipe] = List(FruitSalad)
case class FoodCategory(name: String, foods: List[Food])
private var categories = List( FoodCategory("fruits", List(Apple, Orange)), FoodCategory("misc", List(Cream, Sugar)))
def allCategories = categories }
object SimpleBrowser { def recipesUsing(food: Food) = SimpleDatabase.allRecipes.filter(recipe => recipe.ingredients.contains(food))
def displayCategory(category: SimpleDatabase.FoodCategory) { println(category) } }
Although the examples shown so far did manage to partition your application into separate database and browser modules, the design is not yet very "modular." The problem is that there is essentially a "hard link" from the browser module to the database modules:
SimpleDatabase.allRecipes.filter(recipe => ...Because the SimpleBrowser module mentions the SimpleDatabase module by name, you won't be able to plug in a different implementation of the database module without modifying and recompiling the browser module. In addition, although there's no hard link from the SimpleDatabase module to the SimpleBrowser module,[5] there's no clear way to enable the user interface layer, for example, to be configured to use different implementations of the browser module.
When making these modules more pluggable, however, it is important to avoid duplicating code, because much code can likely be shared by different implementations of the same module. For example, suppose you want the same code base to support multiple recipe databases, and you want to be able to create a separate browser for each of these databases. You would like to reuse the browser code for each of the instances, because the only thing different about the browsers is which database they refer to. Except for the database implementation, the rest of the code can be reused character for character. How can the program be arranged to minimize repetitive code? How can the code be made reconfigurable, so that you can configure it using either database implementation?
The answer is a familiar one: if a module is an object, then a template for a module is a class. Just like a class describes the common parts of all its instances, a class can describe the parts of a module that are common to all of its possible configurations.
The browser definition therefore becomes a class, instead of an object, and the database to use is specified as an abstract member of the class, as shown in Listing 27.6.
abstract class Browser { val database: Database
def recipesUsing(food: Food) = database.allRecipes.filter(recipe => recipe.ingredients.contains(food))
def displayCategory(category: database.FoodCategory) { println(category) } }
The database also becomes a class, including as much as possible that is common between all databases, and declaring the missing parts that a database must define. In this case, all database modules must define methods for allFoods, allRecipes, and allCategories, but since they can use an arbitrary definition, the methods must be left abstract in the Database class. The foodNamed method, by contrast, can be defined in the abstract Database class, as shown in Listing 27.7:
abstract class Database { def allFoods: List[Food] def allRecipes: List[Recipe]
def foodNamed(name: String) = allFoods.find(f => f.name == name)
case class FoodCategory(name: String, foods: List[Food]) def allCategories: List[FoodCategory] }
The SimpleDatabase object must be updated to inherit from the abstract Database class, as shown in Listing 27.8:
object SimpleDatabase extends Database { def allFoods = List(Apple, Orange, Cream, Sugar)
def allRecipes: List[Recipe] = List(FruitSalad)
private var categories = List( FoodCategory("fruits", List(Apple, Orange)), FoodCategory("misc", List(Cream, Sugar)))
def allCategories = categories }
Then, a specific browser module is made by instantiating the Browser class and specifying which database to use, as shown in Listing 27.9.
object SimpleBrowser extends Browser { val database = SimpleDatabase }
You can use these more pluggable modules the same as before:
scala> val apple = SimpleDatabase.foodNamed("Apple").get apple: Food = AppleNow, however, you can create a second mock database, and use the same browser class with it, as shown in Listing 27.10:
scala> SimpleBrowser.recipesUsing(apple) res1: List[Recipe] = List(fruit salad)
object StudentDatabase extends Database { object FrozenFood extends Food("FrozenFood")
object HeatItUp extends Recipe( "heat it up", List(FrozenFood), "Microwave the 'food' for 10 minutes.")
def allFoods = List(FrozenFood) def allRecipes = List(HeatItUp) def allCategories = List( FoodCategory("edible", List(FrozenFood))) }
object StudentBrowser extends Browser { val database = StudentDatabase }
Often a module is too large to fit comfortably into a single file. When that happens, you can use traits to split a module into separate files. For example, suppose you wanted to move categorization code out of the main Database file and into its own. You could create a trait for the code as shown in Listing 27.11.
trait FoodCategories { case class FoodCategory(name: String, foods: List[Food]) def allCategories: List[FoodCategory] }
Now class Database can mix in the FoodCategories trait instead of defining FoodCategory and allCategories itself, as shown in Listing 27.12:
abstract class Database extends FoodCategories { def allFoods: List[Food] def allRecipes: List[Recipe] def foodNamed(name: String) = allFoods.find(f => f.name == name) }
Continuing in this way, you might try and divide SimpleDatabase into two traits, one for foods and one for recipes. This would allow you to define SimpleDatabase, for example, as shown in Listing 27.13:
object SimpleDatabase extends Database with SimpleFoods with SimpleRecipes
The SimpleFoods trait could look as shown in Listing 27.14:
trait SimpleFoods { object Pear extends Food("Pear") def allFoods = List(Apple, Pear) def allCategories = Nil }
So far so good, but unfortunately, a problem arises if you try to define a SimpleRecipes trait like this:
trait SimpleRecipes { // Does not compile object FruitSalad extends Recipe( "fruit salad", List(Apple, Pear), // Uh oh "Mix it all together." ) def allRecipes = List(FruitSalad) }The problem here is that Pear is located in a different trait from the one that uses it, so it is out of scope. The compiler has no idea that SimpleRecipes is only ever mixed together with SimpleFoods.
There is a way you can tell this to the compiler, however. Scala provides the self type for precisely this situation. Technically, a self type is an assumed type for this whenever this is mentioned within the class. Pragmatically, a self type specifies the requirements on any concrete class the trait is mixed into. If you have a trait that is only ever used when mixed in with another trait or traits, then you can specify that those other traits should be assumed. In the present case, it is enough to specify a self type of SimpleFoods, as shown in Listing 27.15:
trait SimpleRecipes { this: SimpleFoods =>
object FruitSalad extends Recipe( "fruit salad", List(Apple, Pear), // Now Pear is in scope "Mix it all together." ) def allRecipes = List(FruitSalad) }
Given the new self type, Pear is now available. Implicitly, the reference to Pear is thought of as this.Pear. This is safe, because any concrete class that mixes in SimpleRecipes must also be a subtype of SimpleFoods, which means that Pear will be a member. Abstract subclasses and traits do not have to follow this restriction, but since they cannot be instantiated with new, there is no risk that the this.Pear reference will fail.
One final feature of Scala modules is worth emphasizing: they can be linked together at runtime, and you can decide which modules will link to which depending on runtime computations. For example, Listing 27.16 shows a small program that chooses a database at runtime and then prints out all the apple recipes in it:
object GotApples { def main(args: Array[String]) { val db: Database = if(args(0) == "student") StudentDatabase else SimpleDatabase
object browser extends Browser { val database = db }
val apple = SimpleDatabase.foodNamed("Apple").get
for(recipe <- browser.recipesUsing(apple)) println(recipe) } }
Now, if you use the simple database, you will find a recipe for fruit salad. If you use the student database, you will find no recipes at all using apples:
$ scala GotApples simple fruit salad $ scala GotApples student $
You may wonder if you are not backsliding to the hard links problem of the original examples in this chapter, because the GotApples object shown in Listing 27.16 contains hard links to both StudentDatabase and SimpleDatabase. The difference here is that the hard links are localized in one file that can be replaced.
Every modular application needs some way to specify the actual module implementations to use in a particular situation. This act of "configuring" the application will by definition involve the naming of concrete module implementations. For example, in a Spring application, you configure by naming implementations in an external XML file. In Scala, you can configure via Scala code itself. One advantage to using Scala source over XML for configuration is that the process of running your configuration file through the Scala compiler should uncover any misspellings in it prior to its actual use.
Despite using the same code, the different browser and database modules created in the previous section really are separate modules. This means that each module has its own contents, including any nested classes. FoodCategory in SimpleDatabase, for example, is a different class from FoodCategory in StudentDatabase!
scala> val category = StudentDatabase.allCategories.head category: StudentDatabase.FoodCategory = FoodCategory(edible,List(FrozenFood))
scala> SimpleBrowser.displayCategory(category) <console>:12: error: type mismatch; found : StudentDatabase.FoodCategory required: SimpleBrowser.database.FoodCategory SimpleBrowser.displayCategory(category) ^
If instead you prefer all FoodCategorys to be the same, you can accomplish this by moving the definition of FoodCategory outside of any class or trait. The choice is yours, but as it is written, each Database gets its own, unique FoodCategory class.
The two FoodCategory classes shown in the previous example really are different, so the compiler is correct to complain. Sometimes, though, you may encounter a case where two types are the same but the compiler can't verify it. You will see the compiler complaining that two types are not the same, even though you as the programmer know they perfectly well are.
In such cases you can often fix the problem using singleton types. For example, in the GotApples program, the type checker does not know that db and browser.database are the same. This will cause type errors if you try to pass categories between the two objects:
object GotApples { // same definitions... for (category <- db.allCategories) browser.displayCategory(category) // ... } GotApples2.scala:14: error: type mismatch; found : db.FoodCategory required: browser.database.FoodCategory browser.displayCategory(category) ^ one error foundTo avoid this error, you need to inform the type checker that they are the same object. You can do this by changing the definition of browser.database as shown in Listing 27.17:
object browser extends Browser { val database: db.type = db }
This definition is the same as before except that database has the funny-looking type db.type. The ".type" on the end means that this is a singleton type. A singleton type is extremely specific and holds only one object, in this case, whichever object is referred to by db. Usually such types are too specific to be useful, which is why the compiler is reluctant to insert them automatically. In this case, though, the singleton type allows the compiler to know that db and browser.database are the same object, enough information to eliminate the type error.
This chapter has shown how to use Scala's objects as modules. In addition to simple static modules, this approach gives you a variety of ways to create abstract, reconfigurable modules. There are actually even more abstraction techniques than shown, because anything that works on a class, also works on a class used to implement a module. As always, how much of this power you use should be a matter of taste.
Modules are part of programming in the large, and thus are hard to experiment with. You need a large program before it really makes a difference. Nonetheless, after reading this chapter you know which Scala features to think about when you want to program in a modular style. Think about these techniques when you write your own large programs, and recognize these coding patterns when you see them in other people's code.
[1] This terminology was introduced in DeRemer, et. al., "Programming-in-the-large versus programming-in-the-small." deremer:large-small
[2] Fowler, "Inversion of control containers and the dependency injection pattern." fowler:dependency
[3] The naming of these layers follows that of Evans, Domain-Driven Design. evans:domain-driven-design
[4] These entity classes are simplified to keep the example uncluttered with too much real-world detail. Nevertheless, transforming these classes into entities that could be persisted with Hibernate or the Java Persistence Architecture, for example, would require only a few modifications, such as adding a private Long id field and a no-arg constructor, placing scala.reflect.BeanProperty annotations on the fields, specifying appropriate mappings via annotations or a separate XML file, and so on.
[5] This is good, because each of these architectural layers should depend only on layers below them. | http://www.artima.com/pins1ed/modular-programming-using-objectsP.html | CC-MAIN-2015-14 | refinedweb | 3,532 | 52.49 |
Subject: Re: [OMPI devel] MPI Forum question?
From: Larry Baker (baker_at_[hidden])
Date: 2010-04-29 19:07:13
Ralph,
I don't know if there is any standard ordering of non-zero exit status
codes. If so, another option would be to return the the largest
(smallest) value, when that is the most serious exit status.
Larry Baker
US Geological Survey
650-329-5608
baker_at_[hidden]
On Apr 29, 2010, at 3:52 PM, Ralph Castain wrote:
> I ran into something this week that I think may require
> consideration by the MPI Forum. Specifically, Rolf found a problem
> in their MTT runs where the tests expect mpirun to return a non-zero
> exit status because one or more application processes did so, even
> though all application procs terminate normally.
>
> I jury-rigged a simple algo that has mpirun return the exit status
> of the lowest rank that returned non-zero in the case where the job
> terminated normally. We still return the exit code of the first
> process to abnormally terminate (i.e., the process that is first
> reported to the HNP - may not be the first process that aborted).
>
> However, it begs the question - what is the actual behavior supposed
> to be in the case where all procs terminate normally, but some may
> return (possibly different) non-zero codes?
>
> I asked a few MPI users, and got a different answer from every one
> of them. Only consistent response I got was that the MPI standard
> doesn't say what should happen (can someone confirm that?).
>
> Here is a sampling of the responses:
>
> 1. return the exit status of the lowest rank that returned non-zero
> (which I implemented for now to silence Rolf's MTT problem)
>
> 2. return the exit status of the highest rank that returned non-zero
>
> 3. printout a histogram of exit statuses
> - ranks 0-9: 0
> - ranks 10-21,110: 1
> - ranks 22-35,40-51: 2
> ...
>
> 4. printout ALL the exit statuses
>
> 5. ignore it - mpirun's exit code should only reflect OMPI
> internals. It is the app developer's responsibility to properly deal
> with non-zero exit conditions (e.g., by calling MPI_Abort).
>
> When I circled back around with these alternatives, I got the
> expected answer: everyone felt that all of them were good, and
> wanted a cmd line option to select the behavior for their job. They
> also noted that --xml should cause any of them to output in a
> defined xml format.
>
> As I told Rolf, I honestly don't care what we do in this case. All I
> ask for is a clearly defined behavior so I don't get yanked in
> multiple directions, constantly circling around from one solution to
> the next.
>
> So if the MPI standard doesn't specify this behavior, could someone
> involved in the Forum -please- get it to address this??
>
> In the interim, what do -we- think it should do?
>
> Thanks
> Ralph
>
>
> _______________________________________________
> devel mailing list
> devel_at_[hidden]
> | https://www.open-mpi.org/community/lists/devel/2010/04/7847.php | CC-MAIN-2016-22 | refinedweb | 494 | 61.97 |
Using Wing with Django
Wing. Django. To get started using Wing as your Python IDE, please refer to the tutorial in Wing's Help menu or read the Quickstart Guide.
Automated Configuration
The fastest way to get started working with a local installion of Django is to use Wing Pro's Django extensions. Skip ahead to the Manual Configuration section below if you have Wing Personal or if you need to work with Django running on a remote host.
Existing Django Project
To set up a Wing Pro project for an existing Django project, create a new project from the Project menu using project type Django. You will be prompted to enter the full path to the Python executable used for Django and the directory for your existing Django project, where your manage.py is located..
In some cases, the project creation process may prompt you to take additional steps manually:
- If django-admin.py could not be found from the specified Python Executable then you will be prompted to change this value in Project Properties, from the Project menu. Wing looks for django-admin.py in the same directory as the Python executable.
- If settings is a package in your project (instead of a settings.py file), you will need to manually enable template debugging in Django. This is done by setting debug to True under OPTIONS in the TEMPLATES section of your settings.py or settings package. If you are using Django 1.8 or earlier, instead set TEMPLATE_DEBUG to True.
New Django Project
If you are starting a new Django project at the same time as you are setting up your Wing project:
- Select Start Django Project from the Extensions sub-menu of the Project menu, fill in the requested values, and press OK.
- Wing will display a confirmation dialog, with a detailed list of actions taken. This may include a command that needs to be run manually to set up the superuser account for your new Django project. If so, copy and paste to run it in a command shell.
- Finally, press Create Wing Project to create and configure a new Wing project for the new Django project. This confirms the project configuration, as described above for existing Django projects..
Remote Development
Wing Pro can work with Django running on a remote host. See Remote Python Development for instructions on setting up remote access. Then use the following manual configuration instructions. You'll be able to use either of the described methods for debugging.
Manual Configuration
This section describes manual configuration of Wing projects for use with Django. Manual configuration is necessary when Django is running on a remote host or when using Wing Personal. If you are using Wing Pro with a local installation of Django, see Automated Configuration above instead.
Configuring the Project
To get started, create a new project from the Project menu using the Generic Python project type for a local installation and Connect to Remote Host via SSH for a remote installation of Django. Set the Python Executable to the full path of the Python used for Django. This path can be found by running Python outside of Wing and typing the following interactively:
import sys sys.executable
Then add your project files with Add Existing Directory in the Project menu.
You may also need to set the DJANGO_SITENAME and DJANGO_SETTINGS_MODULE environment variables and add the project directory and its parent directory to the Python Path under Environment tab in Project Properties, from the Project menu.
In Django 1.7 and later, set PYTHONSTARTUP_CODE in the Environment in Project Properties to import django; django.setup() so Django will be initialized in Wing's integrated Python Shell.
For unit testing in Wing Pro, set the Default Test Framework under the Testing tab of Project Properties to Django Tests and then add manage.py as a test file with Add Single File in the Testing menu.
Configuring the Debugger
There are two ways to debug Django code: Either (1) configure Django so it can be launched by Wing's debugger, or (2) cause Django to attach to Wing from the outside as code that you wish to debug is executed.
Launching from Wing
To start Django from Wing, right-click on manage.py in the Project tool and select Set as Main Entry Point. This causes execution and debugging to start here.
Next, configure the command line arguments sent to manage.py by opening the file in the editor or finding it in the Project tool and right-clicking to select File Properties. Then set the run arguments under the Debug/Execute tab to your desired launch arguments. For example:
runserver 8000
Other command line arguments can be added here as necessary for your application.
If you are using Wing Pro, enable Debug Child Processes under the Debug/Execute tab of Project Properties. This allows Django to load changes you make to code without restarting.
Child process debugging is not available in Wing Personal, so you instead need to add --noreload to the run arguments for manage.py:
runserver --noreload 8000
In this case, you will need to restart Django each time you make a change, or use the debugging method described below.
Launching Outside of Wing
Another method of debugging Django is to use wingdbstub.py to initiate debugging after Django is started from outside of Wing. This method can be used to debug a Django instance remotely or to enable debugging reloaded Django processes with Wing Personal.
This is done by placing a copy of wingdbstub.py into the top of the Django directory, where manage.py is located. This file can be found in the install directory listed in Wing's About box. Make sure that WINGHOME in your copy of wingdbstub.py is set to the full path of the install directory. On OS X, use the full path of Wing's .app folder (without the Contents/Resources part).
If you are developing on a remote host, instead use the copy of wingdbstub.py that is located in the remote agent's installation directory, on the remote host. This is preconfigured to work correctly with your remote project, as described in Remote Web Development.
Next, place the following code into files you wish to debug:
import wingdbstub
Then make sure that the Debugger > Listening > Accept Debug Connections preference is enabled in Wing and start Django. The Django process should connect to Wing and stop at any breakpoints reached after wingdbstub has been imported.
When code is changed, just save it and Django will restart. The debugger should reconnect to Wing once you request a page load in your browser that executes one of your import wingdbstub statements.
Debugging Django Templates
To enable debugging of Django templates, you need to:
- Enable template debug in Django. This is done by setting debug to True under OPTIONS in the TEMPLATES section of your settings.py or settings package. If you are using Django 1.8 or earlier, instead set TEMPLATE_DEBUG to True.
- Turn on Enable Django Template Debugging under the Options tab of Project Properties, from the Project menu. When you change this property, you will need to restart your Django debug process, if one is already running. system): Debugger > Exceptions > Report Exceptions preference is left set to its default value When Printed.
Template Debugging
If you enabled Django template debugging as described above, you should be able. | http://www.wingware.com/doc/howtos/django?gclid=CNHhlPOFsJICFQOB1AodX0RmRg | CC-MAIN-2019-35 | refinedweb | 1,236 | 64.51 |
#include <PDFACompliance.h> in PDF/A Manager:
Definition at line 51 of file PDFACompliance.h.
PDF/A Conformance Level (19005:1/2/3).
Level A conforming files must adhere to all of the requirements of ISO 19005. A file meeting this conformance level is said to be a 'conforming PDF/A -1a file.'
Level B conforming files shall adhere to all of the requirements of ISO 19005 except those of 6.3.8 and 6.8. A file meeting this conformance level is said to be a 'conforming PDF/A-1b file'. The Level B conformance requirements are intended to be those minimally necessary to ensure that the rendered visual appearance of a conforming file is preservable over the long term.
Definition at line 67 of file PDFACompliance.h.
Definition at line 80 of file PDFACompliance.h.
Destructor
Definition at line 421 of file PDFACompliance.h.
Frees the native memory of the object.
Serializes the converted PDF/A document to a file on disk.
Serializes the converted PDF/A document to a memory buffer.
Serializes the converted PDF/A document to a memory buffer.
Definition at line 422 of file PDFACompliance.h. | https://www.pdftron.com/api/PDFTronSDK/cpp/classpdftron_1_1_p_d_f_1_1_p_d_f_a_1_1_p_d_f_a_compliance.html | CC-MAIN-2020-45 | refinedweb | 192 | 52.05 |
In this project, we’ll build a simple parking sensor using a Raspberry Pi. It turns out that every morning I have to face this question: is the ONLY parking spot in front of my office already taken? Because when it actually is, I have to go around the block and use at least 10 more minutes to park and walk to the office.So I thought it would be cool to know whether the spot is free or not, before even trying to get there. At the end, the result was a nice widget that I could check from my iPod or mobile phone:
Materials
- Raspberry Pi Model B:
- USB WiFi Dongle
- Motion sensor by Parallax
- Three female to female wires
Wiring
The motion sensor is very easy to install as it only has three pins: GND, VCC (+5v) and OUT (digital signal “1” or “0”). If there’s movement around it, it will output a “1”, if there isn’t, a “0”. You can see the connection in the diagram below, the cables are plugged directly to the GPIO pins of the Raspberry Pi. If you need more information about GPIO pins you can visit this guide from makezine.com; it’s a good source to become familiar with the Raspberry Pi pins.
Setup your Ubidots account and variables
If you’re new to Ubidots, create an account here.
- Navigate to the “Sources” tab and add a new source.
- Select Raspberry Pi as your new data source and fill the form.
- Now click on the new source “My Raspberry Pi”
- Add a new variable called “free or busy” and don’t forget to complete the fields name and unit.
- Take note of your variable’s id:
- Take note of your API Key found in “My Profile –> API Key“
Coding your Raspberry Pi
You should’ve already configured your Raspberry Pi, having Internet access from it. If not, follow this guide, or check this blog post about setting up WiFi.
When ready, access your Raspberry Pi through a terminal (LxTerminal if you’re accessing your Pi directly through it GUI), navigate to a folder where you want to store this project and create a new file called “presence.py”
$ sudo nano presence.py
Now paste the following code:
import RPi.GPIO as GPIO ##GPIO library from ubidots import ApiClient ##Ubidots Library import time ##time library for delays GPIO.setmode(GPIO.BCM) ##set up BCM as numbering system for inputs GPIO.setup(7,GPIO.IN) ##Declaring GPIO7 as input for the sensor try: api=ApiClient("75617caf2933588b7fd0da531155d16035138535") ##put your own apikey people= api.get_variable("53b9f8ff76254274effbbace")##put your own variable's id except: print "cant connect" ##if this happens check your internet conection while(1): presence=GPIO.input(7) ## saving the value of the sensor if(presence==0):##if presence is zero that means the other car is still there 🙁 people.save_value({'value':presence}) ##sending value to ubidots time.sleep(1)##check every 5 seconds if the other car moves print "cero" if(presence): people.save_value({'value':presence}) ##the other car left so is empty now 🙂 time.sleep(1) print "uno" GPIO.cleanup() ##reset the status of the GPIO pins
Run your program:
$ sudo python presence.py
Creating an indicator in the Ubidots dashboard
Now that we’re getting the live data from the device, we need to create a custom widget that tells us whether the parking spot is taken or not. Click on the dashboard tab, then add a new widget:
Choose “Indicator” widget and follow the steps:
Great! now you should see a live widget indicating the state of the parking spot. Btw you can embed this widget in any web or mobile app:
That’s all for this project! We learned how to plug a motion sensor to the Ubidots cloud using a Raspberry Pi and display its data in a live widget. The project could be improved by using a presence sensor and not exactly a motion sensor (which goes back to “0” after the movement is gone). It can also be extended by setting up SMS or Email alerts, which can be created in the “Events” tab in your Ubidots account.
Have a question? feel free to comment below or leave a ticket in our support page.
Here’s another cool project using Raspberry Pi and a motion sensor:
Still don’t have a Ubidots account? click here to get started today. | https://ubidots.com/blog/how-to-build-a-parking-sensor-to-solve-the-pain-of-finding-a-free-spot/ | CC-MAIN-2019-39 | refinedweb | 736 | 70.63 |
Sun 6 Jan 2008
Django Tip: Complex Forms
Posted at 13:39 +1100 (last edited: 23 Jan 2009, 15:17)
On the Django mailing list, we periodically see requests for help by somebody trying to create a semi-complex form of some description. Often, getting a second perspective is a good choice because the original poster was overlooking a possibly easier alternate approach.
Today, I want to fill in one of the gaps. Something that is really easy once you know the machinery and possibly not so obvious until you sweat it out once: putting multiple repetitive sections into a single form.
[Updated (January, 2009): Multiple people have written to me over the past year, pointing out a bug in the code examples here and a couple of people spotted another typo in the downloadable tarball. I've now fixed both of those occurrences and updated the code to run with Django 1.0.]
The Problem
Let's consider a fairly typical example. You are presenting a selection of multiple choice questions. A Quiz model contains a number of Questions, with each question having a number of Answers associated with it, one of which is the correct answer. I knocked together the following models:
class Answer(models.Model): statement = models.CharField(max_length=200) class Question(models.Model): problem = models.CharField(max_length=200) answers = models.ManyToManyField(Answer) correct_answer = models.ForeignKey(Answer, related_name="correct") class Quiz(models.Model): name = models.CharField(max_length=50) questions = models.ManyToManyField(Question)
All of this code is available for download. The admin user is admin and password is abc123. As you'll see in the download, I've simplified things slightly for conciseness here; leaving out the Admin classes and the like..
Given a quiz id, I want to display the associated questions and their answers in a single HTML form.
Designing The Forms
I'll be using Django's newforms package here, since oldforms is... well... old (and deprecated for good reasons. Don't use it in new code).
[Update (January, 2009): Progress has occurred during the last 12 months and Django 1.0 only contains a forms module, not newforms or oldforms. Everywhere you see newforms in what follows, mentally substitute forms. The downloadable tarball imports the new (Django 1.0) names for everything, so if there's any doubt, have a look at that.]
This is the step where many people get tripped up because it looks like displaying many questions, each with many answers doesn't fit naturally into the layout of the form classes. The trick is to remember that a newforms.Form class corresponds to an HTML form fragment — not the entire HTML form. This is why you need to supply the outer <form>...</form> tags yourself, for example. You can happily use multiple form classes (at the Python level) to produce one form at the HTML level.
Let's build a form class that represents a single question. Then our page will be a collection of those form classes. Well, a question display contains some form data — choices for the answer possibilities — as well as some static data — the question statement itself. We have to remember the question statement, since it's not really "form" information, as it's only displayed, not edited by the end-user.
The form class might look something like this::
from django import newforms as forms class QuestionForm(forms.Form): answers = forms.ChoiceField(widget=forms.RadioSelect()) def __init__(self, question, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) self.problem = question.problem answers = question.answers.order_by('statement') self.fields['answers'].choices = [(i, a.statement) for i, a in enumerate(answers)] # We need to work out the position of the correct answer in the # sorted list of all possible answers. for pos, answer in enumerate(answers): if answer.id == question.correct_answer_id: self.correct = pos break def is_correct(self): """ Determines if the given answer is correct (for a bound form). """ if not self.is_valid(): return False return self.cleaned_data['answers'] == str(self.correct)
A couple of things are worth noting here. Firstly, I made sure that the answers were sorted in some repeatable fashion so that each time I create the form (initial display and later when processing the user's input), the options are in the same order. I also had to make sure the correct answer attribute corresponded to the position of the correct answer in the sorted list. There were a few ways to do this; the way I chose above avoids any extra database queries, relying on the fact that the foreign key attribute correct_answer on the Question model creates a hidden attribute correct_answer_id, which is the primary key value of the related entry. So I can get away with comparing primary key values to check for the correct answer.
Finally, I added a convenience method, is_correct(), to the form class to make it easier to check for correct answers later on. The correct answer to a question has nothing to do with the form's validity (you can successfully submit a form containing an incorrect answer), so this isn't part of cleaning the form's data, but since the user's submission and the correct answer are both available as part of this class, it's worthwhile to check it here. Something to note is that choice values are always strings in Django form classes (since the submission from the HTML form is always a string), so I have to remember to convert my numerical index value (self.correct) to a string before comparing with the form submission. Forgetting something like that can add a few minutes to the debugging process, although after you do it once or twice, you tend to remember forever.
So now we can create a form for a single question and display it in a template. The remaining problem is how to handle multiple instances of this class on the same page, without the HTML input elements clashing (by using the same names). The secret here is the prefix attribute accepted by the Form class. The prefix is attached to the front of any elements produced by that form instance. So we can display multiple questions by giving each one a different prefix.
Since I'm going to need to create these multiple form classes lots of times, I decided to make a convenience method for it. Given a quiz identifier, I want to create a form instance for each question in that quiz and, if the form has any data associated with it, plug in the submitted data. This leads to the following:
from django.http import Http404 def create_quiz_forms(quiz_id, data=None): questions = Question.objects.filter(quiz__pk=quiz_id).order_by('id') form_list = [] for pos, question in enumerate(questions): form_list.append(QuestionForm(question, data, prefix=pos)) if not form_list: # No questions found, so the quiz_id must have been bad. raise Http404('Invalid quiz id.') return form_list
This function creates one form for each question and returns the list of form instances, as required. The data parameter to the function is used when a form submission is made (it will be the request.POST dictionary) Initialising a form with data=None creates an unbound form, which is why I've chosen that default.
The Views and Templates
We have a function to create forms for a given quiz. Now let's pull it together in a view.
from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse def quiz_form(request, quiz_id): if request.method == 'POST': form_list = create_quiz_forms(quiz_id, request.POST) answers = [] for form in form_list: if not form.is_valid(): break answers.append(str(int(form.is_correct()))) else: # All forms are valid. Go to the results page. return HttpResponseRedirect('%s?a=%s' % (reverse('result-display', args=[quiz_id]), ''.join(answers))) else: form_list = create_quiz_forms(quiz_id) return render_to_response('quiz.html', {'forms': form_list})
This should all be fairly straightforward if you've been following along so far. If the user submitted data (a POST), we create the forms using the submitted data, so that we can see if the form is invalid (mostly, this catches missing fields in our case). Otherwise, (a non-POST), we send back an empty form for the given quiz id.
If data was submitted, we check the forms for validity (all of them; remembering that we have more than just a single form instance here) and, if they all pass, build up the list of correct/incorrect answers. I've chosen a fairly simple scheme here for representing the answers. The questions are in a pre-determined order, so I pass a string of '1' and '0' characters to the results page: '1' meaning the user got the question correct.
Attentive readers will notice that I'm using urlresolvers.reverse() in this view to avoid hard-coding the URL. For a simple example, this is slight over-kill, but in a more complicated setup I've found it worthwhile to take this extra effort as it sometimes takes a couple of attempts to get the URLs spelt exactly as I wish, so only have to change one place later on is an advantage.
Display the result of this view in a template is done with something like this:
<form action="." method="post"> <ol> {% for form in forms %} <li> <p>{{ form.problem }}</p> {{ form.as_p }} </li> {% endfor %} </ol> <input type="submit"> </form>
Of course, in practice, you'll probably do a lot more here with CSS classes and perhaps a custom display method instead of as_p(), but that's fairly standard stuff and would take us too far afield for our current purposes.
I haven't given the results display view here, but you can find it in the source code, along with the URL definitions. You can fire up the development server (./manage.py runserver) and point your browser to to see the example in action.
Topics: software/django/tips | http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/ | crawl-002 | refinedweb | 1,649 | 56.76 |
Frequently Asked Questions (FAQ)¶
Driver¶
I run
clang -cc1 ... and get weird errors about missing headers¶
Given this source file:
#include <stdio.h> int main() { printf("Hello world\n"); }
If you run:
$ clang -cc1 hello.c hello.c:1:10: fatal error: 'stdio.h' file not found #include <stdio.h> ^ 1 error generated.
clang -cc1 is the frontend,
clang is the driver. The driver invokes the frontend with options appropriate
for your system. To see these options, run:
$ clang -### -c hello.c
Some clang command line options are driver-only options, some are frontend-only
options. Frontend-only options are intended to be used only by clang developers.
Users should not run
clang -cc1 directly, because
-cc1 options are not
guaranteed to be stable.
If you want to use a frontend-only option (“a
-cc1 option”), for example
-ast-dump, then you need to take the
clang -cc1 line generated by the
driver and add the option you need. Alternatively, you can run
clang -Xclang <option> ... to force the driver pass
<option> to
clang -cc1.
I get errors about some headers being missing (
stddef.h,
stdarg.h)¶
Some header files (
stddef.h,
stdarg.h, and others) are shipped with
Clang — these are called builtin includes. Clang searches for them in a
directory relative to the location of the
clang binary. If you moved the
clang binary, you need to move the builtin headers, too.
More information can be found in the Builtin includes section. | https://clang.llvm.org/docs/FAQ.html | CC-MAIN-2018-34 | refinedweb | 244 | 77.53 |
New XML Features of the Microsoft Office Word 2003 Object Model
Summary: Use the new XML features of the Microsoft Office Word 2003 object model to manipulate files with code. Among other possibilities, the XML-based capabilities of Word allow you to harness the power of XSLT to transform document content into whatever format you need. You can apply these conversions to a single part of a document to create a mailing label from plain text, or to the document as a whole to convert an e-mail into a sales order. (14 printed pages)
Peter Vogel, PH&V Information Services
October 2003
Applies to: Microsoft Office Word 2003
Contents
Working with XML
Working with the XML representation of a document in Microsoft Office Word 2003 includes two different scenarios:
- You can load an XML schema and create documents by adding elements and attributes from the schema. As an example of this scenario, you might load the DocBook schema (an open specification used for creating documents about hardware and software). Figure 1 shows Word 2003 with the DocBook schema loaded.
- You can work with Word 2003 as you always have. You can also choose to have your code work with your Word 2003 document as an XML document, written in the WordML (the native Word XML format) dialect.
In both scenarios, you can access the XML representation of the document to provide new functionality.
Figure 1. Creating an XML document in Word 2003
To work with an XML schema, the first steps are to load the schema and associate it with a document. You can add schemas through code from the Application object or the Document object.
Before adding a schema to the document, make sure that the version of Word that you are working with supports adding schemas. The Microsoft Office Word 2003 core program or Microsoft Office Word 2003 in Microsoft Office Professional Edition 2003 support adding custom schemas. If the ArbitraryXMLSupportAvailable property of the Application object is set to True, Word 2003 supports building documents with XML vocabularies other than WordML.
Adding Schemas with the Application Object
You can add schemas to the Application object by using the Add method of the XMLNamespaces collection. Once added, these schemas are available to the user through the XML task pane. The following code adds the Docbook schema to the Namespaces collection, specifies the namespace to use with the schema if the schema does not define one (dcb), and specifies an alias for the schema that Word 2003 uses in its user interface (UI), in this case, the name Docbook:
Once added, the schema is represented by an XMLNamespace object in the XMLNamespaces collection. Each XMLNamespace can have a collection of XSLT transformations associated with it. You can add new transformations to the XMLNamespace using the Add method of the XSLTransforms collection, creating an XMLTransform object. You must pass the path to the file containing the XSLT transformation to the Add method and, optionally, pass an alias that Word 2003 can use in its UI. This example adds the toc.xsl transformation to the collection, which appear in the UI as Generate TOC:
Using a Schema with a Document
Once you add a schema to the XMLNamespaces collection for the Application object, you can associate the schema with a document by using the AttachToDocument method of the XMLNamespace object. This code associates the second schema in the XMLNamespaces collection with the current document:
The XMLSchemaReferences collection of the Document object allows you to add schemas directly to the document, using the Add method of the XMLSchemaReferences collection. This code adds the DocBook schema to the document's schema references by referring to the NamespaceURI established when you added the schema to the XMLNamespaces collection for the Application object:
Alternatively, you can bypass the XMLNamespaces collection and add the schema directly to the document. This also adds the schema to the XMLNamespaces collection for the Application object:
The first parameter to the Add method for the XMLSchemaReference object is the namespace to use with the schema (in this example, dcb). The second parameter provides an alias for the schema used in the UI. The third parameter is the path to the schema to load.
Accessing the Document
There are two strategies that you can use for accessing the XML representation of document in Word 2003:
- Extract XML text
- Access XML nodes that make up the XML Document Object Model
Extracting Text
A Word 2003 document always consists of WordML tags. When you are working with a schema in Word 2003, the tags of the schema are intermixed with the WordML tags. The WordML tags control how the document is displayed in Word 2003.
You can extract the XML text of your document through the XML property of Range and Selection objects. The XML property always returns a complete WordML document, including the WordML root element (wordDocument). For example, this code pulls the XML from the second paragraph of the active document:
As an example, this sample text contains just two short paragraphs:
Extracting the WordML representation of the first paragraph returns a lot of text—over 3,000 characters. The document returned by the XML property is large because it not only includes the text of the selected range but also all of the context information that affects text: definitions of the styles in the document, information about the document's fonts, the document's page size and margins, and so on.
Within the document returned by the XML property, the paragraphs that make up the content are inside the WordML body element. The body element document contains the document's content enclosed in <t> tags (text), <r> tags (runs of texts), and <p> tags (paragraphs). The <sectPr> tag that also appears in the body holds elements that define the sections of the document (such as the page size or margin).
If you create a document based on some XML schema, the tags that make up that schema are intermixed with the WordML tags that allow Word 2003 to manipulate the text. As an example, this is the start of a DocBook document:
Retrieving the XML property of this document returns a document with this in its body tags:
To keep the WordML and DocBook tags separate, the DocBook tags are flagged with a prefix of ns0. This prefix ties the tags back to a DocBook namespace defined on the wordDocument element:
To retrieve are the elements for the schema that you're working with, the XML property accepts a parameter (called DataOnly) that allows you to remove WordML tags. When DataOnly is set to True, this code returns only the non-WordML XML tags in the document:
For the sample DocBook document, the XML returned looks like this:
Extracting XML Nodes
In documents created with a schema, you can also access the document as a series of XML nodes, using the XMLNodes property of the Range, Selection, and Document objects. The XMLNodes collection contains XMLNode objects, whose methods and properties look very familiar if you work with the DOM parser in the MSXML toolset. This example concentrates on the features of the XMLNode object that are added to the Word 2003 object model, although some of the methods and properties common to MSXML are also useful to the Word 2003 developer.
The sample DocBook document shown previously has two nodes in it: one for the book element and one for the title element. This code retrieves the title element:
Properties of the node object include the content of the node (Text), the name of the node (BaseName), and the node's namespace (NamespaceURI).
On most occasions, you process only some of the nodes in a document. The SelectNodes method of the Document object lets you extract the nodes that you want, using an XPath statement to specify the nodes. When searching for an element with a namespace, you must include the namespace's prefix in the tag name. The second parameter of the SelectNodes method allows you to define the namespace, using the same syntax as in an XML document. This example finds all the TITLE elements in the document in the DocBook namespace, which has ns0 as its prefix, no matter how deeply nested:
The XMLNodes collection first member is at position 1, so this is the code to use to process all members using a For. . .Next loop:
To speed up searching, you can set the third parameter of the SelectNodes method to False, causing the search to skip any text nodes (the text content between an XML element's open and close tag). If you're not searching the content of your nodes and your document contains a lot of text (typical for a Word 2003 document), setting this parameter can speed up your search significantly.
For any particular namespace that you add to the document, you can retrieve the namespace through the NamespaceURI property of the XMSchemaReference object. Rewriting the previous code to use the NamespaceURI property gives this code:
The new XML-based technology of Word 2003 merges smoothly with the Word objects from previous versions of Word. For example, once you retrieve a node, you can work with the Word objects that the node represents by retrieving the Range property of the XMLNode object:
You can also get some feedback on where a node fits within the larger Word 2003 document. The Level property of a node indicates whether a node is, for example, displayable text
(Level = wdXMLNodeLevelInline) or part of a paragraph
(Level = wdXMLNodeLevelParagraph). The Level property also indicates whether the node is part of a table row or cell.
Changing the Document
You can update the document using either the InsertXML method or the XMLNodes collection. Both allow manipulation of the document's content to create new material.
Updating Text
The InsertXML method of the Range and Selection objects allows you to update a document by inserting arbitrary strings of XML text. When updating a WordML document that isn't using a schema, you must insert a complete WordML document. Fortunately, a basic WordML document consists of just five tags (wordDocument, body, p, r, t) and the WordML namespace. For example, this document contains a single string in a minimal WordML document:
As an example, in the following text, let's say the word jumps is selected:
This code replaces the current selection (jumps) with the word leaps:
Updating Nodes
For a document using a schema, the XML property of the Range property of the XMLNode object lets you add new XML. When new material is inserted into your document, it needs to be a combination of WordML tags (so that text is displayed in Word) and the schema's tags. However, to make the code easier to read, the next examples omit the WordML tags.
The sample DocBook document has a title of "Office XML." One change to this DocBook document could insert a subtitle tag to go with the title tag and give this structure:
A prefix is required when inserting the XML so that the tag is tied to the right schema. To ensure that the inserted XML is well formed, the prefix (and its namespace) must be defined within the XML being inserted. This code inserts the subtitle tag into the document:
Inserting XML into a node replaces any existing content for that node. Using the previous code to insert new content into the title node replaces the existing content (as shown in Figure 2):
Figure 2. Replacing the title element content with a subtitle element
If your goal is to add to the existing content (rather than replace it), you must add a child node to the parent node. You add nodes using the Add method of the node's ChildNodes collection, passing the name of the node and the namespace to which the new node belongs (Word 2003 takes care of assigning the appropriate prefix to the node). The following example adds a child node, called subtitle, as part of the DocBook namespace. Once the node is created, the code assigns the node's Text property the string "XML Objects":
The resulting code contains this set of tags (see Figure 3):
Figure 3. Adding a subtitle child element to a title element
Running the code again adds another subtitle following the subtitle just added.
You're not restricted to adding child nodes. Using the Add method of the XMLNodes collection lets you add a node anywhere in the existing document. Where the node is added depends on what object you use. For example, if you use the ActiveDocument object, as in this example, the new node is inserted at the cursor:
The XMLNodes collection is also available from the Range property of any node. Used from an existing node in the document, the new node is added so that it encloses any already existing child nodes. For example, this document nests a paragraph text inside a chapter element:
To add a paragraph node to the chapter (and place the paragraph text inside the newly created paragraph), you could use this code with the chapter's Range property:
The result is this XML:
Transforming Text
The real power in the InsertXML method is in the method's second parameter, which accepts the path name to a file containing XSLT. Passed the pathname, the InsertXML method processes the XML in the first parameter using the XSLT code in the file and inserts the results into the document.
For example, this DocBook document has two chapter elements and an empty table of contents element called toc (for these examples, the relevant WordML tags are included to ensure that the text is displayed by Word 2003 after the text is inserted):
The following XSLT finds all chapter title tags and generates a DocBook table of contents consisting of TOCENTRY and TITLE tags:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet <w:wordDocument> <w:body> <xsl:for-each <ns0:tocchap><ns0:tocentry> <w:p> <w:r> <w:t> <xsl:value-of </w:t> </w:r> </w:p> </ns0:tocentry></ns0:tocchap> </xsl:for-each> </w:body> </w:wordDocument> </xsl:template> </xsl:stylesheet>
In all updates done through the InsertXML method, you must insert a complete wordDocument document, so the stylesheet also adds wordDocument and BODY elements. The <WordML>, <p>, <r>, and <t> tags are required so that the text in the TOCENTRY elements is displayed in Word 2003.
The next bit of code retrieves a reference to the TOC node in the document. The code then calls the InsertXML method for that node, passing the XML text for the document and the path to the file containing the XSLT:
The result is a DocBook document with a table of contents, built from the chapter elements in the document.
If you intend to transform the whole document, rather than the content of a selected node, you can call the TransformDocument method of the Document object. The TransformDocument method accepts two parameters:
- The path to the file with the XSLT code
- A Boolean indicating whether the whole document is to be processed or just the non-WordML tags. Setting this parameter to True causes the WordML tags to be ignored.
Rather than hard coding the path name in the call to these methods, you can use an XSLTransform object from an XSLTransforms collection of a specified namespace. The Location property of an XSLTransform object provides the path name to the file containing the XSLT. If you rewrite the earlier code to use the Location property you would have this code:
Transforming existing document content is only one of the uses for applying XSLT. You can just as easily use XSLT as part of reading in an XML document to convert the document into WordML format (or any other XML format, for that matter). For example, Microsoft Office Access 2003 supports exporting its tables in an XML format. A simple XSLT transform allows files in that format to be converted into WordML for processing as a Word 2003 document—or into DocBook format if that were the ultimate format for the information.
Responding to Changes
Word 2003 also fires events as XML operations are performed. The Document object fires two new XML-related events:
- XMLAfterInsert: Fires when a new node is added. The event routine is passed a reference to the new node.
- XMLBeforeDelete: Fires when a node is deleted. The event routine is passed a reference to a Range object that includes the parts of the document to be deleted and a reference to the node to be deleted.
Both events are also passed a Boolean variable that is set to True if the node is added or deleted during an undo or redo operation.
The Word 2003 Application object fires two new XML-related events:
- XMLValidationError: Fires whenever a validation error occurs in the document. A single parameter is passed to the event: a reference to the node with the error.
- XMLSelectionChange: Fires whenever you select a new node. This event routine is passed four parameters: the WordSelection object for the newly selected material, references to both the node that lost focus and the node that gained focus, and a reason code.
To use these events, you'll need to set up global variables and assign them to the appropriate objects. This code does that as part of a class module's Initialize event:
In some other event, such as the AutoOpen routine in Word 2003, you must create the class module. Once complete, the code in the class module can catch the XML events.
Selection Changed
You may change the currently selected node for a variety of reasons: moving the cursor, inserting a new node, and deleting a node. Not all of those activities generate a selection change event. For example, you may have your cursor between the end element of one child element and the start element of another child element. In that scenario, the currently selected node is the parent node of the two children. If you click between two other children within the same parent, the selected node doesn't change and no selection change event fires.
When a selection change event does fire, the reason code passed as the last parameter to the XMLSelectionChange event indicates why the selection has changed. The reason code can have three values:
- wdXMLSelectionChangeReasonMove: The selection changed because you moved the cursor in the document to select a different node. When, after the document is first opened, you first select a node, the OldXMLNode property is Nothing.
- wdXMLSelectionChangeReasonDelete: The selection changed because a node was deleted. OldXMLNode is always Nothing. Not all deletions trigger a selection change. For example, if the currently selected node is the parent node, deleting a child does not generate a selection change event. Use the XMLBeforeDelete event to catch all deletions.
- wdXMLSelectionChangeReasonInsert: The selection changed because a new node was inserted. The new node is passed in NewXMLNode. You can also use the XMLAfterInsert event to catch node insertions.
As an example, this code, when a TOC element is inserted, runs the code that creates the table of contents:
Validating Documents
One of the benefits of working with XML schemas is the ability to validate any particular document against the schema defining the tags used in the document. When working with a schema, as users insert new tags, Word 2003 flags violations of the schema in two places: the XML task pane and in the document itself.
The generated messages are generic XML error messages (a typical message when an element is first inserted is "Some required content is missing"). These messages give the user no real guidance as to what, exactly, should be done to eliminate the validation error.
Word 2003 lets you customize the messages that are generated for any node in the document. For any node, you can call the node's SetValidationError method, passing a ValidationStatus constant, a message to display on validation errors, and a flag indicating whether the message should be cleared automatically.
In this example, the code adds a new message when a validation error occurs on a TOC element. The message provides more information about what is required in a DocBook table of contents entry:
You can control when validation takes place. The default is for Word 2003 to validate on every user action that changes the document text against the schemas currently in use. So, the first step in managing validation is to turn off Word's automatic validation:
You can then either validate the whole document by calling the Validate method of the XMLSchemaReferences or validate just a single node by calling its Validate method. This code validates only the second node and its children:
For the Validate method to work, you must set the XMLSchemaReferences AutomaticValidation property back to True.
After the Validate method is called, you can check the ValidateStatus method of any node to determine whether an error was found. You can also process the nodes in the document's XMLSchemaViolations collection to find all the nodes in error. This code displays the error message associated with each node that has a validation error:
Saving Your Document
When you are finished with the document, you will want to save it. If you can save the document without completing it, you may want to set the AllowSaveAsXMLWithoutValidation property of the schema that the document is using. This prevents you from getting error messages when the only problem is that all the required portions of the document aren't yet filled in.
The Save method of the Document object still saves the complete Word 2003 document. Setting the XMLSaveDataOnly property of the Document object to True causes Word 2003 to save only the tags associated with the schema into the document's file. Setting the XMLUseXSLTWhenSaving of the Document object to True causes an XSLT transform to be applied to the document and the output of the transform to be saved. If you set XMLUseXSLTWhenSaving to True, you must also set the XMLSaveThroughXSLT property to the path name of the file containing the XSLT code. Finally, you must set the document format to XML.
This code, for example, saves only the added schema-related tags in the document using the ConvertToFOMM.XSL stylesheet:
The document should be valid against its schema before you save it with an XSLT transform. Although you can set the AllowSaveAsXMLWithoutValidation property of the SchemaReferences collection to True, the results of processing an XSLT stylesheet against an invalid document are unpredictable.
The XML data-only document that is created with this code does not include all the information that the original Word 2003 document did. All the WordML tags are lost and, typically, the data in the new document is a subset of the data in the original Word 2003 document. Because of this, you also want to save the original Word 2003 document to hang on to all of the information in it. The easiest way to do that is to set the XSMLSaveDataOnly and UseXSLTWhenSaving properties to False and do another save:
Conclusion
Word 2003 has acquired a rich set of functionality by integrating XML into its object model. This integration provides the tools you need to create applications that take advantage of XML to support document creation. By extending the base functionality of Word 2003 with customized code, you can provide new levels of support to users.
About the Author
Peter Vogel is a consultant on Office and .NET development. He is the author of Visual Basic Object and Component Handbook (Prentice Hall PTR, 2000, ISBN: 0-13023-0731) and the editor of the Smart Access newsletter. | http://msdn.microsoft.com/en-us/library/aa537148(v=office.11).aspx | CC-MAIN-2014-15 | refinedweb | 3,949 | 54.86 |
Before wrapping up this chapter, I want to illustrate how QML and JavaScript can be used for developing a slightly more complex application than the ones shown up to this point. This will also give me the opportunity to explain your application's project structure, something that I skimmed over in Chapter 1 (if you want to give the application a try right away, you can download it from BlackBerry World). SCalc is a simple calculator app written entirely in JavaScript and QML (see Figure 2-4). The application's UI is built in QML and the application logic is handled in JavaScript using Matthew Crumley's JavaScript expression engine (). The engine is packaged as a single JavaScript file that I have dropped in the project's assets folder (parser.js, located at the same level as main.qml).
Figure 2-4. SCalc
As illustrated in Figure 2-4, a root Container contains a TextArea and six child containers, which in turn hold Button controls. Finally, the parent of the root Container is a Page control that represents the UI screen. Another way of understanding the control hierarchy is by looking at the outline view in the QML perspective in Momentics (see Figure 2-5).
Figure 2-5. Outline view (four child Containers below root shown)
You will notice that the containers have a layout property. A layout is an object that controls the way UI elements are displayed on the screen. In our case, we are using a StackLayout, which stacks controls horizontally or vertically. The root container does not define a layout and therefore Cascades will assign it a default StackLayout that stacks controls vertically. (In the child containers, the layout orientation has been set to horizontal, thus displaying the buttons in a row. I will tell you more about layout objects in Chapter 4.) Listing 2-17 is an outline of main.qml.
Listing 2-17. main.qml
import bb.cascades 1.2
import "parser.js" as JSParser Page {
id: calculatorView
// root containter goes here
}
The second import statement imports the JavaScript expression engine as a module and
assigns it to the JSParser identifier (because the file is located in the same folder as main.qml, you don't need to provide a path to the file). Now that the library has been imported, you will be able to use it in your QML document (the expression engine provides a Parser object that you can call using JSParser.Parser.evaluate(expression, "")).
As mentioned previously, the root container contains a TextArea and six child Containers (see Listing 2-18).
Listing 2-18. root Container
Container {
id: root
// padding properties omitted. layout: StackLayout {
orientation: LayoutOrientation.TopToBottom
// background properties and attached object omitted. TextArea {
bottomMargin: 40 id: display
hintText: "Enter expression" textStyle {
base: SystemDefaults.TextStyles.BigText color: Color.DarkBlue
layoutProperties: StackLayoutProperties { spaceQuota: 2
Container{ // 1st row of Buttons, see Figure 2-4 Button{id: lefpar ...}
Button{id: rightpar ...} Button{id: leftArrow ...} Button{id: clear ...}
... // 5 more Containers
The application logic is implemented by handling the clicked signal emitted by the Buttons and by updating the TextView with the current expression. For example, Listing 2-19 shows the implementation for the clicked signal when Button “7” is touched by the user.
Listing 2-19. Button “7”
Button {
id: seven text: "7" onClicked: {
display.text = display.text + 7;
Finally, the JavaScript expression library's Parser.evaluate() method is called when the user touches the “=” button (the TextView is also updated with the result of the evaluation).
Listing 2-20. Button “=”
id: equal text: "=" onClicked: {
display.text = JSParser.Parser.evaluate(display.text, "");
The current input handling logic is quite crude and you can easily enter invalid expressions. As an exercise, you can try to make it more robust.
Figure 2-6 illustrates SCalc's project structure in the Momentics Project Explorer view.
Figure 2-6. Project Explorer
You will find the same structure in all of your applications and you should therefore take some time to get familiar with it. Here is a quick overview of the most important project elements:
n src: You will find the C++ source code of your project in this folder.
n assets: This folder contains your QML documents. You can also create subfolders and include additional assets such as images and sound files. You will generally load at runtime the assets located in this folder.
n x86, arm: Folders used for the build results of your application for the simulator and device respectively. The folders include subfolders, depending on the build type (debug or release). For example, a debug build for the simulator will be located under x86o-g (and the corresponding Device folder is armo.le-v7-g).
n SCalc.pro: This is your project file and includes project settings. You can add dependencies such as libraries in this file (you will see how this works in Chapter 3).
n bar-descriptor.xml: This file defines important configuration settings for your application. In particular, it also defines your application's permissions. You will have to update this file for certain projects in following chapters. The easiest way to proceed is to work with the General and Permissions tabs when the file is open in Momentics (see Figure 2-7).
Figure 2-7. bar-descriptor.xml view
n icon.png: Your application's icon.
This chapter dissected the core elements of the QML language. You discovered how the different elements of QML fit together by designing your own custom control. You also saw that QML, despite its simplicity, is an extremely powerful programming environment. Most importantly, this chapter gave you some insight on how Cascades uses those same QML constructs, and hopefully unveiled some of the magic involved in Cascades programming.
JavaScript is the glue giving you the tools for adding some programmatic logic to your controls. The environment provided by QML runtime is ECMAScript compliant. This means that at this point you can build full-fledged Cascades applications using QML and JavaScript. | http://academlib.com/22399/computer_science/scalc_small_calculator | CC-MAIN-2017-04 | refinedweb | 996 | 55.74 |
Here.’?
internal class GcIsWeird
{
~GcIsWeird()
{
Console.WriteLine("Finalizing instance.");
}
public int data = 42;
public void DoSomething()
{
Console.WriteLine("Doing something. The answer is ... " + data);
// Some other code...
Console.WriteLine("Finished doing something.");
}
}
The answer is: “It depends”. In debug builds this will never happen (as far as I can tell), but in release builds this is possible. To simplify this discussion, let’s consider the following static method:
static void SomeWeirdAndVeryLongRunningStaticMethod()
{
var heavyWeightInstance = new int[42_000_000];
// The very last reference to 'heavyWeightInstance'
Console.WriteLine(heavyWeightInstance.Length);
for (int i = 0; i < 10_000; i++)
{
// Doing some useful stuff.
Thread.Sleep(42);
}
}
The local variable ‘heavyWeightInstance’ is used only in first two lines and theoretically can be collected by the GC after that. One might set the variable to null explicitly to release the reference, but this is not needed. The CLR has an optimization that allows collection of instances once they are no longer being used. The JIT compiler emits a special table, called ‘Pointer Table’ or (GCInfo, see gcinfo.cpp at coreclr repo) that gives the GC enough information to decide when a variable is reachable and when is not.
An instance method is just a static method with an ‘instance’ pointer passed via the first argument. This means that all reachability optimizations are valid for both instance and static methods.
To prove that this is indeed the case, we can run the following program and look at the output.
using System;
internal class GcIsWeird
{
~GcIsWeird()
{
Console.WriteLine("Finalizing instance.");
}
public int data = 42;
public void DoSomething()
{
Console.WriteLine("Doing something. The answer is ... " + data);
CheckReachability(this);
Console.WriteLine("Finished doing something.");
}
static void CheckReachability(object d)
{
var weakRef = new WeakReference(d);
Console.WriteLine("Calling GC.Collect...");
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
string message = weakRef.IsAlive ? "alive" : "dead";
Console.WriteLine("Object is " + message);
}
}
class Program
{
static void Main(string[] args)
{
new GcIsWeird().DoSomething();
}
}
As we would expect, running this program in release mode and with no debugger attached will lead to the following output:
Doing something. The answer is … 42
Calling GC.Collect…
Finalizing instance.
Object is dead
Finished doing something.
The output shows that the object was collected during the execution of the instance method. Now let’s look at how this happens.
There are a few options for doing that. First, you can use WinDbg and run !GCInfo command for a given method table (here is a good blog post for you, Figure out variable lifetime using SOS). Second, you can build CoreClr and run your application with JIT trace enabled.
The first option seemed simpler, however I’ve decided in this case to use the second one. And, believe me, the second option is not as complicated as you would think. You just need to follow the instructions – Viewing JIT Dumps and do the following:
- Build CoreCLR Repo (don’t forget to install all the required stuff, like VC++, CMake and Python).
- Install dotnet cli.
- Create a dotnet core app.
- Build and publish dotnet core app.
- Copy freshly built coreclr binaries into the published folder with your app.
- Set some flags, like COMPlus_JitDump=YourMethodName.
- Run the app.
And here is the output:
*************** After end code gen, before unwindEmit()
IN0002: 000012 call CORINFO_HELP_NEWSFAST
IN0003: 000017 mov rcx, 0x1FE90003070
// Console.WriteLine(“Doing something. The answer is … ” + data);
IN0004: 000021 mov rcx, gword ptr [rcx]
IN0005: 000024 mov edx, dword ptr [rsi+8]
IN0006: 000027 mov dword ptr [rax+8], edx
IN0007: 00002A mov rdx, rax
IN0008: 00002D call System.String:Concat(ref,ref):ref
IN0009: 000032 mov rcx, rax
IN000a: 000035 call System.Console:WriteLine(ref)
// CheckReachability(this);
IN000b: 00003A mov rcx, rsi
// After this point, ‘this’ pointer is reachable for GC
IN000c: 00003D call Reachability.Program:CheckReachability(ref)
// Console.WriteLine
IN000d: 000042 mov rcx, 0x1FE90003078
IN000e: 00004C mov rcx, gword ptr [rcx]
IN000f: 00004F mov rax, 0x7FFB6C6B0160
*************** Variable debug info
2 vars
0( UNKNOWN) : From 00000000h to 00000008h, in rcx
0( UNKNOWN) : From 00000008h to 0000003Ah, in rsi
*************** In gcInfoBlockHdrSave()
Register slot id for reg rsi = 0.
Set state of slot 0 at instr offset 0x12 to Live.
Set state of slot 0 at instr offset 0x17 to Dead.
Set state of slot 0 at instr offset 0x2d to Live.
Set state of slot 0 at instr offset 0x32 to Dead.
Set state of slot 0 at instr offset 0x35 to Live.
Set state of slot 0 at instr offset 0x3a to Dead.
The dump from the JIT compiler is slightly different from the one you might get from WinDBG or theVisual Studio ‘Disassembly’ window. The main difference is that it shows way more information, including the number of local variables (when they were used in terms of ASM offsets) and the GCInfo. Another useful aspect that it shows instruction offset that helps to understand the GCInfo table.
In this case, it is clear that ‘this’ pointer is no longer needed after instruction 0x3A, i.e. right before the call to CheckReachability. And this is the very reason, why the instance was collected once GC was called inside CheckReachability method.
Conclusion
The main idea of this blog post is to show that there is no magic happening during GC. The JIT and the GC are working together to track some auxiliary information that helps the GC to clean objects as soon as possible.
But I want you to be cautious with this knowledge. The C# language specification states that this optimization is possible but not required: ”. So you should not rely on this behavior in your production scenarios. | https://blogs.msdn.microsoft.com/seteplia/2017/05/09/garbage-collection-and-variable-lifetime-tracking/ | CC-MAIN-2017-22 | refinedweb | 921 | 58.38 |
Documentation cleanup: escape "::", and other minor reformatting git-svn-id: 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Sema/SemaLookup.cpp b/lib/Sema/SemaLookup.cpp index ded441c..506a9f8 100644 --- a/lib/Sema/SemaLookup.cpp +++ b/lib/Sema/SemaLookup.cpp
@@ -1231,7 +1231,7 @@ /// using directives by the given context. /// /// C++98 [namespace.qual]p2: -/// Given X::m (where X is a user-declared namespace), or given : @@ -1244,6 +1244,7 @@ /// (namespace.udecl), S is the required set of declarations of /// m. Otherwise if the use of m is not one that allows a unique /// declaration to be chosen from S, the program is ill-formed. +/// /// C++98 [namespace.qual]p5: /// During the lookup of a qualified namespace member name, if the /// lookup finds more than one declaration of the member, and if one | https://android.googlesource.com/platform/external/clang/+/7ba759237afee52f4d53ed1fe07dbfdcfdbabdc6%5E%21/ | CC-MAIN-2020-10 | refinedweb | 135 | 58.99 |
29.9.
traceback — Print or retrieve a stack traceback
This
sys.last_traceback variable and returned as the third item from
sys.exc_info().
The module defines the following functions:
traceback.
print_tb(traceback, limit=None, file=None)
Print up to limit stack trace entries from traceback (starting from the caller’s frame) if limit is positive. Otherwise, print the last
abs(limit)entries. If limit is omitted or
None, all entries are printed. If file is omitted or
None, the output goes to
sys.stderr; otherwise it should be an open file or file-like object to receive the output.
Changed in version 3.5: Added negative limit support.
traceback.
print_exception(type, value, traceback, limit=None, file=None, chain=True)
Print exception information and stack trace entries from traceback to file. This differs from
print_tb()in the following ways:
- if traceback is not
None, it prints a header
Traceback (most recent call last):
- it prints the exception type and value after the stack trace
- if type is
SyntaxErrorand value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error.
The optional limit argument has the same meaning as for
print_tb(). If chain is true (the default), then chained exceptions (the
__cause__or
__context__attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception.
traceback.
print_exc(limit=None, file=None, chain=True)
This is a shorthand for
print_exception(*sys.exc_info(), limit, file, chain).
traceback.
print_last(limit=None, file=None, chain=True)
This is a shorthand for
print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain). In general it will work only after an exception has reached an interactive prompt (see
sys.last_type).
traceback.
print_stack(f=None, limit=None, file=None)
Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last
abs(limit)entries. If limit is omitted or
None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for
print_tb().
Changed in version 3.5: Added negative limit support.
traceback.
extract_tb(traceback, limit=None)
Return a list of “pre-processed” stack trace entries extracted from the traceback object traceback. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for
print_tb(). A “pre-processed” stack trace entry is a 4-tuple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is
None.
traceback.
extract_stack(f=None, limit=None)
Extract the raw traceback from the current stack frame. The return value has the same format as for
extract_tb(). The optional f and limit arguments have the same meaning as for
print_stack().
traceback.
format_list(list).
traceback.
format_exception_only(type, value)
Format the exception part of a traceback. The arguments are the exception type and value such as given by
sys.last_typeand
sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for
SyntaxErrorexceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.
traceback.
format_exception(type, value, tb, limit=None, chain=True)().
traceback.
format_exc(limit=None, chain=True)
This is like
print_exc(limit)but returns a string instead of printing to a file.
traceback.
format_tb(tb, limit=None)
A shorthand for
format_list(extract_tb(tb, limit)).
traceback.
format_stack(f=None, limit=None)
A shorthand for
format_list(extract_stack(f, limit)).
traceback.
clear_frames(tb)
Clears the local variables of all the stack frames in a traceback tb by calling the
clear()method of each frame object.
New in version 3.4.
traceback.
walk_stack(f)
Walk a stack following
f.f_backfrom the given frame, yielding the frame and line number for each frame. If f is
None, the current stack is used. This helper is used with
StackSummary.extract().
New in version 3.5.
traceback.
walk_tb(tb)
Walk a traceback following
tb_nextyielding the frame and line number for each frame. This helper is used with
StackSummary.extract().
New in version 3.5.
The module also defines the following classes:
29.9.1.
TracebackException Objects
New in version 3.5.
TracebackException objects are created from actual exceptions to
capture data for later printing in a lightweight fashion.
- class
traceback.
TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False)
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the
StackSummaryclass.
Note that when locals are captured, they are also shown in the traceback.
__cause__
A
TracebackExceptionof the original
__cause__.
__context__
A
TracebackExceptionof the original
__context__.
__suppress_context__
The
__suppress_context__value from the original exception.
stack
A
StackSummaryrepresenting the traceback.
exc_type
The class of the original traceback.
filename
For syntax errors - the file name where the error occurred.
lineno
For syntax errors - the line number where the error occurred.
text
For syntax errors - the text where the error occurred.
offset
For syntax errors - the offset into the text where the error occurred.
msg
For syntax errors - the compiler error message.
- classmethod
from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the
StackSummaryclass.
Note that when locals are captured, they are also shown in the traceback.
format(*, chain=True)
Format the exception.
If chain is not
True,
__cause__and
__context__will not be formatted.
The return value is a generator of strings, each ending in a newline and some containing internal newlines.
print_exception()is a wrapper around this method which just prints the lines to a file.
The message indicating which exception occurred is always the last string in the output.
format_exception_only()
Format the exception part of the traceback.
The return value is a generator of strings, each ending in a newline.
Normally, the generator emits a single string; however, for
SyntaxErrorexceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred.
The message indicating which exception occurred is always the last string in the output.
29.9.2.
StackSummary Objects
New in version 3.5.
StackSummary objects represent a call stack ready for formatting.
- class
traceback.
StackSummary
- classmethod
extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)
Construct a
StackSummaryobject from a frame generator (such as is returned by
walk_stack()or
walk_tb()).
If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is
False, the returned
FrameSummaryobjects will not have read their lines in yet, making the cost of creating the
StackSummarycheaper (which may be valuable if it may not actually get formatted). If capture_locals is
Truethe local variables in each
FrameSummaryare captured as object representations.
- classmethod
from_list(a_list)
Construct a
StackSummaryobject from a supplied old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.
29.9.3.
FrameSummary Objects
New in version 3.5.
FrameSummary objects represent a single frame in a traceback.
- class
traceback.
FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None)
Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is
False, the source code is not looked up until the
FrameSummaryhas the
lineattribute accessed (which also happens when casting it to a tuple).
linemay be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.
29.9.4. Traceback Examples
This simple example implements a basic read-eval-print loop, similar to (but
less useful than) the standard Python interactive interpreter loop. For a more
complete implementation of the interpreter loop, refer to the
code
module.
import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True:'] | https://documentation.help/Python-3.5.1/traceback.html | CC-MAIN-2020-24 | refinedweb | 1,372 | 50.33 |
So I was asked to solve this question...however when i compile it, it doesn't work...could somebody tell me what's wrong and how to solve it (im guessing it's something to do with overloading since my lecturer was talking abt it just before this was given)? thanks a lot!
#include <iostream> #include <vector> using namespace std; class Integer { public: int value; }; int main() { vector<Integer> v; for( int i=0; i<10; i++ ) { Integer x; x.value = i; v.push_back( x ); } vector<Integer>::iterator itr; for( itr=v.begin(); itr!=v.end(); itr+=2 ) cout << *itr << endl; return 0; } | https://www.daniweb.com/programming/software-development/threads/468802/iterator-and-overloading | CC-MAIN-2020-34 | refinedweb | 103 | 68.97 |
As the element hierarchy plays such a role in routed events you can only create new routed events in classes that derive from UIElement. The simplest way to do this is derive a new class from an existing WPF UIElement such as a button:
public class MyButton : Button{
To define a new even we first need to use the EventManager class to register the new event.
This is how the system knows how to handle the event and in particular what sort of routing is to be applied. The RegisterRoutedEvent returns a RoutedEvent object which has to be stored as a static field for later use within the new control.
For example, we use the m_MyEvent field to store the object:
public static readonly RoutedEvent m_MyEvent =EventManager.RegisterRoutedEvent( "MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
The first parameter specifies the name of the event that clients will use to add handlers to the event. This name has to be unique within the new control. Next we specify the type of routing, bubble in this case, and the type of the event handler and the type of object that can fire the event. The event handler delegate, RoutedEventHandler in this case, specifies the signature of any method that is to be added to the invocation list.
Now that we have registered the event we have to create some of the infrastructure needed to use the event. First we need to create the event property and an add and remove method using event accessors:
public event RoutedEventHandler MyEvent{ add { AddHandler(m_MyEvent, value); } remove { RemoveHandler(m_MyEvent, value); }}
These are automatically used by the system when you add and remove event handlers using the += and -= operators. Notice that the event property has to have the same name as you registered using the EventManager.
Finally we need a RaiseEvent method that can be used to trigger the new event:
void RaiseMyEvent(){ RoutedEventArgs newEventArgs = new RoutedEventArgs(MyButton.m_MyEvent); RaiseEvent(newEventArgs);}
The only tricky part here is that the RoutedEventArgs constructor accepts a RoutedEvent object and creates the correct set of arguments based on the information it contains but the Source and OriginalSource properties are null. However you don’t have to do anything about them because they are filled in correctly when you use the RaiseEvent method.
For simplicity we can connect the new event to an existing Button event:
protected override void OnClick(){ RaiseMyEvent();}
Of course in a real situation you would have some complex set of conditions to be fulfilled before the new event was raised.
Now we can make use of the new MyButton class and its associated routed event. Start a new project, enter the definition of the new button class below the Window() class, after all it isn’t worth creating the class as a separate entity and add a stackFrame using the designer. Now we can create an instance of MyButton at runtime (again it isn’t worth adding it to the Toolbox for an example):
MyButton B1=new MyButton();
We need to set some minimal properties to ensure that it displays in a reasonable way:
B1.Width = 50;B1.Height = 50;B1.Content = "ClickMe";
and we need to add it to the stackPanel’s Children collection;
stackPanel1.Children.Add(B1);
Given that it now has a position within the element hierarchy – it is a child element of the stackPanel - we can use the new routed event and expect it to be bubbled up to the stackPanel if we add:
stackPanel1.AddHandler(MyButton.m_MyEvent, new RoutedEventHandler(MyButtonHandler));void MyButtonHandler(object sender, RoutedEventArgs e){ MessageBox.Show("My New Clicked Event");}
Notice that when using AddHandler you have to use the static field to specify the type of event that is going to be attached to the stackPanel. Contrast this to adding an event handler to a control that supports the event directly, for example:
B1.MyEvent += (object sender, RoutedEventArgs e) => { MessageBox.Show("MyClicked"); };
Now when you run the program the new event will bubble up to the stackPanel as promised. You can change the nature of the routing as part of the registration using the EventManager to see how it all works.
<ASIN:0123745144>
<ASIN:1430210842>
<ASIN:073562710X> | http://www.i-programmer.info/programming/wpf-workings/1024-routed-events.html?start=3 | CC-MAIN-2014-10 | refinedweb | 697 | 56.79 |
" may need more precise wording. This manual is constantly evolving until the 1.0 release and is not to be considered as the final proper specification. the, more easily comprehensible,.
Whether!
Multiline comments. ]## unorthodox way to do identifier comparisons is called partial case insensitivity and has some advantages over the conventional case sensitivity:
It allows programmers to mostly use their own preferred spelling style, be it humpStyle, snake_style or dash fully style-insensitive language. This meant that it was not case-sensitive and underscores were ignored and there was no even a' ('o' | 'c' | 'C')_SUFFIX = ('f' | 'F') ['32'] FLOAT32_LIT = HEX_LIT '\'' FLOAT32_SUFFIX | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT32_SUFFIX FLOAT64_SUFFIX = ( ('f' | 'F') '64' ) | 'd' | 'D' FLOAT64_LIT = HEX_LIT '\'' FLOAT64_SUFFIX | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT64_SUFFIX
As can be seen in the productions, numerical constants can contain underscores for readability. Integer and floating point literals may be given in decimal (no prefix), binary (prefix 0b), octal (prefix 0o or 0.
Literals are bounds checked so that they fit the datatype. Non base-10 literals are used mainly for flags and bit pattern representations, therefore bounds checking is done on bit width, not value range. If the literal fits in the bit width of the datatype, it is accepted. Hence: 0b10000000'u8 == 0x80'u8 == 128, but, 0b10000000'i8 == 0x80'i8 == -1 instead of causing an overflow error.
Operators
Nim allows user defined treated as.
proc `^/`(x, y: float): float = # a right-associative division operator result = x / y echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then 12 / 0.5 = 24.0) echo 12 / 4 / 8 # 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375).').
Most native Nim types support conversion to strings with the special $ proc. When calling the echo proc, for example, the built-in stringify operation for the parameter is called:
echo 3 # calls `$` for `int`
Whenever a user creates a specialized object, implementation of this procedure provides for string representation.
type Person = object name: string age: int proc `$`(p: Person): string = # `$` always returns a string result = p.name & " is " & $p.age & # we *need* the `$` in front of p.age, which # is natively an integer, to convert it to # a string " years old."
While $p.name can also be used, the $ operation on a string does nothing. Note that we cannot rely on automatic conversion from an int to a string like we can for the echo proc. meaning compatible string is the native representation of a string for the compilation backend. For the C backend []., `$`]) {...}. The of operator is similar to the instanceof operator in Java.
type Person = object of RootObj name*: string # the * means that `name` is accessible from other modules age: int # no * means that the field is hidden Student = ref object of Person # a student is a person id: int # with an id field var student: Student person: Person assert(student of Student) # is true assert(student of Person) # also)
Note that, unlike tuples, objects require the field names along with their values.. Also, when the fields of a particular branch are specified during object construction, the correct value for the discriminator must be supplied at compile-time.
Set typeThe set type models the mathematical notion of a set. The set's basetype can
- only be an ordinal type of a certain size, namely:
- int8-int16
- uint8/byte-uint16
- char
- enum
or equivalent. The reason is that sets are implemented as high performance bit vectors. Attempting to declare a set with a larger type will result in an error:
var s: set[int64] # Error: set is too large. In general, a ptr T is implicitly convertible to the pointer type.) =) = abstract type and its base type. Explicit.
Auto type
The auto type can only be used for return types and parameters. For return types it causes the compiler to infer the type from the routine body:
proc returnsInt(): auto = 1984
For parameters it currently creates implicitly generic routines:
proc foo(a, b: auto) = discard
Is the same as:
proc foo[T1, T2](a: T1, b: T2) = discard
However later versions of the language might change this to mean "infer the parameters' types from the body". Then the above foo would be rejected as the parameters' types can not be inferred from an empty discard statement. HashSet[: HashSet[)
Covariance.
Convertible relation
A type a is implicitly convertible to type b iff the following algorithm returns true:
# XXX range types? proc isImplicitlyConvertible(a, b: PType): bool = if isSubtype(a, b) or isCovariant(a, b): return true categories.
proc sayHi(x: int): string = # matches a non-var int result = $x proc sayHi(x: var int): string = # matches a var int result = $(x + 10) proc sayHello(x: int) = var m = x # a mutable version of x echo sayHi(x) # matches the non-var version of sayHi echo sayHi(m) # matches the var version of sayHi sayHello(3) # 3 # 13
Automatic dereferencing
If the experimental mode is active and no other match is found, the first argument a is dereferenced automatically if it's a pointer type and overloading resolution is tried with a[] instead.
Automatic self insertions)
Lazy type resolution for untyped indented.
Void context. next statement.
In if statements new scopes begin immediately after the if/elif/else keywords and ends after the corresponding then block. For visualization purposes the scopes have been enclosed in {| |} in the following example:
if {| (let m = input =~ re"(\w+)=\w+"; m.isMatch): echo "key ", m[0], " value ", m[1] |} elif {| (let m = input =~ re""; m.isMatch): echo "new m in this scope" |} else: {| echo "m not declared here" |}.
When nimvm statement
nimvm is a special symbol, that may be used as expression of when nimvm statement to differentiate execution path between runtime and compile time.
Example:
proc someProcThatMayRunInCompileTime(): bool = when nimvm: # This code runs in compile time result = true else: # This code runs in runtime result = false const ctValue = someProcThatMayRunInCompileTime() let rtValue = someProcThatMayRunInCompileTime() assert(ctValue == true) assert(rtValue == false)
when nimvm statement must meet the following requirements:
-.:" var pw = readLine(stdin) while pw != "12345": echo "Wrong password! Next try:". unusual. A procedure declaration consists of an identifier, zero or more formal parameters, a return value type and a block of code. Formal parameters are declared as a list of identifiers separated by either comma or semicolon. A parameter is given a type by : typename. The type applies to all parameters immediately before it, until either the beginning of the parameter list, a semicolon separator or an already typed parameter, is reached. The semicolon can be used to make separation of types and subsequent identifiers more distinct.
# Using only commas proc foo(a, b: int, c, d: bool): int # Using semicolon for visual distinction proc foo(a, b: int; c, d: bool): int # Will fail: a is untyped since ';' stops type propagation. proc foo(a; b: int; c, d: bool): int
A parameter may be declared with a default value which is used if the caller does not provide a value for the argument.
# b is optional with 47 as its default value proc foo(a: int, b: int = 47): int
Parameters can be declared mutable and so allow the proc to modify those arguments, by using the type modifier var.
# "returning" a value to the caller through the 2nd argument # Notice that the function uses no actual return value at all (ie void) proc foo(inp: int, outp: var int) = outp = inp + 47
If the proc declaration has no body, it is a forward declaration. If the proc returns a value, the procedure body can access an implicitly declared variable named result that represents the return value. Procs can be overloaded. The overloading resolution algorithm determines which proc' # (x=0, y=1, s="abc", c='\t', b=false)
A procedure may call itself recursively.eLine("Hallo") # the same as writeLine(stdout, "Hallo")
Another way to look at the method call syntax is that it provides the missing postfix notation.
The method call syntax conflicts with explicit generic instantiations: p[T](x) cannot be written as x.p[T] because x.p[T] is always parsed as (x.p)[T].
Future directions: p[.T.] might be introduced as an alternative syntax to pass explict types to a generic and then x.p[.T.] can be parsed as x.(p[.T.])..
Creating closures in loops
Since closures capture local variables by reference it is often not wanted behavior inside loop bodies. See closureScope for details on how to change this behavior.
Anonymous Procs. preceeding, sizeOf,. For dynamic dispatch to work on an object it should be a reference type as well.
type Expression = ref object of RootObj ## abstract base class for an expression Literal = ref object of Expression x: int PlusExpr = ref object of Expression a, b: Expression method eval(e: Expression): int {.base.} = #.
As can be seen in the example, base methods have to be annotated with the base pragma. The base pragma also acts as a reminder for the programmer that a base method m is used as the foundation to determine all the effects that a call to m might cause.
In a multi-method all parameters that have an object type are used for the dispatching:
type Thing = ref object of RootObj Unit = ref object of Thing x: int method collide(a, b: Thing) {.base,s) and ends iteration.
- Neither inline nor closure iterators can be recursive.
Iterators that are neither marked {.closure.} nor {.inline.} explicitly default to being inline, withineLine. We call such type classes bind once types.. Such type classes are called bind many types. typedesc params, you must prefix the type with an explicit type modifier. The named instance of the type, following the concept keyword is also considered an explicit typedesc value: type Matrix): expr = M.M template Cols*(M: type Matrix): expr = M.N template ValueType*(M: type future, typetraits type Functor[A] = concept f type MatchedGenericType = genericHead(f.type) # Equaly
Converter type classes])
VTable types.*: untyped =: untyped): untyped = # untyped, typed or typedesc (stands for type description). These are "meta types", they can only be used in certain contexts. Real types can be used too; this implies that typed expressions are expected.
Typed vs untyped parameters.
Passing a code block to a template
You can pass a block of statements as a last parameter to a template via a special : syntax:
template withFile(f, fn, mode, actions: untyped): untyped = var f: File if open(f, fn, mode): try: actions finally: close(f) else: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): txt.writeLine("line 1") txt.writeLine("line 2")
In the example the two writeLine statements are bound to the actions parameter.
Varargs of untyped].
Symbol binding in templates
A template is a hygienic macro and so opens a new scope. Most symbols are bound from the definition scope of the template:
# Module A var lastId = 0 template genId*: untyped =: untyped, typ: typedesc) =): untyped =: untyped, actions: untyped): untyped = block: var f: File # since 'f' is a template param, it's injected implicitly ... withFile(txt, "ttempl3.txt", fmWrite): txt.writeLine("line 1") txt.writeLine(: untyped) =[untyped]): untyped = # eLine", newIdentNode("stdout"), n[i])))
Arguments that are passed to a varargs parameter are wrapped in an array constructor expression. This is why debug iterates over all of n's children.
BindSym
The above debug macro relies on the fact that write, writeLine)))
However, the symbols write, writeLine: untyped): untyped = #: untyped) = discard proc p() {.m.} = discard
This is a simple syntactic transformation into:
template m(s: untyped) =
Note: Dot operators are still experimental and so need to be enabled via {.experimental.}.: `` const . = key t[idx].val = val proc `[]=`*(t: var Table, key: string{call}, val: string{call}) = ## puts a (key, value)-pair into `t`. Optimized version that knows that ## the strings are unique and thus don't need to be copied: let idx = findInsertionPosition(key) shallowCopy t[idx].key, key shallowCopy t[idx].val,
Note on paths
In module related statements, if any part of the module name / path begins with a number, you may have to quote it in double quotes. In the following example, it would be seen as a literal number '3.0' of type 'float64' if not quoted, if uncertain - quote it:
import "gfx/3d/somemod, in that case it takes a list of, see type bound operations instead.. Since version 0.12.0 of the language, a proc that uses system.NimNode within its parameter types is implictly declared compileTime:
proc astHelper(n: NimNode): NimNode = result = n
Is the same as:
proc astHelper(n: NimNode): NimNode {.compileTime.} = result = n: untyped,.
used pragma
experimental pragma
The noDecl pragma can be applied to almost any symbol (variable, proc, type, etc.) and is sometimes useful for interoperability with C: It tells Nim that it should not generate a declaration for the symbol in the C code. For example:
var EACCES {.importc, noDecl.}: cint # pretend EACCES was a variable, as # Nim does not know its value
However, the header pragma is often the better alternative.
Note: This will not work for the LLVM backend.
Header pragma
The header pragma is very similar to the noDecl pragma: It can be applied to almost any symbol and specifies that it should not be declared and instead the generated code should contain an #include:
type PFile {.importc: "FILE*", header: "<stdio.h>".} = distinct pointer # import C's FILE* type; Nim will treat it as a new pointer type
The header pragma always expects a string constant. The string contant contains the header file: As usual for C, a system header file is enclosed in angle brackets: <>. If no angle brackets are given, Nim encloses the header file in "" in the generated C code.
Note: This will not work for the LLVM backend.
IncompleteStruct pragma
The incompleteStruct pragma tells the compiler to not use the underlying C struct in a sizeof expression:
type DIR* {.importc: "DIR", header: "<dirent.h>", final, pure, incompleteStruct.} = object
Compile pragma
The compile pragma can be used to compile and link a C/C++ source file with the project:
{.compile: "myfile.cpp".}
Note: Nim computes a SHA1 checksum and only recompiles the file if it has changed. You can use the -f command line option to force recompilation of the file.
Link pragma
The link pragma can be used to link an additional file with the project:
{.link: "myfile.o".}
PassC pragma
The passC pragma can be used to pass additional parameters to the C compiler like you would using the commandline switch --passC:
{.passC: "-Wall -Werror".}
Note that you can use gorge from the system module to embed parameters from an external command at compile time:
{.passC: gorge("pkg-config --cflags sdl").}
PassL pragma
The passL pragma can be used to pass additional parameters to the linker like you would using the commandline switch --passL:
{.passL: "-lSDLmain -lSDL".}
Note that you can use gorge from the system module to embed parameters from an external command at compile time:
{.passL: gorge("pkg-config --libs sdl").}
Emit pragma
The emit pragma can be used to directly affect the output of the compiler's code generator. So it makes your code unportable to other code generators/backends. Its usage is highly discouraged! However, it can be extremely useful for interfacing with C++ or Objective C code.
Example:
{.emit: """ static int cvariable = 420; """.} {.push stackTrace:off.} proc embedsC() = var nimVar = 89 #.
For a toplevel emit statement the section where in the generated C/C++ file the code should be emitted can be influenced via the prefixes /*TYPESECTION*/ or /*VARSECTION*/ or /*INCLUDESECTION*/:
{.emit: """/*TYPESECTION*/ struct Vector3 { public: Vector3(): x(5) {} Vector3(float x_): x(x_) {} float x; }; """.} type Vector3 {.importcpp: "Vector3", nodecl} = object x: cfloat proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl}
ImportCpp pragma
Note: c2nim can parse a large subset of C++ and knows about the importcpp pragma pattern language. It is not necessary to know all the details described here.
Similar to the importc pragma for C, the importcpp pragma can be used to import C++ methods or C++ symbols in general. The generated code then uses the C++ method calling syntax: obj->method(arg). In combination with the header and emit pragmas this allows sloppy interfacing with libraries written in C++:
# Horrible example of how to interface with a C++ engine ... ;-) {.link: "/usr/lib/libIrrlicht.so".} {.emit: """ using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; """.} const irr = "<irrlicht/irrlicht.h>" type IrrlichtDeviceObj {.final, header: irr, importcpp: "IrrlichtDevice".} = object IrrlichtDevice = ptr IrrlichtDeviceObj proc createDevice(): IrrlichtDevice {. header: irr, importcpp: "createDevice(@)".} proc run(device: IrrlichtDevice): bool {. header: irr, importcpp: "#.run(@)".}
The compiler needs to be told to generate C++ (command cpp) for this to work. The conditional symbol cpp is defined when the compiler emits C++ code. @ is replaced by the remaining arguments, separated by commas.
For example:
proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".} var x: ptr CppObj cppMethod(x[], 1, 2, 3)
Produces:
x->CppMethod(1, 2, 3)
As a special rule to keep backwards compatibility with older versions of the importcpp pragma, if there is no special pattern character (any of # ' @) at all, C++'s dot or arrow notation is assumed, so the above example can also be written as:
proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".}
Note that the pattern language naturally also covers C++'s operator overloading capabilities:
proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".} proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".}
- An apostrophe ' followed by an integer i in the range 0..9 is replaced by the i'th parameter type. The 0th position is the result type. This can be used to pass types to C++ function templates. Between the ' and the digit an asterisk can be used to get to the base type of the type. (So it "takes away a star" from the type; T* becomes T.) Two stars can be used to get to the element type of the element type etc.
For example:
type Input {.importcpp: "System::Input".} = object proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.} let x: ptr Input = getSubsystem[Input]()
Produces:
x = SystemManager::getSubsystem<System::Input>()
- #@ is a special case to support a cnew operation. It is required so that the call expression is inlined directly, without going through a temporary location. This is only required to circumvent a limitation of the current code generator.
For example C++'s new operator can be "imported" like this:
proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.} # constructor of 'Foo': proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".} let x = cnew constructFoo(3, 4)
Produces:
x = new Foo(3, 4)
However, depending on the use case new Foo can also be wrapped like this instead:
proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".} let x = newFoo(3, 4)
Wrapping constructors
Sometimes a C++ class has a private copy constructor and so code like Class c = Class(1,2); must not be generated but instead Class c(1,2);. For this purpose the Nim proc that wraps a C++ constructor needs to be annotated with the constructor pragma. This pragma also helps to generate faster C++ code since construction then doesn't invoke the copy constructor:
# a better constructor of 'Foo': proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.}
Wrapping destructors
Since Nim generates C++ directly, any destructor is called implicitly by the C++ compiler at the scope exits. This means that often one can get away with not wrapping the destructor at all! However when it needs to be invoked explicitly, it needs to be wrapped. But the pattern language already provides everything that is required for that:
proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".}
Importcpp for objects
Generic importcpp'ed objects are mapped to C++ templates. This means that you can import C++'s templates rather easily without the need for a pattern language for object types:
type StdMap {.importcpp: "std::map", header: "<map>".} [K, V] = object proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {. importcpp: "#[#] = #", header: "<map>".} var x: StdMap[cint, cdouble] x[6] = 91.4
Produces:
std::map<int, double> x; x[6] = 91.4;
- If more precise control is needed, the apostrophe ' can be used in the supplied pattern to denote the concrete type parameters of the generic type. See the usage of the apostrophe operator in proc patterns for more details.
type VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object var x: VectorIterator[cint]
Produces:
std::vector<int>::iterator x;
ImportObjC pragma
Similar to the importc pragma for C, the importobjc pragma can be used to import Objective C methods. The generated code then uses the Objective C method calling syntax: [obj method param1: arg]. In addition with the header and emit pragmas this allows sloppy interfacing with libraries written in Objective C:
# horrible example of how to interface with GNUStep ... {.passL: "-lobjc".} {.emit: """ #include <objc/Object.h> @interface Greeter:Object { } - (void)greet:(long)x y:(long)dummy; @end #include <stdio.h> @implementation Greeter - (void)greet:(long)x y:(long)dummy { printf("Hello, World!\n"); } @end #include <stdlib.h> """.} type Id {.importc: "id", header: "<objc/Object.h>", final.} = distinct int proc newGreeter: Id {.importobjc: "Greeter new", nodecl.} proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.} proc free(self: Id) {.importobjc: "free", nodecl.} var g = newGreeter() g.greet(12, 34) g.free()
The compiler needs to be told to generate Objective C (command objc) for this to work. The conditional symbol objc is defined when the compiler emits Objective C code.
CodegenDecl pragma()
InjectStmt pragma
The injectStmt pragma can be used to inject a statement before every other statement in the current module. It is only supposed to be used for debugging:
{.injectStmt: gcInvariants().} # ... complex code here that produces crashes ...
compile time define pragmas $$. to implement customized flexibly sized arrays. Additionally an unchecked array is translated into a C array of undetermined size:
type ArrayPart{.unchecked.} = array[0,.Effect implies gcsafe. The only way to create a thread is via spawn or createThread..
To override the compiler's gcsafety analysis a {.gcsafe.} pragma block can be used:
var someGlobal: string = "some string here" perThread {.threadvar.}: string proc setPerThread() = {.gcsafe.}: deepCopy(perThread, someGlobal)[FlowVarBase]. | https://nim-lang.org/docs/manual.html | CC-MAIN-2017-47 | refinedweb | 3,697 | 56.66 |
Extract by Polygon (Spatial Analyst)
Summary
Extracts the cells of a raster based on a polygon.
Usage
To extract based on a polygon in a feature class instead of providing a series of x,y pairs, you can use the Extract By Mask tool.
The center of the cell is used to determine whether a cell is inside or outside a polygon. If the center is within the arcs of the polygon, the cell is considered fully inside even if portions of the cell fall outside the polygon.
The polygon has a limit of 1,000 vertices. Polygon vertices must be entered in a clockwise order. The first and last vertex must be the same to close the polygon if multiple polygons are to be used. If the last points are not identical, the polygon will be closed automatically. The arcs of the polygon can cross one another, but convoluted polygons are not recommended.
Cell locations that are not selected are assigned a value of NoData..
If the input raster is integer, the output raster will be integer. If the input is floating point, the output will be floating point.
Syntax
Return Value
Code Sample
This example extracts cells from a raster based on the defined polygon coordinates.
import arcpy from arcpy import env from arcpy.sa import * polyPoints = [arcpy.Point(743050, 4321275), arcpy.Point(743100, 4321200), arcpy.Point(743500, 4322000),arcpy.Point(742900, 4321800)] env.workspace = "C:/sapyexamples/data" extPolygonOut = ExtractByPolygon("soil", polyPoints, "INSIDE") extPolygonOut.save("c:/sapyexamples/output/extpoly")
This example extracts cells from a raster based on the defined polygon coordinates.
# Name: ExtractByPolgyon_Ex_02.py # Description: Extracts the cells of a raster based on a polygon. # Requirements: Spatial Analyst Extension # Author: ESRI # Import system modules import arcpy from arcpy import env from arcpy.sa import * # Set environment settings env.workspace = "C:/sapyexamples/data" # Set local variables inRaster = "soil" polyPoints = [arcpy.Point(743050, 4321275), arcpy.Point(743100, 4321200), arcpy.Point(743500, 4322000),arcpy.Point(742900, 4321800)] # Check out the ArcGIS Spatial Analyst extension license arcpy.CheckOutExtension("Spatial") # Execute ExtractByPolygon extPolygonOut = ExtractByPolygon(inRaster, polyPoints, "INSIDE") # Save the output extPolygonOut.save("c:/sapyexamples/output/extpoly02") | http://help.arcgis.com/en/arcgisdesktop/10.0/help/009z/009z0000002q000000.htm | CC-MAIN-2018-47 | refinedweb | 354 | 51.75 |
The Microsoft DNS Server supports the new AAAA record necessary for IPv6. We thought some information on the representation and structure of IPv6 addresses would be appropriate to help you understand the record.
IPv6 addresses are 128 bits long. The preferred representation of an IPv6 address is eight groups of as many as four hexadecimal digits, separated by colons. For example:
0123:4567:89ab:cdef:0123:4567:89ab:cdef
The first group of hex digits (0123, in this example) represents the most significant (or highest order) four bits of the address.
Groups of digits that begin with one or more zeros don't need to be padded to four places, so you can also write the previous address as:
123:4567:89ab:cdef:123:4567:89ab:cdef
Each group must contain at least one digit, though, unless you're using the :: notation. The :: notation allows you to compress sequential groups of zeros. This comes in handy when you're specifying just an IPv6 prefix. For example, this notation:
dead:beef::
specifies the first 32 bits of an IPv6 address as dead:beef and the remaining 96 as zeros.
You can also use :: at the beginning of an IPv6 address to specify a suffix. For example, the IPv6 loopback address is commonly written as:
::1
or 127 zeros followed by a single one. You can even use :: in the middle of an address as a shorthand for contiguous groups of zeros:
dead:beef::1
You):
dead:beef:0000:00f1:0000:0000:0000:0000/64 dead:beef::00f1:0:0:0:0/64 dead:beef:0:f1::/64
Clearly, the existing A record won't accommodate IPv6's 128-bit addresses. RFC 1886 defines the solution: an address record that's four times as long as an A record. That's the AAAA (pronounced "quad A") record. The AAAA record takes as its record-specific data the textual format of an IPv6 record as described earlier. So for example, you'd see AAAA records like this one:
ipv6-host IN AAAA 4321:0:1:2:3:4:567:89ab
RFC 3152 established ip6.arpa, a new reverse-mapping namespace for IPv6 addresses.[6]:
[6] Several aspects of IPv6 addressing have been a moving target within the Internet standards community. We should point out that the original domain for IPv6 reverse mapping as defined in RFC 1886 was ip6.int. This domain was changed to ip6.arpa by RFC 3152 for both technical and political reasons.
b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.0.0.1.2.3.4.ip6.arpa.
These domain names have PTR records attached, just as the domain names under in-addr.arpa do:
b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.0.0.1.2.3.4.ip6.arpa. IN PTR mash.ip6.movie.edu. | https://flylib.com/books/en/2.600.1.87/1/ | CC-MAIN-2019-43 | refinedweb | 504 | 64.2 |
Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 28, 2012 5:50 AM
I am having a problem with the FlexGlobals.topLevelApplication. I have five situations:
1) Running in the prjector;
2) Firefox, running the swf directly in the browser;
3) Firefox, running with the swf embedded in a HTML page;
4) IE, running the swf directly in the browser;
5) IE, running with the swf embedded in a HTML page.
The following are the returns of the FlexGlobals.topLevelApplication command:
1) Main0;
2) Main0;
3) Main0;
4) Main0;
5) flexglobals.
The last one looks very, very wrong to me, and it means that I can't get the topLevelApplication in IE when the SWF is embedded in a HTML page (the most common scenerio!). Instead I get either:
1) The value of attributes.id;
2) or if that is not specified, the id of the HTML div that the SWF is enclosed in, which in this case is 'altContent'.
I have tried on 3 different machines all running Windows 7 with the following player versions:
11.4.402.265
11.3.300.265
11.3.300.271
As Application.application is now depreciated and I can't even compile with that at the moment, is there another reliable way to get the topLevelApplication? My application is failing in IE and it seems to be due to the FlexGlobals.topLevelApplication.
The code is using SWFObject which I haven't included.
-- Main.mxml ---
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx=""
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.core.FlexGlobals;
private function onCreationComplete():void {
Alert.show("FlexGlobals.topLevelApplication [" + FlexGlobals.topLevelApplication + "]");
}
]]>
</fx:Script>
</s:Application>
--- index.html ---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>flexglobals</title>
<meta name="description" content="" />
<script src="js/swfobject.js"></script>
<script>
var flashvars = {
};
var params = {
menu: "false",
scale: "noScale",
allowFullscreen: "true",
allowScriptAccess: "always",
bgcolor: "",
wmode: "direct" // can cause issues with FP settings & webcam
};
var attributes = {
id:"flexglobals"
};
swfobject.embedSWF(
"flexglobals.swf",
"altContent", "100%", "100%", "10.0.0",
"expressInstall.swf",
flashvars, params, attributes);
</script>
<style>
html, body { height:100%; overflow:hidden; }
body { margin:0; }
</style>
</head>
<body>
<div id="altContent">
<h1>flexglobals</h1>
<p><a href="">Get Adobe Flash player</a></p>
</div>
</body>
</html>
1. Re: Bug in FlexGlobals.topLevelApplication?Flex harUI Aug 28, 2012 8:32 AM (in response to cdsvvxv)
Are you saying the Alert.show is displaying something different on IE?
2. Re: Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 28, 2012 10:33 AM (in response to Flex harUI)
Yes, the alert in IE is showing flexglobals, in all other situations it shows Main0.
I would upload the files but this forum doesn't seem to allow it.
3. Re: Bug in FlexGlobals.topLevelApplication?Flex harUI Aug 28, 2012 10:49 AM (in response to cdsvvxv)
Which version of IE? Can you make the test SWF and HTML wrapper publicly available?
4. Re: Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 28, 2012 3:41 PM (in response to Flex harUI)
Click here and do a File > Download to get the files.
Unzip and look in the bin folder.
The version of IE that I am using is 9.0.8112.16421 (64 bit).
5. Re: Bug in FlexGlobals.topLevelApplication?Flex harUI Aug 28, 2012 4:38 PM (in response to cdsvvxv)
And which version of IE are you using?
6. Re: Bug in FlexGlobals.topLevelApplication?Flex harUI Aug 28, 2012 11:47 PM (in response to cdsvvxv)
Sorry, wasn’t clear. I don’t want a zip file, I want a URL hosting the test app.
7. Re: Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 29, 2012 4:14 AM (in response to Flex harUI)
I have uploaded the HTML page here and the SWF can be accessed directly here. I edited my above post to include the IE version, you must have read it before I made the edit.
Unfortunatly this is hosted on my home server which does not have a fixed IP address and does not use a dynamic DNS service hence it goes down quite often. I will try and check it often over the next day or so to try and keep the DNS up. I don't have any other servers available to me at the moment.
8. Re: Bug in FlexGlobals.topLevelApplication?Flex harUI Aug 29, 2012 12:10 PM (in response to cdsvvxv)
Interesting. I’d never come across that before. I noticed you are relying on object to string conversion (the toString() method). You might have better luck using FlexGlobals.topLevelApplication.name
9. Re: Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 31, 2012 12:57 AM (in response to Flex harUI)
I was really looking to be able to access an object in the Application object, but that is due to bad programme design. I will need to redesign it a little as FlexGlobals.topLevelApplication.name doesn't give me what I need.
I have filed a bug report (SDK-32294) but don't have a link as it is incorrectly flagged by the bug tracking system as a potential security issue.
Thanks for your help.
10. Re: Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 31, 2012 5:39 AM (in response to cdsvvxv)
I have now also tried this using an Object tag in a HTML page to load the SWF and I don't have the same issue, the problem only appears to be there using SWFObject and also another JavaScript solution that I found. In your opinion where is the most likely place for the bug to be? It would seem to me that the FlashPlayer should be handling the result of FlexGlobals.topLevelApplication, but the method of adding the SWF to the HTML page seems to have an affect as well. Looking at the FlexGlobals and spark.Application code, there doesn't seem to be any ExternalInterface type calls.
I am asking as I am finding it difficult to work around the issues I am having, and it would be better to find a fix rather than a workaround.
11. Re: Bug in FlexGlobals.topLevelApplication?Flex harUI Aug 31, 2012 7:55 AM (in response to cdsvvxv)
I’m not sure what your goal is. FlexGlobals.topLevelApplication is correctly returning the Main class instance in all browsers. It is only the toString() implied in your Alert test that displays something different on IE. If you need to access any other properties on the application, they will be there in all browsers.
12. Re: Bug in FlexGlobals.topLevelApplication?cdsvvxv Aug 31, 2012 8:31 AM (in response to Flex harUI)
Thanks for putting me straight, you are of course correct and made me look elsewhere for the problem.
In the end it was an issue with calls to error.getStackTrace() in a non-debug version of the FlashPlayer that was installed on IE. I am now checking Capabilities.isDebugger before calling that. I had originally thought that I was not getting the Application object back, but as you say, I am.
Sorry for all the posts and thanks for your help. | https://forums.adobe.com/message/4655604 | CC-MAIN-2015-18 | refinedweb | 1,192 | 66.54 |
As part of my PhD I write a lot of Matlab. I am not particularly fond of Matlab but because I need to collaborate and work on older code bases I dont have much choice in the matter. All that aside, sometimes in Matlab youll find that things can get a little slow. In my field of computational electrodynamics this is typically around the time we need to calculate a matrix of inductance contributions with 100 million elements. Because code like this is hard to vectorise we tend to write code in other languages like C to speed up that section of code. In Matlab land this is typically referred to as writing a Mex file. Mex files can be written in C, C++, Fortran and possibly others.
As a fan of Rust I wanted to see what I could do to get Rust and Matlab talking to one another. It took some time to work out how it could all fit together but I have ported one of the older C Mex files to Rust and successfully linked them to Matlab. While I cant share the specifics of that code here I will work through a working example of sending data from Matlab to Rust and back again. Lets get started.
Just in case something falls apart with updates this is my current setup:
This step is fairly well documented but for completeness I will start from the beginning. I assume you have all of the components above installed and Matlab knows what C compiler you will be using.
So lets create an empty Rust project.
cargo new rustlab cd rustlab
Open up your
Cargo.toml file and add the following lines to the end.
[dependencies] libc="0.2.4" [lib] name="rustlab" crate-type=["staticlib"]
We ask for
libc so we can send data between Matlab and Rust, we also declare this project as a library and say we want to build a static library. As it stands we need to create a static library which will be linked to a C file which wraps the Matlab Mex calling interface, more on that later.
Now to write our functions. In this example we will be writing a function which takes two vectors and does an element wise multiplication on their elements. Something Matlab already does, and does quickly, but enough of an example to show the process of getting data sent both ways.
In our Rust code we will be writing two functions.
One, which we will call
multiply_safe is where we will use only Rust variables and do the actual computation.
The other
multiply will be a wrapper, and our interface to C which takes C types, populates Rust variables with them, calls our
multiply_safe function and then passes the result back as a C type.
This way we keep our Rust code and glue separate as much as possible.
Allowing us to test our Rust code on its own without having to set up all the glue each time.
So lets get going with implementing
multiply_safe and writing a simple test to ensure it is doing what we want.
First open up lib.rs and add the following function to the file:
fn multiply_safe(a : Vec<f64>, b : Vec<f64>) -> Vec<f64> { if a.len() != b.len() { panic!("The two vectors differ in length!"); } let mut result : Vec<f64> = vec![0f64; a.len()]; for i in 0..a.len() { result[i] = a[i]*b[i]; } return result; }
Nice and simple, there should be no surprises here. Because it is good practice we will also write a test to ensure the results are indeed what we expect. Edit the default
it_works test to look like the following:
#[test] fn it_works() { let a : Vec<f64> = vec![1f64, 2f64, 3f64]; let b : Vec<f64> = vec![3f64, 2f64, 1f64]; let c : Vec<f64> = multiply_safe(a, b); let expected : Vec<f64> = vec![3f64, 4f64, 3f64]; assert!(c.len() == expected.len()); for i in 0..c.len() { assert!(c[i] == expected[i]); } }
Now if you run
cargo test you should see our test passing. The other thing we now have is a file called
librustlab.a in the
target/debug folder. It wont do anything right now because we havent written the
multiply function but this is were our library will end up.
Now lets look at the function that makes the link between C and Rust. As I mentioned before we will be writing a C file which acts as a middleman between Matlab and Rust. This is clearly not ideal but in currently it appears to be the most straightforward way to get things working.
Before we write this new function lets add the
libc requirements to the top of the file.
extern crate libc; use libc::{c_double, c_long};
The C function will be passing us double pointers so we use rusts c_double type and c_long to pass the length of the two arrays. Next to create our exported function add the following.
#[no_mangle] pub extern fn multiply(a_double : *mut c_double, b_double : *mut c_double, c_double : *mut c_double, elements : c_long) { let size : usize = elements as usize; let mut a : Vec<f64> = vec![0f64; size]; let mut b : Vec<f64> = vec![0f64; size]; for i in 0..size { unsafe { a[i] = *(a_double.offset(i as isize)) as f64; b[i] = *(b_double.offset(i as isize)) as f64; } } let c : Vec<f64> = multiply_safe(a, b); for i in 0..size { unsafe { *c_double.offset(i as isize) = c[i]; } } }
Some things to note here. First up
#[no_mangle] this tells rust to keep the
function name the same so we can link to it, typically it gets mangled to
reduce the risk of two things having the same name. Next
pub extern is needed
to make sure the function is publicly exported. The last thing worth noting is
the
unsafe block. We use one of these to mark where potentially unsafe things
might happen (like dereferencing pointers). Hopefully the rest of the function
is clear enough. Build the code again and we will move on to writing the final
piece of the puzzle.
Create a new file
rustlab.c and add the following code. If you have used the
mex interface before it should be pretty straightforward.
#include "mex.h" // Multiplies a and b element wise, and puts the result in c extern void multiply(double* a, double* b, double* c, long elements); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double* a; double* b; double* c; mwSize elements; if (nrhs != 2) { mexErrMsgTxt("Wrong number of input args"); } if (nlhs != 1) { mexErrMsgTxt("Wrong number of output args"); } a = mxGetPr(prhs[0]); b = mxGetPr(prhs[1]); elements = mxGetM(prhs[0]); plhs[0] = mxCreateDoubleMatrix(elements, 1, mxREAL); c = mxGetPr(plhs[0]); multiply(a, b, c, elements); }
Now that both of these are done, open up Matlab and move to a folder that
contains both
librustlab.a and
rustlab.c. While in Matlab run the following.
mex rustlab.c librustlab.a a = 1:10; c = rustlab(a', a'); disp(c);
Woohoo! You did it. Hopefully this made things clear and helps in some way. While I am probably not considered an expert in rust I am happy to help out if you get in touch with me via twitter @smitec.
I plan over time to move more of my mex files to Rust. It offers a lot in terms of safety and high level concepts that can be more difficult to achieve in C.
All of the code related to this post is available on Github: rustlab and so if things are broken on your system feel free to post an issue or pull request.
Continue reading on smitec.io | https://hackerfall.com/story/allowing-matlab-to-talk-to-rust | CC-MAIN-2017-26 | refinedweb | 1,285 | 72.97 |
Patch looks fine to me.On Tue, 4 Dec 2007, Steven Rostedt wrote:> > Note: I'm a bit nervious to add "linux/types.h" and use u32 and u64> in thread_info.h, when there's a #ifdef __KERNEL__ just below that.> Not sure what that is there for.Hmm. I'd not expect user-mode headers to ever include <linux/thread-info.h>, and if they do, they'd already get get totally invalid namespace pollution ("struct restart_block" at a minimum) along with stuff that simply isn't sensible in user-space at all, so I think this part is fine.And I guess somebody will scream if it bites them ;)Anyway, my gut feel is that this is potentially a real problem, and we should fix it asap (ie it should go into 2.6.24 even at this late stage in the game), but it would be nice to know if the problem actually hit any actual real program, and not just a test-setup.So here's a question for David Holmes: What caused you to actually notice this behaviour? Can this actually be seen in real life usage?Anyway, at a minimum, here's an Acked-by: Linus Torvalds <torvalds@linux-foundation.org>and I suspect I should just apply it directly. Any comments from anybody else? Linus | http://lkml.org/lkml/2007/12/4/478 | CC-MAIN-2017-13 | refinedweb | 222 | 74.29 |
Studio Menu Reference
This chapter describes menu and keyboard options available from the Studio menus.
File Menu
The File menu contains options for opening and saving documents and projects. Options vary depending on whether a file is open. See also the section “Keyboard Accelerators.”
Edit Menu
The Edit menu contains editing and navigation options. Most of the options have keyboard shortcuts; see the section “Keyboard Accelerators”.
Basic Editing
Find and Replace
More on Find
The search engine normally interprets a backslash (\) as a metacharacter; that is, a character that means something other than itself. In this case — the backslash and the following character form a two-character code. When you want to search for the backslash itself, you need to create a two-character code since the search engine always looks for a second character when it sees a backslash. Create a two-character code with a second backslash (\\). The search engine interprets this as the backslash character itself.
This convention was implemented during the development of the UNIX grep command and the convention, if not the underlying C code, has been duplicated many times since.
To find text that is in a particular element type (such as a command, variable, operator, and so on), enter the desired text in the Find what field and select the Match Element Type check box.
Find displays the searched-for text in all elements of that type in the open file, regardless of language selected. In the Language field, select the language that you are interested in to limit the number of element types shown in the Element list. In the Element field, select the element type that contains the text you are looking for and select Find Next.
For example, searching for the word Set in a Comment with the Class Definition Language selected matches all instances of the word Set in comments that exist in any language in the file.
Find in Files
When you select Find in the Find in Files dialog, Studio searches the selected files in the current InterSystems IRIS namespace and returns a list of all (up to the first 5,000) files that contain the search string. Double-click an item in the search results to open the file and display the item, highlighted. Line & column numbers for the selected item are displayed in the right corner of the status bar.
Find in Files searches stored data; it does not search modified open documents. If you search only in the current project and the current project is either a new project or a modified project, you are prompted to save the project. If you refuse, Find in Files is canceled.
To find a backslash (\) in Find in Files, you need to escape the backslash with another backslash (\\).
The Filter field can contain the elements in the list below. You can use SQL AND and OR logical operators to enter more than one filter. For example, Type=5 AND Modified>01/01/08. The contents of the Filter field forms part of an SQL WHERE clause. The fields come from the %Studio.OpenDialogItems class.
You can enter your own custom mask in the In files/file types field, such as al*.mac. Use a comma delimited list to enter multiple filters in any field.
You can use the following items in the Filter field.
Bookmarks
You can use bookmarks to keep track of locations in your application source. Bookmarks are stored on the local machine in which Studio is running; they are not shared among multiple users. The bookmark options are:
Advanced Editing
The Advanced Editing menu contains some commands that are displayed in certain circumstances only.
View Menu
The View menu contains options that control what is displayed. Which options are shown on this menu depends on where your cursor is. See also the section “Keyboard Accelerators.”
Toolbars
The Toolbars menu lets you toggle the display of toolbars and lets you customize toolbars.
Toolbars, displaying text labels, are shown below. To display text labels in Studio, choose View > Toolbars > Customize, the Toolbars tab. Select a toolbar and select Show text labels. (If a toolbar is already selected, uncheck the toolbar, recheck the toolbar, and check Show text labels.)
The BPL toolbar is only applicable in InterSystems IRIS.
Project Menu
The Project menu contains options for working with projects.
Common Project Tasks
To delete a project, select File > Open Project and right-click the project that you want to delete.
To import a project, select Tools > Import Local and select the .xml file that contains the project.
To export a project, open the project, select Tools > Export, select Export Current Project, browse to the output directory, and enter a file name.
Project names cannot include the characters .,;/\ (that is, period, comma, semi-colon, slash, or backslash).
Class Menu
The Class menu contains options for editing class definitions and is available only when you are in a class definition file.
The class options are arranged in an Add submenu and an Override dialog. The options include:
A projection automatically creates related files for other languages when you compile a class. For example, adding a Projection of type %Projection.Java generates a new Java class when it compiles so that you can use your class from a Java application.
Build Menu
The Build menu contains options for compiling and building applications. The behavior of the Build options is controlled by the Compile settings in the Studio Options dialog (Tools > Options).
The build options include:
Debug Menu
The Debug menu contains debugging options. To see the Debug Menu options, see the section “Debug Menu” in the chapter “Using the Studio Debugging .” See also the section “Keyboard Accelerators.”
Tools Menu
The Tools menu contains miscellaneous options.
The tools options include:
Utilities Menu
The Utilities menu contains links to resources outside of Studio, such as:
Management Portal
Telnet
Window Menu
The Window menu contains standard window options for manipulating the windows in Studio.
Help Menu
The Help menu contains options for accessing online Help.
The help options include:
Context Menus
Right-clicking areas in Studio displays different context menu. These include those described in the following sections.
Editor Context Menu
Right-clicking in the Studio Editor window displays a context menu. Within this context menu are many items available from the main menus, such as on the Editor menu are Cut, Copy, Paste, Find, Toggle Breakpoint, and Go Back, and so on. There are also additional options that are not available from the main menu. These include:
Workspace Context Menu
Right-clicking the Workspace window displays a context menu. Which menu is displayed depends on the cursor location. Different context menus are displayed if the cursor is on a package, a class, and so on. This table below shows items on the Workspace Package context menu not available on the menu bar.
Inspector Context Menu
Right-clicking the Inspector window displays a context menu with the following items (if they are applicable to the current document in the editor window):
Tab Context Menu
Right-clicking the tabs header displays a context menu with these items:
Window Display Context Menu
Right-clicking a window where no other context menus apply shows the generic window context menu:
Keyboard Accelerators
This section lists Studio's keyboard accelerators (keyboard shortcuts)—combinations of keys that, when pressed, perform a Studio function.
In the following table, a block of text means a number of whole lines. To select a block of text, put the caret at the start of the first line, press Shift, and select the down arrow till all of the relevant lines are highlighted. The caret is then displayed at the start of the line beneath the last whole line. | https://docs.intersystems.com/irisforhealthlatest/csp/docbook/Doc.View.cls?KEY=GSTD_Commands | CC-MAIN-2021-17 | refinedweb | 1,285 | 63.29 |
On 9/12/06, Dominique Devienne <ddevienne@gmail.com> wrote:
>
> > > > > > 2) Introduce a <tagdef> or <roledef> for the purpose
> > > > > > of locating extension points as nested elements.
>
> > Ok, I dug out my old code and after digging out some of the bugs
> > and misunderstanding, I have modded IH, CH (componenthelper),
> > and <typedef> to allow "restricted" types.
>
> Cool!!!
>
>
> > I am not too sure this should be user visible but it can be implemented
> > by an extra attribute to the typedef task - restrict=yes/no default is
> no.
>
> I'd personally prefer a new <*def>, rather than overloading <typedef>,
> perhaps called <tagdef> or <roledef> or <elementdef>.
I do not really mind what it is called, <roledef> is probally the best of
the bunch.
> One problem is that the antlib.xml for antlib:org.apache.tools.ant would
> > be long and tedious when all the conditions, selectors, mappers,
> resources
> > are added.
>
> long, for sure, for not more tedious than before. But I'm not against
> automating this, on the contrary.
>
> > To solve the startup problem, I propose that we use an AntLibDefinitions
> > class associated
> > with a name-space which would contain the definitions.
>
> Do you mean to having a .java equivalent to an antlib.xml?
Yes, it would be a class that has a public method AntTypeDefintion[]
getDefinitions().
The name of the class could be fixed <package>.AntTypeDefinitions - or
set by the jar service entry. The XML namespace would be the same as
a corresponding antlib.xml ie <package> -> antlib:<package>
> * @ant.type [restrict="yes"/"no"] [name="whatever"]
> > Where the defaults are restrict=no,
>
> Against, I'm not fond of restrict, but I wouldn't -1 is I'm the only one.
>
> > I will create a bugzilla issue where I will place the diffs and task.
> > This will not of course be for ant 1.7!,
>
> Thanks again. This is great.
>
> > however we can add the @ant.type tags now for documentation?,
>
> Sure, provided we settle on a doc tag name, which ideally would match
> the <*def> we choose. --DD
@ant.type --> <typedef>
@ant.task --> <taskdef>
@ant.role --> <roledef>
Peter
---------------------------------------------------------------------
> To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org
> For additional commands, e-mail: dev-help@ant.apache.org
>
> | http://mail-archives.apache.org/mod_mbox/ant-dev/200609.mbox/%3Cdffc72020609121505p74f531f0v9d4086f069e5b0f9@mail.gmail.com%3E | CC-MAIN-2015-14 | refinedweb | 365 | 68.97 |
Sencha Touch - First Program
In this chapter, we will list down the steps to write the first Hello World program in Ext JS.
Step 1
Create an index.htm page in an editor of our choice. Include the required library files in the head section of html page as follows.
index.htmLive Demo
<!DOCTYPE html> <html> <head> <link href = "" rel = "stylesheet" /> <script type = "text/javascript" src = ""> </script> <script type = "text/javascript"> Ext.application( { name: 'Sencha', launch: function() { Ext.create("Ext.tab.Panel", { fullscreen: true, items: [{ title: 'Home', iconCls: 'home', html: 'Welcome to sencha touch' }] }); } }); </script> </head> <body> </body> </html>
Explanation
Ext.application() method is the starting point of Sencha Touch application. It creates a global variable called 'Sencha' declared with the name property - all the Application's classes such as its Models, Views and Controllers will reside under this single namespace, which reduces the chances of colliding global variables and file names.
launch() method is called once the page is ready and all the JavaScript files are loaded.
Ext.create() method is used to create an object in Sencha Touch. Here, we are creating an object of simple panel class Ext.tab.Panel.
Ext.tab.Panel is the predefined class in Sencha Touch for creating a panel.
Every Sencha Touch class has different properties to perform some basic functionalities.
Ext.Panel class has various properties such as −
fullscreen property is to make use of a complete screen, hence the panel will take fullscreen space.
items property is the container for various items.
iconCls is the class used for displaying different icons.
title property is to provide the title to the panel.
html property is the html content to be shown in the panel.
Step 2
Open the index.htm file in a standard browser and you will get the following output. | https://www.tutorialspoint.com/sencha_touch/sencha_touch_first_app.htm | CC-MAIN-2018-39 | refinedweb | 301 | 66.23 |
Introduction
In the previous part of this custom adapter development series, we have walked through the steps to clone the sample JCA adapter and deploy it into the PI system.
In this part, we will be having a closer look at the Java source codes that form the custom adapter. We will only be looking at some of the key classes and their methods, in order to have a better understanding on the behavior of the adapter during the different stages in its life cycle.
This part will be a bit “drier” compared to the previous part as it will not have as much hands-on steps. However, it is crucial to have an understanding of these key elements as the basis for subsequent modification of the adapter according to specific requirements.
Deployment and Adapter Registration
During deployment of the adapter, it will perform registration of itself with the adapter framework. Following are some of the key aspects of the registration process.
SPIManagedConnectionFactory (SMCF) is one of the central classes for the adapter. Below are the description of the class as taken from the comments section of the class:-
An object of the class SPIManagedConnectionFactory (MCF) is a factory of both,
ManagedConnection and CCIConnectionFactory instances.
This class supports connection pooling by defining methods for matching and creating connections.
When an object of SMCF is created, it will perform a JNDI Lookup to retrieve an object of SAPAdapterResources.
Subsequently, SMCF is started by the AS Java server which calls its start() method. This in turn calls the startMCF() method. Within the startMCF() method, the above SAPAdapterResources object will execute its startRunnable() method using the SMCF object as a reference. This is to enable the SMCF to run in its own thread which is used to handle inbound processing.
As SMCF implements the Runnable interface, its run() method will subsequently be executed in its on thread.
Within the run() method, the adapter type and namespace are set. As mentioned in the first part of the series, it is important that the combination of the type and namespace forms a unique pair as this combination will be used during the registration of the adapter. This unique pair also has to match the name used for the Adapter Metadata in ESR.
The above combination is used as input values during construction of an XIConfiguration object. This class manages all the channel information.
Within the init() method of the XIConfiguration object, an execution of the registerAdapter() method of AdapterRegistry is performed to register the adapter with the adapter framework.
Successful registration of the adapter with the framework is crucial to ensure proper behavior and processing of the associated channels.
If the registration was not successful, channels created for this adapter will have the error “No adapter registered for this channel” when viewed in the Communication Channel Monitor.
Side Note: Although the SMCF class implements the Runnable interface, it is not mandatory for it to do so. Implementation of the Runnable interface (to handle threads for inbound processing) can be delegated to a separate/new class as long as an object of the class is passed as an input value to the startRunnable() method.
Channel Management
During the lifecycle of a deployed adapter, channels can be created, changed and deleted for the adapter type. The XIConfiguration class is responsible for managing the details of channels for an adapter.
Following are some of the methods executed when actions for channels of an adapter are taken.
Following is an example of the one of the methods, channelAdded().
The class maintains private attributes that contain lists of both inbound (sender) and outbound (receiver) channels that belongs to the adapter.
During the execution of the method, the newly created channel will be added to the list. Note that this logic is executed within a synchronized block to ensure that the contents of the list is consistent in multi-threaded executions.
Runtime Processing
Following are some of the key aspects during runtime execution of channels for the adapter.
A) Receiver Channel Processing
For receiver channel processing, the message is processed by the execute() method of class CCIInteraction. Within this method, it determines whether it is an asynchronous (Send) or synchronous (Call) execution and calls the corresponding method accordingly.
As an example, for an asynchronous message, the send() method is called. In the sample JCA adapter, it will create an output file (according to the directory and filename configured in the receiver channel) in the file system of the PI server.
The following logic section in the method constructs the target output file.
An below is an example output generated by a sample message processed by the receiver JCA adapter.
B) Sender Channel Processing
The sample JCA adapter provides a polling mechanism for the sender channel to poll files from the file system of the PI server.
The logic is implemented within the run() method of the SPIManagedConnectionFactory class.
After the wait time is completed for each polling interval, method sendMessageFromFile() is executed to pick up file(s) from the configured directory and generate an message in the Messaging System.
Refactoring Hard-coded Adapter Constant Values
Now that we have examined some of the key aspects of the adapter logic, we will have some hands-on to prepare the adapter project for modifications that will be introduced in the later parts of this series.
The source code for the sample JCA adapter contains many hard-coded values across the different classes. In this section, we will consolidate all these hard-coded values in a separate class as static final attributes. This is an optional yet recommended step in order to allow for ease of change in the future.
Below is the new class AdapterConstants that contains these constant values. Subsequently, the various classes are updated to reference these constants instead of hard-coding them within the classes themselves.
i) CCIConnectionMetaData
ii) CCIResourceAdapterMetaData
iii) SPIManagedConnection
iv) SPIManagedConnectionFactory
v) SPIManagedConnectionMetaData
vi) XIAdapterCategories
vii) XIConfiguration
Conclusion
Phew! Finally, we have come to the end of this part and hopefully gained a better understanding on some of the internal behavior of the custom adapter. This will provide the foundation needed when we introduce modifications to the adapter later on in this series. In the next post, we will be looking at the deployment descriptor, manifest and adapter metadata files.
Other Parts of this Series
Demystifying Custom Adapter Development: Part 1a – Cloning the Sample JCA Adapter
Demystifying Custom Adapter Development: Part 1b – Cloning the Sample JCA Adapter
Demystifying Custom Adapter Development: Part 3 – Examining the Deployment and Metadata Files
Demystifying Custom Adapter Development: Part 4 – Modifying the Adapter’s Functionality
Demystifying Custom Adapter Development: Part 5 – Creating an HTTP Poller with OAuth 2.0 authentication
Great post again making it easy to understand the not documented part.
Fantastic series Eng Swee! Good Job! 😀 | https://blogs.sap.com/2016/05/04/demystifying-custom-adapter-development-part-2-examining-the-adapters-key-classes-and-methods/ | CC-MAIN-2019-09 | refinedweb | 1,136 | 51.07 |
Created on 2020-09-22 11:47 by vstinner, last changed 2020-10-12 08:58 by vstinner. This issue is now closed.
When debugging race conditions in a multithreaded application with many threads, it's hard to debug when threads have generic names like "Thread-3".
I propose to use the target name in threading.Thread constructor if the name parameter is omitted.
See for example bpo-41739 with "Dangling thread: <Thread(Thread-3, started daemon 4396088817936)>": the "Thread-3" name is not helpful. I suspect that the bug comes from threading.Thread(target=remove_loop, args=(fn, del_count)): with my proposed change, the thread would be called "target=remove_loop", which is more helpful than "Thread".
Fall back on _newname() as usual if target.__name__ attribute does not exist.
Attached PR implements this idea.
And what if run different threads with the same target or with different targets with the same name? Would not "Thread-3" be more useful in this case?
for i in range(10):
Thread(target=print, args=(i,)).start()
for i in range(10):
def doit(i=i):
print(i)
Thread(target=doit).start()
> And what if run different threads with the same target or with different targets with the same name?
If multiple Thread objects using the same target (or different targets with the same name), they all get the same name using my PR 22357.
> Would not "Thread-3" be more useful in this case?
Well, that's an open question. In my experience, "Thread" name is pretty useless.
What if I modify my PR to add "-{counter}" (ex: "func-3" for target.__name__="func") to the default name? Reuse _counter().
Pseudo-code:
self._name = str(name)
try:
base_name = target.__name__
except AttributeError:
base_name = "Thread"
if not self._name:
self._name = "{base_name)-{_counter()}"
See also bpo-15500 "Python should support exporting thread names to the OS".
Having the target in the thread name definitely seems like a good idea and would help ease debugging, not just for our tests but when printing thread objects in general.
I would agree with the suggestion of placing the counter in there for when multiple threads get spawned with the same target or maybe even using names like:
Thread-1 (doit)
Thread-2
Thread-3 (print)
might be better just for people who are familiar with them.
I rewrote my PR to generate names like "Thread-3 (func)", rather than just "func". So if two target functions have the same name, or if two threads use the same target, it remains possible to distinguish the two threads.
Ideally, I would prefer separate counters for different names, and omitting a number for the first thread with unique name:
doit
doit-2
Thread-1
Thread-2
print
print-2
doit-3
But it is not feasible. It would require supporting a cache which can grow with every new thread and non-trivial code to avoid race conditions. So I am fine with Ammar's idea.
> Ideally, I would prefer separate counters for different names
IMO if you want to go at the level of details, I suggest you to generate yourself thread names:
threads = [threading.Thread(name=f"MyThread-{i}") for i in range(1, 6)]
Maintaining a list of thread names sounds overkill to me. It would be quite complicated and would increase the memory footprint, for little benefit.
New changeset 98c16c991d6e70a48f4280a7cd464d807bdd9f2b by Victor Stinner in branch 'master':
bpo-41833: threading.Thread now uses the target name (GH-22357)
I merged my change with "Thread-1 (func)" format: add the target name, but keep "Thread-3" to distinguish two different threads with the same target name.
Cool, my threading change works as expected! The name of the target function was logged in bpo-41739 issue.
0:00:28 load avg: 3.58 [ 36/424/1] test_logging failed (env changed)
Warning -- threading_cleanup() failed to cleanup 2 threads (count: 2, dangling: 3)
Warning -- Dangling thread: <Thread(Thread-4 (removeTarget), started daemon 4396862667024)>
Warning -- Dangling thread: <Thread(Thread-11 (removeTarget), started daemon 4396595259664)>
Warning -- Dangling thread: <_MainThread(MainThread, started 4396920310576)>
See "<Thread(Thread-4 (removeTarget), started daemon 4396862667024)>": the two leaked threads are running the removeTarget() function which come from MemoryHandlerTest.test_race_between_set_target_and_flush().
By the way, Serhiy was right about the name of having an unique repr() even if the target is the same, since it's the case here ;-) Well "4396862667024" is different than "4396595259664", but it's more convinient to have short numbers like "Thread-4" and "Thread-11". | https://bugs.python.org/issue41833 | CC-MAIN-2021-43 | refinedweb | 748 | 72.36 |
One of the added benefits to building on top of the Erlang VM (BEAM) is the plethora of existing libraries available to us. Interoperability allows us to leverage those libraries and the Erlang standard lib from our Elixir code. In this lesson we’ll look at how to access functionality in the standard lib along with third-party Erlang packages.
Table of Contents
Standard Library
Erlang’s extensive standard library can be accessed from any Elixir code in our application.
Erlang modules are represented by lowercase atoms such as
:os and
:timer.
Let’s use
:timer.tc to time execution of a given function:
defmodule Example do def timed(fun, args) do {time, result} = :timer.tc(fun, args) IO.puts("Time: #{time} μs") IO.puts("Result: #{result}") end end iex> Example.timed(fn (n) -> (n * n) * n end, [100]) Time: 8 μs Result: 1000000
For a complete list of the modules available, see the Erlang Reference Manual.
Erlang Packages
In a prior lesson we covered Mix and managing our dependencies. Including Erlang libraries works the same way. In the event the Erlang library has not been pushed to Hex you can refer to the git repository instead:
def deps do [{:png, github: "yuce/png"}] end
Now we can access our Erlang library:
png = :png.create(%{:size => {30, 30}, :mode => {:indexed, 8}, :file => file, :palette => palette})
Notable Differences
Now that we know how to use Erlang we should cover some of the gotchas that come with Erlang interoperability.
Atoms
Erlang atoms look much like their Elixir counterparts without the colon (
:).
They are represented by lowercase strings and underscores:
Elixir:
:example
Erlang:
example.
Strings
In Elixir when we talk about strings we mean UTF-8 encoded binaries. In Erlang, strings still use double quotes but refer to char lists:
Elixir:
iex> is_list('Example') true iex> is_list("Example") false iex> is_binary("Example") true iex> <<"Example">> === "Example" true
Erlang:
1> is_list('Example'). false 2> is_list("Example"). true 3> is_binary("Example"). false 4> is_binary(<<"Example">>). true
It’s important to note that many older Erlang libraries may not support binaries so we need to convert Elixir strings to char lists.
Thankfully this is easy to accomplish with the
to_charlist/1 function:
iex> :string.words("Hello World") ** (FunctionClauseError) no function clause matching in :string.strip_left/2 The following arguments were given to :string.strip_left/2: # 1 "Hello World" # 2 32 (stdlib) string.erl:1661: :string.strip_left/2 (stdlib) string.erl:1659: :string.strip/3 (stdlib) string.erl:1597: :string.words/2 iex> "Hello World" |> to_charlist() |> :string.words 2
Variables
In Erlang, variables begin with an uppercase letter and re-binding is not allowed.
Elixir:
iex> x = 10 10 iex> x = 20 20 iex> x1 = x + 10 30
Erlang:
1> X = 10. 10 2> X = 20. ** exception error: no match of right hand side value 20 3> X1 = X + 10. 20
That’s it! Leveraging Erlang from within our Elixir applications is easy and effectively doubles the number of libraries available to us.
Caught a mistake or want to contribute to the lesson? Edit this page on GitHub! | https://elixirschool.com/en/lessons/advanced/erlang/ | CC-MAIN-2021-25 | refinedweb | 511 | 67.55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.