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
Assuming that the "HelloWorld.java" contains the following Java source: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } } (For an explanation of the above code, please refer to Getting started with Java Language .) We can compile the above file using this command: $ javac HelloWorld.java This produces a file called "HelloWorld.class", which we can then run as follows: $ java HelloWorld Hello world! The key points to note from this example are: HelloWorld. If they don't match, you will get a compilation error. java, you supply the classname NOT the bytecode filename. Most practical Java code uses packages to organize the namespace for classes and reduce the risk of accidental class name collision. If we wanted to declare the HelloWorld class in a package call com.example, the "HelloWorld.java" would contain the following Java source: package com.example; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } } This source code file needs to stored in a directory tree whose structure corresponds to the package naming. . # the current directory (for this example) | ----com | ----example | ----HelloWorld.java We can compile the above file using this command: $ javac com/example/HelloWorld.java This produces a file called "com/example/HelloWorld.class"; i.e. after compilation, the file structure should look like this: . # the current directory (for this example) | ----com | ----example | ----HelloWorld.java ----HelloWorld.class We can then run the application as follows: $ java com.example.HelloWorld Hello world! Additional points to note from this example are: If your application consists of multiple source code files (and most do!) you can compile them one at a time. Alternatively, you can compile multiple files at the same time by listing the pathnames: $ javac Foo.java Bar.java or using your command shell's filename wildcard functionality .... $ javac *.java $ javac com/example/*.java $ javac */**/*.java #Only works on Zsh or with globstar enabled on your shell This will compile all Java source files in the current directory, in the "com/example" directory, and recursively in child directories respectively. A third alternative is to supply a list of source filenames (and compiler options) as a file. For example: $ javac @sourcefiles where the sourcefiles file contains: Foo.java Bar.java com/example/HelloWorld.java Note: compiling code like this is appropriate for small one-person projects, and for once-off programs. Beyond that, it is advisable to select and use a Java build tool. Alternatively, most programmers use a Java IDE (e.g. NetBeans, eclipse, IntelliJ IDEA) which offers an embedded compiler and incremental building of "projects". Here are a few options for the javac command that are likely to be useful to you -doption sets a destination directory for writing the ".class" files. -sourcepathoption sets a source code search path. -cpor -classpathoption sets the search path for finding external and previously compiled classes. For more information on the classpath and how to specify it, refer to the The Classpath Topic. -versionoption prints the compiler's version information. A more complete list of compiler options will be described in a separate example. The definitive reference for the javac command is the Oracle manual page for javac.
https://riptutorial.com/java/example/15658/the--javac--command---getting-started
CC-MAIN-2021-43
refinedweb
531
50.94
Understanding ASP.NET View State Scott Mitchell 4GuysFromRolla.com May 2004 Applies to: Microsoft® ASP.NET Microsoft® Visual Studio® .NET Summary: Scott Mitchell looks at the benefits of and confusion around View State in Microsoft® ASP.NET. In addition, he shows you how you can interpret (and protect) the data stored in View State. (25 printed pages) Introduction Microsoft® ASP.NET view state, in a nutshell, is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks. In my experiences as a trainer and consultant, can easily get very large, on the order of tens of kilobytes. Not only does the __VIEWSTATE form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well. This article aims to be an in-depth examination of the ASP.NET view state. We'll look at exactly what view state is storing, and how the view state is serialized to the hidden form field and deserialized back on postback. We'll also discuss techniques for reducing the bandwidth required by the view state. Note This article is geared toward the ASP.NET page developer rather than the ASP.NET server control developer. This article therefore does not include a discussion on how a control developer would implement saving state. For an in-depth discussion on that issue, refer to the book Developing Microsoft ASP.NET Server Controls and Components. Before we can dive into our examination of view state, it is important that we first take a quick moment to discuss the ASP.NET page life cycle. That is, what exactly happens when a request comes in from a browser for an ASP.NET Web page? We'll step through this process in the next section. The ASP.NET Page 1). Figure 1. ASP.NET Page Handling. Note A detailed discussion of the steps leading up to the ASP.NET page life cycle is beyond the scope of this article. For more information read Michele Leroux-Bustamante's Inside IIS & ASP.NET. For a more detailed look at HTTP handlers, which are the endpoints of the ASP.NET pipeline, check out my previous article on HTTP Handlers. What is important to realize is that each and every time an ASP.NET Web page is requested it goes through these same life cycle stages (shown in Figure 2). Figure 2. Events in the Page Life Cycle Stage 0 - Instantiation The life cycle of the ASP.NET page begins with instantiation of the class that represents the requested ASP.NET Web page, but how is this class created? Where is it stored? ASP.NET Web pages, as you know, are made up of both an HTML portion and a code portion, with the HTML portion containing HTML markup and Web control syntax. The ASP.NET engine converts the HTML portion from its free-form text representation into a series of programmatically-created Web controls. When an ASP.NET Web page is visited for the first time after a change has been made to the HTML markup or Web control syntax in the .aspx page, the ASP.NET engine auto-generates a class. If you created your ASP.NET Web page using the code-behind technique, this autogenerated class is derived from the page's associated code-behind class (note that the code-behind class must be derived itself, either directly or indirectly, from the System.Web.UI.Page class); if you created your page with an in-line, server-side <script> block, the class derives directly from System.Web.UI.Page. In either case, this autogenerated class, along with a compiled instance of the class, is stored in the folder, in part so that it doesn't need to be recreated for each page request. WINDOWS \Microsoft.NET\Framework\ version \Temporary ASP.NET Files The purpose of this autogenerated class is to programmatically create the page's control hierarchy. That is, the class is responsible for programmatically creating the Web controls specified in the page's HTML portion. This is done by translating the Web control syntax— —into the class's programming language (C# or Microsoft® Visual Basic® .NET, most typically). In addition to the Web control syntax being converted into the appropriate code, the HTML markup present in the ASP.NET Web page's HTML portion is translated to Literal controls. <asp: WebControlName Prop1="Value1" ... /> All ASP.NET server controls can have a parent control, along with a variable number of child controls. The System.Web.UI.Page class is derived from the base control class ( System.Web.UI.Control), and therefore also can have a set of child controls. The top-level controls declared in an ASP.NET Web page's HTML portion are the direct children of the autogenerated Page class. Web controls can also be nested inside one another.. Since server controls can have children, and each of their children may have children, and so on, a control and its descendents form a tree of controls. This tree of controls is called the control hierarchy. The root of the control hierarchy for an ASP.NET Web page is the Page-derived class that is autogenerated by the ASP.NET engine. Whew! Those last few paragraphs may have been a bit confusing, as this is not the easiest subject to discuss or digest. To clear out any potential confusion, let's look at a quick example. Imagine you have an ASP.NET Web page with the following autogenerated that contains code to programmatically build up the control hierarchy. The control hierarchy for this example can be seen in Figure 3. Figure 3. Control Hierarchy for sample page This control hierarchy is then converted to code that is similar to the following: Page.Controls.Add( new LiteralControl(@"<html>\r\n<body>\r\n <h1>Welcome to my Homepage!</h1>\r\n")); HtmlForm Form1 = new HtmlForm(); Form1.ID = "Form1"; Form1.Method = "post"; Form1.Controls.Add( new LiteralControl("\r\nWhat is your name?\r\n")); TextBox TextBox1 = new TextBox(); TextBox1.ID = "txtName"; Form1.Controls.Add(TextBox1); Form1.Controls.Add( new LiteralControl("\r\n<br />What is your gender?\r\n")); DropDownList DropDownList1 = new DropDownList(); DropDownList1.ID = "ddlGender"; ListItem ListItem1 = new ListItem(); ListItem1.Selected = true; ListItem1.Value = "M"; ListItem1.Text = "Male"; DropDownList1.Items.Add(ListItem1); ListItem ListItem2 = new ListItem(); ListItem2.Value = "F"; ListItem2.Text = "Female"; DropDownList1.Items.Add(ListItem2); ListItem ListItem3 = new ListItem(); ListItem3.Value = "U"; ListItem3.Text = "Undecided"; DropDownList1.Items.Add(ListItem3); Form1.Controls.Add( new LiteralControl("\r\n<br /> \r\n")); Button Button1 = new Button(); Button1.Text = "Submit!"; Form1.Controls.Add(Button1); Form1.Controls.Add( new LiteralControl("\r\n</body>\r\n</html>")); Controls.Add(Form1); Note The C# source code above is not the precise code that is autogenerated by the ASP.NET engine. Rather, it's a cleaner and easier to read version of the autogenerated code. To see the full autogenerated code—which won't win any points for readability—navigate to the folder and open one of thefolder and open one of the WINDOWS \Microsoft.NET\Framework\ Version \Temporary ASP.NET Files .csor .vbfiles. One thing to notice is that, when the control hierarchy is constructed, the properties that are explicitly set in the declarative syntax of the Web control are assigned in the code. (For example, the Button Web control has its Text property set to "Submit!" in the declarative syntax – Text="Submit!" – as well as in the autogenerated class— Button1.Text = "Submit!";. Stage 1 - Initialization After the control hierarchy has been built, the Page, along with all of the controls in its control hierarchy, enter the initialization stage. This stage is marked by having the Page and controls fire their Init events. At this point in the page life cycle, the control hierarchy has been constructed, and the Web control properties that are specified in the declarative syntax have been assigned. We'll look at the initialization stage in more detail later in this article. With regards to view state it is important for two reasons; first, server controls don't begin tracking view state changes until right at the end of the initialization stage. Second, when adding dynamic controls that need to utilize view state, these controls will need to be added during the Page's Init event as opposed to the Load event, as we'll see shortly. Stage 2 - Load View State The load view state stage only happens when the page has been posted back. During this stage, the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchy Page. It is during this stage that the view state is validated. As we'll discuss later in this article, the view state can become invalid due to a number of reasons, such as view state tampering, and injecting dynamic controls into the middle of the control hierarchy. of theof the Stage 3 - Load Postback Data The load postback data stage also only happens when the page has been posted back. A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data. To help clarify things, let's look at a simple example. One nice thing about ASP.NET is that the Web controls in a Web Form remember their values across postback. That is, if you have a TextBox Web control on a page and the user enters some value into the TextBox and posts back the page, the TextBox's Text property is automatically updated to the user's entered value. This happens because the TextBox Web control implements the IPostBackDataHandler interface, and the Page class hands off the appropriate value to the TextBox class, which then updates its Text property. To concretize things, imagine that we have an ASP.NET Web page with a TextBox whose ID property is set to txtName. When the page is first visited, the following HTML will be rendered for the TextBox: <input type="text" id="txtName" name="txtName" />. When the user enters a value into this TextBox (such as, "Hello, World!") and submits the form, the browser will make a request to the same ASP.NET Web page, passing the form field values back in the HTTP POST headers. These include the hidden form field values (such as __VIEWSTATE), along with the value from the txtName TextBox. When the ASP.NET Web page is posted back in the load postback data stage, the Page class sees that one of the posted back form fields corresponds to the IPostBackDataHandler interface. There is such a control in the hierarchy, so the TextBox's LoadPostData() method is invoked, passing in the value the user entered into the TextBox ("Hello, World!"). The TextBox's LoadPostData() method simply assigns this passed in value to its Text property. Notice that in our discussion on the load postback data stage, there was no mention of view state. You might naturally be wondering, therefore, why I bothered to mention the load postback data stage in an article about view state. The reason is to note the absence of view state in this stage. It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler. Stage 4 - Load This is the stage with which all ASP.NET developers are familiar, as we've all created an event handler for a page's Load event ( Page_Load). When the Load event fires, the view state has been loaded (from stage 2, Load View State), along with the postback data (from stage 3, Load Postback Data). If the page has been posted back, when the Load event fires we know that the page has been restored to its state from the previous page visit. Stage 5 - Raise Postback Event Certain server controls raise events with respect to changes that occurred between postbacks. For example, the DropDownList Web control has a SelectedIndexChanged event, which fires if the DropDownList's SelectedIndex has changed from the SelectedIndex value in the previous page load. Another example: if the Web Form was posted back due to a Button Web control being clicked, the Button's Click event is fired during this stage. There are two flavors of postback events. The first is a changed event. This event fires when some piece of data is changed between postbacks. An example is the DropDownLists SelectedIndexChanged event, or the TextBox's TextChanged event. Server controls that provide changed events must implement the IPostBackDataHandler interface. The other flavor of postback events is the raised event. These are events that are raised by the server control for whatever reason the control sees fit. For example, the Button Web control raises the Click event when it is clicked, and the Calendar control raises the VisibleMonthChanged event when the user moves to another month. Controls that fire raised events must implement the IPostBackEventHandler interface. Since this stage inspects postback data to determine if any events need to be raised, the stage only occurs when the page has been posted back. As with the load postback data stage, the raise postback event stage does not use view state information at all. Whether or not an event is raised depends on the data posted back in the form fields. Stage 6 - Save View State In the save view state stage, the Page class constructs the page's view state, which represents the state that must persist across postbacks. The page accomplishes this by recursively calling the SaveViewState() method of the controls in its control hierarchy. This combined, saved state is then serialized into a base-64 encoded string. In stage 7, when the page's Web Form is rendered, the view state is persisted in the page as a hidden form field. Stage 7 - Render In the render stage the HTML that is emitted to the client requesting the page is generated. The Page class accomplishes this by recursively invoking the RenderControl() method of each of the controls in its hierarchy. These seven stages are the most important stages with respect to understanding view state. (Note that I did omit a couple of stages, such as the PreRender and Unload stages.) As you continue through the article, keep in mind that every single time an ASP.NET Web page is requested, it proceeds through these series of stages. The Role of View State View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state. For example, imagine we have a Label Web control in the HTML portion with the following declarative syntax: <asp:Label</asp:Label> When the control hierarchy is built in the instantiation stage, the Label's Text property will be set to "Hello, World!" and its Font property will have its Name property set to Verdana. Since these properties will be set each and every page visit during the instantiation stage, there's no need to persist this information in the view state. What needs to be stored in the view state is any programmatic changes to the page's state. For example, suppose that in addition to this Label Web control, the page also contained two Button Web controls, a Change Message Button and an Empty Postback button. The Change Message Button has a Click event handler that assigns the Label's Text property to "Goodbye, Everyone!"; the Empty Postback Button just causes a postback, but doesn't execute any code. The change to the Label's Text property in the Change Message Button would need to be saved in the view state. To see how and when this change would be made, let's walk through a quick example. Assuming that the HTML portion of the page contains the following markup: <asp:Label</asp:Label> <br /> <asp:Button</asp:Button> <br /> <asp:Button</asp:Button> And the code-behind class contains the following event handler for the Button's Click event: private void btnSubmit_Click(object sender, EventArgs e) { lblMessage.Text = "Goodbye, Everyone!"; } Figure 4 illustrates the sequence of events that transpire, highlighting why the change to the Label's Text property needs to be stored in the view state. Figure 4. Events and View State To understand why saving the Label's changed Text property in the view state is vital, consider what would happen if this information were not persisted in view state. That is, imagine that in step 2's save view state stage, no view state information was persisted. If this were the case, then in step 3 the Label's Text property would be assigned to "Hello, World!" in the instantiation stage, but would not be reassigned to "Goodbye, Everyone!" in the load view state stage. Therefore, from the end user's perspective, the Label's Text property would be "Goodbye, Everyone!" in step 2, but would seemingly be reset to its original value ("Hello, World!") in step 3, after clicking the Empty Postback button. View State and Dynamically Added Controls Since all ASP.NET server controls contain a collection of child controls exposed through the Controls property, controls can be dynamically added to the control hierarchy by appending new controls to a server control's Controls collection. A thorough discussion of dynamic controls is a bit beyond the scope of this article, so we won't cover that topic in detail here; instead, we'll focus on how to manage view state for controls that are added dynamically. (For a more detailed lesson on using dynamic controls, check out Dynamic Controls in ASP.NET and Working with Dynamically Created Controls.) Recall that in the page life cycle, the control hierarchy is created and the declarative properties are set in the instantiation stage. Later, in the load view state stage, the state that had been altered in the prior page visit is restored. Thinking a bit about this, three things become clear when working with dynamic controls: - Since the view state only persists changed control state across postbacks, and not the actual controls themselves, dynamically added controls must be added to the ASP.NET Web page, on both the initial visit as well as all subsequent postbacks. - Dynamic controls are added to the control hierarchy in the code-behind class, and therefore are added at some point after the instantiation stage. - The view state for these dynamically added controls is automatically saved in the save view state stage. (What happens on postback if the dynamic controls have not yet been added by the time the load view state stage rolls, however?) So, dynamically added controls must be programmatically added to the Web page on each and every page visit. The best time to add these controls is during the initialization stage of the page life cycle, which occurs before the load view state stage. That is, we want to have the control hierarchy complete before the load view state stage arrives. For this reason, it is best to create an event handler for the Page class's Init event in your code-behind class, and add your dynamic controls there. Note You may be able to get away with loading your controls in the Page_Loadevent handler and maintaining the view state properly. It all depends on whether or not you are setting any properties of the dynamically loaded controls programmatically and, if so, when you're doing it relative to the line. A thorough discussion of this is a bit beyond the scope of this article, but the reason it may work is because theline. A thorough discussion of this is a bit beyond the scope of this article, but the reason it may work is because the Controls.Add( dynamicControl ) Controlsproperty's Add()method recursively loads the parent's view state into its children, even though the load view state stage has passed. When adding a dynamic control c to some parent control p based on some condition (that is, when not loading them on each and every page visit), you need to make sure that you add c to the end of p's Controls collection. The reason is because the view state for p contains the view state for p's children as well, and, as we'll discuss in the "Parsing the View State" section, p's view state specifies the view state for its children by index. (Figure 5 illustrates how inserting a dynamic control somewhere other than the end of the Controls collection can cause a corrupted view state.) Figure 5. Effect of inserting controls on View State The ViewState Property Each control is responsible for storing its own state, which is accomplished by adding its changed state to its ViewState property. The ViewState property is defined in the System.Web.UI.Control class, meaning that all ASP.NET server controls have this property available. (When talking about view state in general I'll use lower case letters with a space between view and state; when discussing the ViewState property, I'll use the correct casing and code-formatted text.) If you examine the simple properties of any ASP.NET server control you'll see that the properties read and write directly to the view state. (You can view the decompiled source code for a .NET assembly by using a tool like Reflector.) For example, consider the HyperLink Web control's NavigateUrl property. The code for this property looks like so:. Note All Web controls use the above pattern for simple properties. Simple properties are those that are scalar values, like strings, integers, Booleans, and so on. Complex properties, such as the Label's Font property, which might be classes themselves, use a different approach. Consult the book Developing Microsoft ASP.NET Server Controls and Components for more information on state maintenance techniques for ASP.NET server controls. The ViewState property is of type System.Web.UI.StateBag. The StateBag class provides a means to store name and value pairs, using a System.Collections.Specialized.HybridDictionary behind the scenes. As the NavigateUrl property syntax illustrates, items can be added to and queried from the StateBag using the same syntax you could use to access items from a Hashtable. Timing the Tracking of View State Recall that earlier I said the view state only stores state that needs to be persisted across postbacks. One bit of state that does not need to be persisted across postbacks is the control's properties specified in the declarative syntax, since they are automatically reinstated in the page's instantiation stage. For example, if we have a HyperLink Web control on an ASP.NET Web page and declaratively set the NavigateUrl property to then this information doesn't need to be stored in the view state. Seeing the HyperLink control's NavigateUrl property's code, however, it looks as if the control's ViewState is written to whenever the property value is set. In the instantiation stage, therefore, where we'd have something like HyperLink1.NavigateUrl =;, it would only make sense that this information would be stored in the view state. Regardless of what might seem apparent, this is not the case. The reason is because the StateBag class only tracks changes to its members after its TrackViewState() method has been invoked. That is, if you have a StateBag, any and all additions or modifications that are made before TrackViewState() is made will not be saved when the SaveViewState() method is invoked. The TrackViewState() method is called at the end of the initialization stage, which happens after the instantiation stage. Therefore, the initial property assignments in the instantiation stage—while written to the ViewState in the properties' set accessors—are not persisted during the SaveViewState() method call in the save view state stage, because the TrackViewState() method has yet to be invoked. Note The reason the StateBaghas the TrackViewState()method is to keep the view state as trimmed down as possible. Again, we don't want to store the initial property values in the view state, as they don't need to be persisted across postbacks. Therefore, the TrackViewState()method allows the state management to begin after the instantiation and initialization stages. Storing Information in the Page's ViewState Property Since the Page class is derived from the System.Web.UI.Control class, it too has a ViewState property. In fact, you can use this property to persist page-specific and user-specific information across postbacks. From an ASP.NET Web page's code-behind class, the syntax to use is simply: ViewState[keyName] = value There are a number of scenarios when being able to store information in the Page's's ViewState. For more information on creating sortable, pageable DataGrids (or a pageable, sortable, editable DataGrid), pick up a copy of my book ASP.NET Data Web Controls Kick Start. The Cost of View State Nothing comes for free, and view state is no exception. The ASP.NET view state imposes two performance hits whenever an ASP.NET Web page is requested: - On all page visits, during the save view state stage the Pageclass gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __VIEWSTATEform filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy. - The __VIEWSTATEhiddenform field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time. If you are designing a Web site that is commonly accessed by users coming over a modem connection, you should be particularly concerned with the bloat the view state might add to a page. Fortunately, there are a number of techniques that can be employed to reduce view state size. We'll first see how to selectively indicate whether or not a server control should save its view state. If a control's state does not need to be persisted across postbacks, we can turn off view state tracking for that control, thereby saving the extra bytes that would otherwise have been added by that control. Following that, we'll examine how to remove the view state from the page's hidden form fields altogether, storing the view state instead on the Web server's file system. Disabling the View State In the save view state stage of the ASP.NET page life cycle, the Page class recursively iterates through the controls in its control hierarchy, invoking each control's SaveViewState() method. This collective state is what is persisted to the hidden __VIEWSTATE form field. By default, all controls in the control hierarchy will record their view state when their SaveViewState() method is invoked. As a page developer, however, you can specify that a control should not save its view state or the view state of its children controls by setting the control's EnableViewState property to False (the default is True). The EnableViewState property is defined in the System.Web.UI.Control class, so all server controls have this property, including the Page class. You can therefore indicate that an entire page's view state need not be saved by setting the Page class's EnableViewState to False. (This can be done either in the code-behind class with Page.EnableViewState = false; or as a @Page-level directive— <%@Page EnableViewState="False" %>.) Not all Web controls record the same amount of information in their view state. The Label Web control, for example, records only programmatic changes to its properties, which won't greatly impact the size of the view state. The DataGrid, however, stores all of its contents in the view state. For a DataGrid with many columns and rows, the view state size can quickly add up! For example, the DataGrid shown in Figure 6 (and included in this article's code download as HeavyDataGrid.aspx) has a view state size of roughly 2.8 kilobytes, and a total page size of 5,791 bytes. (Almost half of the page's size is due to the __VIEWSTATE hidden form field!) Figure 7 shows a screenshot of the view state, which can be seen by visiting the ASP.NET Web page, doing a View\Source, and then locating the __VIEWSTATE hidden form field. Figure 6. DataGrid control Figure 7. View State for DataGrid control The download for this article also includes an ASP.NET Web page called LightDataGrid.aspx, which has the same DataGrid as shown in Figure 6, but with the EnableViewState property set to False. The total view state size for this page? 96 bytes. The entire page size clocks in a 3,014 bytes. LightDataGrid.aspx boasts a view state size about 1/30th the size of HeavyDataGrid.aspx, and a total download size that's about half of HeavyDataGrid.aspx. With wider DataGrids with more rows, this difference would be even more pronounced. (For more information on performance comparisons between view state-enabled DataGrids and view state-disabled DataGrids, refer to Deciding When to Use the DataGrid, DataList, or Repeater.) Hopefully the last paragraph convinces you of the benefit of intelligently setting the EnableViewState property to False, especially for "heavy" view state controls like the DataGrid. The question now, is, "When can I safely set the EnableViewState property to False?" To answer that question, consider when you need to use the view state—only when you need to remember state across postbacks. The. If, however, you set a DataGrid's EnableViewState property to False, you'll need to rebind the database data to the DataGrid on both the first page load and every subsequent postback. For a Web page that has a read-only DataGrid, like the one in Figure 6, you'd definitely want to set the DataGrid's EnableViewState property to False. You can even create sortable and pageable DataGrids with the view state disabled (as can be witnessed in the LightDataGrid-WithFeatures.aspx page, included in the download), but, again, you'll need to be certain to bind the database data to the DataGrid on the first page visit, as well as on all subsequent postbacks. Note Creating an editable DataGrid with disabled view state requires some intricate programming, which involves parsing of the posted back form fields in the editable DataGrid. Such strenuous effort is required because, with an editable DataGrid blindly rebinding, the database data to the DataGrid will overwrite any changes the user made (see this FAQ for more information). Specifying Where to Persist the View State After the page has collected the view state information for all of the controls in its control hierarchy in the save view state stage, it persists it to the __VIEWSTATE hidden form field. This hidden form field can, of course, greatly add to the overall size of the Web page.. With just a bit of work we can have the view state. Note There is a third-party product called Flesk.ViewStateOptimizer that reduces the view state bloat using a similar technique.: - Strings - Integers - Booleans - Arrays ArrayLists Hashtables Pairs Triplets Note The Pairand Tripletare two classes found in the System.Web.UInamespace, and provide a single class to store either two or three objects. The Pairclass has properties Firstand Secondto access its two elements, while Triplethas First, Second, and Thirdas properties. The SavePageStateToPersistenceMedium() method is called from the Page class and passed in the combined view state of the page's control hierarchy. When overriding this method, we need to use the LosFormatter() to serialize the view state to a base-64 encoded string, and then store this string in a file on the Web server's file system. There are two main challenges with this approach: - Coming up with an acceptable file naming scheme. Since the view state for a page will likely vary based on the user's interactions with the page, the stored view state must be unique for each user and for each page. - Removing the view state files from the file system when they are no longer needed. To tackle the first challenge, we'll name the persisted view state file based on the user's SessionID and the page's URL. This approach will work beautifully for all users whose browsers accept session-level cookies. Those who do not accept cookies, however, will have a unique session ID generated for them on each page visit, thereby making this naming technique unworkable for them. For this article I'm just going to demonstrate using the SessionID / URL file name scheme, although it won't work for those whose browsers are configured not to accept cookies. Also, it won. To persist view state information to a file, we start by creating a class that derives from the Page class. This derived class, then, needs to override the SavePageStateToPersistenceMedium() and LoadPageStateFromPersistenceMedium() methods. The following code presents such a class: public class PersistViewStateToFileSystem : Page { protected override void SavePageStateToPersistenceMedium(object viewState) { // serialize the view state into a base-64 encoded string LosFormatter los = new LosFormatter(); StringWriter writer = new StringWriter(); los.Serialize(writer, viewState); // save the string to disk StreamWriter sw = File.CreateText(ViewStateFilePath); sw.Write(writer.ToString()); sw.Close(); }); } } public string ViewStateFilePath { get { string folderName = Path.Combine(Request.PhysicalApplicationPath, "PersistedViewState"); string fileName = Session.SessionID + "-" + Path.GetFileNameWithoutExtension(Request.Path).Replace("/", "-") + ".vs"; return Path.Combine(folderName, fileName); } } } The class contains a public property ViewStateFilePath, which returns the physical path to the file where the particular view state information will be stored. This file path is dependent upon the user's SessionID and the URL of the requested page. Notice that the SavePageStateToPersistenceMedium() method accepts an object input parameter. This object is the view state object that is built up from the save view state stage. The job of SavePageStateToPersistenceMedium() is to serialize this object and persist it in some manner. The method's code simply creates an instance of the LosFormatter object and invokes its Serialize() method, serializing the passed-in view state information to the StringWriter writer. Following that, the specified file is created (or overwritten, if it already exists) with the contents of the base-64 encoded, serialized view state string. The LoadPageStateFromPersistenceMedium() method is called at the beginning of the load view state stage. Its job is to retrieve the persisted view state and deserialize back into an object that can be propagated into the page's control hierarchy. This is accomplished by opening the same file where the persisted view state was stored on the last visit, and returning the deserialized version via the Deserialize() method in LosFormatter(). Again, this approach won't work with users that do not accept cookies, but for those that do, the view state is persisted entirely on the Web server's file system, thereby adding 0 bytes to the overall page size! Note Another approach to reducing the bloat imposed by view state is to compress the serialized view state stream in the SavePageStateToPersistenceMedium()method, and then decompress it back to its original form in the LoadPageStateFromPersistenceMedium()method. Scott Galloway has a blog entry where he discusses his experiences with using #ziplib library to compress the view state. Parsing the View State When a page is rendered, it serializes its view state into a base-64 encoded string using the LosFormatter class and (by default) stores it in a hidden form field. On postback, the hidden form field is retrieved and deserialized back into the view state's object representation, which is then used to restore the state of the controls in the control hierarchy. One detail we have overlooked up to this point in the article is what, exactly, is the structure of the Page class's view state object? As we discussed earlier, entire view state of the Page is the sum of the view state of the controls in its control hierarchy. Put another way, at any point in the control hierarchy, the view state of that control represents the view state of that control along with the view state of all of its children controls. Since the Page class forms the root of the control hierarchy, its view state represents the view state for the entire control hierarchy. The Page class contains a SavePageViewState(), which is invoked during the page life cycle's save view state stage. The SavePageViewState() method starts by creating a Triplet that contains the following three items: - The page's hash code. This hash code is used to ensure that the view state hasn't been tampered with between postbacks. We'll talk more about view state hashing in the "View State and Security Implications" section. - The collective view state of the Page's control hierarchy. - An ArrayListof controls in the control hierarchy that need to be explicitly invoked by the page class during the raise postback event stage of the life cycle. The First and Third items in the Triplet are relatively straightforward; the Second item is where the view state for the Page's control hierarchy is maintained. The Second item is generated by the Page by calling the SaveViewStateRecursive() method, which is defined in the System.Web.UI.Control class. SaveViewStateRecursive() saves the view state of the control and its descendents by returning a Triplet with the following information: - The state present in the Control's ViewState StageBag. - An ArrayListof integers. This ArrayListmaintains the indexes of the Control's child controls that have a non- nullview state. - An ArrayListof the view states for the children controls. The ith view state in this ArrayListmaps to the child control index in the ith item in the ArrayListin the Triplet's Seconditem. The Control class computes the view state, returning a Triplet. The Second item of the Triplet contains the view state of the Control's descendents. The end result is that the view state is comprised of many ArrayLists inside of Triplets inside of Triplets, inside of Triplets, inside of... (The precise contents in the view state depend on the controls in the hierarchy. More complex controls might serialize their own state to the view state using Pairs or object arrays. As we'll see shortly, though, the view state is composed of a number of Triplets and ArrayLists nested as deep as the control hierarchy.) Programmatically Stepping Through the View State With just a little bit of work we can create a class that can parse through the view state and display its contents. The download for this article includes a class called ViewStateParser that provides such functionality. This class contains a ParseViewState() method that recursively steps through the view state. It takes in three inputs: - The current view state object. - How many levels deep we are in the view state recursion. - A text label to display. The last two input parameters are just for display purposes. The code of this method, shown below, determines the type of the current view state object and displays the contents of the view state accordingly, by recursively calling itself on each of the current object's members. (The variable tw is a TextWriter instance to which the output is being written.) protected virtual void ParseViewStateGraph( object node, int depth, string label) { tw.Write(System.Environment.NewLine); if (node == null) { tw.Write(String.Concat(Indent(depth), label, "NODE IS NULL")); } else if (node is Triplet) { tw.Write(String.Concat(Indent(depth), label, "TRIPLET")); ParseViewStateGraph( ((Triplet) node).First, depth+1, "First: "); ParseViewStateGraph( ((Triplet) node).Second, depth+1, "Second: "); ParseViewStateGraph( ((Triplet) node).Third, depth+1, "Third: "); } else if (node is Pair) { tw.Write(String.Concat(Indent(depth), label, "PAIR")); ParseViewStateGraph(((Pair) node).First, depth+1, "First: "); ParseViewStateGraph(((Pair) node).Second, depth+1, "Second: "); } else if (node is ArrayList) { tw.Write(String.Concat(Indent(depth), label, "ARRAYLIST")); // display array values for (int i = 0; i < ((ArrayList) node).Count; i++) ParseViewStateGraph( ((ArrayList) node)[i], depth+1, String.Format("({0}) ", i)); } else if (node.GetType().IsArray) { tw.Write(String.Concat(Indent(depth), label, "ARRAY ")); tw.Write(String.Concat("(", node.GetType().ToString(), ")")); IEnumerator e = ((Array) node).GetEnumerator(); int count = 0; while (e.MoveNext()) ParseViewStateGraph( e.Current, depth+1, String.Format("({0}) ", count++)); } else if (node.GetType().IsPrimitive || node is string) { tw.Write(String.Concat(Indent(depth), label)); tw.Write(node.ToString() + " (" + node.GetType().ToString() + ")"); } else { tw.Write(String.Concat(Indent(depth), label, "OTHER - ")); tw.Write(node.GetType().ToString()); } } As the code shows, the ParseViewState() method iterates through the expected types— Triplet, Pair, ArrayList, arrays, and primitive types. For scalar values—integers, strings, etc.—the type and value are displayed; for aggregate types—arrays, Pairs, Triplets, etc.—the members that compose the type are displayed by recursively invoking ParseViewState(). The ViewStateParser class can be utilized from an ASP.NET Web page (see the ParseViewState.aspx demo), or can be accessed directly from the SavePageStateToPersistenceMedium() method in a class that is derived from the Page class (see the ShowViewState class). Figures 8 and9 show the ParseViewState.aspx demo in action. As Figure 8 shows, the user is presented with a multi-line textbox into which they can paste the hidden __VIEWSTATE form field from some Web page. Figure 9 shows a snippet of the parsed view state for a page displaying file system information in a DataGrid. Figure 8. Decoding ViewState Figure 9. ViewState decoded In addition to the view state parser provided in this article's download, Paul Wilson provides a view state parser on his Web site. Fritz Onion also has a view state decoder WinForms application available for download from the Resources section on his Web site. View State and Security Implications The view state for an ASP.NET Web page is stored, by default, as a base-64 encoded string. As we saw in the previous section,, as we'll see over the next two sections. Before we delve into the solutions for these concerns, it is important to first note that view state should only be used to store non-sensitive data. View state does not house code, and should definitely not be used to place sensitive information like connection strings or passwords. Protecting the View State from Modification Even though view state should only store the state of the Web controls on the page and other non-sensitive data, nefarious users could cause you headaches if they could successfully modify the view state for a page. For example, imagine that you ran an eCommerce Web site that used a DataGrid to display a list of products for sale along with their cost. Unless you set the DataGrid's EnableViewState property to False, the DataGrid's contents—the names and prices of your merchandise—will be persisted in the view state. Nefarious users could parse the view state, modify the prices so they all read $0.01, and then deserialize the view state back to a base-64 encoded string. They could then send out e-mail messages or post links that, when clicked, submitted a form that sent the user to your product listing page, passing along the altered view state in the HTTP POST headers. Your page would read the view state and display the DataGrid data based on this view state. The end result? You'd have a lot of customers thinking they were going to be able to buy your products for only a penny! A simple means to protect against this sort of tampering is to use a machine authentication check, or MAC. Machine authentication checks are designed to ensure that the data received by a computer is the same data that it transmitted out—namely, that it hasn't been tampered with. This is precisely what we want to do with the view state. With ASP.NET view state, the LosFormatter performs a MAC by hashing the view state data being serialized, and appending this hash to the end of the view state. (A hash is a quickly computed digest that is commonly used in symmetric security scenarios to ensure message integrity.) When the Web page is posted back, the LosFormatter checks to ensure that the appended hash matches up with the hashed value of the deserialized view state. If it does not match up, the view state has been changed en route. By default, the LosFormatter class applies the MAC. You can, however, customize whether or not the MAC occurs by setting the Page class's EnableViewStateMac property. The default, True, indicates that the MAC should take place; a value of False indicates that it should not. You can further customize the MAC by specifying what hashing algorithm should be employed. In the machine.config file, search for the <machineKey> element's validation attribute. The default hashing algorithm used is SHA1, but you can change it to MD5 if you like. (For more information on the SHA1, see RFC 3174; for more information on MD5, read RFC 1321.) Note When using Server.Transfer()you may find you receive a problem with view state authentication. A number of articles online have mentioned that the only workaround is to set EnableViewStateMacto False. While this will certainly solve the problem, it opens up a security hole. For more information, including a secure workaround, consult this KB article. Encrypting the View State Property Microsoft® ASP.NET version 1.1 added an additional Page class property— ViewStateUserKey. This property, if used, must be assigned a string value in the initialization stage of the page life cycle (in the Page_Init event handler). The point of the property is to assign some user-specific key to the view state, such as a username. The ViewStateUserKey, if provided, is used as a salt to the hash during the MAC. What the ViewStateUserKey property protects against is the case where a nefarious user visits a page, gathers the view state, and then entices a user to visit the same page, passing in their view state (see Figure 10). For more information on this property and its application, refer to Building Secure ASP.NET Pages and Controls. Figure 10. Protecting against attacks. In our discussions on the page life cycle, we saw that certain stages—such as loading postback data and raising postback events—were not in any way related to view state. While view state enables state to be effortlessly persisted across postbacks, it comes at a cost, and that cost is page bloat. Since the view state data is persisted to a hidden form field, view state can easily add tens of kilobytes of data to a Web page, thereby increasing both the download and upload times for Web pages. To cut back on the page weight imposed by view state, you can selectively instruct various Web controls not to record their view state by setting the EnableViewState property to False. In fact, view state can be turned off for an entire page by setting the EnableViewState property to false in the @Page directive. In addition to turning off view state at the page-level or control-level, you can also specify an alternate backing store for view state, such as the Web server's file system. This article wrapped up with a look at security concerns with view state. By default, the view state performs a MAC to ensure that the view state hasn't been tampered with between postbacks. ASP.NET 1.1 provides the ViewStateUserKey property to add an additional level of security. The view state's data can be encrypted using the Triple DES encryption algorithm, as well. Happy Programming! Works Consulted There are a number of good resources for learning more about ASP.NET view state. Paul Wilson has provided a number of resources, such as View State: All You Wanted to Know, and the Page View State Parser. Dino Esposito authored an article for MSDN Magazine in February, 2003, titled The ASP.NET View State, which discusses a technique for storing view state on the Web server's file system. Taking a Bite Out of ASP.NET View State, written by Susan Warren, provides a good high-level overview of the view state, including a discussion on encrypting the view state. Scott Galloway's blog has some good posts on working with ASP.NET view state, too. Special Thanks To... Before submitting my article to my MSDN editor I have a handful of volunteers help proofread the article and provide feedback on the article's content, grammar, and direction. Primary contributors to the review process for this article include James Avery, Bernard Vander Beken, Dave Donaldson, Scott Elkin, and Justin Lovell. If you are interested in joining the ever-growing list of reviewers, drop me a line at mitchell@4guysfromrolla.com. via his blog, which can be found at.
https://msdn.microsoft.com/library/ms972976.aspx
CC-MAIN-2015-22
refinedweb
8,357
63.59
FULL PRODUCT VERSION : java version "1.6.0_06" Java(TM) SE Runtime Environment (build 1.6.0_06-b02) Java Hotspot(TM) Client VM (build 10.0-b22, mixed mode, sharing) java version "1.6.0_10" Java(TM) SE Runtime Environment (build 1.6.0_10-b33) Java HotSpot(TM) Client VM (build 11.0-b15, mixed mode, sharing) ADDITIONAL OS VERSION INFORMATION : Linux 2.6.13-15.8-smp x86_64 EXTRA RELEVANT SYSTEM CONFIGURATION : Reproduce with Mozilla 1.7.11 and Firefox 1.0.6. My colleages reproduced with Firefox 2 and Firefox 3. A DESCRIPTION OF THE PROBLEM : If I open the web browser (firefox or mozilla) and load Java applets one by one, it eventually runs out of memory (PermGen space). The reason is that it does not release old classloaders of applets that are not anymore active, and hence does not release the classes that were allocated by this classloader. If I have more than 5 applets and browse them one by one, and after the last applet I come back to the first applet, I see that its classes are reloaded again by a new classloader, even though the classes of this applet are still in the VM hold by an old classloader. The increase of the code memory can easily be observed by using jconsole. I analyzed the situation with jhat, and it seems all class loaders are kept in a HashMap in a static field of sun.awt.X11.XToolkit.winToDispatcher. This is of course a memory leak, since when the class loader is hold, all applet classes loaded by the classloader are also hold and never freed by the Garbage collection. The exact reference chain (shown by jhat) is this: Static reference from sun.awt.X11.XToolkit.winToDispatcher (from class sun.awt.X11.XToolkit) : --> java.util.HashMap@0x79d7ce38 (40 bytes) (field table:) --> [Ljava.util.HashMap$Entry;@0x79d98670 (72 bytes) (Element 8 of [Ljava.util.HashMap$Entry;@0x79d98670:) --> java.util.HashMap$Entry@0x79e75490 (24 bytes) (field value:) --> java.util.Vector@0x79e76220 (24 bytes) (field elementData:) --> [Ljava.lang.Object;@0x79e77450 (48 bytes) (Element 0 of [Ljava.lang.Object;@0x79e77450:) --> sun.awt.X11.XEmbedClientHelper@0x79e77438 (22 bytes) (field embedded:) --> sun.awt.X11.XEmbeddedFramePeer@0x79e760b8 (301 bytes) (field target:) --> sun.plugin.viewer.frame.XNetscapeEmbeddedFrame@0x79e75618 (361 bytes) (field appContext:) --> sun.awt.AppContext@0x79e755e0 (49 bytes) (field contextClassLoader:) --> sun.plugin.security.PluginClassLoader@0x79e74ac0 (123 bytes) All class loaders are hold by such a chain. Indeed the XEmbedClientHelper.install() adds itself to the XToolkit but never removes itself. I think it should remove itself when the applet is destroyed. The XEmbedClientHelper has a link chain to the AppContext, which holds the class loader. STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : In principle, it can be reproduced by creating a couple of large applets (with lots of classes) and load them one by one into the webbrowser without shutting the webbrowser down. The increase in code can be watched with jconsole. If there are many applets, you will eventually notice the OutOfMemory (PermGen space) no matter how high your PermGenSize setting is. For your conveniance, here a csh script that generated 6 large applets, each with 1000 classes: ---------------------------- cut ------------------------------------------- #!/bin/csh mkdir a mkdir b mkdir c mkdir d mkdir e mkdir f foreach d (a b c d e f) pushd . cd $d touch MyApplet.java echo "package "$d";" >> MyApplet.java echo "import java.awt.*;" >> MyApplet.java echo "import java.awt.event.*;" >> MyApplet.java echo "import javax.swing.*;" >> MyApplet.java echo "public class MyApplet extends JApplet {" >> MyApplet.java echo " public void init() {" >> MyApplet.java echo " super.init();" >> MyApplet.java echo ' JButton helpButton = new JButton("Test");' >> MyApplet.java echo " helpButton.addActionListener(new ActionListener() {" >> MyApplet.java echo " public void actionPerformed(ActionEvent evt) {" >> MyApplet.java echo ' System.err.println("Help pressed"); ' >> MyApplet.java echo " }});" >> MyApplet.java echo " JPanel panel = new JPanel(new FlowLayout());" >> MyApplet.java echo " panel.add(helpButton);" >> MyApplet.java echo " getContentPane().add(panel);" >> MyApplet.java foreach i (0 1 2 3 4 5 6 7 8 9) foreach j (0 1 2 3 4 5 6 7 8 9) foreach k (0 1 2 3 4 5 6 7 8 9) echo " new Class"$i$j$k"();" >> MyApplet.java touch Class$i$j$k.java echo "package "$d";" >> Class$i$j$k.java echo "public class Class"$i$j$k >> Class$i$j$k.java echo "{" >> Class$i$j$k.java foreach m (0 1 2 3 4 5 6 7 8 9) foreach n (0 1 2 3 4 5 6 7 8 9) echo " public void method"$m$n"() {}" >> Class$i$j$k.java end end echo "}" >> Class$i$j$k.java end end end echo " }" >> MyApplet.java echo "}" >> MyApplet.java popd end --------------------- cut ---------------------------------------- Run this script in Linux or Unix creates directories a b c d e f which contains the applet 6 times. The only difference is that package name. Compile these one by one and each package into one jar: javac -d . src/a/*.java javac -d . src/b/*.java javac -d . src/c/*.java javac -d . src/d/*.java javac -d . src/e/*.java javac -d . src/f/*.java jar cf appletA.jar a/ jar cf appletB.jar b/ jar cf appletC.jar c/ jar cf appletD.jar d/ jar cf appletE.jar e/ jar cf appletF.jar f/ Now you have 6 applets, each just containing one button. The applet creates instances of 1000 classes, just to make sure 1000 classes are loaded. The instances are garbage collectable. Now create 6 HTML files that load the applets. Here is one (index0.html): ----------------- cut here ------------------------------------------------- <HTML> <HEAD> <META http- <TITLE>Test1</TITLE> </HEAD> <BODY bgcolor="#FFFFFF"> <!--"CONVERTED_APPLET"--> <!-- HTML CONVERTER --> <OBJECT classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" codebase = "" WIDTH = "300" HEIGHT = "40" ALIGN = "baseline" > <PARAM NAME = CODE <PARAM NAME = CODEBASE <PARAM NAME = ARCHIVE <PARAM NAME = "type" VALUE = "application/x-java-applet;version=1.4"> <PARAM NAME = "scriptable" VALUE = "false"> <COMMENT> <EMBED type = "application/x-java-applet;version=1.4" CODE = "a.MyApplet" JAVA_CODEBASE = "." ARCHIVE = "appletA.jar" WIDTH = "300" HEIGHT = "40" ALIGN = "baseline" scriptable = false <NOEMBED> </NOEMBED> </EMBED> </COMMENT> </OBJECT> <!-- <APPLET CODE = "a.MyApplet" JAVA_CODEBASE = "." ARCHIVE = "appletA.jar" WIDTH = "300" HEIGHT = "40" ALIGN = "baseline"> </APPLET> --> <!--"END_CONVERTED_APPLET"--> <!--@@@--> <p> <A HREF="index1.html">NEXT</A> </BODY> </HTML> ----------------------------------- cut here ------------------------------- Create similar index1.html, index2.html ... index5.html. Each one should have the NEXT link pointing to the next one, and index5.html should have the NEXT link pointing to index0.html. Each should load a different applet, i.e. index1.html loads b.MyApplet in appletB.jar index2.html loads c.MyApplet in appletC.jar ... index5.html loads f.MyApplet in appletF.jar. Now open index0.html, wait until the applet is loaded, then repeat to click NEXT, each click loads a new applet, until OutOfMemory. If you don't want to wait until OutOfMemory, use jconsole to see the code memory increase for each applet that is loaded. When I tried this with only 3 applets, the classLoaderCache of the plugin avoided that the classes of an applet are reloaded. In this case, hit the x key in the Java Console before clicking the NEXT link to force that an previously loaded applet is reloaded. On my machine, with 6 applets, when coming from the last applet to the first applet, it is reloaded independent of hitting the x key. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - When an applet is destroyed, then all its memory should be freed. The applet classloader should not be hold by a reference chain from XToolkit. Or to say it differently: If I have 100 large applets that individually are small enough to run in the brower without OutOfMemory, then it should be possible to browse through all 100 large applets without shutting down the browser and without OutOfMemory caused by accumulated memory. ACTUAL - OutOfMemory (PermGen space) ERROR MESSAGES/STACK TRACES THAT OCCUR : OutOfMemory (PermGen space) REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- See Description. It contains a csh script to generate 6 large applets. ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : Shutting down the browser before loading the next applet avoids the OutOfMemory.
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6773985
CC-MAIN-2021-17
refinedweb
1,351
61.43
How to make a command window invisible t The solution is to use a wrapper utility to launch your program. I can send you binaries of two programs but maybe you prefer a source code. If you have acces to a C compiler use the following code: -------- CUT ------- #include <windows.h> #include <string.h> int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; char prog[] = "my_prog.exe"; WinExec(prog, SW_HIDE); return (msg.wParam); } -------- CUT ------- The unhide program is a little longer. I'll send it to you if you want. Also search : for window.zip How to make a command window invisible t In a straight scripting environment, you can't hide the CMD window from your users. You can launch it minimized by using the "start /m" command. This will put it in the systray at the bottom of the screen. All other methods of hiding the CMD prompt require writing a program to accomplish what you want to do. How to make a command window invisible t Have the Schedule Service launch the program, and set it not to be Interactive. However, you must configure the Schedule service on each system properly. You'll also have to get an exe called soon.exe, from the resource kit. SOON is similar to the AT command, except that you don't have to specify a time, it automatically executes the command line in five seconds. Example "soon C:\myscript.bat" would launch myscript.bat in 5 seconds, and would not be interactive, therefore not visible to any users. Hope this is what you wanted. How to make a command window invisible t This conversation is currently closed to new comments.
http://www.techrepublic.com/forums/discussions/how-to-make-a-command-window-invisible-t/
CC-MAIN-2017-04
refinedweb
284
68.06
Degrees: Fraud detection. Recommendation engines. Graph based search. Master data management. For us data scientists graph databases are an important tool that all of us should have at least some familiarity with. They are no silver bullet, but used right they can lead to simpler solutions in situations where traditional databases just won’t cut it. Enough talk, let me walk you through an example in Neo4j, centered around historical and current members of the German national soccer team. I’ll leave it as an exercise to the interested reader to make the connection to possible applications to fraud detection or recommendation engines. Neo4j provides a free community edition which works great and is well documented. It is very quick to set up, for testing and evaluation purposes all you have to do is download the latest release and run an executable. You can send queries to and inspect results from Neo4j in your web browser, easy as pie. Getting The Data - Web Scraping To get some data we have, like so often, to do some scraping. I’ve mentioned scrapy and beautifulsoup: def parse_tournament(self, response): soup = BeautifulSoup(response.text, "lxml") header = soup.find("span", id=re.compile(".*Germany.*")).parent All you have to do is yield the extracted entities as dictionary and write the result into a CSV file. You can then load the CSV into Neo4j as described in their documentation and start having some fun. Degrees of Rudi Völler Rudi Völler, one of the most prominent past national players, will serve us as a worthy example. So, where did he play? Easy. MATCH (:Player {name: 'Rudi Völler'})-[r:PLAYED]->(c:Club) RETURN * The cypher code above (Neo4j’s internal language is call cypher, but is in contrast to the name’s undertone quite easy to use) will give a result like shown below. ? MATCH (:Player {name: 'Rudi Völler'})-[r]->(c:Club)<-[s:MANAGED]-(p) RETURN * Voila. Since the human brain is so good at recognizing patterns (sometimes even if they’re not really there), some fraud analysts use tools like this to visualize suspected fraud rings. But what if you want to become more quantitative, asking questions like: Who played in the most clubs that Mr. Völler was either playing for or managing? MATCH (:Player {name: 'Rudi Völler'})-[]->(c:Club)<-[r:PLAYED]-(p) RETURN p.name, COUNT(r) ORDER BY -COUNT(r) LIMIT 5 Pretty nice, with a syntax easy enough that I tend to require far less googling that with some SQL dialects when I work with cypher. Now go on your own data adventure and play around with Neo4j!
http://data-adventures.com/2016/10/20/degrees-of-rudi-voller-neo4j-edition.html
CC-MAIN-2018-43
refinedweb
435
63.59
Re: errorlevel handling in DOS batch - From: Ted Davis <tdavis@xxxxxxx> - Date: Thu, 12 Jun 2008 08:04:45 -0500 On Tue, 10 Jun 2008 06:07:36 -0700, bubu.aa wrote: http:/hi I have a question in a toplevel batch I have some thing like: call mybat if NOT (%ERRORLEVEL%) == (0) echo error That will always fail fail because you are testing (assuming ERRORLEVEL is 0) if not "(0) "==" (0)" Note the locations of the spaces prevents a valid test - the correct syntax is if not (%errorlevel%)==(0) but I would advise against using () there since they have syntatical functions - it is usual to use "" or to add a punctuation character (!, for example) to avoid the possibility of testing a null string. in mybat I have some thing like /////////////////////////////////////////////////////////////// pushd %~dp0 ........ call mybat2 GOTO END :END echo, popd /////////////////////////////////////////////////////////////// mybat2 returns an errorlevel. We have ony your word for that - you omitted the code that would allow us to decide whether or not you actually are diong that - that syntax problems with the test indicates that suspicion on the exit code point is warranted. Is it guaranteed that I will see the errorlevel returned by mybat2 in the top level batch file? Or in other words will these DOS commands change the errorlevel (for example on different OS???)? GOTO END :END echo, popd Some commands that were internal commands in COMMAND.COM are externals under CMD.EXE and may return their own errorlevels. ERRORLEVEL is *always* tested immediately after the function that sets it returns just as the return value of a function in high level languages is always tested immediately after return (or is stored in a stable variable or use later). Unless that rule is followed, there is the risk of inserting code later between the function and the test - code that breaks the program. If it is necessary to test a return code later rather than immediately, save it in a dedicated variable. -- T.E.D. (tdavis@xxxxxxx) . - References: - errorlevel handling in DOS batch - From: bubu . aa - Prev by Date: Re: errorlevel handling in DOS batch - Next by Date: Timed jobs in the command window - Previous by thread: Re: errorlevel handling in DOS batch - Next by thread: Re: interrupt definition old DOS code, need to find it - Index(es):
http://newsgroups.derkeiler.com/Archive/Comp/comp.os.msdos.programmer/2008-06/msg00007.html
crawl-002
refinedweb
383
56.49
Top 3 Ways to Write Your Tensorflow Code This article was published as a part of the Data Science Blogathon Having choices gives us flexibility and scope of creativity Introduction I know that not all the choices available to us in our life would make us feel good. But having them makes us feel better and less trapped even if these choices are not the best ones. But today it’s not a matter of survival choices just some productivity choices, these 3 choices are a few out of many others out there. In this article, we will look at 3 ways in which we can use TensorFlow and Keras to create deep learning models AKA Neural Networks. To get all of us on the same page, let’s start with an introduction. Tensorflow: It is an end-to-end open-source platform managed and developed by Google for machine learning. Keras: It is also an open-source software library that provides a Python interface for deep learning neural networks. Keras acts as an interface for the Tensorflow Library. Before moving along with the content, I want to make this clear that for one of the ways, you need to have good knowledge about object-oriented programming (Classes and Objects). If in case you are not familiar with the concepts, no problem just looks at the other 2 for teaching yourself those methods. Now, as mentioned above, Keras acts as a high-level API through which we will interact with most of the TensorFlow code. All these methods are used through Keras API. 1. The Sequential Model API Just like any sequence in real-world or in programming terms, a sequence is an arrangement of elements in some particular order. With sequential API, we easily get to make a plain stack of layers where each layer has exactly one input tensor and one output tensor. Understand this better with this example: import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # Define Sequential model with 3 layers model = keras.Sequential( [ layers.Dense(2, activation="relu", name="layer1"), layers.Dense(3, activation="relu", name="layer2"), layers.Dense(4, name="layer3"), ] ) # Call model on a test input x = tf.ones((3, 3)) y = model(x) In the above code, you have stacked up 3 Dense layers on top of each other to create a single pathway through them. This will be equivalent to writing this: #))) Where the output ‘y’ is produced after the input x goes from one layer to another in a single fixed sequence. One important thing to keep in mind is that all these methods have their strengths and weaknesses. Let us glance over when Sequential is not so appropriate to use: 1. Multiple Inputs and Multiple Outputs: When your network architecture is designed for a task that requires input from more than one input layer or let’s say different inputs are being used parallelly for the execution, using a sequential layer is not the best approach. The same goes for multiple outputs from the network. 2. Any of the individual layers has multiple inputs or multiple outputs: Now it is similar to the above point but not exactly the same. There are various elements involved behind a neural network and let’s say that your architecture needs one or more of the hidden layers to perform certain tasks that are coming from the outside like a ‘T’ joint, then that would not be possible with sequential stacking of layer, they are fixed for a single path without any divergence or junctions. 3. You need to do layer sharing: Layer sharing is done when you want to use the output or let’s say behaviour of one layer and use it in accordance with another layer. That kind of sharing is not possible with sequential modelling through this API. 4. You want non-linear topology: If you are creating something like residual connections, or a multi-branch model. 2. The Functional API The Keras functional API is a great way to create models that are more flexible than the Sequential Model API. The Functional API can easily handle models with non-linear topology, shared layers, and even multiple inputs or outputs. The main idea behind it that is quite clear to understand is that a deep learning model is usually a directed acyclic graph of layers. So the functional AP is a way to build graphs of layers. Now, instead of stacking them all together and had no involvement in handling the hidden layer’s inputs and outputs, with functional API way, we get to use the layers as functions. So, the parameter of the function is input and what they produce will be the output to use further. Let’s see it in action. import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers we will create a basic graph with three layers like above. To start we create an Input Node. inputs = keras.Input(shape=(784,)) The shape specified as a parameter is the shape of the input data which is set to a 784-dimensional vector. The batch size is always omitted since only the shape of each sample is specified. Further making the other layer (Dense) who will use ‘inputs’ object as their input and so this cascading effect follows. dense = layers.Dense(64, activation="relu") x = dense(inputs) x = layers.Dense(64, activation="relu")(x) outputs = layers.Dense(10)(x) Closely observe the cascading of layers through function calls. At last import input layer and output layer as the argument for making an object of Model call, which will define our neural network. model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model") As an experimental task for you, after completing the Model object definition. Call .summary() on the ‘model’ object. model.summary() 3. The Subclassing API This approach required you to understand the concepts of object-oriented programming (Classes and Objects). If you don’t know about them, it’s completely okay to not know it, just skip this method and focus on the above two. For those who are familiar with the concepts, let’s get started! While we are using the method, there are various ways we can inherit other parent classes and use their functionality to even create our own layers and model. Today, I will talk about making your own model with subclassing API. So the first step you do is to define a class that contains all the code for your model architecture and the calling of those layers in whichever order you decide (very versatile and flexible). We will use the concept of inheritance and use the functionalities and methods available to use in tensorflow.keras.Model Class. One more thing before you jump on to the code, DON’T FORGET TO CLASS THE SUPER() FUNCTION, which will direct the access to the parent class and help to call the constructor function of the parent class (tensorflow.keras.Model). class MyModel(tf.keras.Model): def __init__(self, num_classes=2): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(64, activation="relu") self.dense2 = tf.keras.layers.Dense(64, activation="relu") self.classifier = tf.keras.layers.Dense(num_classes) def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) return self.classifier(x) model = MyModel() dataset = ... model.fit(dataset, epochs=10) model.save(filepath) __init__(): this is the constructor which will execute as soon as we define an object from this class. call(): this function is used when we are calling the object that we just created from the class for the purpose of transformation from inputs to outputs. Then things are pretty much the same that they were when we create a model and fit on it with some data. Visual Comparison of these API structures (Again!): I hope you found this article useful and got some ideas about how differently you can create your models using these various methodologies. Gargeya Sharma B.Tech 3rd Year Student Specialized in Deep Learning and Data Science For getting more info check out my Github Homepage Leave a Reply Your email address will not be published. Required fields are marked *
https://www.analyticsvidhya.com/blog/2021/07/top-3-ways-to-write-your-tensorflow-code/
CC-MAIN-2022-27
refinedweb
1,376
62.17
Go to the first, previous, next, last section, table of contents. This chapter describes how to compile programs that use GSL, and introduces its conventions., J0(5) = -1.775967713143382920e-01 The steps needed to compile this program are described in the following sections. GSL gsl_, while exported macros have the prefix GSL_. The library header files are installed in their own `gsl' directory. You should write any preprocessor include statements with a `gsl/' directory prefix thus, #include <gsl/gsl_math.h> If the directory is not installed on the standard search path of your compiler you will also need to provide its location to the preprocessor as a command line flag. The default location of the `gsl' directory is `/usr/local/include/gsl'. A typical compilation command for a source file `example.c' with the GNU C compiler gcc is, gcc -I/usr/local/include -c example.c This results in an object file `example.o'. The default include path for gcc searches `/usr/local/include' automatically so the -I option can be omitted when GSL is installed in its default location. The library is installed as a single file, `libgsl.a'. A shared version of the library is also installed on systems that support shared libraries. The default location of these files is `/usr/local/lib'. example.o -lgsl -lgslcblas -lm The following command line shows how you would link the same application with an alternative bl For more information see section BLAS Support. The program gsl-config provides information on the local version of the library. For example, the following command shows that the library has been installed under the directory `/usr/local', bash$ gsl-config --prefix /usr/local Further information is available using the command gsl-config --help. To run a program linked with the shared version of the library it may be necessary to define the shell variable LD_LIBRARY_PATH to include the directory where the library is installed. For example, in the Bourne shell ( /bin/sh or /bin/bash), the library The inline keyword is not part of ANSI C and the library does not export any inline function definitions by default. However, the library provides optional inline versions of performance-critical functions by conditional compilation. The inline versions of these functions can be included by defining the macro HAVE_INLINE when compiling an application. gcc -c -DHAVE_INLINE example.c If you use autoconf this macro can be defined automatically. If you do not define the macro HAVE_INLINE then the slower non-inlined versions of the functions will be used instead. Note that the actual usage of the inline keyword is extern inline, which eliminates unnecessary function definitions in GCC. If the form extern inline causes problems with other compilers a stricter autoconf test can be used, see section Autoconf Macros. The extended numerical type long double is part of the ANSI C standard and should be available in every modern compiler. However, the precision of long double is platform dependent, and this should be considered when using it. The IEEE standard only specifies the minimum precision of extended precision numbers, while the precision of double is the same on all platforms.. alternate., or any other specific type, file. Go to the first, previous, next, last section, table of contents.
http://linux.math.tifr.res.in/programming-doc/gsl/gsl-ref_2.html
CC-MAIN-2017-39
refinedweb
542
55.24
VB.net - GLControl - Implementation - 01Posted Friday, 10 August, 2012 - 09:25 by AftPeakTank So lets describe the situation... Objective In a few words, we want an opengl window inside a form. We want to create something like a 3d viewer, editor, cad or program with similar functionality. Because to manage Opengl with all the things the user might do to the window is really painfull, we will use the GLControl. Thankfully it exists in OpenTK and it will help us avoid a lot of errors. For this part we will try to create a render window with a background color. What we need before coding I am coding in VB.net express. So if you dont own VS.pro no problem. Download VS express and especially VB.net for what i describe. Then i suppose you can go through the simple steps of creating a new project. After that... 1. Create a new Class (it will be your rendering control). I name mine (aoGLControl). 2. Create in your main Form a Panel in the place you want the rendering control to be positioned (Panel_aoGLControl_host). 3. Put your references to OpenTK. OpenTK OpenTK.Combatibility OpenTK.GLControl The Rendering Control code So in ation... 1. First you need to to import namespaces. Imports OpenTK Imports OpenTK.GLControl Imports OpenTK.Platform Imports OpenTK.Graphics.OpenGL 2. Then we will inherit the functionality of GLControl and add a checking value to see the control is loaded. Inherits GLControl Dim _STARTED As Boolean = False 3. Then we add a color property. ' Background Color Private glbackcolor As Color Public Property glBackColorProp() As Color Get Return glbackcolor End Get Set(ByVal value As Color) glbackcolor = value If _STARTED = True Then GL.ClearColor(glbackcolor) Me.Invalidate() End If End Set End Property 4. Now we have to manage some events. The events to manage are: Load Paint Resize Private Sub aoGLControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load _STARTED = True GL.ClearColor(glbackcolor) SetupViewport() End Sub Private Sub aoGLControl_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint If Not _STARTED Then Return render() End Sub Private Sub aoGLControl_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize If Not _STARTED Then Return render() End Sub Private Sub ResizeGL() SetupViewport() Me.Invalidate() End Sub In the Load event we make sure that the _Started boolean is set to true so we will not try to draw in the Paint Routine and get an error. The SetupViewport() will setup the screen size, projection (ortho in our case) and coordinate system. The render() will render will render our scene. 5. Then we create the Subs that are called in the Paint and Resize events Private Sub SetupViewport() Dim w As Integer = Me.Width Dim h As Integer = Me.Height GL.MatrixMode(MatrixMode.Projection) GL.LoadIdentity() GL.Ortho(0, w, 0, h, -1, 1) GL.Viewport(0, 0, w, h) End Sub Private Sub render() ' Clear screen GL.Clear(ClearBufferMask.ColorBufferBit) GL.Clear(ClearBufferMask.DepthBufferBit) ' Here Pass the data of what it is to be drawn DrawLines() ' Draw it!!!! Me.SwapBuffers() End Sub The DrawLines() will draw lines in our window. 6. Finally we create our DrawLines() sub that will hold all the data to be drawn. Private Sub DrawLines() GL.MatrixMode(MatrixMode.Modelview) GL.LoadIdentity() 'Add Translations : ex. GL.Translate(x, 0, 0) 'Add Rotations : ex. GL.Rotate(rotation, Vector3.UnitZ) 'Add Colors : ex. GL.Color3(Color.Yellow) ' Add Geometry with above Translation/Rotation/Color GL.Begin(BeginMode.Triangles) 'Depending on type of object ' Add Geometry : ex. GL.Vertex2(10, 20) ' GL.Vertex2(100, 20) ' GL.Vertex2(100, 50) GL.End() End Sub Currently it will draw nothing, but if you want, you can type the lines in the comment "Add Geometry" to see something when you run the project. So this is the code for our new control. Now we will add code to the form. The main concept is as follows: 1. We create our custom control. 2. At the load of the form we call a custom initialisation for our control. 3. This will put the control in the panel we added in the form and it will change the color of the background so we will see something. The Form code Imports OpenTK Imports OpenTK.GLControl Imports OpenTK.Platform Imports OpenTK.Graphics.OpenGL Public Class Form1 Dim aoGLControl1 As New aoGLControl Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' Initialisation Calls InitialiseAoGLControl() End Sub #Region "Initialisation Routines" Private Sub InitialiseAoGLControl() ' Set Colors aoGLControl1.glBackColorProp = Color.Black ' Set Widths ' Set LineTypes ' Add the Control Panel_aoGLControl_host.Controls.Add(aoGLControl1) aoGLControl1.Dock = DockStyle.Fill End Sub #End Region End Class Run the Project and enjoy :) - AftPeakTank's blog - Login or register to post comments
http://www.opentk.com/node/3113
CC-MAIN-2015-32
refinedweb
805
60.92
like using braces in a %top block messes up flex 2.5.33. If I put something like: %top{ namespace foo { } Flex outputs the following: foo.l:146: unknown error processing section 1 foo.l:148: premature EOF It seems like the brace screws up flex's concept of the top block, making it extend to the end of the file. Removing the { from the namespace declaration makes flex proceed fine (but obviously the compiler doesn't like the result). I'm trying to enclose all of the code generated by flex in a namespace, but maybe this is a bad idea. Any thoughts? -- Mike Mueller mike@...
https://sourceforge.net/p/flex/mailman/flex-help/thread/20080420022304.GC10237@zelda.subfocal.net/
CC-MAIN-2018-22
refinedweb
107
74.19
Dask-ML Contents Dask-ML¶ Dask-ML provides scalable machine learning in Python using Dask alongside popular machine learning libraries like Scikit-Learn, XGBoost, and others. You can try Dask-ML on a small cloud instance by clicking the following button: Dimensions of Scale¶ People may run into scaling challenges along a couple dimensions, and Dask-ML offers tools for addressing each. Challenge 1: Scaling Model Size¶ The first kind of scaling challenge comes when from your models growing so large or complex that it affects your workflow (shown along the vertical axis above). Under this scaling challenge tasks like model training, prediction, or evaluation steps will (eventually) complete, they just take too long. You’ve become compute bound. To address these challenges you’d continue to use the collections you know and love (like the NumPy ndarray, pandas DataFrame, or XGBoost DMatrix) and use a Dask Cluster to parallelize the workload on many machines. The parallelization can occur through one of our integrations (like Dask’s joblib backend to parallelize Scikit-Learn directly) or one of Dask-ML’s estimators (like our hyper-parameter optimizers). Challenge 2: Scaling Data Size¶ The second type of scaling challenge people face is when their datasets grow larger than RAM (shown along the horizontal axis above). Under this scaling challenge, even loading the data into NumPy or pandas becomes impossible. To address these challenges, you’d use Dask’s one of Dask’s high-level collections like (Dask Array, Dask DataFrame or Dask Bag) combined with one of Dask-ML’s estimators that are designed to work with Dask collections. For example you might use Dask Array and one of our preprocessing estimators in dask_ml.preprocessing, or one of our ensemble methods in dask_ml.ensemble. Not Everyone needs Scalable Machine Learning¶ It’s worth emphasizing that not everyone needs scalable machine learning. Tools like sampling can be effective. Always plot your learning curve. Scikit-Learn API¶ In all cases Dask-ML endeavors to provide a single unified interface around the familiar NumPy, Pandas, and Scikit-Learn APIs. Users familiar with Scikit-Learn should feel at home with Dask-ML. Partner with other distributed libraries¶ Other machine learning libraries like XGBoost already have distributed solutions that work quite well. Dask-ML makes no attempt to re-implement these systems. Instead, Dask-ML makes it easy to use normal Dask workflows to prepare and set up data, then it deploys XGBoost alongside Dask, and hands the data over. from dask_ml.xgboost import XGBRegressor est = XGBRegressor(...) est.fit(train, train_labels) See Dask-ML + XGBoost for more information.
http://ml.dask.org/index.html
CC-MAIN-2022-40
refinedweb
431
53.21
NAME ::clig::Description - set long description text to be included in a manual page SYNOPSIS package require clig namespace import ::clig::* setSpec db Description text DESCRIPTION The Description command should not be used. Instead, the respective section in the generated manual page should be filled out. The main reason for this advice is, that clig copies description AS IS into the manual page, so it can be typed into the manual page file in the first place. Please remember that the generated manual page needs some hand- tuning anyway, because for example the ‘SEE ALSO’-section cannot be generated. Since this command should not be used, no example is given. SEE ALSO clig(1), clig_Commandline(7), clig_Double(7), clig_Flag(7), clig_Float(7), clig_Int(7), clig_Long(7), clig_Name(7), clig_Rest(7), clig_String(7), clig_Usage(7), clig_Version(7), clig_parseCmdline(7)
http://manpages.ubuntu.com/manpages/dapper/man7/clig_Description.7.html
CC-MAIN-2014-10
refinedweb
138
50.67
Copyright © 2007 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. This document and the associated technology are being developed to meet the needs of the Rule Interchange Format (RIF) Working Group. The technology, however, is applicable in many areas beyond RIF, so this document is written to avoid using RIF as more than an example. Standardizing this work in this general form is likely to be out-of-scope for the RIF WG. PXFIM provides forward compatiblity for XML-based languages deployed on the Web, allowing them to evolve in place and to be extended by users independently. It does this by allowing creators of extensions, new languages, and new language versions to publish "fallback" information, including "impact" data. This information is used by PXFIM processors to translate documents from new (unimplemented) formats into old (implemented) ones as needed. sandro@w3.org with a subject including the text "PXFIM". Please "Cc" www-archive@w3.org, so that a public record is made of the mail. This is not a W3C Working Draft. Even if it were: Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress. PXFIM allows XML-based languages to evolve and grow, on the Web, without the need for either central coordination or the foresight to know what changes might someday be desired. It does this, leveraging Web Architecture and Semantic Web ideas, by defining a pre-processor for XML consuming software which downloads XSLT programs as necessary (when possible) to transform documents into a format the consuming software can properly handle. All these use cases begin like this: some individual or organization (the "original author") publishes a stable specification ("version 1.0") for an XML-based language. The author intends the language to be adopted and used in a large and diverse community. The use cases below concern things which might happen after the publication of version 1.0. New "Forked" Version of a Language: ... New Experimental Version of a Language: ... Official Extension to a Language: ... User Extension to a Language: ... Official Profile to a Language: ... User Profile to a Language: ... Competing Languages: ... The Rule Interchange Format (RIF) Working Group was chartered, in part, to "construct an extensible format for rules." This requirement comes from the realities of the rule systems market and rule technologies. There are different rule technologies, which overlap in markets, but which have quite different strengths, so for some applications one particular style of engine is likely to be best. The interchange format (RIF) therefore needs to be a family of languages aligned to the different rule technologies. For example, essentially all rule engines implement "datalog" rules. These rules are sufficient for some types of applications. (Many financial services rulebases used only datalog rules). So RIF has a "Core Dialect" for datalog rules. Many users, however, want additional features, and more powerful styles of engines are common, such as the Prolog-like logic languages, CLIPS-like "production rule" systems, and Event-Condition-Action rules. The goal is that when users writing for any of these system happen to only write datalog rules, their rulesets will run, without modification, on RIF systems as well. @@@ how much detail to go into? @@@ very rough; probably too contrived. Maybe just use books? It took several guesses to come up with a domain that is not addressed with some FooML. A new XML language, PianoML is developed for communicating information about pianos. The first version, 1.0, is adopted by several organizations that buy and sell pianos, as well as music schools, moving companies, and a few musicians. It allows them to pass around information about specific pianos (eg Steinway piano #212640, which has alligatored finish and curve-tapered legs). Their inventory systems and various other software is modified to read and write this format. After some time, it becomes clear that some useful fields were left out. In version 1.0, there was a one-bit flag saying whether the tuning pegs tended to slip. For version 1.1, some users wanted detailed information about which pegs tended to slip, and how strong the tendency was. This could easily be added, but how would the software written to handle PianoML 1.0 files respond? Some systems would probably fail, some would ignore the new information, some might do other odd things. Fortunately, the PianoML 1.0 specification mandated PXFIM processors for PianoML consumers. Because of this, the creators of PianoML 1.1 could publish PXFIM declarations linked from the PianoML 1.1 namespace document and reasonably expect them to followed. These declarations were written to include a fallback procedure which removed the detailed information about pegs slipping, and set the some-pegs-slip flag if one or more of them were stated as slipping with a tendency of more than 20%. Late on, some moving companies realized it would be helpful to them to further extend PianoML with information helpful to them about which kind of bolts needed to be removed to remove the piano's legs. The other communities using PianoML were resistant to this information being included -- it was of no interest to them. However, the moving companies were free to include it, written in their own extension (in their own namespace), because they also published PXFIM declarations which simply said the information could be silently dropped if the backend schemas didn't allow it. Copy from RIF Extensibility Design Choices and edit to be not RIF-specific. We use the terms XML-based language, XML-based format, XML language, and XML format interchangeably. The word "language" suggests something with a more complex grammar than "format", but that difference is immaterial to PXFIM. @@@ talk about Language Conflict, Invisible Extensions, coordinating creators via namespace documents Conceptually, a PXFIM processor is a frontend, in front of normal XML-consuming software. Before the regular software consumes any XML document, the PXFIM processor has a chance to transform the document. When deployed, the PXFIM processor is configured with a set of XML Schemas for validating the documents it is allowed to pass to the backend. These schemas communicate to PXFIM which XML languages the backend implements. They should be written "tightly", so they do not accept anticipated future versions the languages. The PXFIM processor is also configured with a table of weights for different kinds of "impacts". This table will be application specific, as detailed [below]. Here's what a PXFIM processor must do: Try to validate the input document against each of the backend schemas. If it validates against any of them, pass it through and we're done. Otherwise: Parse the input document for any PXFIM declarations and PXFIM import-control information. If there is no PXFIM import-control information, or if there is and it allows it, dereference all the namespaces used in the document. [@@ some issues about rdf-style URIs, but this is close enough for now.] The returned content should contain more PXFIM declarations or be (somehow) linked to other documents which do. Use these PXFIM declarations [ and maybe others? ] to find the minimal-impact fallback path from the input to one of the backend acceptable schemas. Each step on the fallback path is an XSLT which transforms a document from a "new" format to an "old" one, possibly changing the meaning or other characterisitcs. These changes indicated by the associated "impact" information. If there is such a path, perform the fallbacks, and pass the result to the backend along with the accumulated impact flags. If there is not one, let the backend know that fallback is not possible for this document. build up from RIF sketch of adding NAF to BLD full details, including security model RIF Core-to-BLD example, as per RIF Action-373. Others?
http://www.w3.org/2007/11/07-pxfim/
CC-MAIN-2016-22
refinedweb
1,326
56.35
Elastic::Manual::Delta - Important changes in Elastic::Model version 0.50 This documents any important or noteworthy changes in Elastic::Model, with a focus on things that affect backwards compatibility. This does duplicate data from the Changes file, but aims to provide more details and when possible workarounds. This is the first version which supports the 1.x releases of Elasticsearch, and it provides a migration path from the 0.90.x releases of Elasticsearch. You can no longer use the temporary Search::Elasticsearch::Compat client with Elastic::Model. Instead, use the official Search::Elasticsearch client: use Search::Elasticsearch; use MyApp; my $es = Search::Elasticsearch->new( nodes => [ "192.168.1.100:9200", "192.168.1.101:9200"] ); my $model = MyApp->new( es => $es ) You cannot mix nodes from 0.90.x with nodes from 1.x. This leaves you with two options: Either way, the migration path available in Elastic::Model v0.50 will help you through the transition. You can enable a "compatibility mode" which will allow you to use the same code on 0.90.x and on 1.x by telling the Search::Elasticsearch module to use the 0_90::Client: use Search::Elasticsearch; use MyApp; my $es = Search::Elasticsearch->new( nodes => [ "192.168.1.100:9200", "192.168.1.101:9200"], client => '0_90::Client' ); my $model = MyApp->new( es => $es ) If you are planning on running two clusters in parallel, then you can specify a mixture of nodes from the 0.90.x cluster and the 1.x cluster in the nodes list. The client will use whatever nodes are available. This allows you to start with just the 0.90.x cluster, bring up the 1.x cluster (it will talk to both clusters), then take down the 0.90.x cluster. Once the migration is finished, remove the `0_90::Client` and the 0.90.x nodes and the compatibility mode will be disabled. IMPORTANT: If you writing to your index during transition, it is up to you to ensure that writes go to both clusters. A safer approach is to only allow reads during the transition phase. NOTE: While compatibility mode is enabled, include_paths and exclude_paths (see "include_paths / exclude_paths" in Elastic::Model::View) will be ignored. Instead of retrieving just the paths specified, it will retrieve the whole document. ignore_missing The ignore_missing parameter is deprecated and should be replaced by, eg: $namespace->index('foo')->delete(ignore => 404); For now, ignore_missing will be translated to ignore => 404 but will warn about deprecation. omit_normsand omit_term_freq_and_positions These two options have been removed from Elasticsearch and replaced by the following mapping: { "my_string_field": { "type": "string", "norms": { "enabled": "false" }, "index_options": "docs" }} These options were most useful for not_analyzed fields, but they are no longer required as they are now the default settings for not_analyzed fields. If you want to apply these settings to an analyzed string field, you can do so as follows: has 'name' => ( is => 'rw', isa => 'Str', type => 'string', mapping => { norms => { enabled => 0 }, index_options => 'docs' } ); Some response formats have changed in Elasticsearch. The structure of the C <get-mapping> and get-settings responses have changed, responses no longer include the ok key, and the exists has been replaced by found. The field values are now returned as arrays rather than scalars. Compatibility mode makes some effort to normalize responses between 0.90.x and 1.x, but you should test your code on 1.x before migrating. Mvel is no longer enabled by default in Elasticsearch, and in 1.4 it will be removed. However, the new scripting language (Groovy, which is available in 1.3 and will become the default in 1.4) is not available in 0.90.x. To aid migration, you should reenable Mvel scripting during transition. Once complete, update all scripts to use Groovy instead. See for more. Some queries have been removed in 1.x. The text, text_phrase, and text_phrase_prefix queries have been replaced by match, match_phrase, and match_phrase_prefix. The custom_score, custom_boost_factor, and custom_filters_score queries have been replaced by the function_score query. The numeric_range filter no longer exists. Elastic::Model::SearchBuilder supports the match* queries but still needs to be updated to support the function_score query. In the meantime, you can use the "raw" syntax. See "RAW-ELASTICSEARCH-QUERY-DSL" in ElasticSearch::SearchBuilder. Aggregations are now supported (see "aggs" in Elastic::Model::View) but only in Elasticsearch 1.0 and above. The following attribute deprecations are deprecated and will be removed in a future version: boost index_name precision_step path Clinton Gormley <drtech@cpan.org> This software is copyright (c) 2014 by Clinton Gormley. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
http://search.cpan.org/~drtech/Elastic-Model-0.50/lib/Elastic/Manual/Delta.pod
CC-MAIN-2016-30
refinedweb
784
67.55
Why it works as it does is actually quite complex. First of all, match (m//) and substitution (s///) have a special case for an empty regex: they will apply the last successful regex instead, so: if (condition) { $str =~ /ab/; } else { $str =~ /ef/; } $str2 =~ //; [download] defined or: // and //= and Re: Perl 5.8.3) to 5.8.x, since a // where perl may be expecting either an operator or a term could mean defined-or or could mean ($_ =~ //). Without the feature, the latter would be overwhelmingly less likely to occur in real code. People more often use this "feature" by accident than on purpose, with code like m/$myregex/ where $myregex is empty (since the "is it an empty regex" test occurs after interpolation). One solution is to use m/(?#)$myregex/ if you anticipate that $myregex may be empty. But all that is beside the point, because special treatment of // (documented with respect to s/// and m// in perlop) is not a feature of perl's regexes but a feature of the match and substitution operators, and doesn't apply to split at all. So what does happen when you say split //, $str? Well, in general terms, split returns X pieces of a string that result from applying a regex X-1 times and removing the parts that matched, so split /b/, "abc" produces the list ("a","c"). (Throughout, I will ignore the effects of placing capturing parentheses in the regex.) Similarly, split //, "ac" matches the empty string between the letters and returns ("a","c"). The analytic of mind will note that there are also empty strings before and after the "ac". Spreading it out, the regex will match at each //: "// a // c //", making 3 divisions in the string, so you might expect split to return a list of the four pieces produced ("","a","c",""), but instead a little dwimmery comes into play here. Dealing first with the empty string at the end, split has a third parameter for limiting the number of substrings to produce (which normally defaults to 0, and where <= 0 means unlimited), so split /b/, "abcba", 2 returns ("a","cba"). As a special case, if the limit is 0, trailing empty fields are not returned. However, if the limit is less than zero or large enough to include empty trailing fields, they will be returned: split /b/, "ab", 2 for example does return "a" and an empty trailing field, while split /b/, "ab" returns only an "a". The same provision applies to the empty string following the zero-width match at the end of the string. split //, "a" returns only the "a", while split //, "a", 2 returns (, my ($a,$b,$c) = split //, "a" will result in the split having a default limit of 4, obverting the usual suppression of the empty trailing field: split will return ("a",""), leaving $b blank and $c undefined.) But there is also an empty string before the zero-width match at the beginning of the string. The above methodology doesn't apply to that. If you say split /a/, "ab" it will break "ab" into two strings: ("","b"), whether or not limit is specified (unless you limit it to one return, which basically will always ignore the pattern and return the whole original string). Similarly, split //, "b" doesn't base returning or not returning the leading "" on limit. Instead, a different rule applies. That rule is that zero-width matches at the beginning of the string won't pare off the preceding empty string; instead, it is discarded. So while split /a/, "ab" does produce ("","b"), split //, "b" only produces ("b"). This rule applies not only to the empty regex //, but to any regex that produces a zero-width match, e.g. /^/m. (While on the topic of /^/, that is special-cased for split to mean the equivalent of /^/m, as it would otherwise be pretty useless.) So split /(?=b)/, "b" returns ("b"), not ("","b"). One last consideration, that also plays a part with s/// and m//: if you match a zero-width string, why doesn't the next attempt at a match also do so in the same place? For instance, $_ = "a"; print "at pos:",pos," matched <$&>" while /(?=a)/g should loop forever, since after the first match, the position is still at 0 and there is an "a" following. Applying this logic to split //,. For example: $_ = "3"; /(?=\w)/g && /\d??/g && print $&; does print "3", even though the ?? requests a 0 digit match be preferred over 1 digit, because a 0-length match isn't allowed at that position. (Update: s/FMTEYEWTK/FMTYEWTK/; googlefight shows the latter winning by 10. Update: added links to defined-or stuff; thanks graff, Trimbach, hardburn... Gary Blackburn Trained Killer I. I always used ()=$string=~/(.)/gs; to split a string to characters. Also, it's sometimes useful to iterate through the characters of a list, for which you can use the scalar-context variation: while($string=~/(.)/gs){DO SOMETHING WITH ($1)}; -- you can't do this with split, can you? Update: added s flags, strange noone noticed that adding to Roger's reply, print $_, $/ for @{[ split // => $bar ]}; [download] is strict and warnings friendly, as well, and twisted in it's (useless) indirection. ~Particle *accelerates* for (split //, $string) { print "$_\n"; } [download] Thanks, ysth your meditation is certainly more than I knew about split. xench.
https://www.perlmonks.org/?node_id=322751
CC-MAIN-2018-39
refinedweb
893
69.72
I'm developing a mobile app with a view that contains 1 Text Area, 1 Text Input and a group of 3 buttons. The app runs well in Desktop mode ( Run & Debug ), but when run in an android device ( Sony Tablet S) when the view is loaded, the text (text property set at design or runtime) "flashes" and disappear, if I change the device orientation of the tablet (phisically) the text draws correctly and don't disappear, even if you return to the original orientation. Also, if I pop-up a message (SkinnablePopUpContainer) in the same view, the text appears, and when I close the pop-up the text disappears again. Is this an identified bug ? ... is there a workaround ? ... I tried to set visible property to false and true and sometimes it works and sometimes not at random. Thank you for you help. UPDATE : if I set Focus=true the text appears. I think that the text should be there even if I don't set focus. This simple code when run in the device (Sony Tablet S) doesn't work as expected ... ( the text in the textbox dissapears, and if you change orientation appeears). <?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="" xmlns:s="library://ns.adobe.com/flex/spark" title="Editar acción" xmlns: <fx:Script> <![CDATA[ import mx.events.FlexEvent; protected function view1_creationCompleteHandler(event:FlexEvent):void { txt1.text="Hola"; txt1.validateNow(); txt1.setFocus(); // <---- if not set the text "Hola" flashes and dissapear. } ]]> </fx:Script> <s:TextInput </s:View> Just for people who doesn't see other post, you can also apply the spark skin mobile to get it fixed (with some border effects, like softKeyboardType not working). More there : Thank you. Anyone knows if Adobe is addressing this bug?
https://forums.adobe.com/thread/959588
CC-MAIN-2017-30
refinedweb
295
66.03
On Dec 12, 2006, at 2:23 AM, Karl Koch wrote: > However, what exactly is the advantage of using sqare root instead > of log? Speaking anecdotally, I wouldn't say there's an advantage. There's a predictable effect: very long documents are rewarded, since the damping factor is not as strong. For most of the engines I've built, that hasn't been desirable. In order to get optimal results for large collections, it's often necessary to customize this, by overriding lengthNorm. IME, for searching general content such as random html documents, the body field needs a higher damping factor, but more importantly a plateau at the top end to prevent very short documents from dominating the results. public float lengthNorm(String fieldName, int numTerms) { numTerms = numTerms < 100 ? 100 : numTerms; return (float)(1.0 / Math.sqrt(numTerms)); } In contrast, you don't want the plateau for title fields, assuming that malignant keyword stuffing isn't an issue. This stuff is corpus specific, though. > Is there any scientific reason behind this? Does anybody know a > paper about this issue? Here's one from 1997: Lee, Chuang, and Seamons: "Document Ranking and the Vector Space Model" > Is there perhaps another discussion thread in here which I have not > seen. Searching the mail archives for "lengthNorm" will turn up some more. Marvin Humphrey Rectangular Research --------------------------------------------------------------------- To unsubscribe, e-mail: java-user-unsubscribe@lucene.apache.org For additional commands, e-mail: java-user-help@lucene.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-java-user/200612.mbox/%3C127CFEBA-9C18-4CAF-AAEF-86EF1AB585B9@rectangular.com%3E
CC-MAIN-2014-15
refinedweb
245
57.67
replace function guy038 Your procedure works only in the open file, it can’t be applied to several files (especially on disk)! Replace in files is where the action is. I look with anticipation to see the replace box behave exactly like the find box without changes in EOL. Don Ho? For now, the Parpaluck procedure (\r\n) remains the only one applicable to multiple files directly on disk. I didn’t say that this procedure was "THE" solution. Of course, It’s just an interesting work-around, which may be helpful to some of us, from time to time ! And I agree, with you, that this multi-lines S/R is rather difficult to run on multiples files, because each of them must be "Unix" files, before performing the S/R, in the Replace in files dialog :-(( If you long for a true Multi-lines S/R feature, you could add a pull request, at the address, below : But, please, don’t expect a rapid reply to your request !! Best Regards, guy038 thanks all for your answers my english is not very good i tried the link to add a pull request but it open so i dont understand what to do… i have 2 others questions for s/r i have noticed that when i used the s/r function it not begin at the top of the file but where i was looking in the file, it will be great if this function by default could begin by the top of the file and an other question it will be nice if we could know in which files, which line notepad++ did the job. in dont see how to see that when i use s/r in directories. but perhaps its me who dont use well notepad++ - Scott Sumner Before this thread went all crazy-nuts… @Claudia-Frank said: but now comes my time to shorten your eol conversion. Goto Edit->EOL Conversion-> and choose the appropriate one ;-) Even shorter is double-clicking the “Windows (CR LF)” area of the status bar (or whatever that area of the status bar currently says for you) and making the “appropriate” choice that appears in the 3-item menu that appears. :-D - Scott Sumner The intriguing aspect here is the difference in the two boxes. The find box works as-is, with no changes in EOL codes. Don Ho? Here’s the difference as I see it: When a Find is invoked with a selection active, the selected text is put into the find-what box with this C++ code: void FindReplaceDlg::setSearchText(TCHAR * txt2find) { ... ::SetDlgItemText(_hSelf, IDFINDWHAT, txt2find); the txt2finddata may contain carriage-return (CR) characters; it is no problem for the SetDlgItemText() function to put those into the find-what box’s data. On the other hand, there is no corresponding automatic way to get Notepad++ to put data into the replace-with box, so we have to Paste it in with Windows’ normal paste functionality. Controls like the find-what and replace-with box do not accept CR via this Windows paste functionality. Thus multiline data pasted in gets truncated just before the first CR. I did a simple test with a new Visual Studio C++/MFC app, dialog-based, with a combobox dropped onto the dialog form. It, too, cannot accept any data pasted in after (and including) a CR. The linefeed (LF) character presents no such difficulty to Windows’ normal paste, which we have seen in the experimentation discussed previously in this thread. @Scott Still the replace box accepts \r\n in extended mode, which is CR+LF. Several other editors accept direct copy and paste in the replace-with box, be it CR+LF, LF or combination of both. They are probably written in C++. But I think it can be done in any language since CR and LF have the same codes. Don is busy now with other issues in 7.4.1. I saw there are problems with replacing again in several open files. - Scott Sumner Still the replace box accepts \r\n Do you mean literally \followed by rfollowed by \followed by n? If so then that’s not what I’m talking about just above. However, if you’re saying that you can get the replace-with box to accept more than one line where the line-separator has a definite CR character in it, even in Extended mode, then I’m afraid I can’t duplicate that behavior (all I get is the first line). At the time of paste, it is irrelevant which search-mode is in effect, a paste into the replace-with box is just a paste… other editors accept…they are written in C++ Certainly, but that’s not relevant to the current discussion. Unless the complaint is “Other editors can do it, why not Notepad++?” To that I’d say it is just a limitation, and the C++ code could be changed in the future to remove that limitation. @go2to said:Don is busy now with other issues in 7.4.1. I saw there are problems with replacing again in several open files.\r\n It is now one line after deleting CR+LF and adding \r\n. Everything is pasted in the replace box. It works flawlessly in the current file, or all open files, or in find in files.
https://notepad-plus-plus.org/community/topic/13823/replace-function/?page=3
CC-MAIN-2019-35
refinedweb
898
65.96
We've written a handy CircuitPython library for the various DC Motor and Stepper kits called Adafruit CircuitPython MotorKit that handles all the complicated setup for you. All you need to do is import the appropriate class from the library, and then all the features of that class are available for use. We're going to show you how to import the MotorKit class and use it to control DC and stepper motors with the Adafruit Stepper + DC Motor Shield. First assemble the Shield exactly as shown in the previous pages. There's no wiring needed to connect the Shield to the Metro. The example below shows wiring two DC motors to the Shield once it has been attached to a Metro. You'll want to connect a barrel jack to the power terminal to attach an appropriate external power source to the Shield. The Shield will not function without an external power source! You'll need to install a few libraries on your Metroca9685 - adafruit_bus_device - adafruit_register - adafruit_motor - adafruit_motorkit Before continuing make sure your board's lib folder or root filesystem has the adafruit_pca9685.mpy, adafruit_register, adafruit_motor, adafruit_bus_device and adafruit_motorkit files and folders copied over. Next connect to the board's serial REPL so you are at the CircuitPython >>> prompt. To demonstrate the usage, we'll initialise the library and use Python code to control DC and stepper motors from the board's Python REPL. First you'll need to import and initialize the MotorKit class. from adafruit_motorkit import MotorKit kit = MotorKit() from adafruit_motorkit import MotorKit kit = MotorKit() The four motor spots on the Shield are available as motor1, motor2, motor3, and motor4. In this example we'll use motor1. Note: For small DC motors like sold in the shop you might run into problems with electrical noise they generate and erratic behavior on your board. If you see erratic behavior like the motor not spinning or the board resetting at high motor speeds this is likely the problem. See this motor guide FAQ page for information on capacitors you can solder to the motor to reduce noise. Now to move a motor you can set the throttle attribute. We don't call it speed because it doesn't correlate to a particular number of revolutions per minute (RPM). RPM depends on the motor and the voltage which is unknown. For example to drive motor M1 forward at a full speed you set it to 1.0: To run the motor at half throttle forward use a decimal: Or to reverse the direction use a negative throttle: You can stop the motor with a throttle of 0: To let the motor coast and then spin freely set throttle to None. That's all there is to controlling DC motors with CircuitPython! With DC motors you can build fun moving projects like robots or remote controlled cars that glide around with ease.. You can alsoLEAVED DC motor""" import time from adafruit_motorkit import MotorKit kit = MotorKit() kit.motor1.throttle = 1.0 time.sleep(0.5) kit.motor1.throttle = 0 """Simple test for using adafruit_motorkit with a DC motor""" import time from adafruit_motorkit import MotorKit kit = MotorKit() kit.motor1.throttle = 1.0 time.sleep(0.5) kit.motor1.throttle = 0 For stepper motors: "")
https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/python-circuitpython
CC-MAIN-2020-34
refinedweb
540
61.56
In this article, I will cover how we connected to our Android project, shared (between iOS and Android) library written in C++. If you don't know anything about Android NDK (native development kit) or C++, you can still learn from this article the overall method. That could help your team write logic once and share it. So let’s begin from the library file structure. In the image below we can see that we have three subfolders in our library. “Shared” folder is a place where we keep our shared library logic written in C++. In the “Android” folder, we have a project with our Android library module (which use shared code) and sample app, and of course the same is in “iOS” folder but for iOS platform of course. Our Android project has three modules: The sample app where we connect our library module and check if all is working just fine, OpenCV module which is needed by our library, Library module itself. Our Android library uses Shared code which uses OpenCV so we need to add it to our library in the first place. If you have a hard time to fully understand you can go to our example. Ok so let's focus on library module. In build.gradle from this module, under android {.. we need to add two things. A path to our shared logic: and information that we are using native build, with a path to CMakeLists.txt file (which we will add later).and information that we are using native build, with a path to CMakeLists.txt file (which we will add later). sourceSets { main { jni.srcDirs "../../Shared" } } externalNativeBuild { cmake { path "CMakeLists.txt" } } Also, we need to add our dependence to opencv module. implementation project(':opencv') Let's move to CMakeLists.txt file. We need to add it next to build.gradle in the library module. If you create a new project and mark to include C++ support it will generate automatically in your app module. You can then copy that file to your library module and based on comments change to use your native library code. Define the name of the library, set it as “SHARED” and add the path to your source files. add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). src/main/cpp/native-lib.cpp ../../Shared/SheetDetection.cpp ) Under that in the same file, add the library to target_link_libraries(.. and add the same for OpenCV (example below). The best way is to check our sample and read the comments or documentation. You can say, “Ok, but how OpenCV is connected to your shared files?”. So in shared C++ classes, we have importes to OpenCV like #include <opencv2/core/core.hpp> which are ok because we added dependency in CMakeLists.txt file as: set(OpenCV_DIR "../opencv/src/sdk/native/jni") find_package(OpenCV REQUIRED) message(STATUS "OpenCV libraries: ${OpenCV_LIBS}") target_link_libraries(native-lib ${OpenCV_LIBS}) Now it’s time to add our native-lib.cpp under main -> cpp folder. If you want to know how to write your own just check documentation and you can look at our example. Sample function starts like: extern "C" JNIEXPORT jobject JNICALL Java_co_netguru_vrhouseframework_NativeRecognizer_cropSelectedArea( JNIEnv *env, jobject _this, jobject bitmap, jfloatArray points) {... Inside we declare functions that we will use in our Kotlin (or Java) classes which will be the “interface” for our library. So moving to those classes first you need to load your native library you can do it in static function to do it as quick as possible. companion object { init { System.loadLibrary("native-lib") } } To expose your native method you need to override it with a special keyword for Kotlin it will be “external” and for Java “native”. external override fun cropSelectedArea(bitmap: Bitmap, points: FloatArray): Bitma Remember that function from native-lib.cpp must be correct with you package, class name and function name (each separated by “_”) like in the example above with Java_co_netguru_vrhouseframework_NativeRecognizer_cropSelectedArea(...). That’s all for the library part! Now how to add it to your project: Open AndroidStudio project (I assume it has Git configured). From android studio project terminal add library repository as a submodule (our example) git submodule add git@github.com:netguru/3d-house-framework.git It will also add files like sample app but don’t worry it won't be added to our app repository. You will get a message like "Unregistered VCS root detected ..." Click on "Add root". Now you can see multiple git repositories at the bottom right of the android studio (Git branches view). Go to “File” menu -> project structure Click ‘+’ on left top to add a module Select ‘Import Gradle Project’ from the new window Select the sub-module folder with lib Give the actual sub-module project name (if needed) Sync You should have your sub-module added! Just add library module to app level build.gradle as a dependency (eg. implementation project(':vrhouseframework') and that's all! Now you can use your library in app classes. Photo by rawpixel on Unsplash
https://www.netguru.com/codestories/handling-cross-platform-frameworks-in-native-applications
CC-MAIN-2020-16
refinedweb
851
66.33
Windows 3.1 From Uncyclopedia, the content-free encyclopedia - Due to technical reasons, the article is named thus, the correct name would be WINDOW~3.1 (too long file name error) Windows 3.1 is the operating system of choice for Uncyclopedia's server administrators due the variety of software available and the low system footprint “Still better than Windows ME.” “I'm telling you, Windows 3.1 is just DOS in disguise!” “NOOOOOOOOOOO!!” “Objection!” “Windows 3.1 is stupid!” “Pssst...wanna buy a counterfeit windows copy. Here are the 11 disks you need and 2 extra disks for printer support. And here's is some drivers for your motherboard and graphics card. If you wanna keep you computer safe from bugs keep it inside and cover it. That will be $4.” Windows 3.1™, also known as WINDOW~3.1. was an attempt by quadruple-glass window manufacturers to get consumers to buy more Windows by brainwashing them. They claimed that when new holographic imaging systems came onto the market, only their kind of windows would be compatible. This, however, was untrue, as holographic imaging systems are the sole property of Starfleet and would not be coming into the market until the year 2095. The end result was a powerful, but lightweight operating system that at its peak achieved a 90% market share. edit Features Windows 3.1 is a popular platform for gaming with support for a variety of graphics accelerators and chipsets It is terribly difficult to identify the features of Windows 3.1 as it has so many design flaws. It is also difficult to identify the design flaws because there are so many superficial design flaws that they crowd out the fundamental design flaws. According to Microsoft, the fundamental design flaws are listed by Microsoft Developers as being in the basic engine/core/kernel of Windows 3.1, and the superficial design flaws are found in the Accessories folder - demonstrating Microsoft's Help systems to be as unhelpful as ever. The accessories include Paintbrush, Notepad, Solitaire, Calculator, Minesweeper, Windows Tutorial (which teaches you how to use a mouse), your mom, and Hello World. It also plays movies. Windows 3.1 is notable for its low system requirements. It is capable on running on anything from a 16-bit 8086 to a 64-bit quad-core system. Additionally, Windows 3.1 was shipped with that new-fangled creation called "Fonts 2.0". Not only did this break Microsoft's reliance on Adobe for fonts, after the 3.11 upgrade those fonts became legible, ushering in a new era in desktop publishing. In order to capture the Central and Eastern European markets, Microsoft went so far as to issue yet another version of Windows 3.1 called Windows 3.1 for Central and Eastern Europe. As you might have guessed, this operating system came with all red fonts, to please the ultra-nationalistic-red commie palate. While this offering allowed Microsoft to initially dominate the communist market, they would later lose much of it to Linux, an operating system designed by, for, and around communists. edit Security Contrary to popular belief, Windows Vista was not the first operating system to feature User Account Control Due to the popularity of other operating systems, such as Windows Vista and Mac OS X, malware developers no longer target Windows 3.1, making the operating system almost immune to most viruses, spyware, and rootkits although Microsoft has cooperated with the government to add a piece of spy code in their os. In addition, the TCP/IP stack is not integrated into the system kernel, reducing the number of security holes in the system. Windows 3.1 is one of few Microsoft operating systems that is not bundled with Internet Explorer, further reducing vulnerabilities significantly. The first beta versions of Windows 3.1 were equipped with all the drivers necessary to fully support 128 GB cable connections, 1024 TB-sized drives, undecipherable encryption algorithms, wireless networking with satellite capabilities, and a full set of professional-level software. They also included quantum copyright tags to prevent illegal copying of the diskettes. This caused any computer present at the time run too slowly, so the features were dropped in the final release. It's widely suspected that computers running the original beta are used as central hubs in the Internet. Microsoft later released Windows 3.2, which is based on Windows 3.1 for Central and Eastern Europe and was targeted to the Chinese market in order to compete against Linux. This version included Chinese language support, Freecell, extra security updates, and several versions of Mahjong. edit The upgrade from Windows 1.0 Nothing much different. Bill Gates hired some children instead of monkeys. And the Blue Screen of Death was brought to a whole new level with some words on it such as "too bad" and "your computer is out of RAM and therefore Minesweeper is unavailable." Also, this version introduced the highly debated wmiprvse.exe application, which constantly runs in the background greatly "enhancing" the user experience. Although Bill Gates was a genius with numbers, Windows version 2.0 went unnoticed, and 3.0 had some critical flaws and only existed in beta, so the new operating system was named Windows "3.1", not only to make the naming process much more confusing but to make Microsoft's reputation turn into the wackiest company in America, a reputation which it still holds proudly today. edit Requirements and Installation - This section was written by Strong Bad, and may be of questionable accuracy. Well, first off, you're gonna need lots more RAM. Lots more frekkin' RAM. It doesn't matter how much frekkin' RAM your computer has, you're gonna need more because Windows is greedy. You will also need a large hard drive because Windows needs storage space to install all the programs that you will never use. The best part of this experience is that these applications can't be uninstalled. Also Windows will make extra copies of it self and other programs to keep them safe, in particular it will overwrite other useless files such a pictures of your grandmother or your term paper. Windows just keeps sucking free hard drive space the more you use the operating system that you will eventually need to be a new hard drive in just a few months. If that isn't enough, installing required weekly security updates will eat up the remainder of free space. So you're gonna need such a big hard drive and so much frekkin' RAM that you're gonna be afraid that your computer is going to explode when you turn it on. When you turn it on however, don't be alarmed. It's not going to explode or do anything near that exciting. The first thing that's gonna happen is a buncha text is gonna appear on your screen saying things like " Non-system disk or disk error." I'd suggest going out to lunch or doing something else fun away from your computer at this point. If the same text is still there when you return as when you left, you could have problems. The next thing you're going to need to do is to buy a mouse. Just go to your local pet store and pick one out. I'd suggest reading the Murphy's Laws of DOS chapter on "The Care and Feeding of your Mouse." Mouses (they aren't called mice, they're called mouses in the PC world, moron) are like your best friend. You can pretty much throw your keyboard away at this point because you won't need it anymore once you get your new quadruple-glass Windows running in order to play Minesweeper. They take like 50 frekkin' megs of RAM (wow isn't that an incredibly huge amount?) but those quadruple glass windows with the little Xs on them are like the most windows in Starfleet, man. Windows 3.1 is also good for watching porn in hd ! edit Windows 3.1.4159 This version of Windows appears after the user had updated Windows 159 times. The source code had been reproduced at below: /************************************************************************************\ * Windows 3.1.4159 build OSFX * * Copyright (C) 1985-1992 Micro$oft Inc. All rights reserved. * * This program is not free software; you cannot do anything with it. * * This program is programmed to be NOT USEFUL, as the UNG Unique Private License * said. See the UNG Unique Private License for details. * * You should have not received a copy of the UNG Unique Private License * along with this program. If you do, burn it using the super burner included in * the Windows 3.1.4159 package or get one for free (shipping fee is not included) * at <> \**********************************************************************************/ #include <system/system.h> /////////////////////////////////////// // include 16bit/32bit system class #ifndef __WIN32__ #include <system/system16.h> #else #include <system/system32.h> #endif /* __WIN32__ */ /////////////////////////////////////// #include <system/crash.h> #include <stdio.h> #include <iostream> #include <math.h> #include <gov.h> #ifndef BOOL typedef BOOL int; #endif /* BOOL */ /******************************Public*Routine******************************\ * BOOL IsVaildCrashCode (int, System *) * * Check if input is a vaild crash code. * * Returns 1 if input is a vaild crash code, and 0 if not. * * History: * - Feb. 92 - This part is fixed by the new guy, Kevin David Mitnick. * - Dec. 91 - 18% is finished. Bill gates found a new guy to fix it. * - Aug. 91 - 12% of this part is finished. * - May. 91 - 5% of this part is finished. * - Feb. 91 - Two million people started on fixing this part. * - Jan. 91 - This part is deleted by Bill Gates' son. * - Feb. XX - This part is added by Darth Vader. * - Jun. 8 - This part is added by George W. Bush. \**************************************************************************/ BOOL IsVaildCrashCode(int input, System *system) { if(input == 0) { printf("Divide by zero error"); return 0; } if(system == NULL) { return 0; } int tmp = input*input/input; if(system->IsVaildCrashCode(tmp)) // check if tmp is a vaild crash code return 1; return 0; } int main() { int s = 0; // the System class 4159 is extremely easy to use // it has almost any feature we need to program an OS like windows System system = System::CreateAWindowsSystem(SYS_LOGO_UNKNOWN, TYPE_PC, (unsigned __int128)(3.14159)); system.Init(); system.PrintSystemVersion(); srand((unsigned )atoi(system.ConvertToSeconds(system.GetMilliSecondsPassedSince1970(system.GetCurrentTimeInDatetimeFormat())).ToString())); // Here we make use of gov.h to collect data about the user and send it to the government GovernmentConnection govConn(GovernmentConnection::GetGovernmentID("United States of America"), "George w. Bush"); try { Government *gov = NULL; gov = govConn.Connect(true, true, "Micro$oft Windows 3.14159", ENCRYPTION_AES); if (gov != NULL) { system.OpenDataPipe(SYS_MODULE_FILE_SYSTEM); HANDLE hFileSystem = NULL; system.SendInfoToModule(SYS_MODULE_FILE_SYSTEM, (unsigned __int204800) FS_REQUEST_READ_ACCESS); system.RecvInfoFromModule(SYS_MODULE_FILE_SYSTEM, (unsigned __int204800 *) &hFileSystem); if(hFileSystem) { SpyData *data = GovernmentUtils::CollectData(hFileSystem); gov.SendDataEncrypted("SpyData", data, sizeof(data)); } else { gov.SendDataEncrypted("Plain_Text", "Unable to collect user data.", 30); } system.CloseDataPipe(SYS_MODULE_FILE_SYSTEM); gov.Flush(); gov.Close(); } } catch (Exception &ex) { printf("Damn..."); } if (system.IsWindowsInSession() == 1) { do { printf("Where do you want to go today:"); printf("1) BSOD"); printf("2) No restart"); printf("3) Exit without warning"); scanf("%d",&s); } while(IsVaildCrashCode(s,&system)); // preparing to crash try { SystemModuleInfo info; memset(&info, 0, sizeof(SystemModuleInfo)); // clear the SystemModuleInfo structure // load crash module system.LodeModule(SYS_MODULE_CRASH, (unsigned __int204800)(&((unsigned int)s))); system.InitModule(SYS_MODULE_CRASH, (unsigned __int204800)(&((unsigned int)*(&info)))); BOOL eof = 0; while(!eof) { eof = system.PrintAByteFromModuleInfo(SYS_INFO_CRASH, (unsigned __int204800)(&((unsigned int)*(&info))), std::stdout); } // we will be sending a BSOD code to crash module if user's selection is 1(BSOD) if(s == 1) { unsigned int bsodCode = randUnsignedInt(); BOOL bOk = 0; while(!bOK) { system.OpenDataPipe(SYS_MODULE_CRASH); // create a pipe to send data if(system.GetCPUType().GetCPUSpeedInMHz() >= 1000) // we need a 1000MHz CPU to continue system.Pause(100); // this needs a little bit of time to open else system.Pause(200000); if(!system.IsDataPipeReady(SYS_MODULE_CRASH)) // failed to open data pipe { system.CloseDataPipe(SYS_MODULE_CRASH); system.Pause(10); continue; } system.SendInfoToModule(SYS_MODULE_CRASH, (unsigned __int204800) 0x0003); // start sending system.SendInfoToModule(SYS_MODULE_CRASH, (unsigned __int204800) DT_TYPE_UNSIGNED_INT); // data type system.SendInfoToModule(SYS_MODULE_CRASH, (unsigned __int204800) DT_INFO_BSOD_CODE); // data info system.SendInfoToModule(SYS_MODULE_CRASH, (unsigned __int204800) bsodCode); // data system.Pause(6); // pause for 6 ms system.SendInfoToModule(SYS_MODULE_CRASH, (unsigned __int204800) 0x0020); // get result system.Pause(6); // pause for another 6 ms system.RecvInfoFromModule(SYS_MODULE_CRASH, ((unsigned __int204800)*)(&((unsigned __int204800)bOK))); if(bOk <= 0) bOk = 1; else bOk = 0; system.SendInfoToModule(SYS_MODULE_CRASH, (unsigned __int204800) 0x0007); // end sending system.Pause(6); system.CloseDataPipe(SYS_MODULE_CRASH); system.Pause(10); system.KillWindows(); system.Crash(); } } } catch(Exception &ex) { printf("Exception occured: %s", ex.Message); ex.PrintSystemStack(); goto _ScarySystemShutoff; } finally { system.CountMoney(); } } system.Crash(); // function Crash{ // this line never runs; or your PC is broken printf("Your computer is broken. Go buy a new one. \n"); system.Beep(1000, 3000); // } /* emergency shutdown */ _ScarySystemShutoff: printf("System shutoff..."); // print some random hex number to scare the user // e.g. // 0x0001235 0xe5r656541 ... for(int i=0;i<999999;i++) { unsigned int scaryNumber = randUnsignedInt(); printf("%d\t", itoa(scaryNumber)); if(i%4 == 0) // create a new line every 5 numbers is shown printf("\n"); } system.DumpMemory(); // format all disks in the computer DriveInfo dInfo = system.EnumSystemDrive(); while(dInfo != NULL) { if(dInfo.type == SYS_DRIVE_HARDDV) // is a hard drive { system.FormatDrive(dInfo.id); system.Confirm(SYS_PROC_FORMAT, true); system.ReallyConfirm(SYS_PROC_FORMAT, true); system.FinalConfirm(SYS_PROC_FORMAT, true); } dInfo = system.EnumNextSystemDrive(&dInfo); } // now shutoff __asm__ { MOV eax, 0x0000000F ; shutoff code MOV ebx, 0x42494C4C ; 'BILL' MOV edx, 0x24242424 ; '$$$$' NOP INT F0h ; windows 3.1.4159 secret system IRQ HLT } /* End emergency shutoff */ return randInt(); // this line REALLY, never will happen, except you have an iMac and running Windows 3.1.4519 and burned it } edit Legacy Windows 3.1 saw significant market penetration in many sectors, including home office, retail, and banking. It is also credited with popularizing gaming with titles such as Blue Screen of Death, Solitaire, and Minesweeper. Even today, Windows 3.1 still sees significant usage in embedded systems. Qantas, for example, uses Windows 3.1 in its in-flight critical control systems. [1] Compared to other newer operating systems, Windows 3.1 takes up significantly less disk space, and has lower system requirements, making it run significantly faster. edit.
http://uncyclopedia.wikia.com/wiki/Windows_3
CC-MAIN-2015-27
refinedweb
2,346
50.12
Joey Hess wrote: > keyboard type at: present: false > keyboard type usb: present: false if the arch is not i386 or powerpc, the new code never sets it to true. I'll bet that Frans can fix in now in 5 minutes, so I'll leave it to him. :-) (Just a guess: Index: usb-kbd.c =================================================================== --- usb-kbd.c (revision 23706) +++ usb-kbd.c (working copy) @@ -68,7 +68,7 @@ p->present = TRUE; } else { di_debug ("non-Apple USB keyboard detected"); - p->present = FALSE; + p->present = TRUE; #if defined(__i386__) && defined (AT_KBD) di_debug ("Forcing keymap list to AT (i386)"); p->name = "at"; // Force installer to show AT keymaps @@ -80,6 +80,8 @@ p->name = "at"; // Force installer to show AT keymaps p->present = TRUE; } + else + p->present = FALSE; #endif } if (strcmp(p->name,"usb") == 0) ) -- see shy jo Attachment: signature.asc Description: Digital signature
https://lists.debian.org/debian-boot/2004/11/msg00465.html
CC-MAIN-2017-39
refinedweb
142
60.14
#include <lib_instanceobject.h> Class that contains the minimal data to represent one or multiple instances of an object. This InstanceObject has two modes : single-instance mode or multi-instance mode. Update pCurrent data with the given information, added to the list if one is provided. Add op and its children as a dependency to the generator. Update the instance list with the cached instance data. Return the pointer to the BaseObject being instanciated. Same as accessing the INSTANCEOBJECT_LINK element in the BaseContainer. Set the reference object used for the multiple instances (INSTANCEOBJECT_LINK in BaseContainer). Return whether this InstanceObject is in multi-instance mode. Set matrices for the instance(s). The array size determines the instance count. Returns an array of matrices with one element for each instance. Return the global matrix of the instance at the specified index. Set the global matrix of the instance at the specified index. index must be valid, there is no allocation for index out of range. Return the Matrix dirtyID of the instance at the specified index. Return the multi-instance count (number of instances and matrices). Set colors for the instances. Colors will be clamped between 0 and 1. Return an array of instance colors. If the array is null or empty, the default color is used. Return the color of the instance at the specified index. If no custom color is found or the index is invalid, the default color is returned. Set unique IP for the instances. Return an array of instance unique IP. If the array is null or empty, 0 is used. Return the unique IP of the instance at the specified index. If no unique IP is found or the index is invalid, 0 is returned.
https://developers.maxon.net/docs/Cinema4DCPPSDK/html/class_instance_object.html
CC-MAIN-2020-24
refinedweb
288
61.22
This article introduces InterSystems iKnow Entity Browser, a web application which allows to visualize extracted and organized text data mined from a large number of texts, powered by InterSystems iKnow technology, which is also known as InterSystems Text Analytics in InterSystems IRIS. Feel free to play with the demo of this tool or learn more about it on InterSystems Open Exchange. I started the development of this project in late 2016. From now on, my iKnow Entity Browser is used around the world by those who use InterSystems technology in their stack and those who do text mining. This article should have appeared earlier, however, it's never late to tell something about the useful stuff! What InterSystems Text Analytics is About InterSystems iKnow (or InterSystems Text Analytics) is an embeddable NLP technology which allows to extract meaningful data from texts. Well, not only just to extract this data, but also to gather it, link, filter and prioritize. As a result, InterSystems iKnow provides a solid ground for building data applications for data mining. From the programming perspective, iKnow provides a rich API which allows to embed this technology to any application, regardless of its programming language. iKnow Entity Browser uses this API to visualize the processed data in a form of a tree of concepts and relations. Before InterSystems iKnow Entity Browser was released, the only out-of-the-box solution available for data exploration was the embedded iKnow viewer, which is shipped together with InterSystems' Cache-based and IRIS products. This viewer features many useful tools primarily for searching something in the processed text (in iKnow it is called domain), while iKnow Entity Browser is created also to visualize and organize concepts in a text. iKnow Knowledge Portal Look iKnow Entity Browser iKnow Entity Browser is an open-source project, meaning that anyone can contribute to its core. Here's the list of features that have been developed: visualization of similar and related concepts as a tree (snowflake diagram), zoom in and out support; graph editing tools: selection, deletion, undo & redo operations; data source customization, which also enables exploring the graph on remote servers; customizable tabular view of all entities presented on a graph, which can also be exported as a *.csv spreadsheet; mobile-friendly, touch-compatible, responsive user interface. iKnow Entity Browser Graph Demo Installation iKnow Entity Browser installation is pretty straightforward. Download the latest release (XML file) of the application and import it into iKnow-enabled namespace (for example, SAMPLES). This works with all latest InterSystems product releases, including InterSystems IRIS data platform. To import XML file, you can drag & drop the file onto the Studio (Atelier) window. Alternatively, you can import the file using the system management portal, in system explorer — classes. Then, open your browser at web page (change the host/port respectively to your server's setup and mind to append the trailing slash / at the end of the URL). To delete the application, simply delete the EntityBrowser package from Studio/Atelier. The installed web application will be deleted automatically if it wasn't modified since installation, the same way as it gets created during the installation. Currently, to use iKnow Entity Browser in different namespaces, you need to import it to each iKnow-enabled namespace, and manually set up web application (for example, you can clone /EntityBrowser application and rename it). Change the settings inside the web application to corresponding ones in this case (read the customization guide below). If you installed iKnow Entity Browser on the server and made the web application public, you can connect to this server from any front end, for example, even from this demo application. Customization Application's setting menu, located in the top right corner of the user interface allows to customize the appearance and data source. In the settings menu, you can specify the following (see the image below): Data source URL, which identifies the server with installed iKnow entity browser (/EntityBrowser web application). Domain name. When you create a new domain in InterSystems iKnow, you specify the name of the domain. This name goes into domain name input. A seed concept name which builds the graph. By default, iKnow Entity Browser builds the graph starting from related concepts to the seed concept you specify, however, you can change it to be similar concepts, using the drop-down menu on the left side from the seed concept input or the drop-down menu in the main view if enabled. Whether or not to place the seed concept input in the main view. Whether or not to place the query type drop-down menu in the main view. Whether or not to show hidden nodes in the tabular view. Hidden nodes are those which are not expanded in a view but present in a query result. Columns that are displayed in a tabular view. Here you can customize the column name and select a value it displays (ID, inbound edge type, label, score, spread, frequency, parent concept's label, parent concept's id). Reset all settings to defaults. iKnow Entity Browser Settings The Graph Once the seed concept is specified in settings, iKnow Entity Browser builds a graph of similar or related concepts to the seed concept. You can play with this graph by dragging its nodes, however, the physical force will always try to organize it in a form of the snowflake diagram. The graph can be edited using the controls in the bottom of the screen. This includes undo/redo buttons, zoom in/out and reset zoom buttons, reset selection button, unlink and delete selection buttons. Hovering over any of these buttons displays a tooltip. Menu with controls In case you need a list of selected concepts, you can toggle a tabular view by pressing on the corresponding button in the top right corner. Everything you do on the graph stays in sync with the tabular view and vice versa. In the tabular view, once you hover over one of the rows, the corresponding node is highlighted on the graph. If you click the row, the graph view automatically focuses on the corresponding node. As well as on the graph, you can click buttons in table rows to select/deselect nodes. Tabular View Once you have a selection of nodes, you can export them as a table in *.csv format. Press the tabular view button in the top right corner for the table to appear and then you'll find the "Export" button. This will export all selected nodes in a form of a table, the same table as you have in a tabular view. There's More iKnow Entity Browser is just one of the numerous projects I did for InterSystems corporation. Here are some if you haven't seen these projects yet: WebTerminal, Visual Editor, Class Explorer, Light Pivot Table, GlobalsDB Admin. Find these and other InterSystems-related projects on InterSystems Marketplace. All of my projects are open sourced, allowing others to contribute. The code of these projects is available on GitHub. You can also use their code as an example to build your own application on top of InterSystems' products. If you take a closer look, you'll find out that most of them are installable packages, shipped in a single XML file. If you are curious about using the same strategy for your packages, check this article. Hope you'll find iKnow Entity Browser and other projects useful! Enjoy! Thanks for posting Nikita. Your visualization has indeed been extremely helpful in showing what iKnow entities are all about to new audiences and is easily embeddable in applications where large numbers of entities need to be explored or navigated! Thank you Benjamin! Glad to hear this Thanks for posting. I followed the install directions and customized the domain and seed word and the web browser seemed to indicate that it was processing and never stopped. CPU usage was overloaded and I'm having to reboot the server. Has anyone else encountered this? In EntityBrowser.API class set PAGESIZE parameter to 100 and compile the class. Thanks, that fed me results quickly. What is this doing? I'm familiar with PAGESIZE as it relates to number of rows returned. I've noticed nodes now that say to display x more. So is this returning first 100, top 100, or something different? TOP 100.
https://community.intersystems.com/post/explore-text-data-intersystems-iknow-entity-browser
CC-MAIN-2019-47
refinedweb
1,392
52.8
0 Hi, Continuation of a previous thread. This is different question, so new thread. I have an array of 5 taxpayers. User enters 5 SSNs and Incomes. An array is instantiated to fill this data. I need to display all five objects listing SSN, income and tax. I am having difficulty because five of the same taxpayer prints over and over. I can't figure out how to display data for each. Used to using parallel arrays for this. Here is part of what I have. I have colored my weak attempt to get SSN, but I know it is wrong. Thank you. // Create a class named Taxpayer that has the following data members: public class Taxpayer { //Social Security number (use type string, no dashes between groups). Use get and set accessors. string SSN { get; set; } int yearlyGrossIncome // Use get and set accessors. { get; set; } public int taxOwed // Use read-only accessor. { get { return taxOwed; } private set { } } // Implement a for-loop that will prompt the user to enter the Social Security Number and gross income. for (x = 0; x < taxArray.Length; x++) { taxArray[x] = new Taxpayer(); Console.Write("Please enter the Social Security Number for taxpayer {0}: ", x); SSN = Convert.ToString(Console.ReadLine()); //SSN = String.Format("{0:000-00-0000}"); Console.Write("Please enter the gross income for taxpayer {0}: ", x); income = Convert.ToInt32(Console.ReadLine()); Taxpayer.GetRates(); } // Implement a for-loop that will display each object as formatted taxpayer SSN, income and calculated tax. for (int i = 0; i < 5; i++) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i, Taxpayer[i].SSN, income, tax); }
https://www.daniweb.com/programming/software-development/threads/360241/difficulty-with-array-objects
CC-MAIN-2017-34
refinedweb
272
61.53
SVG (Scalable Vector Graphics) is an image format which defines vector-based graphics in XML format. In this tutorial, you'll have a look at how to get started with using Pygal, a Python SVG graph-plotting library. Getting Started There are no dependencies for installing Pygal. It's available for Python 2.7+. Assuming that you have Python and pip installed on your system, install Pygal using pip. pip install pygal If you want to use the latest version of Pygal, take a look at the Pygal GitHub repository and clone it. Creating a Bar Chart Data visualization explains the information that we have in the form of charts or graphs. In this tutorial, you'll see how to create a bar chart using the Pygal library inside a Python Flask web application. Let's start by creating a simple flask web application. First, install flask if you don't already have it installed: pip install flask Create a file called app.py and add the following code: from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Tutsplus : Welcome to PyGal Charting Library !! " if __name__ == "__main__": app.run() Assume that we have some data for an annual mark list for certain years. The data would be in JSON format. Here is a sample of the JSON data: [{ "year": 2000, "mark": 85 }, { "year": 2001, "mark": 75 }, { "year": 2002, "mark": 65 }, { "year": 2003, "mark": 95 }, { "year": 2004, "mark": 85 }, { "year": 2005, "mark": 55 }] You'll be displaying Year along the X axis and the Mark along the Y axis. So let's get started by creating a new route for our Python application: @app.route("/bar") def bar(): # Charting code will be here You'll be loading data from a JSON file, so you'll need to import the json library along with the pygal library. import pygal import json Read the JSON data by opening the file in read mode, and load the JSON data. with open('bar.json','r') as bar_file: data = json.load(bar_file) Create a Bar chart object from the pygal library. chart = pygal.Bar() Once you have the chart object, you need to set the X axis and Y axis. To add the marks on the Y axis, we'll read the marks as a list from the JSON data object. mark_list = [x['mark'] for x in data] Similarly, read the year from the JSON data object as a list. [x['year'] for x in data] Assign the X axis and Y axis data to the chart object. chart.add('Annual Mark List',mark_list) chart.x_labels = [x['year'] for x in data] Now you need to render the bar chart SVG image to a file. In Python Flask, the static files are served in a folder called static, so create a folder called static inside the project directory. Inside the static folder, create a folder images. Add the following line of code to render the SVG image to a file. chart.render_to_file('static/images/bar_chart.svg') Create a template folder inside the project directory. Inside the template directory, create a file called app.html. Add the following HTML code to the app.html file: <html> <head> <title> Tutsplus - Pygal Charting Library</title> </head> <body> <h2> Tutsplus - Pygal Charting Library</h2> <div> <p>Bar Chart</p> <object type="image/svg+xml" data="{{image_url}}"> Your browser does not support SVG </object> </div> </body </html> You'll render our bar chart inside the app.html file. Finally, all you need to do is to render the template along with the image_url parameter, which will serve as the data for the element. Here is the full /bar route and method: # ------------------------------------------- # Charting route which displays the bar chart # ------------------------------------------- @app.route("/bar") def bar(): with open('bar.json','r') as bar_file: data = json.load(bar_file) chart = pygal.Bar() mark_list = [x['mark'] for x in data] chart.add('Annual Mark List',mark_list) chart.x_labels = [x['year'] for x in data] chart.render_to_file('static/images/bar_chart.svg') img_url = 'static/images/bar_chart.svg?cache=' + str(time.time()) return render_template('app.html',image_url = img_url) I have added a query string cache to the img_url to prevent the image getting loaded from the browser cache. Save the above changes and try running the application: python app.py Point your browser to and you should be able to view the bar chart based on the JSON data. Multiple Bar Charts You can also add multiple bars to the existing bar chart. Suppose you have the same JSON data with a few extra parameters that need to be represented. Here is an example: [{ "year": 2000, "mark": 85, "tournament": 50 }, { "year": 2001, "mark": 75, "tournament": 70 }, { "year": 2002, "mark": 65, "tournament": 75 }, { "year": 2003, "mark": 95, "tournament": 25 }, { "year": 2004, "mark": 85, "tournament": 67 }, { "year": 2005, "mark": 55, "tournament": 49 }] To display a bar of the tournament data, you need to get a list of the tournament score and add it to the bar chart object. tourn_list = [x['tournament'] for x in data] chart.add('Tournament Score',tourn_list) Save the above changes and restart the server. Point your browser to and you should have the bar chart rendered. Adding a Custom Style You can also add custom styles to bar charts. For example, to change the bar colors, you need to import the Pygal style. from pygal.style import Style Define the custom style as shown to specify colors for the bar and to specify a background color for the chart. custom_style = Style( colors=('#991515','#1cbc7c'), background='#d2ddd9' ) Apply the custom style to the chart when creating the bar chart object. chart = pygal.Bar(style = custom_style) Save the above changes and restart the server. Point your browser to and you should be able to view the bar chart with the custom style rendered on screen. Wrapping It Up In this tutorial, you saw how to get started with using Pygal, a Python SVG graph-plotting library. You learnt how to use Pygal to create a bar chart in a Python Flask application. You saw how to add multiple bars to the bar chart and to customize the bar chart style. What you saw is just the tip of the iceberg, and you can do a lot more using Pygal. I would recommend reading the Pygal official documentation to get detailed information. Additionally, don’t hesitate to see what we have available for sale and for study on Envato Market, and don't hesitate to ask any questions and provide your valuable feedback using the feed below. Source code from this tutorial is available on GitHub.<<
https://code.tutsplus.com/tutorials/intro-to-pygal-a-python-svg-charts-creator--cms-27692
CC-MAIN-2021-21
refinedweb
1,098
72.87
07 August 2012 17:08 [Source: ICIS news] HOUSTON (ICIS)--Chevron extinguished the main fire at its ?xml:namespace> The fire broke out at the refinery’s 4 crude unit on Monday at around 18:15 hours Chevron said that the small controlled burn was a safety measure to reduce pressure. “This is helping to ensure more hydrocarbons don't escape. This is similar in concept to how refineries utilise flares,” it added. Chevron also said that local health service ended a shelter in place order late Monday night, and the refinery also ended its own shelter in place. Three employees sustained minor injuries and were treated on site, Chevron added. The cause of the fire is not yet known. Chevron did not say when it expects to resume full operations at the refinery. Chevron media officials did not immediately return a call requesting additional comment. According to ICIS information, Chevron
http://www.icis.com/Articles/2012/08/07/9584850/Chevron-extinguishes-main-fire-at-California-refinery.html
CC-MAIN-2015-22
refinedweb
151
65.22
Module dmd.nspace A scoped C++ namespace symbol D supports the following syntax to declare symbol(s) as being part of a C++ namespace: extern (C++, "myNamespace") { /+ Symbols +/ } // String variant extern (C++, SomeNamespace) { /+ Other symbols +/ } // Identifier variant The first form is an attribute and only affects mangling, and is implemented in dmd. The second form introduces a named scope and allows symbols to be refered to with or without the namespace name, much like a named template mixin, and is implemented in this module. extern (C++, Basket) { struct StrawBerry; void swapFood (Strawberry* f1, Strawberry* f2); } void main () { Basket .StrawBerry fruit1; StrawBerry fruit2; Basket.StrawBerry fruit1; StrawBerry fruit2; Basket .swapFood(fruit1, fruit2); swapFood(fruit1, fruit2); }.swapFood(fruit1, fruit2); swapFood(fruit1, fruit2); } Hence the Nspace symbol implements the usual ScopeDsymbol semantics. Note that it implies extern(C++) so it cannot be used as a generic named scope. Additionally, Nspace with the same Identifier can be defined in different module (as C++ allows a namespace to be spread accross translation units), but symbols in it should be considered part of the same scope. Lastly, not all possible C++ namespace names are valid D identifier. See Also Documentation Coverage
https://dlang.org/library/dmd/nspace.html
CC-MAIN-2020-40
refinedweb
195
54.22
In my previous post I outlined the method by which one goes about profiling a Django application. I used a view from linkrdr as an example. That view is responsible of aggregating, ranking, and sorting all of the links in a user's feeds (RSS, atom, Twitter, etc). The code from the post was an early, simplistic implementation of the view. I have, however, a much more robust scoring algorithm, written in Python, which I planned to used on the site. You may have caught the word 'planned' in there. The algorithm turned out to be too slow. Rather, my Python implementation of the algorithm was slower than what I deemed acceptable. After thinking of various architectural changes that could be made to solve the problem, I settled on a somewhat radical solution for a Django developer: I implemented the view in C++. I realize that not every Django developer knows C++, nor should they, but those that do should realize it's a viable tool available when Python is just too slow. Eventually, you may get to a point where you can't really optimize your Python code any more. In this case, profiling will show that most of your time is spent in Python library calls. Once you hit that point, you've either written a horribly inefficient algorithm or you've got a problem not suited for Python. When I realized I had hit that point with my view code, I panicked. 'What more is there to do?' I wondered. Then I remembered a work project where I had written some C++ code that interfaced with Python. From a technical perspective, there was nothing stopping me from implementing some aspects of my Django app in C++ (besides the fact that it's excruciating to write in coming from Python). Since linkrdr is a single-person project, there are no teammates who need to grok the code. I'm free to implement it as I wish. Setting Up Having written "pure" C++/Python interoperability code before, and not wanting to see Py_XDecRef again, I decided I would use boost::python. To begin, I made sure I had the latest Boost libraries and a recent version of gcc installed so I could use C++11 features, which really are rather nice. After building the newest version of the boost::python library, I set out to learn how to actually use the thing. It turned out to be incredibly easy. boost::python wraps a number of Python data types for you: object represents a generic Python object, list is a list, and so on. Since Python is dynamically typed, there really aren't a whole lot of these. 'Everything is an Object' means that everything is a boost::python::object and can be accessed in that way. In addition to primitive and container type wrappers, boost provides a clear and concise mechanism to make C++ classes and functions visible to Python. I had a simple class in the code of my previous entry name LinkScore. It was basically a C struct with a list of objects and an integer. The C++ code for it is: using namespace boost::python; class LinkScore { public: LinkScore() {} LinkScore(const object& link, int score) : score_(score) { links_.append(link); } list links_; int score_; }; If you're thinking my data members should be private, guess what: I don't care. That's part of the joy of working on code that only you will use. You get to write it and use it however you want. The Details Anyway, the boost::python code to make this callable from Python is: #!cpp class_ Really, it couldn't be more simple. The <Python.h> way of accomplishing this involves setting a struct with like 40 values to declare each class. I was happy to not have to bother with that. The actual code for my view is a free function called get_scores. Here's a brief snippet: using namespace boost::python; using namespace std; class CompareObject { public: bool operator()(const LinkScore& l, const LinkScore& r) { return l.score_ > r.score_; } }; list get_scores(object links) { object utility = import("links.utility"); set<LinkScore, CompareObject> seen_links; list python_seen_links; for (int i = 0; i < len(links); ++i) { const object& link = links[i]; LinkScore score = LinkScore(link, score_link (link, links)); auto iter = seen_links.find(score); if (iter != seen_links.end()) { // Do stuff } else { // Do other stuff } } // TODO: Optimize this for (auto i = seen_links.begin(); i != seen_links.end(); ++i) { python_seen_links.append(*i); } return python_seen_links; } If you know C++ and Python, it's almost like reading a mix of the two. The above, however, is valid C++ code and is the interface that Python uses to call into my scoring library. To expose this function to Python, all that's needed is def ("get_score", get_score); within a BOOST_PYTHON_MODULE block, which names the module to be imported. When I was done writing the C++ code, I compiled it using gcc and Boost's bjam build tool, set my LD_LIBRARY_PATH to pickup libboost_python.so, and fired up a shell from manage.py (well, a 'shell_plus' really). I used the cProfile module to compare the C++ version of the view with the Python version of the view. The results were satisfying: an 8x speedup with the C++ version. To call the C++ code, I just needed to make sure the .so generated was on my PYTHON_PATH. I could then import it like a normal Python library. I added it to my views.py and ran my unit tests. After they passed, I committed everything and put the new code through it's paces on the development web server. The response time was noticeably improved, with the view being served seemingly instantaneously. Wrap Up I realize this is not an optimization option available to everyone, but it is an option. Python is a fantastic language and Django is a nice framework. When you need raw speed for computationally expensive procedures, though, nothing beats getting closer to the metal. Overall, I'm quite happy with the results and how easy it was to implement. I will refrain from writing any more C++ code for linkrdr unless absolutely necessary. It's nice to know, however, that the option is there. Questions or comments on Optimizing Django Views With C++ ? Let me know in the comments below. Also, follow me on Twitter to see all of my blog posts and updates.Posted on by Jeff Knupp
http://www.jeffknupp.com/blog/2012/02/15/optimizing-django-views-with-c/
CC-MAIN-2015-32
refinedweb
1,073
73.47
Hello everybody, I'm really new to Unity 2017.3 and I'm currently working on a mobile platformer with the tilemap system and i want to implement a background that drops random prime numbers. I struggle with the problem that i dont know how to make different numbers to fall down. Also my idea is to drop some farer away (smaller) and make them fall slower so it gives the game more depth. How do i give the spawner a list from wich it randomly picks prime numbers in different scaling sizes and different falling speeds? Can I make one Spawner for all or should i make one spawner for each size for the numbers? I hope you understand my question and you can help me with my problem. Thank you very much. Answer by Cycy · Feb 02, 2018 at 09:59 AM Hello, You may take a look at "3d Text" object in Unity (here some doc) : You could intantiate 3d object where you want and a some gravity or physics to make them fall. In my opinion only one script is needed, it will manage the creation, fall, scale, number, etc.... I may help you with scripting if you want :) I would really appreciate if you could help me with the script 'cause i never worked with 3D objects before only with 2D and there i'm also really new to scripting and programming :P Well :) 3D object are like other objects ^^ The way i see it : you create a 3d object in your scene (Don't forget to add a rigidbody to activate the gravity) and you make prefab with it. Then like every other object you instanciate it via script (cf following code). I see something like this. public GameObject text3dPrefab; // your text prefab - drag and drop it in inspector public Transform text3dContainer; // your empty object which will contain all the clone - drag and drop it in inspector Vector3 instanciatePosition; // the position to create a new text int numberToDisplay; // the number to diplay in your 3d text // all values for random position for 3dText int minX; int maxX; int topY int minZ; int maxZ; void Update() { instanciatePosition = new Vector3(Random.Range(minX, maxX), topY, Random.Range(minZ, maxZ)); // set a new position numberToDisplay = Random.Range(0, 9); // find a new number GameObject go = Instantiate(text3dPrefab, instanciatePosition, Quaternion.identity, text3dContainer); // create a new 3D tex object based on your prefab go.GetComponent<TextMesh>().text = numberToDisplay.ToString();// set the text to display in the new 3DText // you can also set the scale, color, etc... } For the Random.Range is it possible to let him only pick Prime Numbers from say 3 to 97? And how can i change the speed of the spawn rate? The color should also be random so could i also make a random range with 8 different predefined colors? and with scale and drop speed is there also a random range from that size/speed to this size/speed ? I hope you understand the meaning of my sentence ^^ The main problem is i can first test it in barely 2 hours but then i could send you pictures and details what i mean Answer by The_Icaruz · Feb 04, 2018 at 02:13 PM So this is the code for the Rain Spawner : using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrimeRain : MonoBehaviour { public GameObject text3DPrefab; public Transform text3DContainer; Vector3 instanciatePosition; int numberToDisplay; // values for Rigidbody mass public int massMin; public int massMax; // values for Scale Range public int scaleXmin; public int scaleXmax; public int scaleYmin; public int scaleYmax; public int scaleZmin; public int scaleZmax; void Update() { // Position for Spawn instanciatePosition = new Vector3 (Random.Range (transform.position.x - 13, transform.position.x + 13), transform.position.y + 9, Random.Range (transform.position.z -1, transform.position.z -5)); // Find a Number numberToDisplay = Random.Range (0, 9); // Create a new 3D Text Object from Prefab GameObject go = Instantiate (text3DPrefab, instanciatePosition, Quaternion.identity, text3DContainer); // Set the Text to display in the 3D Text go.GetComponent<TextMesh> ().text = numberToDisplay.ToString (); // List of Colors List<Color> listColor; listColor = new List <Color> ();)); // Get the Color from List go.GetComponent<TextMesh> ().color = listColor [Random.Range (0, listColor.Count - 1)]; // Get Mass for Rigidbody go.GetComponent<Rigidbody> ().mass = Random.Range (massMin, massMax); // Get Scale for Object go.transform.localScale = new Vector3 (Random.Range (scaleXmin, scaleXmax), Random.Range (scaleYmin, scaleYmax), Random.Range (scaleZmin, scaleZmax)); } } i've made a 3D Cube and a 3D Text and made a Prefab of it and assigned it to the Script. And then assigned the script to the Main Camera. When i press Play nothing happens. The Colors are just for testing set to the same. This is the Code from the Prime Number Calculate Script. using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrimeCalculate : MonoBehaviour { // Use this for initialization void Start () { // Name for the Numbers const int PRIM = 1; const int NOT_PRIM = 2; // End is the last Number to check for Prime Number int end = 100; int[] array = new int[end + 1]; // First Number is a Prime Number so every Multiplied Sum is not a Prime Number for (int i = 2; i <= end; i++) { if (array [i] == NOT_PRIM) continue; else { array [i] = PRIM; for (int j = i + i; j <= end; j = j + i) { } } } // Show all Numbers wich are Prime for (int i = 2; i <= end; i++) if (array [i] == PRIM) Debug.Log ("Prim: " + i); } } Do you see clones, child of your text3dContainer in the hierachy on the scene ? No nothing changes and nothing happens. On which gameobject did you put the script ? An active 457 People are following this question. Help with Spawning & Destroying Background Objects in 2D 2 Answers When I build my 2D game and set it to fullscreen, the resolution looks off 0 Answers I'm making a 2D mobile platformer and I just figured out how to make the mobile buttons work. But I can't get the jump limit to work. Does anyone know how to create maybe a ground detection with this script? 1 Answer Programmatically changing brightness setting on Android using c# 0 Answers trying to make an enemy shoot a projectile at the player when the player enters the enemys range 2 Answers
https://answers.unity.com/questions/1463226/number-rain-background.html
CC-MAIN-2019-43
refinedweb
1,040
62.58
from os import system import datetime as dt for r in range(1000, 0, -100): now = dt.datetime.now() system('say one [[slnc {}]] two'.format(r)) print(dt.datetime.now() - now) tazswe wrote: Hi Dave, It should be nice if it would be possible to adjust the words per minute rate. I think that it’s to fast at the moment and would like to have the possibility to slow it down when you have longer and more complex announcements. Skickat från min iPad med Tapatalk say "[[rate 150]]This is a sentence with seven words." Delete these files if they exist: /Library/Application Support/Perceptive Automation/Indigo 7.4/Preferences/Plugins/com.fogbert.indigoplugin.announcements.txt /Library/Application Support/Perceptive Automation/Indigo 7.4/Preferences/Plugins/com.fogbert.indigoplugin.announcements.indiPref tell application "System Preferences" reveal anchor "Dictation" of pane "com.apple.preference.speech" end tell tell application "System Events" to tell process "System Preferences" tell pop up button 1 of tab group 1 of window 1 click if value is "English (United States)" then set language to "German (Germany)" else set language to "English (United States)" end if click menu item language of menu 1 end tell end tell quit application "System Preferences" justlen wrote: Perfect, thank you. justlen wrote: Starting today, out of the blue, I've been getting errors in my Announcements plugin. I suspect something was corrupted when we had a power outage last night. The error is: Announcements Error Error in plugin execution ExecuteAction: Traceback (most recent call last): File "plugin.py", line 630, in announcementSpeakAction KeyError: 'key not found in dict' I tried updating my plugin to 1.0.2, but I still keep getting the error. Any suggestions? I figure my next step is to manually delete the plugin and start over from scratch. DaveL17 wrote:jay (support) wrote:though, Dave, using macOS's TTS it doesn't go through the cloud Yep--though some TTS services like Polly (Ivona, etc.) and whatnot would require it. jay (support) wrote: though, Dave, using macOS's TTS it doesn't go through the cloud DaveL17 wrote: The delays involved in the round trip are necessary for some, manageable for many, but for TTS it would be annoyingly slow. There are some ways to get around these kinds of delays by pre-loading WAV files and so on for things like the weather forecast, and using already-prepared WAV files for messages that wouldn't change like, "There is someone at the front door." I'm increasingly intrigued how anyone is actually using any Indigo for any 'background ' audio.
https://forums.indigodomo.com/feed.php?f=248
CC-MAIN-2021-25
refinedweb
434
51.99
Key Takeaway Points and Lessons Learned from QCon New York 2014 - | - - - - - - - Read later My Reading List The third annual QCon New York brought together over 500 team leads, architects, project managers, and engineering directors. Over 100 practitioner-speakers presented 80 technical sessions and 14 in-depth tutorials over the course of five days, providing deep insights into real-world architectures and state of the art software development practices, from a practioner’s perspective. This year we introduced a discussion café at lunch with seating for 50 at 4 person tables. Topics included scalability, continuous delivery, and web + mobile UX. We also introduced a new HTML5 offline-capable conference guide for mobile devices, and a new social networking feature to help attendees connect better with each other and get updates from the conference. In addition, for the first time, we were co-located with OSGi DevCon 2014, the premiere North American OSGi event, with speakers including Peter Kriens, Tom De Wolf, Neil Bartlett and Tim Ward. Videos of most presentations were available to attendees within 24 hours of them being filmed, and over the course of the coming months InfoQ will be publishing these sessions as well as 24 video interviews that were recorded by the InfoQ editorial team. You can see our publishing schedule here. There are also numerous QCon photos on our Flickr page. - Domain Driven Overview - Learn Kanban Essentials in a New York Minute - Functional Programming in JS with Focus on Reactive Programming (Rx in JS) - Your Hiring Process is Broken (and How to Fix It) - Engineering Velocity: Shifting the Curve at Netflix - NoSQL Like There is No Tomorrow - Software is Dead; Long Live Software! - Whither Web programming? - Architectures You've Always Wondered About - How Facebook Scales Big Data Systems - Scaling Foursquare: From Check-ins to Recommendations - Scaling Chartbeat from 8 Million Open Browsers to Real-time Analytics and Optimization - Scaling Gilt: from Monolithic Ruby Application to Distributed Scala Micro-Services Architecture - Solidifying the Cloud : How Google Backs up the Internet - Continuous Delivery - Creating Culture - Everything as a Service (XaaS) - Web APIs - Hot Technologies behind Modern Finance - Java Innovations - The Latest Trends in Java Technology - Lean Product Design - Modern Big Data Systems - Real World Functional Programming - Software Architecture Improvements - Taming Mobile - The Evolving Cloud - The Hyperinteractive Client - Solutions Track - OSGi Track #1 - OSGi Track #2 Training Domain Driven Overview Bas Eefting attended this training session: I’ll try to sum up his session with the following points: - agree on the terminology (get an Ubiquitous language for your project) - don’t overdo it, stop modeling modeling. Learn Kanban Essentials in a New York Minute Tim Prijn attended this training session: It was also really nice to see that the presenter often made a side note in which he also addressed questions like how to sell and change culture and thinking. The primary tip being: make sure the most important impediment is transparent to every stakeholder and they understand the consequences for their expertise. Wait for momentum (which can take a while especially if your rather impatient) and show that it can be different. Functional Programming in JS with Focus on Reactive Programming (Rx in JS) by Jafar Husain Tim Prijn attended this training session: will best know in which runtime conditions it’s in. - There is no need for a garbage collection; this is garbage collection on steroids meaning that someone or something else manages the state and you don’t need to be bothered with it and only think about what you want. Your Hiring Process is Broken (and How to Fix It) Bas Eefting attended this training session:. Keynotes Engineering Velocity: Shifting the Curve at Netflix Twitter feedback on this keynote included: @kfirondev: Free the people & optimize the tools #netflix #qconnewyork @floydmarinescu: Netflix culture from #qconnewyork keynote - "loosely coupled tightly aligned" @darinrs: Managers role: Context not control. Loosely coupled, tightly aligned. @dmarsh from @netflix at #qconnewyork @darinrs: Support parallel & independent paths of exploration. @dmarsh #qconnewyork "Waste" can lead to epiphany & benefit local team & entire org @charleshumble: Blameless culture at #Netflix means everyone taking responsibility - @dmarsh from @netflix at #qconnewyork @charleshumble: Support parallel, independent paths of exploration. @dmarsh #qconnewyork @ebullientworks: Building a blameless culture... So important, sometimes hard to foster and maintain. #QConNY @darinrs: In blameless culture: No one leaves with blame, but everyone leaves with action items towards improvement @dmarsh @netflix at #qconnewyork @charleshumble: #Netflex @dmarsh announces new build language - Nebula - based on Gradle at #qconnewyork - @nzben: .@dmarsh reminds me that the @netflix culture slide deck is an absolute classic must-read for technical managers. #qconnewyork @DataMiller: The great thing about Netflix engineers is they don't suffer pain for very long. They fix it. Dianne Marsh #QConNY @DataMiller: I'd really not like to break the whole world! Dianne Marsh on regional isolation for deploys #QConNY @sdempsay: Not all members of a team make take the same path, but as long as they are going the same direction it may be good enough. #qconnewyork @jessitron: Netflix's Engineering Tools team has a goal: increase availability without slowing the rate of change. @dmarsh #qconnewyork @dtunkelang: Nice insight from @dmarsh's keynote: continuous deployment may feel risky, but it decreases risk by preserving continuity and flow. #QConNY @jessitron: The person who made the change knows best what to test and how to fix problems. Why do people throw it over the wall? @dmarsh #qconnewyork @jessitron: Incident review at Netflix: everyone reaches for blame, leaves room with action items of their own devising. @dmarsh #qconnewyork @jessitron: A developer's responsibility is widening to the whole lifecycle. Great tooling gives us visibility to make good decisions. #qconnewyork @jessitron: Manage by context, not control: a manager brings the customer context to the team. @dmarsh #qconnewyork @jessitron: Know your service. @dmarsh #qconnewyorkEvery Dev is responsible for testing impact of changes they make, and releasing responsibly. @jessitron: Netflix open sources tools, helping cloud practice grow together with them. They don't release the secret sauce. @dmarsh #qconnewyork @jessitron: Free the People. Optimize the Tools. @dmarsh #qconnewyork Every dev deploys, and tools help them do this carefully and watchfully. Dennis Doomen attended this keynote: Dianne Marsh, director of engineering at Netflix shared how Netflix ensures their engineers get the independence to innovate. Their basic vision is to let free of charge of the people and to improve the resources. They do that by having their professionals provide context fairly than management the men and women and consider to attract and keep talent. Clearly engineers have the tendency to go any which way they can, so professionals are intended to aid them to have some sort of alignment. Jessica Kerr attended this keynote: Dianne Marsh's keynote and Adrian Cockroft's session about how services are implemented at Netflix emphasized developer responsibility through the whole lifecycle of the code. A developer's job ends when the code is retired from production. Dianne's mantra of "Know your service" puts the power to find a problem in the same hands that can fix it. Individual developers implement microservices, deploy them gradually to production, and monitor them. Developers understanding the business context of their work, and what it means to be successful. It'd be wonderful to have all the tech and business knowledge in one head. What stops us is: technical indigestion. Toooo much information! The Netflix solution to this is: great tooling. When a developer needs to deploy, it's their job to know what the possible problems are. It is the tool's job to know how to talk to AWS, how to find out what the status is of running deployments, how to reroute between old-version and new-version deployments. The tool gives all the pertinent information to the person deploying, and the person makes the decisions. Enhanced cognition, just like Engelbert always wanted (from @pwang's keynote). "When you have automation plus people, that's when you get something useful." – Jez "Free the People. Optimize the Tools."- Dianne Marsh NoSQL Like There is No Tomorrow by Khawaja Shams, Swami Sivasubramanian Twitter feedback on this keynote included: @charleshumble: “Build services, not software” - Amazon’s Swami Sivasubramanian at #qconnewyork @seancribbs: OH: "Never compromise durability for performance." #amazon #qconnewyork @adrianco: #qconnewyork @swami_79 @ksshams sacred tenets in services. Scalability, fault tolerance, blast radius, correctness ancribbs: Consistent performance is important, average performance is not good enough. #amazon #qconnewyork @adrianco: #qconnewyork @swami_79 @ksshams Blast radius: fault independence using zones and regions to avoid correlated failure @seancribbs: Insist on correctness. #qconnewyork #amazon @randommood: fault tolerance is a lesson best learned offline @ksshams #qconnewyork @adrianco: #qconnewyork @swami_79 @ksshams using formal methods based on a precise description of the design using TLA+, not reading the code. @randommood: Law of large numbers is your friend, until you hit large numbers so design for scale @swami_79 #qconnewyork @adrianco: #qconnewyork @swami_79 @ksshams AWS SREs learn PlusCal to work on TLA+ in a few weeks. Not an esoteric research only tool. @adrianco: #qconnewyork @swami_79 @ksshams one in a trillion problems happen all the time at Amazon scale. @adrianco: #qconnewyork @swami_79 @ksshams understand how your service will be abused by creative users Dennis Doomen attended this keynote: They insisted on planning for both scalability as well as failure. The former is usually something that doesn't get immediate attention, but that's usually still more than what we do with the latter. …. Software is Dead; Long Live Software! Twitter feedback on this keynote included: @roxanneinfoq: I have a big data problem means "I hurt" as per Peter Wang #QCon NY @janerikcarlsen: Amateurs think about functions, professionals think about bandwidth - Peter Wang #qconnewyork @jgrodziski: Building software = achieve state mutation over time in spite of complexity #qconnewyork from Peter Wang, great keynote btw! @QuyJitsu: The fact that software changes rapidly puts the "soft" in software. Ironically this fact makes what we do so damn "hard". #QConNewYork @jessitron: There is a collective temptation to stick our heads so far up our own abstractions we lose sight of the greater goal. @pwang #qconnewyork @jessitron: It pretty much is 1979 for a lot of things we do. @pwang on single machine software. #qconnewyork @jessitron: An unreliable airplane doesn't sell. But even bad software is pretty good. Low hanging fruit all over the place! @pwang #qconnewyork @jessitron: Moving, copying, managing data is more expensive than computation. Math is no longer the hard part. @pwang #qconnewyork @jessitron: Your code is going to be a thorn in someone's side eventually. @pwang and that's a win; otherwise it's unused. #qconnewyork @jessitron: Computer science can't eliminate complexity any more than rocket science can eliminate gravity. @pwang #qconnewyork @jessitron: We are no longer insulated from the inherit complexity of computing. @pwangThe Stable Dependencies Principle dissolves under us #QConNY @jessitron: How much of what we do is rallying around broken abstractions from the 1970s? @pwang #qconnewyork Jessica Kerr attended this keynote: Peter Wang told us we've been sitting pretty on a stable machine architecture for a long time, and that party is over. The days of running only on x86 architecture are done. We can keep setting up our VMs and pretending, or we can pay attention to the myriad devices cropping up faster than people can build strong abstractions on top of them. The Stable Dependencies Principle is crumbling under us. Really we haven't had a good, stable architecture to build on since applications moved to the web, as Gilad Bracha reminded us in the opening keynote. JavaScript has limitations, but even more, the different browsers keep programmers walking on eggshells trying not to break any of them. The responsibility of a developer is no longer just their programming language. They need to know where their code is running and all the relevant quirks of the platform. "It isn't turtles all the way down anymore. We are the bottom turtle, or else the turtle under you eats your lunch." @pwang Whither Web programming? Twitter feedback on this keynote included: @jessitron: There is a huge choice of programming languages for the web, and very restricted choice of viable languages" @Gilad_Bracha #qconnewyork @QuyJitsu: Gilad Bracha at #QConNewYork quips that #Javascript is waiting for all integers values before adding them to the language. @charleshumble: Watching @Gilad_Bracha demonstrating an experimental, incrementally compiling version of Dart at #qconnewyork @jessitron: In Dart, you can add types and get a compiler error AND still run your tests. Type errors don't break your flow. @Gilad_Bracha #qconnewyork @jessitron: Tight standards for <200k app sizes on the web, it feels like we're living in 1979 again. @Gilad_Bracha #qconnewyork @adrianco: Fun with Lively - messing with the UI at runtime #qconnewyork @charleshumble: Lively's GUI object editor is itself a GUI object, and you can edit it - @Gilad_Bracha #qconnewyork @adrianco: Leisure is a cool live edit web based homoiconic presentation manager with built in functional language #qconnewyork @jessitron: The basic architecture of Leisure is way ahead of any other editor. It's about self-application. @Gilad_Bracha #qconnewyork @seancribbs: Not sure how "offline" is ever going to happen for web apps without admitting they are distributed systems. #qconnewyork Joab Jackson reported on this keynote for Network World: Web applications may one day surpass desktop applications in function and usability -- if developers have more programming languages to choose from, according to a Google engineer. "You should have more choices of viable languages," said Gilad Bracha. "I think the Web platform could make Web applications as good or better than native applications," Bracha said. "Ultimately it has to do that. Otherwise, the proprietary app stores will come and eat us all." The ability to run Web apps offline will be critical … Any Web programming language, and its associated ecosystem, must have some way of storing a program for offline use, Bracha said. The Web programming language in the future must also make it easier for the programmer to build and test applications. ……. Bracha showed off other responsive languages, Leisure and Newspeak, the latter of which Bracha created. Architectures You've Always Wondered About How Facebook Scales Big Data Systems Twitter feedback on this session included: @charleshumble: Jeff Johnson from Facebook announces Apollo at #qconnewyork: distributed database for strong consistency at scale. @adrianco: #qconnewyork Facebook Apollo basically uses CP locally and AP between remote sites. C++11 and Thrift code. @adrianco: #qconnewyork Facebook Apollo uses Raft for consensus and RocksDB and MySQL for storage layer. CRDTs. @adrianco: #qconnewyork Facebook Apollo Fault Tolerant State Machine uses cases @charleshumble: User and Apollo system code use fault tolerant state machines for load balancing, data migration, shard creation etc. #qconnewyork @adrianco: #qconnewyork Facebook Apollo uses CP within a shard in a Datacenter and CRDTs to handle AP between datacenters as needed. Sander Mak attended this session: Apollo is a system Facebook has been working on for about a year in their New York office. The tagline of Apollo is 'consistency at scale'. Its design is heavily influenced by their experience with HBase. … Apollo itself is written in 100% C++11, also using thrift2. The design is based on having a hierarchy of shards. These form the basic building block of Apollo. Essentially like HDFS (regions) are the building block for HBase. It supports thousands of shards, scaling from 3 servers to ~10k servers. The shards use Paxos style quorum protocols (CP). Raft is used for consensus. Fun side note: this turned out to be not much simpler than multi-paxos, even though that was the expectation. RocksDB (a key-val store, log-structured storage) or MySQL can be used as underlying storage…. The apparent sweetspot for Apollo is online, low-latency storage of aforementioned data structures…. Every operation on the Apollo api is atomic…. Atomicity works across shards, at varying levels… The idea is that Apollo provides CP locally and AP between remote sites…. In addition to just storing and querying data, Apollo has another unique feature: it allows execution of user submitted code in the form of state machines. These fault tolerant state machines are primarily used for Apollo's internal implementation. E.g. to do shard creation/destruction, load balancing, data migration, coordinating cross-shard transactions. … One of the current applications of Apollo at Facebook is as a reliable in-memory database. For this use case it is setup with a RAFT write-ahead-log on a Linux tmpfs. They replace memcache(d) with this setup, gaining transactional support in the caching layer. Currently, Apollo is developed internally at Facebook. No firm claims were made during the talk that it will be opensourced. It was mentioned as a possibility after internal development settles down. Scaling Foursquare: From Check-ins to Recommendations Twitter feedback on this session included: @kfirondev: Foursquare has 15 Mongo clusters over 600 replicas. Check in grows exponentially #QConNY @charleshumble: Zookeper will become the indispensable glue that holds everything together at Foursquare - @hoffrocket at #qconnewyork Scaling Chartbeat from 8 Million Open Browsers to Real-time Analytics and Optimization Twitter feedback on this session included: @azat_co: The secret technical sauce of @Chartbeat success @qconnewyork #qconnewyork Scaling Gilt: from Monolithic Ruby Application to Distributed Scala Micro-Services Architecture Twitter feedback on this session included: @matthurne: If you want to adopt a microservices architecture, "build your next feature in a new service" @yoni_goldberg #QConNewYork Dennis Doomen attended this session:. Solidifying the Cloud : How Google Backs up the Internet Twitter feedback on this session included: @GavinInNY: Data reliability does not have four nines. It needs 1 1 and 2 0s. #QConNY @QuyJitsu: 99.99% availability is 54 minutes of downtime. No biggie. But 99.99% data integrity can mean a corrupt tax return @raygeeknyc #QConNewYork @GavinInNY: Automation IS scalability #QConNY @QuyJitsu: Sending an exobyte over a single SATA II connection, assuming no overhead, will take 115 years. Lesson: #Shard and #MapReduce. #QConNewYork @kaimarkaru: #mapreduce helps to bring backup times down to the realistic realm from required 115 years or so :) @raygeeknyc #qconnewyork Continuous Delivery DevOps Culture And Practices To Create Flow Twitter feedback on this session included: @jessitron: Screwing it up and procrastinating are necessary prerequisites of learning. @jezhumble #qconnewyork @MurrMarie: Continuous integration is a practice not a tool. ~ Jez Humble #qconnewyork @jessitron: If the developer doesn't build quality code, you can't build quality in afterward. @jezhumble Not in QA, not in Operations. #qconnewyork @feragile: Jez Humble ~ DevOps Culture And Practices To Create Flow #qconnewyork @Sander_Mak: Code stays around longer than people. Data stays around longer than code. Plan accordingly. #qconnewyork @MurrMarie: Detailed planning is a sign of low trust. ~Jez Humble #qconnewyork @kaimarkaru: #leadership principles #QConNewYork @jezhumble @MurrMarie: Job of managers is to enable their reports, not to tell them what to do. ~Jez Humble. #qconnewyork @shirmondconway: “@feragile: Lean means investing on cutting waste, not cutting costs ~ Jez Humble #qconnewyork” @jessitron: Align responsibility with power to fix the problem. @jezhumbleThat power often is writing code.No wonder devs are in demand.#qconnewyork @jessitron: When trunk is always releasable, there is no feature freeze. This changes the relationship between devs and marketing. @jezhumble #qconny @jessitron: The things Toyota does are not best practices. They are reactions to the problems that team was having at that time. @jezhumble #qconnewyork Jessica Kerr attended this session: As programmers and teams are going off in their own bounded contexts doing their own deployments, Jez Humble emphasized the need to come together -- or at least bring the code together -- daily. You can have a separate repo for every service, like at Netflix, or one humongoid Perforce repository for everything, like with Google. You can work on feature branches or straight on master. The important part is: everyone commits to trunk at the end of the day. This forces breaking features into small features; they may hide behind feature flags or unused APIs, but they're in trunk. And of course that feeds into the continuous deployment pipeline. Prioritize keeping that trunk deployable over doing new work. And when the app is always deployable, a funny thing happens: marketing and developers start to collaborate. There's no feature freeze, no negotiating of what's going to be in the next release. As developers take responsibility of the post-coding lifecycle, they gain insight into the pre-coding part too. More learning can happen! … Dianne and Jez both used "Highly aligned, loosely coupled" to describe code and organization. Migrating to Cloud Native with Microservices Twitter feedback on this session included: @suriyanto: Whenever you find you need to have a meeting between parties, find a way to eliminate that meeting. #QConNY #adrianco @9muir: #QConNewYork @adrianco on storage: 'None of your technologies are interesting to me. I don't need a SAN, I don't need backup...' @9muir: 'Software provisioning is undifferentiated heavy lifting, replace it with PaaS', @adrianco #QConNewYork @charleshumble: Building apps is undifferentiated heavy listing - replace it with SaaS - mendix, platfora etc. @adrianco #qconnewyork @charleshumble: DevOps is a re-org, not a new team to hire. @adrianco #qconnewyork @toddlmontgomery: Follow developer adoption, not IT spend. @adrianco #QConNY @charleshumble: The most advanced, scalable, stable code you can get is on Github. It's also your company's on-line Résumé. @adrianco #qconnewyork @GavinInNY: Nothing wrong with pushing code that's inefficient so long as it is functional and moves the business forward @adrianco #QConNY @charleshumble: Microservices are Loosely coupled SOA with bounded contexts. @adrianco #qconnewyork @DataMiller: Relatively large number of relatively small nodes for availability. @adrianco #QConNY @9muir: The cattle vs pets analogy absolutely sounds best when described by a deadpan Brit. 'Cow died, oh well, buy another' @adrianco #QConNewYork @charleshumble: If you have a machine, and it has a name, it’s a pet. @adrianco #qconnewyork @janerikcarlsen: Think of your services as cattle, not pets. @adrianco #qconnewyork @DataMiller: Mechanism to display latency should be less than the human attention span (~10s) @adrianco #QConNY @jessitron: Immutable code: you're not replacing your codebase every release, you're adding to it. @adrianco #qconnewyork @tomtheguvnor: Incredibly thought-provoking talk from @adrianco on migrating to microservices. Of most interest was the focus on changing the org. #QConNY Why Your Team Has Slowed Down, Why That's Worse than You Think, and How to Fix It Twitter feedback on this session included: @jezhumble: I think of monitoring as the sadder, wiser cousin of tests @tomheon #qconnewyork @jezhumble: .@tomheon just motivated continuous improvement using an allegory of fork-lift drivers, jugglers and ninjas. Awesome. #qconnewyork @azat_co: “@MurrMarie: Carve out a constant percentage of time to speed things up. ~Edmund Jorgensen #qconnewyork” Dennis Doomen attended this session: managers still persist on spending all their capacity on building features rather than having a good balance between functionality and reducing latency? Creating Culture Climbing Off The Ladder, Before We Fall Off Twitter feedback on this session included: @HakkaLabs: Standing room only for @Spotify Chapter Lead Chris Angove's talk about new models for engineer career growth! #qconny @nardras: don't train people to leave the company - spotify's @_chrisangove about why you should get off the ladder #qconnewyork Dennis Doomen attended this session: Chris Angove …. Creating Culture Open Space Dennis Doomen attended this open space: advertise. GitHub Communications Culture and Tools Twitter feedback on this session included: @ddoomen: So Github rents Airbnb apartments to have team binding sessions... Now I understand the recent news about Airbnb ;-) #qconnewyork @darinrs: Optimize engagement by allowing serendipitous discovery of topics / conversations / meetings @matthewmccull @github #qconnewyork @darinrs: Support group, know what working on is important to company, have plan to move goal constantly forward @matthewmccull @github #qconnewyork @darinrs: This is the best place you have ever worked": What you need/want friends and family to be saying" @matthewmccull @github #qconnewyork Dennis Doomen attended this session:. Learning from Building and Scaling Gilt Twitter feedback on this session included: @darinrs: Management structure, technology architecture: all constructed to attract and retain great people @mbryzek @gilttech #qconnewyork @darinrs: Move fast with minimal risk. Remember that it is very easy to underestimate the risk of doing nothing. @mbryzek @gilttech #qconnewyork @darinrs: Any time you sit down at the keyboard, you are creating the tech debt of the future. @mbryzek @gilttech #qconnewyork @darinrs: By default strive for no coordination outside of team for success. Make required coord very explicit @mbryzek @gilttech #qconnewyork @darinrs: Startup to Dunbar - Ratio of services to headcount should be increasing @mbryzek @gilttech #qconnewyork @darinrs: Testing in production: Do everything else for verification but provide safe way to validate in production @mbryzek @gilttech #qconnewyork @darinrs: If it is hard to quickly figure out what a micro service does, likely time for mitosis @mbryzek @gilttech #qconnewyork @darinrs: With smart, autonomous people you need to make the room for them to fail towards improvement @mbryzek @gilttech #qconnewyork @QuyJitsu: Insightful definition of a "great coworker" from @mbryzek: Someone better than me (in some way). These are the people to hire. #QConNewYork Mentoring Humans and Engineers Twitter feedback on this session included: @kendaleiv: Getting the strongest people at any level and keeping them is the single hardest thing in any organization. @dblockdotorg #qconnewyork @roxanneinfoq: Mentorship=setting expectations & letting the person know what is expected as the outcome. "Mentoring Humans and Engineers" #qconnewyork Dennis Doomen attended this session: Daniel Doubrovkine showed us how he approaches mentoring new employees within his current…. Everything as a Service (XaaS) - Web APIs 10 Reasons Why Developers Hate Your API by John Musser Twitter feedback on this session included: @azat_co: Number 1 your API sucks is documentation @qconnewyork #qconnewyork #QConNY @jgrodziski: What's your TTFHW? Time To First Hello World? @johnmusser #qconnewyork think of it as "0 To 60 mph" for your API Hot Technologies behind Modern Finance Python: Why Are the Big Dealers Making Big Bets? by Andy Fundinger, Mario Morales Twitter feedback on this session included: @qconnewyork: #Python's strength is in its flexibility, which is why the big banks are investing in it: @Andriod at #qconnewyork Java Innovations - The Latest Trends in Java Technology Evolving Java by Brian Goetz Twitter feedback on this session included: @charleshumble: Why add closures to #Java? Languages have to evolve or they become irrelevant - @BrianGoetz at #QconNewYork @charleshumble: Lambda expressions enable you to specify the what and let the library take care of the how. @BrianGoetz #QconNewYork Nashorn - Native JavaScript Support in Java 8 by Viktor Gamov Twitter feedback on this session included: @vgrazi: #QConny I always wondered why project Nashorn? Just heard a great answer-we have front end JavaScript engineers we need for server-side code @QuyJitsu: Shell scripting with #JavaScript using the REPL built-in with #JDK8 #Nashorn!"#! /usr/bin/jjs -scripting" #QConNewYork Lean Product Design Roadmap to the Lean Enterprise by Trevor Owens Dennis Doomen attended this session:. The Product Design Sprint and Test-Driven Design by Alex Baldwin Twitter feedback on this session included: @qconnewyork: The 5 phases of a Design Sprint: Build, Diverge, Converge, Prototype, Test. @alexbaldwin #lean #agile #qconnewyork Modern Big Data Systems Analyzing Big Data On The Fly by Shawn Gandhi Twitter feedback on this session included: @Sander_Mak: Amazon AWS generates tens of millions of billing events/second. Hence they created Kinesis for realtime stream processing #qconnewyork @GavinInNY: AWS built kinesis to solve their billing stream problems. 100s millions of billing events per second. #qconnewyork @shawnagram Real World Functional Programming A Day in the Life of a Functional Data Scientist Twitter feedback on this session included: @jessitron: Lessons of a data scientist: Be Paranoid. Test the data too. @rickasaurus #qconnewyork @jessitron: Life: 60% munging data, 35% redoing work, 5% fun algorithms. We do everything we can to grow that 5% @rickasaurus #qconnewyork @jessitron: Barb: a language designed around the issues faced by normal people loading really bad data. @rickasaurus #qconnewyork @jessitron: The entire program is one big IEnumerable. It works amazingly well because it's so easy to test. @rickasaurus #qconnewyork @jessitron: F# type providers: explore other people's web APIs from the comfort of your IDE. via @rickasaurus #qconnewyork The Functional Programming Concepts in Facebook's Mobile Apps by Adam Ernst Twitter feedback on this session included: @jessitron: Data should flow in one direction through your app. All updates flow in through the top. @adamjernst #qconnewyork @jessitron: Functional UI: challenging for performance, but great for the code. @adamjernst and it seems the performance is achieved. #qconnewyork Jessica Kerr attended this session:putting all the messages on a bus ("the rapids") and let services spy on the messages relevant for them ("the river"). The only output a service has is more messages, delivered into the rapids for any other service to consume. Software Architecture Improvements If We Took Conway's Law Seriously... Twitter feedback on this session included: @codepiper: Software should be open for extension but closed for modification #qconNY 2014 #mike feathers @jessitron: Architecture devolves when there's (I hate to say it) too much communication. @mfeathers #qconnewyork @jessitron: Everyone here knows what Conway's Law is, and only two people are using it. Why? @mfeathers #qconnewyork @jessitron: Instead of an Ops team that does deployments, a tools team enables deployments. An extension of cognition for developers. #qconnewyork @jessitron: Move people among teams constantly to balance fresh eyes on the code against maintaining indepth knowledge. @mfeathers #qconnewyork @jessitron: Our job is harder than we anticipate because everything matters. Build system, team structure. Burdens or leverage? @mfeathers #qconnewyork @jessitron: Code has inherent value that makes us want to keep it alive; that works short-term. It is not a Redwood tree. @mfeathers #qconnewyork @jessitron: We can readjust team structure to the needs of the code, or adjust code to new teams - by deleting and rewriting. @mfeathers #qconnewyork @jessitron: Nature solved the longevity problem: we survive because we die. Our cruft dies with us.Software needs renewal too.@mfeathers #qconnewyork @jessitron: There is no escaping decision making. @mfeathers #qconnewyorkSupport the decision with information. Don't try to take it away. Dennis Doomen attended this session: Michael Feathers is one particular of my hero speakers, not only because of his exceptional e-book, but also since most of his talks are truly inspiring. He has spoken about Conway’s Legislation numerous times, but this was the initial one exactly where he employed this legislation to propose organizational answers. About he said that irrespective of the greatness of your architecture and all the agile practices your making use of, faster or later you will operate into scaling problems caused by the organizational composition. I’ve been functioning at a client that grew from 8 to one hundred twenty men and women in about three years and Conway’s Legislation is truly seen there. It starts to get specific hard when you can not get all the developers on the very same flooring. That’s one of the factors Michael has a fantastic interest in the whole micro-companies hype. Given that every micro-services can be managed by at most 1 crew, it supplies not only architectural scalability but also on the organizational degree. Jessica Kerr attended this session: Connection between code and people was the subject of Michael Feathers' talk. Everyone knows Conway's Law: architecture mirrors the org chart. Or as he phrases it, communication costs drive structure in software. Why not turn it to our advantage? He proposed structuring the organization around the needs of the code. Balance maintaining an in-depth knowledge base of each application against getting new eyes on it. Boundaries in the code will always follow the communication boundaries of social structure, so divide teams where the code needs to divide, by organization and by room. Eric Evans also suggested using Conway's Law to maintain boundaries in the code. Both of these talks also emphasized the value of legacy code, and also the need for renewal: as the people turn over, so must the code. Otherwise that code+coder symbiosis breaks down. Strategic Design: Embrace Imperfection! by Eric Evans Twitter feedback on this session included: @jgrodziski: @ericevans0 team vithin bounded context must agree on design, architecture and process #qconnewyork @jgrodziski: Multiple models: inevitable and desirable. Good reminders about bounded context by @ericevans0 #qconnewyork @ddoomen: . @ericevans0 just admitted he wasn't sure what architecture is... What happened to the world? #qconnewyork @ddoomen: According to @ericevans0 Netflix have reached perfectionism in handling imperfections #qconnewyork @jessitron: If you want to make elegant designs, you need the ability to make an assertion and let it be true. @ericevans0 #qconnewyork @jessitron: Multiple models: inevitable and desirable. Models are the way you think about a problem; have more than one. @ericevans0 #qconnewyork @jessitron: Bounded Context: "at least in a few places, we have drawn a line around a space where there is one model present." @ericevans0 #qconnewyork @jessitron: Bad design is going to be there. Allowing varied levels of quality makes room for good design. @ericevans0 #qconnewyork @jessitron: Most of my career, "robust" meant "won't go down." Now it means "the system keeps working as parts of it go down." @ericevans0 #qconnewyork @jessitron: Service architecture creates a boundary on one side. Keep the other side independent: no shared DB, separate deploy @ericevans0 #qconnewyork @jessitron: Some people say "my service explains itself" :eyesroll:You have to think a certain way to use a good service well.@ericevans0 #qconnewyork @jessitron: An architecture directive must include where it applies: not everywhere. Architectures have contexts too. @ericevans0 #qconnewyork @jessitron: Everywhere it's gonna be like this! leads to halfhearted implementations that don't achieve the benefits. @ericevans0 #qconnewyork @jessitron: Escape from the Big Ball of Mud means creating boundaries. @ericevans0 #qconnewyorkHe suggests an Anti-Corruption Layer. @jessitron: Language interoperability is a two-edged sword. It lets you thoughtlessly create dependencies. @ericevans0 #qconnewyork @jessitron: For a well-designed system, choose TrendyNewLanguage. It enforces strong boundaries and attracts sharp people. @ericevans0 #qconnewyork @jessitron: Sometimes software looks like a fossilized picture of an earlier version of the organization. @ericevans0 #qconnewyork @jessitron: No: this is so elegant we need to use it everywhereYes: this is so elegant we need to establish a context for it@ericevans0 #qconnewyork @qconnewyork: .@ericevans0: "A practical architecture gives you a path from where you are now to someplace better."#qconnewyork Jessica Kerr attended this session: Eric Evans emphasized: When you have a legacy app that's a Big Ball of Mud, and you want to work on it, the key is to establish boundaries. Use social structure to do this, and create an Anti-Corruption Layer to intermediate between the two, and consider using a whole new programming language. This discourages accidental dependencies, and (as a bonus) helps attract good programmers. … In code and with people, successful relationships are all about establishing boundaries. At QCon it was a given that people are writing applications as groups of services, and probably running them in the cloud. A service forms a bounded context; each service has its internal model, as each person has a mental model of the world. Communications between services also have their own models. Groups of services may have a shared interstitial context, as people in the same culture have established protocols. (analogy mine) No one model covers all of communications in the system. This was the larger theme of Eric Evans' presentation: no one model, or mandate, or principle applies everywhere. The first question of any architecture direction is "When does this apply?" Dennis Doomen attended this session: Right after admitting he wasn’t really sure what architecture genuinely is (!), he talked on our failed tries to create strong and resilient methods. Which is why he thinks Netflix is performing these kinds of excellent tasks. They have in essence managed to reach perfection in dealing with imperfection. As a prolonged-term architect that will profoundly influence my future endeavors. Presented that I comprehended him appropriately, his standard rule-of-thumb is that inside a bounded context (BC) you ought to have 90% of the features lined by an elegant architecture. The remainder doesn’t have to be so excellent, as extended as the BC is aligned with the group structure. That assures that any shortcuts that are having are properly-identified inside of the crew and won’t shock other teams. By more decoupling the BCs from every single other using special interchange contexts that translate messages among BCs (aka the Anti-corruption Layer), and not sharing any sources this kind of as databases, you can localize the imperfections. Oh, and with that assertion of ‘not becoming so perfect’, he actually intended to use if-then-else constructs fairly than properly-created polymorphic abstractions! Taming Mobile Optimizing Mobile Performance with Real User Monitoring @darinrs: % users intent delete during slow UI responsiveness? 48% unforgiving & will delete app when perceive slowness @brittanytarvin #qconnewyork @darinrs: Real User Monitoring: the only way to know what normal feels like to your mobile app users @brittanytarvin #qconnewyork @darinrs: Monitor first for baseline, validate acceptable range with iterative user studies --> performant Mobile app @brittanytarvin #qconnewyork @darinrs: Real User Monitoring - understand what users see on daily basis and what you can do to make experience better @brittanytarvin #qconnewyork The Evolving Cloud Canary Analyze All The Things: How we learned to Keep Calm and Release Often by Roy Rapoport Twitter feedback on this session included: @dmarsh: Canary analyze all the things at Netflix. @royrapoport #qconnewyork @cpswan: 'Absolute numbers are relatively unimportant' says @royrapoport about canary analysis on cloud track at #qconnewyork @dmarsh: Describing challenges faced when implementing canary analysis, hoping to save you time. @royrapoport #qconnewyork @cpswan: 'the cloud gives you infinite scalability for suitably small values of infinite' @royrapoport #qconnewyork The Hyperinteractive Client Front End Ops Tooling Twitter feedback on this session included: @qconnewyork: .@nzgb on the benefits of using #Browserify to write Common.JS code for the browser #javascript #qconnewyork Mobile Web: So Hot Right Now Twitter feedback on this session included: @QuyJitsu: The key to performance in an HTML5 mobile web app is "compositing",, says @davearel #QConNewYork @azat_co: We built our own custom HTML5 CSS keyboard @davearel #QConNY @qconnewyork // super cool! @QuyJitsu: Think like mobile engineers, says @davearel. Consider memory management, and how to leverage the GPU #QConNewYork Web Application Development with Flight Twitter feedback on this session included: @burkeholland: DOM hating is unnecessary via @kassandra_perch #qconnewyork Zero To Testing In JavaScript by Pamela Selle Twitter feedback on this session included: @kendaleiv: This: "What do you call code without tests? Legacy code" /via @pamasaur #qconnewyork Solutions Track Deployed in 60 Minutes: Increasing Production Deployments from Six Months to Every Hour by Matt Makai Twitter feedback on this session included: @darinrs: Have a meeting time budget. Make meeting time a limited resource. Prioritize & minimize @mattmakai @twilio #qconnewyork OSGi Track #1 What’s Cool in the New and Updated OSGi Specs (DS, Cloud and more) by David Bosschaert, Carsten Ziegeler Twitter feedback on this session included: @garyrfield: OSGi Core Release 6 has added async services and promises. Also cross-namespace capability lookup for repositories. #OSGi #QConNewYork @garyrfield: JPM4J from @pkriens looks really good. Indexes repositories like Maven Central, but understands OSGi capabilities. #OSGi #QConNewYork OSGi Track #2 Intro to OSGi – The Microservices Kernel by Peter Kriens, Tim Ward Twitter feedback on this session included: @jessitron: You can move your coupling to an XML file, but that's just fooling yourself. @pkriens #qconnewyork #OSGi @denschu: Ok, #microservices are not a hype anymore #qconnewyork @jessitron: Complexity is in the eye of the beholder. @TimothyWard #qconnewyorkIs #OSGi hard, or is it solving a hard problem that we'd rather ignore? @jessitron: A system well aware of failure is much more reliable than a system that tries to pretend nothing will go wrong. @pkriens #qconnewyork #OSGi @jessitron: Contract based programming: When replacing a module is easy, quality of modules is less important. @pkriens #qconnewyork #OSGi @jessitron: OSGi extends the type safety of the language into the evolution of the application. @pkriens #qconnewyork #OSGi Opinions about QCon Opinions expressed on Twitter included: @ddoomen: #qconnewyork is the place to be if you want your brain to be fried of information overload... @kaimarkaru: So it *is* possible to provide non-stop coffee at an IT conference in NYC. What a contrast. Who knew ;) Great job #QConNewYork @emilioguarino: I understand maybe half of what they're talking about at #QConNY Getting out of my field is super inspiring Qingsong Yao’ opinion on QCon was: The main reason I attend this conference is to know the industry trend in the software and service development, learning more people use bigdata and machine learning techniques in there services and find existing Microsoft customer and understand their user cases. Takeways @jtdavies: Sat back in comfort on @VirginAtlantic, good bye New York, it was a great #QConNewYork. London and family here I come! @JamesKLavin: Enjoyed #qconnewyork, esp. excellent talks by @netflix, @facebook and @continuumIO. They've got some talented engineers & managers. @paulwilliamhill: Really enjoyed presenting at @qconnewyork #QConNewYork an excellent conference filled with top minds. @GavinInNY: What a great week at #qconnewyork. Met some amazing people and got truly inspired. #LetsGo Jessica Kerr’ takeaways were : Overall, QCon New York emphasized: question what you're used to. Question what's under you, and question what people say you can't do. Face up to realities of distributed computing: consistency doesn't exist, and failure is ever present. We want to keep rolling through failure, not prevent it. We can do this by building tools that support careful decision making. If we each support our code, our code will support our work, and we can all improve. Qingsong Yao’ takeaways were: Application monitoring and NoSQL/other database techniques are dominating the booths, nearly all booths are related to one of the techniques, which is also a good indicator of what is hot in industry. Azat Mardan’s takeaways were: - Hybrid mobile apps are successful and use stacks such as: Cordova+Ionic+Angular+SASS (Salesforce.com) and Backbone+React (Belly) - Dev managers starting to use badges to motivate developers as oppose to traditional managerial ladder promotions (Spotify) - ECMAScript 6 is going to be awesome but coming only next year - Breaking monolithic apps into microservices is the hottest discussion topic in enterprise teams - Developers deploy code 30 time a day and even dogs can deploy changes with Continuous Delivery (Etsy) September 23-25 and San Francisco November 3-7 this year. QCon New York will continue to run in New York around June of every year. Rate this Article - Editor Review - Chief Editor Action
https://www.infoq.com/articles/qcon-new-york-2014
CC-MAIN-2016-30
refinedweb
7,026
52.6
Minutes of Community Calls/COSMOS 1.0 Archive Contents Reference - Docs - Eclipse Legal Process - V0.9 Documentation (drafts) - COSMOS 1.0 Release Plan - COSMOS i8-i11 Enhancements - May F2F Meeting Minutes - Archived: Original COSMOS 1.0 Release Plan - COSMOS Release Review Prep - COSMOS 1.0 Documentation Table of Contents - COSMOS 1.0 Documentation Schedule Iteration 13 - i13 week 1 status - i13 week 2 status - i13 week 3 status - i13 week 4 status - i13 week 5 status - i13 week 6 status Iteration 12 - i12 week 1 status - i12 week 2 status - i12 week 3 status - i12 week 4 status - i12 week 5 status - i12 week 6 status Iteration 11 Questions from Jimmy @ CA - Are Data Managers hard-coded in the UI? The UI does not hard-code the list of data managers. The list of data managers is provided by the data broker. The COSMOS UI queries the data broker to get this list. Information such as the mdrid, display name and supported services is provided for each data manager in the list. The COSMOS UI interprets this information to determine if the data manager is a MDR, statistical datamanager, logging datamanager or a MDR that supports registration services. Based on these categories the COSMOS UI adds the appropriate menu options(e.g. register/deregister CI, submit query, view meta data, etc.) to the navigation node that represents the data manager or MDR. - Security namespaces are now in the Broker? - Toolkit code generator needs to add stub config files in the project? It already does. That defect was completed in i12. - Comment: Register all Data Managers now works as part of 233690. - Comment: i12 E2E will be the same and we will need to ensure these ERs work
http://wiki.eclipse.org/Minutes_of_Community_Calls/COSMOS_1.0_Archive
CC-MAIN-2016-26
refinedweb
287
58.28
: def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod function(args), since in that case there is always exactly one argument. The use of apply() is equivalent to function(*args, **keywords). Use of apply() is not necessary since the ``extended call syntax,'' as used in the last example, is completely equivalent. isinstance(obj, basestring)is equivalent to isinstance(obj, (str, unicode)). New in version 2.3. xis false, this returns False; otherwise it returns True. boolis also a class, which is a subclass of int. Class boolcannot be subclassed further. Its only instances are Falseand True.. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f). New in version 2.2. x < y, zero if x == yand strictly positive if x > y. '<string>'is commonly used).). When compiling multi-line statements, two caveats apply: line endings must be represented by a single newline character ( '\n'), and the input must be terminated by at least one newline character. If line endings are represented by '\r\n', use the string replace() method to change them into '\n'. The optional arguments flags and dont_inherit (which are new in Python 2.2) control which future statements (see PEP 236) affect the compilation of string.. If keyword arguments are given, the keywords themselves with their associated values are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary. For example, these all return a dictionary equal to {"one":. >>> x = 1 >>> print eval('x+1') 2 This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. The code object must have been compiled passing 'eval'. Warning:.. string.atof(x).may. 0.. New in version 2.2. sequence[:]. For instance, list('abc')returns ['a', 'b', 'c']and list( (1, 2, 3) )returns [1, 2, 3]. If no argument is given, returns a new empty list, [].... If initializer is not given and sequence contains only one item, the first item is returned.and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: "a[start:stop:step]" or "a[start:stop, i]". A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C: def f(arg1, arg2, ...): ... f = staticmethod(f). New in version 2.2.) repr(object)is that str(object)does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.. None. With a single sequence argument, it returns a list of 1-tuples. New in version 2.0.
http://docs.python.org/release/2.3.1/lib/built-in-funcs.html
crawl-003
refinedweb
504
67.96
To coordinate your repository with another repository, you define a remote. A remote is a named entity stored in the config file of a repository. It consists of two different parts. The first part of a remote states the name of the other repository in the form of a URL. The second part, called a refspec, specifies how a ref (which usually represents a branch) should be mapped from the namespace of one repository into the namespace of the other repository. Let’s look at each of these components in turn. Git supports several forms of Uniform Resource Locator (URL) that can be used to name remote repositories. These forms specify both an access protocol and the location or address of the data. Technically, Git’s forms of URL are neither URLs nor URIs, because none entirely conform to RFC 1738 or RFC 2396, respectively. However, because of their versatile utility in naming the location of Git repositories, Git’s variants are usually referred to as Git URLs. Furthermore, the .git/config file uses the name url as well. As you have seen, the simplest form of Git URL refers to a repository on a local filesystem, be it a true physical filesystem or a virtual filesystem mounted locally via the Network File System (NFS). There are two permutations: /path/to/repo.git path/to/repo.git Although these two formats are essentially identical, there is a subtle but important distinction between the two. The former uses hard links within ... No credit card required
https://www.oreilly.com/library/view/version-control-with/9780596158187/ch11s02.html
CC-MAIN-2019-35
refinedweb
254
55.95
how Send forgot Password through mail - JSP-Servlet is provided) Now my question is how do i send the password if admin click on forgot password and i need to send that password through mail after answering a few...Send forgot Password through mail hello every one I Technology What is and FAQs Technology What is and FAQs  ... and willing to access their mail in the way from their home based desktop... of Java Programming Language API (Application programming interface) that is very How i can send mail by using jsp.............. - JavaMail How i can send mail by using JSP Hi, will you please tell me how i can send mail by using jsp. Tell me in detail. Thanks! Example and JSP... to create a send mail program using JSP.JSP Send Mail Program Resources:-http Java faqs Java faqs Hello Java Developers, I am beginner in Java and trying to find the best java faqs. Where I can find java faqs? Thanks Hi, Please see the thread java faq Thanks code and specification u asked - Java Beginners code and specification u asked you asked me to send the requirements... displayed on the buttons...i need to change this with their apppropriate actions>...(); display.dispose(); } } so i have sent u the code Java faqs This section contains collection of frequently asked questions(faqs) in interview or viva of Java J2EE Interview Questions J2EE Interview Questions Question: What is J2EE? Answer: J2EE Stands for Java 2... be assembled into J2EE applications. Question: Tell me mail mail how to send mail using jsp Please visit the following links: JSP Send Mail Java Mail Tutorials i need project i need project can u send online shoppin project 2 my mailid. Please visit the following links: Struts2 Shopping cart JSP-Servlet Shopping cart java mail (MailClient.java:90) help me clear this error..send suggestions to mail mail...: Java Mail Thanks...java mail import javax.mail.*; import javax.mail.internet. J2EE - Java Interview Questions J2EE What is J2EE architecture? Hi friend, The Java? 2 Platform, Enterprise Edition (J2EE) provides a standard for developing... Java applications provide a dynamic interface to the middle tier. 2. Middle send mail using smtp in java send mail using smtp in java How to send mail using smtp in java? Sending mail in JSP - SMTP mail mail I wrote a program to send mail using smtp. But there is an error message " could not connect to smtp.gmail.com port 465. what is the problem how can i solve it ... Please visit the following link: Java Mail API send without authentication mail using java - JavaMail send without authentication mail using java Dear All, I am tring to send simple mail without authentication using java. is it possible, could i send email without authentication. I have written following code. public mail programs output.actually,do I need a mail server to get correct output of these codes?plz help me, I have to make a web application which helps to send mail,plz give me a solution...java mail programs I got some codes from this about sending mail j2ee - Java Interview Questions j2ee What is MVC Architecture..How JTable,JButton,......etc... of a MVC architecture in a web application,and in struts. Give me...","3"}, {"Vinod","Histry","2 send mail from j2me application send mail from j2me application how to send mail from j2me application? i need some example code related how to send mail with multiple attachments in jsp how to send mail with multiple attachments in jsp how to send mail with multiple attachments in java script java mail sending with images java mail sending with images I need to send images through java mail without giving content path(i.e. we don't want hard code the image path)can you tell me the idea? Please visit the following links: http java mail java mail sir, I need a source code to understand the working of java mail.plz help me. Reply so on. Thanks, mohit Hi Friend... want to understand the working of Java Mail download the source code from here How i can send testing mail on my id using java? How i can send testing mail on my id using java? Which packages i should use to implementing java mail service??? Thanks Collection of Large Number of Java Interview Questions! Java Interview Question Page 2 Does it matter in what order... Questions JSP - Java Server Pages Interview Questions Jsp...Interview Questions - Large Number of Java Interview Questions Here you Java Mail - JMS Java Mail Thanks for the previous jsp answer,that program is now running very well,creating no other problems. Now i am trying to learn java mail... will be glad if you help me out. Do i need to install any servers?if i install tomcat java mail java mail Hi deepak, sorry to trouble again but with reference to apache mail server (james) tutorial i use the link that u have provided it redirects to apache offical site what there 4 zip and taz Design patterns interview questions2 Design patterns interview questions2  ... or a JSP (through a Java Bean). This Controller takes over the common processing.... These are normal java classes which may have different constructors (to fill in the Confirmation Mail Confirmation Mail hi, i need the code.when we sign up it will send the confirmation mail to the e-mail right.how to do that part.....and also help me whether the AJAX is better or PHP better for the front design sending mail with attachment in jsp - JSP-Servlet me how to send email with attachment in jsp. I know how to send mail without attachment but with attachment its not working for me. If u hve any idea please.... Thanks Hi Frnd, Sry to tell u this,, actly i tried dat... bt its nt Send me Binary Search - Java Beginners Send me Binary Search how to use Binary think in java give me...]; for(int i = 0; i < SIZE; i++) a[i] = i * 2; for(int i = 0; i < SIZE * 2; i++) System.out.println("Found " + i java - Java Interview Questions java hello sir this is suraj .i wanna ask u regarding interview... difficult 2 answer....so could u plz suggest me with sme information regarding tis.../interviewquestions/ Here you will get lot of interview questions send mail in PHP send mail in PHP what are configurations needed to send mail in php.ini file by localhost ,please give me complete details about this,and code in datail Unable to send mail using php script Unable to send mail using php script Hello i am trying to send mail using mail function.But the message is never sent. I have installed a free smtp... anyone please tell me where am i going wrong..i am new to php. thank you J2EE Tutorial - Introduction . J2EE ( Java 2 -Enterprise Edition) is a basket of 12 inter... presentation of what & why of J2EE. (It is better for aspiring Java... security.) J2EE is not the Java , that comprises Send Email From JSP & Servlet J2EE Tutorial - Send Email From JSP & Servlet... by the server. We need not compile the jsp file. It is automatically compiled...(rs.getString(2)+"<br>"); // telephone number j2ee - Java Interview Questions j2ee what is the best place to write the database connection code in servlet. if the write the database connection code in service() or doGet... in init() method of a servlet.Give me the correct answers....... with explanation - JSP-Interview Questions java hi.. snd some JSP interview Q&A and i wnt the JNI(Java Native Interface) concepts matrial thanks krishna Hi friend, Read more information. Send multipart mail using java mail Send multipart mail using java mail This Example shows you how to send multipart mail... parts. When u send a multipart mail firstly create a Multipart class object mail through jsp and servlet - JSP-Servlet mail through jsp and servlet H! Rose India team, kindly let me know what is the error in this code (java file) because the java file is not compiling and gives 100 errors saying that you cannot user assert key word. I java mail java mail By Which code or function i can send E-mail to given E-mail Address Hi Friend, Please visit the following link: Java Mail Thanks Hi Friend, Please visit the following link: Java Mail how can i send a mail to a particular user from a many user dropdown list in jsp how can i send a mail to a particular user from a many user dropdown list in jsp how can i a sent a user question to a particular person from a drop down list in jsp that matter in another jsp and stored in a string using getParameter(),then i splitted Jsp - Java Interview Questions Need JSP Interview Questions Hi, I need JSP interview questions.Thanks Reply Me - Java Beginners class (which contain your database information). Check previous I send U two... use this i don't know... please tell me what is the use... with databse. Controller are servlet,jsp which are act as mediater. If u j2ee j2ee hi i'm beginner 2 j2ee.. my question is... when user enters... is when user submit without entering i,e blank it also get inserted into db even though i have given not null for each elements in table help me 2 help me 2 write java program to enter five numbers and will determine the location of the number sample output: ENTER 5 NUMBERS: 1 2 3 4...]; System.out.println("Enter Array Elements: "); for(int i=0;i< JAVA MAIl - JavaMail JAVA MAIl Hi, I am trying to send a mail using java mail api. But I am getting following error: javax.mail.SendFailedException: Sending failed...:99) at TestMail.main(TestMail.java:36) can anyone please help me regarding pls send me the code for login and register - Java Beginners pls send me the code for login and register pls immediately send me the jsp code for login and registration with validation with java bean in mysql.... ------------------------------------------------- I am sending you a link Need Java Source Code - JDBC Need Java Source Code I have a textfield for EmployeeId in which... on the that textfield for every employees. Can u please tell me how this can be implemented. Hi friend, Please send me code because your posted need need i need a jsp coding based project plz help me J2EE interview questions page1 J2EE interview questions page1 What is J2EE? J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set java questions - Java Interview Questions java questions HI ALL , how are all of u?? Plz send me the paths of java core questions and answers pdfs or interview questions pdfs... the interview for any company for <1 year experience thanks for all of u in advance J2EE - Java Beginners J2EE I am a non java programmer.I am interested in learning... knowledge on core java,and also that in future I want to become a XML... consentarate on j2ee(jdbc,servlets,jsp,struts).Then you can start XML.And also plz help me - Java Interview Questions value in not found . you also need to use a sort algorithm for this problem " you should solve this problem in two ways: using iteration and recursion 2... . use linear search for this algorithm .then test your method in java application J2EE - Java Server Faces Questions J2EE I have knowlage of core java.So i have to learn J2EE properly.What are the seqence of J2EE component should i follow??? Hi friend... * Hibernate * Struts 1 * Struts 2 * JSF * Spring * java mail API java mail API <html> <head> <title>Mail API<...="submit" value="Send Mail" name="sendMail"></td> </tr> <...%" cellpadding="0" cellspacing="0"> <h1>Mail API</h1> 2EE - Java Beginners J2EE Programming What i need to learn to start programming in J2EE help me in these - Java Interview Questions help me in these hello every body i have some question if you cam plz answer me it is important to me and these are the questions : 1)Write...=input.next(); System.out.println(); for(int i=0;i 2) import i need latest oracle certified java dumps.. Pleas help me? i need latest oracle certified java dumps.. Pleas help me? i need latest oracle certified java dumps.. Pleas help me Thank U - Java Beginners Thank U Thank U very Much Sir,Its Very Very Useful for Me. From SUSH2ee - JSP-Servlet j2ee please provide code for search options(example codes) or please tell me where can i get exaple codes of searh options Hi friend, Please explain which technologies you want to use: JSP Servlet Open Source E-mail , a lightweight e-mail client will suffice. I, on the other hand, get hundreds.... This point was driven home to me when I spoke recently at a meeting of CIOs, chief...Open Source E-mail Open Source E-Mail CAN U HELP ME TO CODE IN JSP FOR ONLINE VOTING SYSTEM CAN U HELP ME TO CODE IN JSP FOR ONLINE VOTING SYSTEM can u help me to code in jsp for online voting system Reply me - Java Beginners Reply me Hi, this code is .java file but i am working in jsp... in the database... if u understood my question then then please send me code oterwise........ You Want only Jsp Code? You Heard About MVC Architecture or not. Before I Send Sending images through java mail Sending images through java mail Am trying to develop greeting application that having images..... in one jsp page i displayed all images... to body part and the mail will sent to recipients..... please give me any idea Send Mail Bean ; In this article we use Java Mail API to send emails. This is standard.... Now we write java source code to send a mail. Very... Send Mail Bean   Sending mail - JavaMail Sending mail Need a simple example of sending mail in Java Hi,To send email you need a local mail server such as apache james. You first... emails using outlook client.From java program you can also send email.Here java, - JSP-Interview Questions java, hi.. define URI? wht is difference b/w URL and URI wht..., mail server, etc.). URLs are typed into a Web browser to access Web pages... Resource Identifier) It is address of Internet. 2) A URI is the unique to access Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/1476
CC-MAIN-2015-40
refinedweb
2,436
65.42
There is a bug in _initHeap as well. I've posted a bug report on Sourceforge. Peter There are other problems.... Having enabled building of libio , it seems there are problems with dependencies as the libio code it being rebuilt every time , even if no changes have been made, and after running "make install" as root, the copies in the bin directory are owned by root and thus the next time I run make I'm being prompthed like this for every library file... make[6]: Leaving directory `/opt/sdcc-cvs/sdcc/device/lib/pic16/libio' mv -v libio18f442.lib ../bin mv: overwrite `../bin/libio18f442.lib', overriding mode 0644? I'll try and sort out these problems this evening, but I'm not very good with make files etc..... Peter I think the line labelled "*** BUG ***" below should read hsize += pHeap->bits.count - 1; The minus one is needed because pHeap->bits.count is the offset to the start of the next block. The amount of memory available in the block pointed to by pHeap is one byte less than this because of the byte taken to hold the _malloc_rec header. Peter Onion unsigned int memfree(void) { _malloc_rec _MALLOC_SPEC *pHeap; unsigned int hsize=0; pHeap = (_malloc_rec _MALLOC_SPEC *)&heap; while(pHeap->datum) { if(!pHeap->bits.alloc) hsize += pHeap->bits.count; /* *** BUG *** */ pHeap = (_malloc_rec _MALLOC_SPEC *)((unsigned int)pHeap + pHeap->bits.count); } return (hsize); } Peter, You write about the build times for SDCC and gpsim. In your case, it might make sense to use CCACHE. For gpsim, I write: CXX="ccache g++" ./configure Once the project has been built once, everything is cached on your hard disk. If you change a file dependency, then the dependent code is rebuilt only if CCACHE determines the change affects the resultant object file. I don't think CCACHE may be applicable to nightly SDCC builds though. Scott On Fri, 2005-08-05 at 11:40 +0200, Raphael Neider wrote: > Hi Peter, >...). I'm building on a 2.6Ghz box with 512Mb RAM. Building just the PIC port with ./configure --disable-mcs51-port --disable-gbz80-port --disable-z80-port --disable-avr-port --disable-ds390-port --disable-ds400-port --disable-hc08-port --disable-xa51-port time make = 2min31s Now with libio included for all the target PICs time make = 3min53s Hardly a "long" build compared for example to gpsim which takes 12min5s. My personal preference would be to make the default build process as simple as possible for the users, even if this does waste about 90 seconds building some unnecessary libraries. The instructions in the manual should cover the changes needed to customise the build if it is an issue for users. Out of interest do the versions built for distribution as binaries have all the target libio's prebuilt ? Peter Hi Peter, > One minor niggle remains... the io device library "libio" still isn't > built automatically because it is commented out in the make file. Is > there a reason for this ? If this were corrected the build process > would be the normally expected Actually, there is a reason: building the I/O library cannot be done in a processor independant way (actually one could build it for the largest PIC out there, but that might cause problems with unsupported IO functions on smaller devices like undefined sfr CANCON or the like)....). On the compile farm (as you could locally) we could build the complete libio by simply adding a call to "make libio" somewhere (I could do it, but I believe Borut (is/has been) working on this, right?). > ./configure > make > su -c "make install" Regards, Raphael Neider Hi Ben, > The included test.c file shows how the bit test in the 'if' operates > on the wrong byte of the two-byte structure. As you can see from > the assignment, it sometimes selects the right member: This is now fixed in SDCC 2.5.2 #1081. Thanks for the stripped down code, that makes bug hunting a reasonably easy job! [BTW: "main should return a value" or be declared void main()... ;-)] Regards, Raphael Neider > #include <pic16/pic18fregs.h> > > typedef unsigned char uchar; > typedef unsigned int uint; > > typedef union { > uint w; > struct { > uchar bl, bh; > }; > } uwb; > > uwb blinky; > > int > main() > { > blinky.bh = 17; > if (blinky.bh & (1<<5)) > LATCbits.LATC3 = 1; > } I just tried this again with fresh CVS check out and all seems to have been fixed :-) Great Stuf... One minor niggle remains... the io device library "libio" still isn't built automatically because it is commented out in the make file. Is there a reason for this ? If this were corrected the build process would be the normally expected ./configure make su -c "make install" I have this exact information on the screen in front of me, but I can't find what Makefile or script was executing. Where is this? I think the problem is that there is no semicolon after 'mkdir -p pic16/bin'. Notice that the error message complains about the C option for 'mkdir', not 'make'. The make command was concatated with the mkdir command above it. I think we only need to add a ';' after the mkdir command. If we can find it. -Ken Jackson Peter Onion writes: > On Thu, 2005-08-04 at 21:12 +0100, Peter Onion wrote: > > It fails later in the build as well ..... > > make[2]: Entering directory `/opt/sdcc-cvs/sdcc/device/lib' > mkdir -p build/pic16 > if [ -d pic16 ]; then \ > mkdir -p pic16/bin \ > make -C pic16; \ > cp -f pic16/bin/*.* build/pic16; \ > fi > mkdir: invalid option -- C > Try `mkdir --help' for more information. > cp: cannot stat `pic16/bin/*.*': No such file or directory > make[2]: *** [port-specific-objects-pic16] Error 1 > make[2]: Leaving directory `/opt/sdcc-cvs/sdcc/device/lib' > make[1]: *** [model-pic16] Error 2 > make[1]: Leaving directory `/opt/sdcc-cvs/sdcc/device/lib' > make: *** [sdcc-device] Error 2 > > > Peter Star dot star matches all files in DOS and Windows command shells, but it will only match filenames containing a dot when used in bash under Linux, Cygwin and Mingw32. $ grep -n '[*][.][*]' $(find . -name Make\*) ./device/lib/Makefile:261: cp -f $(PORT)/bin/*.* $(PORTDIR); \ ./device/lib/pic16/Makefile:40: $(RM) -f bin/*.* ./device/lib/Makefile.in:261: cp -f $(PORT)/bin/*.* $(PORTDIR); \ -Ken Jackson I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/sdcc/mailman/sdcc-user/?viewmonth=200508&viewday=5
CC-MAIN-2016-40
refinedweb
1,087
65.22
My primary motivation for purchasing a Teensy is to emulate a keyboard to set up a little practical joke for someone. So I need to get the Teensy running in a manner in which if I press a button, it will transmit text as if it were a keyboard attached to the PC. This turns out to be quite easy. I have a push button switch attached to PIN 2 of my Teensy and I will be using the bounce library to read and debounce the switch. Here is the code: #include <Bounce.h> int sw = 2; Bounce swBounced = Bounce(sw, 10); void setup() { pinMode(sw, INPUT); digitalWrite(sw, HIGH); } void loop() { swBounced.update(); if (swBounced.risingEdge()) { // due to negative logic, button released on rising edge Keyboard.print("Hello World "); } } The action is all in the Keyboard.print statement. This is like the normal Arduino Serial.print statement except instead of transmitting the output to a USB serial port, it is going to transmit the output as if it where a keyboard. Before compiling, you have to make sure the USB type is set to keyboard+mouse+joystick: Now just compile and run as normal. Place the cursor into a window you don’t mind seeing ‘hello world’ in, and press the button: The various methods for the Keyboard class can be found here: if your vict^H^H^H^H target’s system supports bluetooth, your could extend this by pairing their system with your device, which would enable you to manipulate the input without an apparent device connected to their system, and without having to be right there to trigger it. Of course, they may have some big icon in their systray or similar that shows bluetooth activity, and to pair the devices, you’d have to have console access to the system (but that may be true for detecting a new HID device when you plug your teensy in via USB). If you untether, you need to independently power your device, but that could be done from a USB port of another system (or a wall wart). A bluetooth approach also remains fairly stealthy if say the target system is a laptop without an external keyboard, where the extra something dangling off of it would be readily noticed Another take would be to use an IR detector on another input and then you could use an IR remote (you can get a compact media type for less than US$1), which again would allow you to trigger without having to seem to be interacting with their workarea, and also, you have multiple codes you can enter or single-button trigger, allowing for multiple phrases/actions. This would be suitable either for a bluetooth or direct-cabled approach.
https://bigdanzblog.wordpress.com/2014/12/27/teensy-3-1-emulating-a-usb-keyboard/
CC-MAIN-2017-39
refinedweb
460
62.31
(circa November 15, 2001) I think this column stands up pretty well without caveat. I should note that I wrapped the image class to provide nicer pixel-based access in a class you can find here. I suggest basing your code on that rather than what I wrote in the column. I should also note that the grey-scale code isn't what you want. The human eye is not equally sensitive to all colors, so you should use the following to determine the intensity: 0.299 * red + 0.587 * green + 0.114 * blue Finally, I'll note that the extreme speedup I get here is because of how the underlying unmanaged GDI+ code is structured. ****** Unsafe Image Processing Last month, we talked a bit about what unsafe code was good for and worked through a few examples. If you looked at the associated source code, you may have noticed that there was an image-processing example. This month, we're going to work through that example. Grey Scale Images Last summer, I was writing a program to process some pictures from my digital camera and I needed to do some image processing in C#. My first task was to figure out how to do that using the .NET fFrameworks. I did a bit of exploration, and found the Image and Bitmap classes in the System.Drawing namespace. These classes are thin covers over the GDI+ classes that encapsulate the image functions.One task I wanted to do was to walk through an image and convert it from color to grayscale. To do this, I needed to modify each pixel in the bitmap. I started by writing a BitmapGrey class that would encapsulates the bitmap, and then writing a function in that class to do the image conversion. I came up with the following class: public class BitmapGrey{ Bitmap bitmap; public BitmapGrey(Bitmap bitmap) { this.bitmap = bitmap; } public void Dispose() { bitmap.Dispose(); } public Bitmap Bitmap { get { return(bitmap); } } public Point PixelSize { get { GraphicsUnit unit = GraphicsUnit.Pixel; RectangleF bounds = bitmap.GetBounds(ref unit); return new Point((int) bounds.Width, (int) bounds.Height); } } public void MakeGrey() { Point size = PixelSize; for (int x = 0; x < size.X; x++) { for (int y = 0; y < size.Y; y++) { Color c = bitmap.GetPixel(x, y); int value = (c.R + c.G + c.B) / 3; bitmap.SetPixel(x, y, Color.FromArgb(value, value, value)); } } }} The meat of the class is in the MakeGrey() method. It gets the bounds of the bitmap, and then walks through each pixel in the bitmap. For each pixel, it fetches the color and determines what the average brightness of that pixel should be. It then creates a new color value for the brightness value, and stores it back into the pixel. This code was simple to write, easy to understand, and worked the first time I wrote it. Unfortunately, it's pretty slow. ; iIt takes about 14 seconds to process a single image. That's pretty slow if I compare it to a commercial image processing program, such as Paint Shop Pro, which can do the same operation in under a second. Accessing the Bitmap Data Directly The majority of the processing time is being spent in the GetPixel() and SetPixel() functions, and to speed up the program, I needed a faster way to access the pixels in the image. There's an interesting method in the Bitmap class called LockBits(), which can be used – not surprisingly – to lock a bitmap in memory so that it doesn't move around. With the location locked, it's safe to deal with the memory directly, rather than using the GetPixel() and SetPixel() functions. When LockBits() is called, it returns a BitmapData class. The scan0 field in the class is a pointer to the first line of bitmap data. We'll access this data to do our manipulation.First, however, we need to understand a bit more about the how the data in the image is arranged.Bitmap Data OrganizationThe organization of the bitmap depends upon the type of data in the bitmap. By looking at the PixelFormat property in the BitmapData class, we can determine what data format is being used. In this case, I'm working with JPEG images, which use the Format24bppRgb (24 bits per pixel, red green blue) format. Since we're going to be looking at these pixels directly, we'll need a way to decode a pixel. We can do that with the PixelData struct:public struct PixelData{ public byte blue; public byte green; public byte red;} Now, we'll need a way to figure out what the offset is for a given pixel. Basically, we treat the bitmap data as an array of PixelData structures, and figure out what index we'd be looking for to reference a pixel at x, y. In memory, a bitmap is stored as one large chunk of memory, much like an array of bytes. We therefore need to figure out what the offset is of a given pixel from the beginning of the array. Here's what a 4x4 bitmap would look like, with the index and (y, x) location of each pixel. For each line, the offset is simply the width of the line in pixels times the y value. This gives the index of the first element of the line, and the x value is simply added to that value to determine the actual index of an element. This is the way that multi-dimensional arrays are typically stored in memory.So, we can figure out the offset as follows:Offset = x + y * width; The code to access a given pixel is something like:PixelData *pPixel;pPixel = pBase + x + y * width; Where pBase is the address of the first element.If we go off and write some code, we'll find that this works great for some bitmaps, but doesn't work at all for other bitmaps. It turns out that the number of bytes in each line must be a multiple of 4 bytes, and since the pixels themselves are 3 bytes, there are some situations where there's some unused space at the end of each line. If we use the simple version of indexing above, we'll sometimes index into the unused space.Here's an example of what this looks like in a bitmap, with each box now corresponding to a byte rather than a pixel. This bitmap occupies 24 bytes, with 12 bytes per line. However, it only has three entries, so each line must be padded with an extra 3 bytes. To make our code work everywhere, we need to switch from working in terms of pixels to working in terms of bytes, at least for dealing with the line indexing. We also need to calculate the width of a line in bytes. We can write a function that handles this all of this for us:public PixelData* PixelAt(int x, int y){ return (PixelData*) (pBase + y * width + x * sizeof(PixelData));} Once that we've gotten that written that bit of code, we can finally write an unsafe version of our grey scale function:public void MakeGreyUnsafe(){ Point size = PixelSize; LockBitmap(); for (int x = 0; x < size.X; x++) { for (int y = 0; y < size.Y; y++) { PixelData* pPixel = PixelAt(x, y); int value = (pPixel->red + pPixel->green + pPixel->blue) / 3; pPixel->red = (byte) value; pPixel->green = (byte) value; pPixel->blue = (byte) value; } } UnlockBitmap();} We start by calling a function to lock the bitmap. This function also figures out the width of the bitmap and stores the base address away. We then iterate through the pixel, pretty much just as before, except that for each pixel, we get a pointer to the pixel and then manipulate it through the pointer.When this is tested, it only takes about 1.2 seconds to do this image. That's over 10 times faster. It's not clear where all the overhead is in GetPixel() / SetPixel(), but there's obviously some overhead in the transition from managed to unmanaged code, and when you have to do the transition 3.3 million times per image, that overhead will adds up. I originally stopped with this version, but a bit of reflection suggested another opportunity for improvement. We're calling the PixelAt() function for every pixel, even when we know that the pixels along a line are contiguous. We'll exploit that in the final version:public void MakeGreyUnsafeFaster(){ Point size = PixelSize; LockBitmap(); for (int y = 0; y < size.Y; y++) { PixelData* pPixel = PixelAt(0, y); for (int x = 0; x < size.X; x++) { byte value = (byte) ((pPixel->red + pPixel->green + pPixel->blue) / 3); pPixel->red = value; pPixel->green = value; pPixel->blue = value; pPixel++; } } UnlockBitmap();} The loop in this version does the y values in the outer loop, so we can walk through the entire x line. At the beginning of each line, we use PixelAt() to find the address of the first element, and then use pointer arithmetic (the pPixel++ statement) to advance to the next element in the line.My test bitmap is 1,536 pixels wide. With this modification, I'm replacing a call to PixelAt() with an additional operation in all but one of those pixels.When this version is tested, the elapsed time is 0.52 seconds, which is over twice as fast as our previous version, and nearly 28 times faster than the original version. Sometimes unsafe code can be really extremely useful, though gains of 28x are pretty rare.
http://blogs.msdn.com/ericgu/archive/2007/06/20/lost-column-2-unsafe-image-processing.aspx
crawl-002
refinedweb
1,587
62.58
This page is a migration guide for helping Apache WSS4J 1.6.x users to migrate to the 2.0.x releases. Also see the new features page for more information about the new functionality available in WSS4J 2.0.x. WSS4J 2.0.0 introduces a streaming (StAX-based) WS-Security implementation to complement the existing DOM-based implementation. The DOM-based implementation is quite performant and flexible, but having to read the entire request into memory carries performance penalties. The StAX-based code offers largely the same functionality as that available as part of the DOM code, and is configured in mostly the same way (via configuration tags that are shared between both stacks).". For more information on the streaming functionality available in WSS4J 2.0.0, please see the streaming documentation page. Typically, a user configures Signature and Encryption keys via a Crypto properties file. In WSS4J 1.6.x, the property names all start with "org.apache.ws.security.crypto.*". In WSS4J 2.0.0, the new prefix is "org.apache.wss4j.crypto.*". However, WSS4J 2.0.0 will accept the older prefix value. No other changes are necessary for migrating Crypto properties. In WSS4J 1.6.x, it was only possible to specify a Crypto implementation for both Signature Creation + Verification. In WSS4J 2.0.0, there is now a separate Signature Verification Crypto instance, that can be configured via the following configuration tags:. Therefore, the properties file that is used in WSS4J 1.6.x to sign a SAML Assertion is no longer used in WSS4J 2.0.0, and the "samlPropFile" and "samlPropRefId" configuration tags have been removed. The SAMLCallback Object contains the additional properties in WSS4J 2.0.0 that can be set to sign the Assertion: In WSS4J 1.6.x, configuration tags were configured in the WSHandlerConstants class. In WSS4J 2.0.0, both the DOM and StAX-based code largely share the same configuration options, and so the configuration tags are defined in ConfigurationConstants. Note that the WSS4J 1.6.x configuration class (WSHandlerConstants) extends this class in WSS4J 2.0.0, so there is no need to change any configuration code when upgrading. The configuration tags that have been removed and added are detailed below. The non-standard key derivation and UsernameToken Signature functionality that was optional in WSS4J 1.6.x has been removed. Some new actions are added for the streaming code, as well as some options surrounding caching. An important migration point is that there is now a separate configuration tag used for verifying signatures. In WSS4J 1.6.x, there was only one tag used for both signature creation and verification. Removed Configuration tags in WSS4J 2.0.0 This section details the Configuration tags that are no longer present in WSS4J 2.0.0. New Configuration tags in WSS4J 2.0.0 This section details the new Configuration tags in WSS4J 2.0.0. In WSS4J 1.6.x, the default namespace used for Derived Key and Secure Conversation was the older "" namespace. In WSS4J 2.0.0, the default namespace is now "". To switch back to use the older namespace, you can set the new configuration property "USE_2005_12_NAMESPACE" to "false". WSS4J 2.0.0 uses three EhCache-based caches by default for the following scenarios, to prevent replay attacks: If you are seeing a error about "replay attacks" after upgrade, then you may need to disable a particular cache. WSS4J supports two key transport algorithms, RSA v1.5 and RSA-OAEP. A number of attacks exist on RSA v1.5. Therefore, you should always use RSA-OAEP as the key transport algorithm. In WSS4J 2.0.0, the RSA v1.5 Key Transport algorithm is not allowed by default (as opposed to previous versions of WSS4J, where it is allowed). If you wish to allow it, then you must set the WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM property to "true". In WSS4J 1.6.x, when BSP Compliance was switched off on the outbound side,.
http://ws.apache.org/wss4j/migration/wss4j20.html
CC-MAIN-2017-13
refinedweb
669
61.33
I’m trying to do something relatively simple, but running into roadblocks at every turn. I want the standalone version of my plugin to: - use the native OS titlebar - expand to fullscreen when the fullscreen icon in the titlebar is pressed, and return to original size when pressed again - when fullscreen, my editor should grow as large as possible while still maintaining it’s original aspect ratio All of that seems simple and most or all of that behavior should be the default anyway, but it’s not. The StandaloneFilter classes don’t seem to have been designed with much customization in mind. There are very few hooks or virtual methods and several private classes. This makes customization difficult and the only reason I’m frustrated by this is that I really don’t want to have to rewrite all that code when I’m using a framework for that very purpose to begin with. Here are the steps I took…along with the encountered roadblocks: Copy the juce_StandaloneFilterApp.cpp and juce_StandaloneFilterWindow.h files to my own folder In MyStandaloneApp.cpp - Comment out the includes and add #include "../JuceLibraryCode/JuceHeader.h" - Change #include "juce_StandaloneFilterWindow.h"to use my file #include "MyStandaloneWindow.h" - Rename the class StandaloneFilterApp to MyStandaloneFilterApp - Comment out the #if ! JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APPline and it’s matching #endif - Add START_JUCE_APPLICATION(MyStandaloneFilterApp)to the end of the file In MyStandloneWindow.h - Rename StandaloneFilterHolder to MyStandaloneFilterHolder - Rename StandaloneFilterWindow to MyStandaloneFilterWindow In PluginEditor.cpp - Add #include “MyStandaloneApp.cpp” Add JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APP=1to the Projucer Preprocessor Definitions field After all that, I now have a working, customizable standalone plugin app, but still with the Juce titlebar. So now, to change to a native titlebar and enable the green zoom icon: In MyStandaloneWindow.h - Just before the pluginHolder is created, I add: setUsingNativeTitleBar(true); - And add | DocumentWindow::maximiseButtonto setTitleBarButtonsRequired() And in PluginEditor.cpp resized()method, I added this to keep an eye on it’s size: g.fillAll(Colours::blue); g.setColour(Colours::white); String s = "Size: " + String(getWidth()) + "x" + String(getHeight()) + " -- Should be 400x300"; g.drawFittedText (s, getLocalBounds(), Justification::centred, 1); And now, when I run the program, I see a 400x300 editor as expected. But when I hit the green fullscreen icon (in OSX), the window goes full but now my editor is 400x322 instead of 400x300. I have no idea why my 22 was added to my editor’s height. When I click the fullscreen button again to bring it back to normal size, it stays 400x322. If I hit the fullscreen icon again, it adds ANOTHER 22 to the height and my editor is now 400x344. Something is adding 22 every time it goes fullscreen. But…and here’s the catch…only when using a native titlebar. When using the Juce titlebar, all is well and it stays at 400x300. This is definitely a bug. So I tried an alternate approach: calling the window’s setFullScreen() method. I added a simple button to my editor trigger the following code: void Editor::toggleFullscreen() { if(TopLevelWindow::getNumTopLevelWindows() == 1) { ResizableWindow* rw = static_cast<ResizableWindow*>(TopLevelWindow::getTopLevelWindow(0)); if(rw) rw->setFullScreen(!rw->isFullScreen()); } } The results here were different and still not what I expected. When going fullscreen, it doesn’t go actually all the way full, leaving the top menu bar and dock visible as well as the window’s own titlebar. So this is probably using different code (Juce?) than when the green fullscreen icon is pressed (OS?). And when pressing my button again to trigger going back to normal size, it simply doesn’t…it stays there at nearly fullscreen. So, calling setFullScreen(false) doesn’t work. When I tried this all again but with the Juce titlebar, it grows to nearly fullscreen and then does go back to original size as expected. Once again, using a native titlebar seems to have some issues. And finally, trying to go fullscreen while keeping my editor’s aspect ratio. If I set my window to setResizable(false, false), then when going fullscreen, the editor doesn’t grow to fit the window, so obviously I have to setResizable(true, false). But that also has the byproduct of letting the user drag the window size and that’s problematic in several areas. The MainContentComponent of the window is a ComponentListener of the the editor class so it can adjust the window to the editor’s preferred size which makes sense. But the editor is also resized by the window being resized which makes it difficult to make the editor a consistent aspect ratio regardless of the window’s size. The ComponentListener::componentMovedOrResized() which wants to make the window the size of the editor and the MainContentComponent’s resized() method sets the editor’s size based on the window’s new size. It almost works but because of the interaction it looks bad until the mouse button is released. So I tried adding a constrainer to the window…which almost worked. I know the aspect ratio of my editor but the constrainer needs to also add the height of the titlebar…ah, the extra 22 pixels. So setting setFixedAspectRatio(400 / (300 + 22)) is not the same as setFixedAspectRatio(800 / (600 + 22)) which it needs to be. As you can see, this is WAY more difficult than it should be. In summary: - The Standalone classes are difficult if not impossible to customize without any hooks, very un-JUCE-like. - The StandaloneWindow should use the native titlebar by default. - Going fullscreen when using a native titlebar adds 22 to the height of the MainContentComponent every time it goes fullscreen, but not when using the Juce titlebar. - Clicking the green fullscreen icon on a native titleBar in OS X uses the OS’s fullscreen code, but uses Juce’s fullscreen code when using the Juce titlebar and they produce different results. - Calling setFullScreen(false)doesn’t return the window to it’s original size when using the nativeTitlebar. - There doesn’t seem to be a good way to make the window fullscreen and keep the plugin editor’s window it’s original aspect ratio. Any help would be very much appreciated. Thanks.
https://forum.juce.com/t/standalone-issues/26643
CC-MAIN-2020-40
refinedweb
1,020
54.83
Just a matter of adding a statfs wrapper for the valgrind port. Happy to code this up if nobody has any objections. Error occurred as follows: (568)|thinkpad|gardei|~/valgrind-debug| $>>freebsd-version 12.0-RELEASE (569)|thinkpad|gardei|~/valgrind-debug| $>>cat disk.c #include <sys/statvfs.h> int main() { struct statvfs fs; return statvfs("/", &fs); } (570)|thinkpad|gardei|~/valgrind-debug| $>>valgrind ./a.out ==12810== Memcheck, a memory error detector ==12810== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==12810== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info ==12810== Command: ./a.out ==12810== --12810-- WARNING: unhandled syscall: 555 --12810-- You may be able to write your own handler. --12810-- Read the file README_MISSING_SYSCALL_OR_IOCTL. --12810-- Nevertheless we consider this a bug. Please report --12810-- it at. ==12810== ==12810== HEAP SUMMARY: ==12810== in use at exit: 0 bytes in 0 blocks ==12810== total heap usage: 0 allocs, 0 frees, 0 bytes allocated ==12810== ==12810== All heap blocks were freed -- no leaks are possible ==12810== ==12810== For counts of detected and suppressed errors, rerun with: -v ==12810== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) Seems to be related to A patch is already provided there, although it does not handle syscalls with following ids: fhstat 553 statfs 555 fhstatfs 558 Maintainership dropped ports r495096. Assign to new maintainer. (In reply to Michael Buch from comment #0) With my github repo () I get paulf> ../../../vg-in-place ./statvfs ==26238== Memcheck, a memory error detector ==26238== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==26238== Using Valgrind-3.16.0.GIT and LibVEX; rerun with -h for copyright info ==26238== Command: ./statvfs ==26238== ==26238== ==26238== HEAP SUMMARY: ==26238== in use at exit: 0 bytes in 0 blocks ==26238== total heap usage: 0 allocs, 0 frees, 0 bytes allocated ==26238== ==26238== All heap blocks were freed -- no leaks are possible ==26238== ==26238== For lists of detected and suppressed errors, rerun with: -s ==26238== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=235720
CC-MAIN-2020-24
refinedweb
347
72.46
The system.time() function returns the current system time. Function type: Date/Time Output data type: Timestamp import "system" system.time() Examples import "system" data |> set(key: "processed_at", value: string(v: system.time() )) system.time() vs now() system.time() returns the current system time of the host machine, which typically accounts for the local time zone. This time represents the time at which system.time() it is executed, so each instance of system.time() in a Flux script returns a unique value. now() returns the current UTC time. now() is cached at runtime, so all instances of now() in a Flux script return the same value.
https://docs.influxdata.com/flux/v0.50/stdlib/system/time/
CC-MAIN-2020-05
refinedweb
106
61.73
You know who you are. So does the IRS, the DMV, and every website and service online where you have a login and a password for. But none of those entities really knows you. What they know is what the techies call a namespace. That namespace is not your identity. Instead, it’s an identifier. That identifier is an administrative construction. It’s something created so—you—no matter what you’re called. The names that matter most to you are the one you were given at birth and the ones you choose to be called by. Neither is fixed. You can change your names without changing who you are. So can others, but managing how you are known is a self-sovereign power. Samuel Clemens used the pen name Mark Tw.) My surname is one my father chose to spell the same as did his father, but not his grandparents. (They went by Searles.) The nickname Doc came along after I started a company with two other guys, one of whom was named David. He and the other guy (the late great Ray Simone, who also drew the Doctor Dave image above) called me Doctor Dave around the office, and with clients and suppliers. After awhile three syllables seemed too many, and they all just called me Doc. Also relevant: David was actually David’s middle name. His first was Paul. Nicknames are often context-dependent. People who knew me through business called me Doc. Everybody else called me David or Dave. That was in North Carolina, where I had lived for most of the two decades before our company opened an office in Silicon Valley and I went out there prospecting. That was in the Fall of ’85. I knew almost nobody in California, other than a few business contacts who called me Doc. But I wasn’t sure about keeping Doc as a nickname, since in a way I was starting over in a new place. So, I market tested Doc vs. David when I went to the Comdex conference in October of that year in Las Vegas. The test was simple. authority over that.!
https://blogs.harvard.edu/vrm/2012/03/25/ssi/
CC-MAIN-2019-26
refinedweb
358
85.39
Could we do a followup pattern-match to compliment this? I like the start, but it’s not really doing anything that leverages “Features” or the specific implementations. Hey swoogles, Thank you for the feedback, how about the code below ? By the way, code works on Linux and MacOs, but it does not work on Scala Fiddle and i did not test it on windows. trait Feature case class ObjectOriented(description: String) extends Feature case class Functional(description: String) extends Feature case class StaticallyTyped(description: String) extends Feature def colorize(feature: Feature): Feature = feature match { case ObjectOriented(description) => ObjectOriented( s"${Console.BLUE} ${description} ${Console.RESET}" ) case Functional(description) => Functional( s"${Console.GREEN} ${description} ${Console.RESET}" ) case StaticallyTyped(description) => StaticallyTyped( s"${Console.BLUE} ${description} ${Console.RESET}" ) } val scalaFeatures = List( ObjectOriented("Define new types and behaviors using classes and traits"), Functional("Define functions as values, pass them as higher-order functions or return them as curried functions"), StaticallyTyped("Programs are statically checked for safe and correct type usage at compile time") ) scalaFeatures.map(colorize).foreach(println) This is my contribution. It includes pattern matching, named arguments, default values, a basic ADT with case class and case object, high order functions and finally some operations on a collection. trait State case class Gas(noble: Boolean) extends State case class Solid(classe: String = "unknown") extends State case object Liquid extends State def describe(state: State): String = state match { case Liquid => "an incompressible fluid" case Solid(classe) => s"an $classe solid" case Gas(noble = true) => "a noble gas" case Gas(noble = false) => "a simple gas" } val elements = Map("Helium" -> Gas(true), "Mercury" -> Liquid, "Calcium" -> Solid("alkaline")) elements .filterKeys(name => name != "Helium") .map { case (name, state) => s"The element '$name' is ${describe(state)}." } .foreach(println) Thanks a lot for everybody participating. I’m going to let this going until the 25th of September. Then we can do a poll to decide the winner(s). Actually, it doesn’t work correctly on either Scalafiddle or Scastie – this is designed specifically for printing on the console, not embedded in the browser, which is the point of this particular challenge… @jducoeur @SubMachineGhost I just added support for colors in the console: Something similar, but hey, I gotta try: // default kind is "cat", because everyone loves cats case class Animal(name: String, kind: String = "cat") def isCat(a: Animal): Boolean = a.kind == "cat" val pets = List( Animal("Kitty"), // default params Animal("Fido", "dog"), Animal("Tigger"), Animal("Luna"), Animal(name = "Charlie", kind = "parrot") // named params, yay! ) val catNames = pets filter(isCat) map(p => p.name) mkString(", ") // lambdas // prints "My cats are Kitty, Tigger, Luna." println(s"My cats are $catNames.") @MasseGuillaume wow that was really quick (that’s what she said), thank you for the effort. @jducoeur i’ll open an enhancement issue to support the CLI ANSI colors on the Scala Fiddle Github page, and Hopefully we’ll have that feature pretty soon. Cheers. Not really good : Use ASCII art naming instead? Maybe such fancy looper for parallel computing? Futures with a kind of recurrence? (I’m aware more than 18 lines) import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits._ import scala.concurrent.duration._ def loop[T, U](syncFunc: => T, heavyComputeFunc: T => Future[U], accumulator: Seq[Future[U]]): Future[Seq[U]] = Future { Looper.synchronized { syncFunc } }.flatMap { t: T => val longComputation = heavyComputeFunc(t) loop(syncFunc, heavyComputeFunc, accumulator :+ longComputation) }.recoverWith { case _ => Future.sequence(accumulator) } // example for stream val stream = (1 to 100).toStream.toIterator val k = loop( if (stream.hasNext) stream.next else throw new RuntimeException("EOF"), (v: Int) => Future { Thread.sleep(834); println(v); v }, Seq.empty) println(s"done ${Await.result(k, 20 second).sum}") I think that the best solution is a carousel of snippets demonstrating different features of the language. See @nafg’s post above for examples. This way readers with no background in certain field, will always find something new for them and even those who already know what all the buzz-words are about will be able to compare Scala syntax with the other languages. I think the code snippet should be simple and don’t need to show too many features in Scala. I find some good code examples in old Scala home page. Some code snippets (came from here and there and modified) I like: 1. object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } } object Fib { def fibonacci(n: Int): Int = n match { case 0 | 1 => n case _ => fibonacci(n - 1) + fibonacci(n - 2) } def main(args: Array[String]) { val numbers = List(4, 2) for (n <- numbers) println(fibonacci(n)) } } 3. object Sort { def quickSort(list: List[Int]): List[Int] = list match { case Nil => Nil case head :: tail => val (low, high) = tail.partition(_ < head) quickSort(low) ::: head :: quickSort(high) } def main(args: Array[String]) { val numbers = List(6, 2, 8, 5, 1) println(quickSort(numbers)) } } The third one looks good, but I still think it is a bit complex. I try to use if/else instead of pattern match (Nil is odd for beginners) but still like the latter. if/else pattern match (Nil is odd for beginners) For reference, it looks like this on windows: I’m going to chip in and say that the front page snippet should not be to show off language features. The goal should be two things: Show how the user can do things they already know they want to do, easily Show how easy it is to solve small problems These concerns are contradictory, but neither of them involves showing off how many features the language has. It’s not an uncommon feeling that the number of features Scala has is a disadvantage of using the language! Ideally the snippet would show no features a newbie would not immediately understand. Abstract types, multiple-inheritance/trait-stacking, context bounds, implicits, and many other things can wait for later. The example can use them just fine, but they should not be necessary for understanding what the example is doing. That said, I’m going to throw my hat in the ring and offer the Scala.js Oscilloscope: 18 lines of non-whitespace code, uses a lot of basic language features (Seqs, anonymous functions, tuples, destructuring, for-loops) and puts together something pretty in relatively few lines of code. A user can tweak this and get immediate feedback, e.g. changing the functions used to draw the graph or changing the colors used. And anyone can appreciate the output, not just people interested in a particular algorithm or technique. Seq for I’m also going to vote for using ScalaFiddle instead of Scastie, even though that was not the original question. Apart from ScalaFiddle compiling code way faster than Scastie, Scastie also takes forever (almost 10 seconds!) to load over here in Singapore: It appears the fault is split between lack of full optimizations on the JS blob, as well as lack of gzip compression on the server. Apart from initial download speed, ScalaFiddle does a bunch of things Scastie doesn’t, e.g. caching compilation output using a CDN for instant initial page loads that include running the compiled output. Overall, ScalaFiddle ends up being a much slicker experience in the places where it matters, and the shortcomings are in places where it doesn’t matter. Newbies aren’t going to care that you can’t run code using java.lang.ProcessBuilder in the “try it now!” sandbox, nor are they going to care that they can’t tweak SBT settings or compile using Dotty. java.lang.ProcessBuilder There’s a time and place for Scastie, when you want to reproduce more involved setups with custom SBT config and esoteric Scala versions. But for this use case, it seems ScalaFiddle is just the right tool for the job. Cannot agree more, thanks for putting together this detailed explanation! Show how the user can do things they already know they want to do, easily - I agree a class with fields/constructor on one line: that is an eye opener for many. IMO this should come with a remark on the number of lines in equivalent Java code, and a link to such code. Sudoku: While I appreciate the elegance and conciseness of the Sudoku solver that Pathikrit posted in this thread, it also intimidates me, since I just don’t see how it works. At least it should come with a link to a page that explains the magic. Hey, Thank for this detailed review. Your feedback points to directly actionable items. I agree with this. Notice in the embedding above, there is no settings or anything like this. There is a run button and a button to go to Scastie. The cool thing with Scastie, it’s its extensibility. A new user might want to try a library for parsing JSON for example. We make this super easy. We have a really cool DOM binding: They need to use akka.js because scalafiddle does not allow you to run JVM code by design. I don’t want to underevaluate the work that was done in akka.js, but it’s not akka. The execution model on the jvm versus the js vm is completly different. More generally, I see This is a limitation. You should be able to use any target (JS, JVM, etc) you want. Scastie can be a little bit slower than scalafiddle since we need to reload configuration or wait for execution on the JVM. However, it is a more general solution. It allows all possibilities of libraries and targets where scalafiddle is limited to a predefined set of libraries and Scala.js. Using sbt directly allows us to quickly enable new platforms (Scala-Native, Dotty, Typelevel Scala, etc) and evolve quickly when new Scala version are available. Lastly, It is a project supported by the Scala Center and we are committed to ensure the continuity of the projects for years to come. It shoud be clear what the exact goal of putting a snippet of Scala on the front page is. My guess is conversion rate. The snippet should get as many visitors as possible to play around / read more about Scala, right? It doesn’t matter if we show off crazy features when the page visitor does not stay and invest more time. So in my opinion the only way to find out is measuring the conversion rate of different snippets being shown. The one with the best rate wins. @MasseGuillaume I totally understand that there are pros and cons in both choices. I personally think that this argumentation has fond but is biased, and I can see that there are different positions here in the community, I will love to have the Scala site that clearly reflect the Scala community and I think that a poll on this decision will simply and effectively stop discussions and give us a strong feedback. I’m not arguing that we will have a clear winner and I will be extremely happy if all of your arguments are felt by the the major part of the rest of the community. B.T.W. if you and Scala Center have already taken a decision I’m wondering why it’s worth to ask people about the content, you are totally free to go your way even on this topic!
https://contributors.scala-lang.org/t/contest-scala-lang-org-frontpage-code-snippet/1141?page=2
CC-MAIN-2017-43
refinedweb
1,889
63.7
What is an encoding and how it works? A computer can't store letters or anything else - it stores bits. Bit can be either 0 or 1 ("yes"/"no", "true"/"false" - these formats are called binary therefore). To use these bits some rules are required, to convert the bits into some content. There rules are called encodings, where sequences of 1/0 bits stand for certain characters. A sequence of 8 bits is called byte. Encodings work like tables, where each character is related to a specific byte. To encode something in ASCII encoding, one should follow the entries from right to left, searching for bits related to characters. To decode a string of bits into characters, one substitutes bits for letters from left to right. Bytes can be represented in different formats: for example 10011111 in binary is 237 in octal, 159 in decimal and 9F in hexadecimal formats. What is the difference between different encodings? First character encoding like ASCII from the pre-8-bit era used only 7 bits from 8. ASCII was used to encode English language with all the 26 letters in lower und upper case form, numbers and plenty of punctuation signs. ASCII could not cover other European languages with all the ö-ß-é-å letters - so encodings were developed that used the 8-th bit of a byte to cover another 128 characters. But one byte is not enough to represent languages with more than 256 characters - for example Chinese. Using two bytes (16 bits) enables encoding of 65,536 distinct values. Such encodings as BIG-5 separate a string of bits into blocks of 16 bits (2 bytes) to encode characters. Multi-byte encodings have the advantage to be space-efficient, but the downside that operations such as finding substrings, comparisons, etc. all have to decode the characters to unicode code points before such operations can be performed (there are some shortcuts, though). Another type of encoding are such with variable number of bytes per character - such as UTF standards. These standards have some unit size, which for UTF-8 is 8 bits, for UTF-16 is 16 bits, and for UTF-32 is 32 bits. And then the standard defines some of the bits as flags: if they're set, then the next unit in a sequence of units is to be considered part of the same character. If they're not set, this unit represents only one character fully (for example English occupies only one byte, and thats why ASCII encoding maps fully to UTF-8). What is the Unicode? Unicode if a huge character set (saying in a more understandable way - a table) with 1,114,112 code points, each of them stands for specific letter, symbol or another character. Using Unicode, you can write a document which contains theoretically any language used by people. Unicode is not an encoding - it is a set of code points. And there are several ways to encode Unicode code points into bits - such as UTF-8, -16 and -32. There is a useful package in Python - chardet, which helps to detect the encoding used in your file. Actually there is no program that can say with 100% confidence which encoding was used - that's why chardet gives the encoding with the highest probability the file was encoded with. Chardet can detect following encodings: You can install chardet with a pip command: pip install chardet Afterward you can use chardet either in the command line: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 or in python: import chardet rawdata = open(file, "r").read() result = chardet.detect(rawdata) charenc = result['encoding'] Detailed instructions on getting encoding set up or installed.
https://riptutorial.com/encoding
CC-MAIN-2019-22
refinedweb
625
62.78
Moose::Manual::Contributing - How to get involved in Moose - NAME - VERSION - GETTING INVOLVED - WORKFLOWS - BRANCH ARCHIVAL - TESTS, TESTS, TESTS - DOCS, DOCS, DOCS - BACKWARDS COMPATIBILITY - AUTHORS NAME Moose::Manual::Contributing - How to get involved in Moose VERSION version 2.2009 GETTING INVOLVED Moose is an open project, and we are always willing to accept bug fixes, more tests, and documentation patches. Commit bits are given out freely and it's easy to get started! Get the Code. People As Moose has matured, some structure has emerged in the process. - Cabal - people who can release moose. - Contributors - people creating a topic or branch You! New Features. Branch Layout The repository is divided into several branches to make maintenance easier for everyone involved. The branches below are ordered by level of stability. - stable/* The branch from which releases are cut. When making a new major release, the release manager makes a new stable/X.YYbranch. - master The main development branch. All new code should be written against this branch. This branch contains code that has been reviewed, and will be included in the next major release. Commits which are judged to not break backwards compatibility may be backported into stableto be included in the next minor release. - topic/* Small personal branches that are still in progress. They can be freely rebased. They contain targeted features that may span a handful of commits. Any change or bugfix should be created in a topic branch. - rfc/* Topic branches that are completed and waiting on review. A Cabal member will look over branches in this namespace, and either merge them to masterif they are acceptable, or move them back to a different namespace otherwise. This namespace is being phased out now that we are using GitHub's pull requests in our "Development Workflow". - attic/* Branches which have been reviewed, and rejected. They remain in the repository in case we later change our mind, or in case parts of them are still useful. - abandoned/*. WORKFLOWS Getting Started. Development Workflow The general gist of the STANDARD WORKFLOW is: - 1. Update your local repository with the latest commits from the official repository - - 2. Create a new topic branch, based on the master branch - - 3. Hack away - - 4. Commit and push the topic branch to your forked repository - - 5. Submit a pull request through GitHub for that branch - What follows is a more detailed rundown of that workflow. Please make sure to review and follow the steps in the previous section, "Getting Started", if you have not done so already. Update Your Repository Update your local copy of the master branch from the remote: git checkout master git pull --rebase Create Your Topic Branch Hack. Commit. Repeat.). Clean Up Your Branch. Rebase on the Latest Publish and Pull Request! Approval Workflow. - Small bug fixes, doc patches and additional passing tests. These items don't really require approval beyond one of the core contributors just doing a simple review. For especially simple patches (doc patches especially), committing directly to master is fine. - Larger bug fixes, doc additions and TODO or failing tests. "Development Workflow" and start hacking away. Failing tests are basically bug reports. You should find a core contributor and/or cabal member to see if it is a real bug, then submit the bug and your test to the RT queue. Source control is not a bug reporting tool. - New user-facing features. Anything that creates a new user-visible feature needs to be approved by more than one cabal member. Make sure you have reviewed "New Features" to be sure that you are following the guidelines. Do not be surprised if a new feature is rejected for the core. - New internals features. New features for Moose internals are less restrictive than user facing features, but still require approval by at least one cabal member. Ideally you will have run the xt/author/test-my-dependents.t script to be sure you are not breaking any MooseX module or causing any other unforeseen havoc. If you do this (rather than make us do it), it will only help to hasten your branch's approval. - Backwards incompatible changes.. Release Workflow # Release How-To Perls. Testing should be done against at least two recent major versions. Emergency Bug Workflow (for immediate release) Project Workflow). BRANCH ARCHIVAL. TESTS, TESTS, TESTS. DOCS, DOCS, DOCS. BACKWARDS COMPATIBILITY.
http://docs.activestate.com/activeperl/5.26/perl/lib/Moose/Manual/Contributing.html
CC-MAIN-2018-17
refinedweb
723
67.65
I found it effective to use loadlin, a DOS-based loader; this has the distinct advantage of always booting a working system before running Linux. My experience with LILO has been if you don't do it right, your system is only useful as a paper weight. In my MS-DOS config.sys, I take advantage of the menus, and the result is shown in Listing 1. menuitem=dos menuitem=simple.dos menuitem=linux.1.2.8 menuitem=scandisk menudefault=linux.1.2.8,5 [linux.1.2.8] SHELL=C:\loadlin\loadlin.exe \loadlin\zimage.128 root=/dev/hdc2 -v ro [simple.dos] [dos] DEVICE=C:\DOS\HIMEM.SYS DEVICEHIGH=C:\MAGICS20\CDIFINIT.SYS /T:X DEVICEHIGH=C:\MTM\MTMCDAI.SYS /D:MTMIDE01 DEVICEHIGH /L:2,12048 =C:\DOS\SETVER.EXE DOS=HIGH STACKS=9,256 [scandisk] SHELL=c:\dos\scandisk.exe /all /checkonly I boot Linux with a delay of 5 seconds, the advantage being that the system can always boot DOS and will work in some capacity. I find this preferable to using LILO and modifying the master boot record on your hard disk (if you do anything wrong, you need to boot from floppy to recover). One can easily select several kernels and/or configurations from the command line. Using loadlin, you have to make a compressed kernel (make zImage), and then put it on a DOS partition. I find this strategy effective even when installing Linux the first time (instead of dealing with a boot and root floppy, the system can boot the kernel with only a root floppy needed). You can easily add to the menu to have several different kernels to boot from. Remember, you can use the rdev utility to build defaults (like the root device) into the kernel. In your autoexec.bat you can use the strategy: goto %config% :simple.dos PATH=C:\marty\bin;C:\gnu\bin;C:\dos;C:\ goto end :dos SET SOUND16=C:\MAGICS20 C:\MAGICS20\SNDINIT /b SET BLASTER=A220 I7 D1 T4 C:\DOS\SMARTDRV.EXE 512 512 /C C:\DOS\IMOUSE.COM PROMPT $p$g SET PATH=c:\gnu\bin;C:\MARTY\BIN;C:\WINDOWS;C:\DOS; SET TEMP=C:\DOS JOIN d: \marty JOIN f: \gnu goto end :end The simple.dos setting is conceptually the same as booting Linux in single user mode. I find it very useful for debugging a DOS system. If you want, you can add config.sys menu entries to boot different kernels, boot Linux in single user mode, boot Linux from floppies, etc. In the standard Linux kernel configuration, the UMSDOS file system isn't enabled. UMSDOS has a number of major advantages if you need file systems to be shared between Linux and DOS. It retains full Unix semantics, so you don't have to always be handicapped by DOS problems such as: lack of links restrictions of 8+3 file naming conventions restrictions of characters in file names one date (instead of access/change/modify time) lack of owner/groups Using UMSDOS you can take advantage of a file system shared between DOS and Linux, with the appearance of being a Linux file system when you run Linux. If you want files to be portable between MS-DOS and Linux, restrict yourself to DOS filenames (8+3 characters). Don't use links if you want the files to appear under DOS. With a Linux file system, it's easy do things like create “dot files”, do gzip-r on trees, and create links and backup files. Any file is readable in MS-DOS; however, if you don't conform to the MS-DOS file naming conventions, files are “munged” (that is, their names are squeezed to fit within the 8+3 namespace). This munging is similar to what happens in mfs; those who use PC-NFS are probably familiar with this. When you start running the UMSDOS file systems, remember to run the application called umssync, which creates consistency between the --linux-.--- files and the directory contents. You can have problems if you add or delete files under DOS without Linux knowing about it. Call umssync from /etc/rc.d/rc.local or /etc/rc.d/rc.M after the mount takes place, and this shouldn't be a problem. I've noticed a problem in UMSDOS files systems—the mount points are owned by root, only writable by root, and the date is the beginning of the epoch. A simple workaround is after mounting, do chown/chmod to the mount points as appropriate (in your /etc/rc.d/rc.local file. Also, I find it useful to occasionally run scandisk from DOS (notice the scandisk target in config.sys). There is a performance penalty for DOS and UMSDOS file systems compared to normal ext2. The penalty becomes severe if you have several hundred files in a single directory (when you do an ls, get a cup of coffee). What I've noticed is sequential I/O (with a tester called Bonnie) is marginally faster on ext2 than UMSDOS. But UMSDOS is ideal if you're doing work with DOSEMU. You put DOS files on UMSDOS partitions, and you can easily access them from DOS, DOSEMU or Linux. If they keep within the DOS file system bounds of 8+3 characters, they look the same on both DOS and Linux. UMSDOS partitions provide a big advantage when sharing files with DOS (much more so then the MSDOS file system, since it treats Linux files as Linux files), but performance has to be watched. 3 hours 3 min ago 3 hours 21 min ago 3 hours 51 min ago 3 hours 51 min ago 3 hours 52 min ago 6 hours 52 min ago 15 hours 19 min ago 15 hours 24 min ago 15 hours 54 min ago
http://www.linuxjournal.com/article/1137?page=0,1
CC-MAIN-2013-20
refinedweb
973
63.19
Content All Articles PHP Admin Basics PHP Forms PHP Foundations ONLamp Subjects Linux Apache MySQL Perl PHP Python BSD In today's PHP Foundations, I'll begin my introduction of working with HTML forms from PHP. Since there is only time to discuss strictly PHP-related materials, I'll assume that you are already comfortable with HTML and creating HTML forms for user input. If you would like a refresher, there are a number of HTML resources available online. A personal favorite is Sizzling HTML. Assuming that you have already designed a form to process with PHP, the first step is setting your form to submit its data to the PHP script. This is done via the <form> tag's action attribute. This attribute defines the URL to which the form submits its data. Set it to your PHP script. For instance, if your PHP processing script is called process.php, your <form> tag would resemble: <form> action process.php <form action="process.php" method="POST"> Also in PHP Foundations: Using MySQL from PHP, Part 2 Using MySQL from PHP MySQL Crash Course, Part 3 MySQL Crash Course, Part 2 MySQL Crash Course When a form is submitted, the web server executes the PHP script and passes to it the values which were submitted in the submission. At this point, PHP automatically creates three "superglobal" arrays and populates them with the submitted data. For those who have not been exposed to the term "superglobal," let me explain its meaning. The term refers to the scope in which a variable in PHP is normally available. For instance, an arbitrary variable $foobar may be defined outside of a function. It will not be available inside of the function unless the global statement is used. This is not the case with superglobal variables--they can be accessed from anywhere inside of a PHP script, regardless of the current scope, without using the global statement. $foobar global Which of these three superglobal arrays are used to store the data received from a form submission depends on the method by which the data was submitted. In the above <form> tag, the submission method was set to POST via the method attribute. Hence, PHP will store any data that is submitted in this form in the $_POST superglobal array. Likewise, if the GET method had been used then the $_GET superglobal array would contain the data. method GET $_GET Most of the time, it is good practice to write PHP scripts that look at only one method or another (whichever your form uses) when receiving input from the user. In certain circumstances it may not matter, so PHP also provides a third superglobal array, $_REQUEST, which contains all of the values from GET and POST submissions as well as any cookie variables that were passed, as well. $_REQUEST Related Reading PHP Cookbook By David Sklar, Adam Trachtenberg How are these three arrays structured based on the submission? All three superglobals are created as associative arrays whose key/value pairs represent the name of the given HTML element (specified by the name attribute) and the value of that element, respectively. Hence, the value from the following HTML input box: name <input type="TEXT" name="mytextbox" value="my value"> could be accessed by either $_GET['mytextbox'] or $_POST['mytextbox'], depending on the form submission method. Of course, the value can always be found in $_REQUEST['mytextbox']. $_GET['mytextbox'] $_POST['mytextbox'] $_REQUEST['mytextbox'] register_globals In versions of PHP prior to 4.2.0, any variables that were sent from the client to the web server were automatically created as normal variables. (A text box named foo would have its value placed in the $foo variable.) This behavior could be turned on and off by adjusting the register_globals PHP directive in the php.ini file. In the post-version-4.2.0 world, this feature has been disabled by default because of security concerns. Although it is slightly less "clean" to use associative arrays instead of PHP variables, it is strongly recommended that this feature remain disabled for any script where security is a concern. A much better approach (without sacrificing security) is to use the import_request_variables() function. This function will create the same scalar variables as if register_globals were enabled, and has the following syntax: foo $foo php.ini import_request_variables() import_request_variables($types [, $var_prefix]) $types represents which of the three types of variables to import (GET, POST, or cookie variables) by passing a string containing any combination of the characters G, P, and/or C representing GET, POST, and COOKIE values, respectively. The second parameter, $var_prefix, is an optional parameter representing a string with which to prefix the created variable names. The following code snippet will register all POSTed variables as scalar variables (each prefixed with mypost_ in the variable name): $types G P C COOKIE $var_prefix mypost_ <?php import_request_variables("P", "mypost_"); /* Assuming $_POST['foo'] exists, the next line will now print its value to the client browser */ echo $mypost_foo; ?> As I have already illustrated, PHP will use the name of a form element as a key in the superglobal array to store its value. However, one thing that has not been covered at all is dealing with a form element in which more than one value is returned (for example, a list where multiple items can be selected). In such a case, you'll need to define your HTML form element names so that PHP can import the variables as an array. In order for PHP to identify a particular variable name as containing an array, the name must include square brackets ([]) at the end of the value of its name attribute. This is illustrated in the following <select> form element: [] <select name="mylist[]" multiple> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> When the form containing this list is submitted, PHP will still register the key mylist in the appropriate superglobal ($_GET or $_POST). Instead of being a simple scalar value, however, mylist will be a zero-indexed array containing each element selected from the list. mylist This behavior is not limited to list HTML elements, but can be used for any information passed to the server by the client. Furthermore, the specific key for each element in the array can be specified. For instance, the following three input fields will all be stored under the mytext key of the relevant superglobal as an array containing the keys text1, text2, and text3: mytext text1 text2 text3 <input type="TEXT" name="mytext[text1]"> <input type="TEXT" name="mytext[text2]"> <input type="TEXT" name="mytext[text3]"> Due to the nature of checkboxes, you may have already realized that checkboxes will not show up in PHP unless they have been checked. Dealing with this circumstance can be annoying (and perhaps insecure) unless properly dealt with. The first of these methods basically involves creating a hidden form element with the same name as the checkbox element and setting its value to zero, as shown below: <input type="hidden" name="mycheckbox" value="0"> <input type="checkbox" name="mycheckbox" value="1"> The idea behind this solution is based on how PHP will respond if two elements (using the same method) have the same name. As was the case with the <select> element when in multi-select mode, PHP uses the last value provided to it. The hidden element will be used because the checkbox element is not sent to PHP if it is unchecked. Likewise, if the checkbox element is checked when the form is submitted, its value will override that of the hidden element. Unfortunately, the drawback to this solution is a complete reliance on the browser to always send the hidden element before the checkbox element. Although it is logical to assume that elements will be sent in the same order as they are presented in the HTML document, there is no guarantee that this situation will be the case. The second solution to this problem is much more eloquent for most situations. Unless you are unsure if a given checkbox was displayed to the user (if it may or may not be present in the form, depending the logic that created the form) create a boolean value based on the existence of the checkbox: <?php /* Assume a checkbox by the name 'mycheckbox' exists */ $checkbox = ($_GET['mycheckbox'] == 1); ?> The value of the $checkbox boolean will be set to true if the mycheckbox element exists (with the proper value), and false otherwise. $checkbox mycheckbox That's it for today's discussion of using forms in PHP. As you can see, in PHP, as long as you are aware of how PHP will respond, using user-submitted form data in your scripts is fairly simple. In my next article, I'll tackle the issue of uploading files from a HTML form using HTTP file uploads..
http://archive.oreilly.com/pub/a/php/2003/03/13/php_foundations.html
CC-MAIN-2015-22
refinedweb
1,478
57.5
here it is I am currently learning C by reading "Beginning C" by Ivor Horton and there is an example that is not explained as detailed as I would hope: #include <stdio.h> void main() { int number = 0; int rebmun = 0; int temp = 0; printf("\nEnter a positive integer: "); scanf("%d", &number); temp = number; do { rebmun = 10 * rebmun + temp % 10; temp = temp/10; } while(temp); printf("\nThe number %d reversed is %d rebmun ehT\n", number, rebmun); } that which is bolded is what I have a question on, why does C claculate the modulus before multiplying. I have a chart that explains it but it has only: * / % From left to right now from what I learned back in Algebra that meant that they were all equal and would be performed in order they appeared except that the modulus operator is located after the multiplication. Some one please explain the logic behind this. Sean
http://cboard.cprogramming.com/c-programming/3976-c-number-operator-question-printable-thread.html
CC-MAIN-2013-48
refinedweb
153
51.35
Overview Todays post will show how you can make a Google Command Line script with Python (version 2.7.x) """ Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API. """ To make a request to the Web search API, we have to import the modules that we need. urllib2 Loads the URL response urllib To make use of urlencode json Google returns JSON Next we specify the URL for which we do the request too: To make it a bit interactive, we will ask the user for an input and save the result to a variable that we name "query". query = raw_input("What do you want to search for ? >> ") Create the response object by loading the the URL response, including the query we asked for above. response = urllib2.urlopen (url + query ).read() # Process the JSON string. data = json.loads (response) From this point we can play around with the results GoogleSearch.py Let's see the complete script import urllib2 import urllib import json url = "" query = raw_input("What do you want to search for ? >> ") query = urllib.urlencode( {'q' : query } ) response = urllib2.urlopen (url + query ).read() data = json.loads ( response ) results = data [ 'responseData' ] [ 'results' ] for result in results: title = result['title'] url = result['url'] print ( title + '; ' + url ) Open an text editor , copy & paste the code above. Save the file as GoogleSearch.py and exit the editor. Run the script: $ python searchGoogle.py What do you want to search for ? >> python for beginners BeginnersGuide - Python Wiki; Python For Beginners; Python For Beginners;:
https://www.pythonforbeginners.com/code-snippets-source-code/google-command-line-script
CC-MAIN-2020-16
refinedweb
290
75.1
This is a two for one article -- learn to build a brush of blended colors, and get a couple of cool color blending user controls in the process. There can be a lot of trial and error, tweaking the code and running it many times, to create a color blend. I thought it would be nice to have a control like those seen in drawing programs that would create the blend visually to get a proper placement of the colors. I will also try to explain the basics of making a color blended brush to paint with. Building a two color color blend is fairly simple. Using a LinearGradientBrush from the System.Drawing.Drawing2D namespace, you can paint an area with a blend from one color to another color. Dim rect As New Rectangle(0, 0, 100, 100) Using br As New LinearGradientBrush( _ rect, _ Color.White, _ Color.Black, _ LinearGradientMode.Horizontal) 'Fill the rect with the blend g.FillRectangle(br, rect) End Using If you want more than two colors, a ColorBlend is needed. First, create an array of colors for each position in the blend. Then, create an array of values representing the position of each color in the color array. The first color has a position of 0, and the last color has a position of 1. All the other colors in between have a decimal position value between 0 and 1. After creating the arrays, assign them to the ColorBlend's Colors and Positions properties. Then, create the same LinearGradientBrush as before, setting the two colors to any color just as a placeholder. Set the Brush's InterpolationColors property to the ColorBlend just created to set the new multicolor blend. The LinearGradientBrush can be replaced with the PathGradientBrush for more complex shapes. Dim blend As ColorBlend = New ColorBlend() 'Add the Array of Color Dim bColors As Color() = New Color() { _ Color.Red, _ Color.Yellow, _ Color.Lime, _ Color.Cyan, _ Color.Blue, _ Color.Violet} blend.Colors = bColors 'Add the Array Single (0-1) colorpoints to place each Color Dim bPts As Single() = New Single() { _ 0, _ 0.327, _ 0.439, _ 0.61, _ 0.777, _ 1} blend.Positions = bPts Dim rect As New Rectangle(0, 0, 100, 100) Using br As New LinearGradientBrush( _ rect, _ Color.White, _ Color.Black, _ LinearGradientMode.Horizontal) 'Blend the colors into the Brush br.InterpolationColors = blend 'Fill the rect with the blend g.FillRectangle(br, rect) End Using The ColorBlender User Control consists of a horizontal bar of color with a starting and ending color gradient. Clicking along the bar adds a new color pointer. The pointer can be dragged back and forth to any position along the bar with the left button, and removed with the right button. Click the dropdown to access preset color swatches, an owner-drawn combobox with all the known colors, and the ARGB color values that can be changed to alter the color and transparency of the selected pointer. There is a sample preview on the control to display the effects of changing the other options available to each brush type. The LinearGradientBrush paints the ColorBlend on a line from point A to point B. The PathGradientBrush paints the blend around a path. The control’s properties are accessible to recreate the blend as needed outside the control. Note: The separate ColorBlenderLite control is the same except it does not have the sample preview and brush properties built in. Public Event BlendChanged() This event will fire in the BuildABlend subroutine. Here is a list of the primary properties: BlendColors Array of colors used in ColorBlend. BlendPositions Array of color positions used in ColorBlend. BlendGradientType Type of brush used to paint the ColorBlend - Linear or Path. BlendGradientMode Type of linear gradient color blend. BlendPathShape Shape of path for the ColorBlend - Rectangle, Ellipse, Triangle, Polygon. BlendPathCenterPoint Position of the center of the path ColorBlend. BarHeight Height of color blender bar. Methods to use outside the control. Currently, just one to convert the center point to another area's dimensions. Track if the cursor is over a pointer to select or add a pointer, or to adjust the position of the center point of a path. Contains the routines to draw the pointers, build the brushes, and build the ColorBlend. Paint the control to a Bitmap to create a buffer, eliminating flicker. Protected Overrides Sub _ OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs) 'Do Nothing End Sub Protected Overrides Sub _ OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) 'Go through each Pointer in the collection to get 'the current Color and Position arrays BuildBlend() 'Create a canvas to aint on the same size as the control Dim bitmapBuffer As Bitmap = _ New Bitmap(Me.ClientSize.Width, Me.ClientSize.Height) Dim g As Graphics = Graphics.FromImage(bitmapBuffer) g.Clear(Me.BackColor) g.SmoothingMode = SmoothingMode.AntiAlias ' Paint the ColorBlender Bar with the Linear Brush Dim barRect As Rectangle = _ New Rectangle(10, 0, Me.ClientSize.Width - 20, BarHeight) Dim br As Brush = LinearBrush(barRect, LinearGradientMode.Horizontal) g.FillRectangle(br, barRect) ' Paint the ColorBlender Sample with the chosen Brush Dim sampleRect As Rectangle = _ New Rectangle(Me.Width - 85, BarHeight + 20, 75, 75) If BlendGradientType = eBlendGradientType.Linear Then br = LinearBrush(sampleRect, GetBrushMode) Else br = PathBrush(sampleRect) g.DrawString(String.Format("X: {0} Y: {1}", _ BlendPathCenterPoint.X - (Width - 85), _ BlendPathCenterPoint.Y - (BarHeight + 20)), _ New Font("Arial", 8, FontStyle.Regular), _ Brushes.Black, Width - 85, BarHeight + 100) End If g.FillRectangle(br, sampleRect) 'Draw all the pointers in their Color, 'at their Position along the Bar Using pn As New Pen(Color.Gray, 1) pn.DashStyle = DashStyle.Dash g.DrawLine(pn, 10, BarHeight + 7, _ Me.ClientSize.Width - 15, BarHeight + 7) pn.Color = Color.Black pn.DashStyle = DashStyle.Solid DrawPointer(g, StartPointer.pColor, 0, StartPointer.pIsCurr) DrawPointer(g, EndPointer.pColor, 1, EndPointer.pIsCurr) If MiddlePointers IsNot Nothing Then For I As Integer = 1 To MiddlePointers.Count DrawPointer(g, MiddlePointers(I).pColor, _ MiddlePointers(I).pPos, I = CurrPointer) Next End If End Using 'Draw the entire image to the control 'in one shot to eliminate flicker e.Graphics.DrawImage(bitmapBuffer.Clone, 0, 0) bitmapBuffer.Dispose() br.Dispose() g.Dispose() End Sub Use the CallByName function to sort the collection of pointers by the pPos property value. Contains the events for the controls on the ColorBlender control. Contains the DrawItem event for the owner-drawn combobox to list the known colors. The Pointer class contains three properties. pPos- Position of the color. pColor- Color at the position value. pIsCurr- The pointer currently selected. General News Question Answer Joke Rant Admin
http://www.codeproject.com/kb/miscctrl/colorblender.aspx
crawl-002
refinedweb
1,111
52.05
Fibonacci numbers (PIR) - Other implementations: bc | C | C Plus Plus templates | dc | E | Erlang | FORTRAN | Haskell | Icon | Java | JavaScript | Lisp | Lua |. In this article we show two ways of calculating fibonacci numbers in PIR. <<fib.pir>>= fib fastfib test [edit] Recursive This is a very simple recursive implementation. This will become slow on big numbers, because the numbers are recalculated for each recursion. The PIR language gives us some help not available in regular assembly languages. The .param and .local macros creates named local registers, so that we don't need to care about register allocation, lifetime and other such details. <<fib>>= .sub fib .param int n .local int f1 .local int f2 if n <= 1 goto END n = n - 1 f1 = fib(n) n = n - 1 f2 = fib(n) n = f1 + f2 END: .return (n) .end [edit] Iterative This is a faster, but also somewhat more complicated way to calculate fibonacci numbers. To avoid recalculation, the numbers are stored in local registers, for later reuse. <<fastfib>>= .sub ffib .param int n .local int f1 .local int f2 .local int tmp if n <= 1 goto END f1 = 0 f2 = 1 n = n - 1 LOOP: tmp = f2 f2 = f1 + f2 f1 = tmp n = n - 1 if n > 0 goto LOOP n = f1 if f1 > f2 goto END n = f2 END: .return (n) .end [edit] Test If we run this test code, we can see that the iterative method is significantly faster then the recursive. <<test>>= .sub main :main .local int f .local int n n = 0 FIBLOOP: f = fib(n) print n print ": " print f print "\n" n = n + 1 if n > 30 goto FIBEND goto FIBLOOP FIBEND: n = 0 FFIBLOOP: f = ffib(n) print n print ": " print f print "\n" n = n + 1 if n > 30 goto END goto FFIBLOOP END: .endhijackerhijacker
http://en.literateprograms.org/Fibonacci_numbers_(PIR)
CC-MAIN-2014-42
refinedweb
302
72.56
Hi guys I am playing with the Sketch API and have managed to learn a few things but to far I can't figure out how to grab user input. Would anyone please let me know how to do this successfully? Thanks This is my first script: ` import sketch from 'sketch' // documentation: export default function() { // sketch.UI.message("It's alive 🙌") const doc = sketch.getSelectedDocument() const selectedLayers = doc.selectedLayers const layerArr = selectedLayers.layers; const selectedCount = selectedLayers.length const LABEL = doc.getLayersNamed("LABEL") var msg ="" var count = 0 if (selectedCount === 0) { sketch.UI.alert("oh boy", 'No layers are selected.') } else { /* // sketch.UI.message(layerArr[4].name) selectedLayers.forEach(function(item){ msg = msg + ++count + "-" + item.name + "\n" }) // if (LABEL) { // sketch.UI.message(LABEL[0].layerID) // }*/ sketch.UI.getInputFromUser( "What's your name?", { initialValue: 'Appleseed', }, (err, value) => { if (err) { // most likely the user canceled the input return } } ) } sketch.UI.message(msg) }` This is my paste: Not sure how the code came as text Hiya @gegagome! Some formatting tips for ya first - to make a code block use a set of three backticks. Inline code is only one set of backticks. As for getting the input from the user you can do something like this (try this code right within Sketch under Plugins -> Run Script…) Plugins -> Run Script… let sketch = require('sketch') sketch.UI.getInputFromUser( "What's your name?", { initialValue: 'Appleseed' }, (err, value) => { if (err) { // most likely the user canceled the input return } else { sketch.UI.message(value) } } ) You can see that getInputFromUser returns two things. An err and a value. If there is an error then we return early otherwise we display what the user inputted as a toast message. getInputFromUser err value Hi kevgski Thank you for the formatting code tip. The code is throwing an error in line 4. The problem is that this input code is the same from the docs. line: 4 sourceURL: /Users/garces/Library/Application Support/com.bohemiancoding.sketch3/Plugins/Untitled.sketchplugin column: 27 stack: onRun@/Users/garces/Library/Application Support/com.bohemiancoding.sketch3/Plugins/Untitled.sketchplugin:4:27``` Not sure I follow what that error is from. Here is what I get when I run my code: I don’t understand why this is a problem? The provided code from the docs works just fine. Can you provide more details about the error you are getting? kevgski so I am not getting that. I am getting this error instead: TypeError: null is not a function (near '...sketch.UI.getInputFromUser...') line: 4 sourceURL: /Users/garces/Library/Application Support/com.bohemiancoding.sketch3/Plugins/Untitled.sketchplugin column: 27 stack: onRun@/Users/garces/Library/Application Support/com.bohemiancoding.sketch3/Plugins/Untitled.sketchplugin:4:27 Script executed in 0.051684s Ah interesting, what version of Sketch are you running? getInputFromUser was recently added in 53. If that's the case then you will want to try UI.getStringFromUser(message, initialValue) UI.getStringFromUser(message, initialValue) kevgski hi there That's exactly what it was, thanks for letting me know, now I can move on. Last question, I am planning on making a tag system and I was wondering what's the usage for layerID? There isn't a UI way to set this property so I am confused. It looks like it can only be set programmatically. @mathieudutour Is there a way to display a user input dialog that has multiple fields or does getInputFromUser only support one input at the moment? only one input. You can either use a webview or a nib view to create a custom ui. There is an example of a nib view here: and you will probably need
https://sketchplugins.com/d/1230/5
CC-MAIN-2020-05
refinedweb
603
52.46
>> InputMisMatchException in Java how do we handle it? Get your Java dream job! Beginners interview preparation 85 Lectures 6 hours Core Java bootcamp program with Hands on practice 99 Lectures 17 hours From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next(). Whenever you take inputs from the user using a Scanner class. If the inputs passed doesn’t match the method or an InputMisMatchException is thrown. For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs. Example import java.util.Scanner; public class StudentData{ int age; String name; public StudentData(String name, int age){ this.age = age; this.name = name; } public void display() { System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); } public static void main (String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); int age = sc.nextInt(); StudentData obj = new StudentData(name, age); obj.display(); } } Runtime exception Enter your name: Krishna Enter your age: twenty Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at july_set3.StudentData.main(StudentData.java:20) Handling input mismatch exception The only way to handle this exception is to make sure that you enter proper values while passing inputs. It is suggested to specify required values with complete details while reading data from user using scanner class. - Related Questions & Answers - What is EOFException in Java? How do we handle it? - What is loose coupling how do we achieve it using Java? - What is BGP and why do we need it? - How do we handle circular dependency between Python classes? - Why do we forget things? Is it normal? - What is Variable Handle in Java 9? - What is Handle? - Can We handle the RuntimeException in java? - What is Aarti and how do Hindus perform it? - What is Keiretsu and how do companies follow it? - What is the cause of NoSuchElementException and how can we fix it in java? - What is colon cancer and how can we avoid it? - How do we compare String in Java - How do we copy objects in java? - How can we handle authentication popup in Selenium WebDriver using Java?
https://www.tutorialspoint.com/what-is-inputmismatchexception-in-java-how-do-we-handle-it
CC-MAIN-2022-40
refinedweb
456
53.17
I am terribly new at C programming. I have stumbled upon a few answers. Some using the old syntax. The problem is I have to create a program the will read a text file and use the read postfix lines to convert to an infix equation. The text file would be something like this: 6 #this is the number ofcontainters 1 + 3 4 # it's no_operation_if op!=v then read value of nos mention 2 + 5 6 3 v 2.1 4 v 2.4 5 v 3.5 6 v 1.5 The C file will be read in the Ubuntu terminal where the text file is the only input and the output is the infix form. A few suggestion as to how I will accomplish this using struct, arrays, and unions. We were already given a format of creating struct opnode, vnode, and uniting them. The array part I'm clueless how to transfer from reading to the array itself. C is so weird compared to java as of this moment. [EDIT] Sorry I forgot to mention that this is homework... no longer postfix to infix. It's postfix to solve the equation. Without prior knowledge of syntax and used to object oriented programming I don't know how to edit. #include <stdio.h> #include<stdlib.h> #define MAXLENGTH 512 /* Codes by DocM * struct opnode, vnode, union */ struct opnode{ char operator int loperand; int roperand; }; struct vnode { char letterv; double value; }; union { struct opnode op; struct vnode val; } nodes[100]; /*node[2].op.loperand *node[6].val.value */ /* This reads text file string input in terminal * Then commands the text file be read * etc. * and everything else actually */ int main() { char text[MAXLENGTH]; fputs("enter some text: ", stdout); fflush(stdout); int i = 0; int f = 0; if ( fgets(text, sizeof text, stdin) != NULL ) { FILE *fn; fn = fopen(text, "r"); } /* The code below should be the body of the program * Where everything happens. */ fscanf (text, "%d", &i); int node[i]; for(int j = 0; j<i;j++) { int count = 0; char opt[MAXLENGTH]; fscanf(text,"%d %c", &count, &opt); if(opt == -,+,*,) { fscanf(text,"%d %d", &node[j].op.loperand,&node[j].op.roperand); node[j].op,operator = opt; } else { fscanf(text, "%lf", &node[j].val.value); } fscanf(text,"%lf",&f); } evaluate(1); return 0; } /* Code (c) ADizon below * */ double evaluate(int i) { if(nodes[i].op.operator == '+' | '*' | '/' | '-') {); } else { printf nodes[i].val.value; return nodes[i].val.value; } } I guess the basic algorithm should be: I don't understand the part about the "v" operator, maybe you should clarify that part. This seems a bit too much like homework for us to just blindly post code ... You need to show your own attempt first, at least.
https://expressiontree-tutorial.net/knowledge-base/4332412/c-programming-expression-tree-to-postfix-to-solution-using-lines-read-from-a-file
CC-MAIN-2022-40
refinedweb
457
66.64
This article demonstrates how to write SQL Server extended stored procedures using C++. Visual Studio 2003 Enterprise Edition has got a Wizard for creating extended stored procedures, but in this article, I show how easy they are to create without using the wizard. Extended Stored Procedures are DLLs that run within the address space of SQL server. They are accessed like any other stored procedure in SQL Server except that they have to be registered with SQL Server first. Registering an extended stored procedure can be done using the sp_addextendedproc stored procedure. This takes the name of the extended procedure to register and the name of the DLL that hosts it. sp_addextendedproc exec sp_addextendedproc 'xp_example', 'xp_example.dll' To remove an extended stored procedure, use the sp_dropextendedproc procedure passing it the name of the procedure to drop. sp_dropextendedproc exec sp_dropextendedproc 'xp_example' That's all there is to creating the DLL to host an extended stored procedure! You can see that the Wizard doesn't really do much. All extended stored procedures have the same C signature so that SQL Server can execute them correctly. This signature is shown below and is the entry point by which SQL Server calls the procedure. RETCODE __declspec(dllexport) xp_example(SRV_PROC *srvproc) One of the first things to do when writing an extended procedure is to check that the number of parameters passed from the client is correct. The method of doing this is shown below: // Check that there are the correct number of parameters. if ( srv_rpcparams(srvproc) != 1 ) { // If there is not exactly one parameter, send an error to the client. _snprintf(spText, MAXTEXT, "ERROR. You need to pass one parameter."); srv_sendmsg( srvproc, SRV_MSG_INFO, 0,(DBTINYINT)0, (DBTINYINT)0,NULL,0,0,spText,SRV_NULLTERM); // Signal the client that we are finished. srv_senddone(srvproc, SRV_DONE_ERROR, (DBUSMALLINT)0, (DBINT)0); return XP_ERROR; } To check the number of parameters, we call the srv_rpcparams method. In this example, we are expecting one parameter, so if any other number of parameters are passed, we need to flag an error and stop execution of the procedure. srv_rpcparams If the number of parameters is incorrect, the srv_sendmsg method is used to send a text string back to the client. In this simple example, a string is returned with a simple message. srv_sendmsg After sending the message, we need to indicate to the client that the stored procedure has finished executing. This is done using the srv_senddone method. You can see that the second parameter of this function is SRV_DONE_ERROR which indicates that an error is being returned to the client. Finally, we return XP_ERROR from the method. srv_senddone SRV_DONE_ERROR XP_ERROR Now that we know we have the correct number of parameters, we need to get the information about them. This is done using the srv_paraminfo method. srv_paraminfo // Get the info about the parameter. // Note pass NULL for the pbData parameter to get // information rather than the parameter itself. srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, NULL, &bNull); // Create some memory to get the parameter in to. BYTE* Data = new BYTE[uLen]; memset(Data, '\0', uLen); // Get the parameter srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, Data, &bNull); Two calls are made to this method. The first passes NULL as the pbData parameter. This causes the size of the buffer required to hold the parameter to be returned without returning the parameter itself. After the first invocation, a buffer is created and then the method called again. This time the parameter is returned into the variable Data. NULL pbData Data To define columns for the SQL resultset, the srv_describe method is used. This method specifies the type of the column (SRVINT4 and SRVCHAR in this example) together with the length of the column (MAXTEXT for the char column). srv_describe SRVINT4 SRVCHAR MAXTEXT char // Define column 1 _snprintf(colname, MAXCOLNAME, "ID"); srv_describe(srvproc, 1, colname, SRV_NULLTERM, SRVINT4, sizeof(DBSMALLINT), SRVINT2, sizeof(DBSMALLINT), 0); // Define column 2 _snprintf(colname, MAXCOLNAME, "Hello World"); srv_describe(srvproc, 2, colname, SRV_NULLTERM, SRVCHAR, MAXTEXT, SRVCHAR, 0, NULL); Finally, it's time to return rows to the client. This is done using the srv_setcoldata, srv_setcollen and srv_sendrow methods as shown below. srv_setcoldata srv_setcollen srv_sendrow Each column is initialized using the srv_setcoldata. Finally, when all the columns have been defined, the row is sent to the client using the srv_sendrow method. // Generate "numRows" output rows. for ( long i = 1; i <= numRows; i++ ) { // Set the first column to be the count. srv_setcoldata(srvproc, 1, &i); // Set the second column to be a text string int ColLength = _snprintf(spText, MAXTEXT, "Hello from the extended stored procedure. %d", i); srv_setcoldata(srvproc, 2, spText); srv_setcollen(srvproc, 2, ColLength); // Send the row back to the client srv_sendrow(srvproc); } To notify SQL Server that the processing has finished and to return results to the client, we call the srv_senddone method, although this time, we pass the parameter SRV_DONE_MORE|SRV_DONE_COUNT indicating that there has not been an error and that execution is complete. The last parameter specifies the number of rows returned to the client. SRV_DONE_MORE|SRV_DONE_COUNT // Tell the client we're done and return the number of rows returned. srv_senddone(srvproc, SRV_DONE_MORE | SRV_DONE_COUNT, (DBUSMALLINT)0, (DBINT)i); To run the example, compile the example code to create a DLL called xp_example.dll and then copy this DLL into the MSSQL/Binn directory for SQL Server. Log on to SQL Server as sa and register the stored procedure by executing exec sp_addextendedproc 'xp_example', 'xp_example.dll'. sa You can then test the code by executing exec xp_example 5. This will generate results as shown below: exec xp_example 5 This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here double x; srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, NULL, &bNull); BYTE* Data = new BYTE[uLen]; memset(Data, '\0', uLen); srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, Data, &bNull); x = static_cast<double> (*Data); delete []Data; char * atof() // params.cpp // // getparamcount() // // This little routine retrieves the total number of parameters passed in to us. // Always call this before calling getparam, to ensure that we are not trying to // retrieve more parameters than were passsed in. // // Parameters: // SRV_PROC *srvproc Server process pointer // Returns: // int Number of parameters passed in to from SQL Server // int params::getparamcount(SRV_PROC *srvproc) { return (srv_rpcparams(srvproc)); } // getparam() // // This handy little routine retrieves the specified parameter. For some reason, // SQL numbers parameters beginning with 1, not C-standard 0 as we might expect. // // Parameters: // SRV_PROC *srvproc Server process pointer // int paramnum Number of the SQL Server parameter to retrieve // params *p Pointer to a params object // void params::getparam(SRV_PROC *srvproc, int paramnum, params *p) { // Set the success/failure code SRVRETCODE rc = SUCCEED; // Get the parameter length first rc = srv_paraminfo(srvproc, paramnum, &p->type, &p->maxlength, &p->length, NULL, &p->isnull); if (rc == SUCCEED) { // Now we reserve the required space, +1 extra byte for a '\0' string end marker. p->cdata = new BYTE[p->length + 1]; // Now we retrieve the actual parameter value. rc = srv_paraminfo(srvproc, paramnum, &p->type, &p->maxlength, &p->length, p->cdata, &p->isnull); if (rc == SUCCEED) { // We put a '\0' marker at the end, in case it's a string; although we already have // the length, this comes in handy should we want to manipulate the parameter value // as a '\0'-terminated C-string right out the box; by printing it for instance. *(p->cdata + p->length) = 0; // Now we figure out if this is an input or output parameter. } p->isoutput = (srv_paramstatus(srvproc, paramnum) & SRV_PARAMRETURN); } p->success = rc; } // ~params() // // This destructor will release the cdata array of dynamically allocated memory. // params::~params() { // Only if it was assigned. if (this->cdata != NULL) { delete [] this->cdata; } } // params.h class params { public: params() { }; ~params(); static int getparamcount(SRV_PROC *srvproc); static void getparam(SRV_PROC *srvproc, int paramnum, params *p); SRVRETCODE success; ULONG length; ULONG maxlength; BYTE *cdata; BOOL isnull; BOOL isoutput; BYTE type; }; General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/8571/Writing-Extended-Stored-Procedures-in-Cplusplus
CC-MAIN-2017-04
refinedweb
1,366
52.19
0 Hi, i know how to read specific line form a text file but if we want to delete lines by specifying the line number. here is the code, but it's not working: i want to delete line 1 and 2 of the text file. import java.io.*; public class ReadSpecificLine { public static void main(String[] args){ String line = ""; int lineNo; try { FileReader fr = new FileReader("C://Temp/File.txt"); BufferedReader br = new BufferedReader(fr); for(lineNo=1;lineNo<3;lineNo++) { while (lineNo = 1&&2, br.readLine() !=null); } br.readLine(); } } catch (IOException e) { e.printStackTrace(); } System.out.println("Line: " + line); } } Thank you
https://www.daniweb.com/programming/software-development/threads/341888/delete-specific-line-in-file
CC-MAIN-2018-30
refinedweb
103
65.93
Multiple directories in qmlproject file Is it possible to define more than one directory to the image files (or QML files,...) in the qmlproject file? E.g. @ ImageFiles { directory: "../images" directory: "C:/path/to/my/images" directory: "." } @ - favoritas37 you can try using the import command at the beginning of the .qml file to use folders other that the current: @ import "../images" Rectangle{ ... } @ I have got the "images" folder in the same directory as all my qml files. When I try @import "../images"@ , I get the following error: "../images": no such directory when I try @import "./images"@ , I don't get an error, but what should I set as the source of the images? If I just set @source: "MyImage.png"@ , it has the wrong path. And if I set @source: "images/MyImage.png"@ it works, but then I wouldn't need the import anyway. I've got the same problem when I set the directory in the qmlproject file. I still have to set "images/MyImage.png" as the source. Maybe I didn't understand the usage of the directory property. Can you please explain it to me?
https://forum.qt.io/topic/13180/multiple-directories-in-qmlproject-file
CC-MAIN-2018-22
refinedweb
188
70.6
def compute_bill(food): total=0 for food in shopping_list: total += prices[food] return total compute_bill(["apple"]) it says compute_bill(['apple']) returned 7.5 instead of 2 def compute_bill(food): total=0 for food in shopping_list: total += prices[food] return total compute_bill(["apple"]) it says compute_bill(['apple']) returned 7.5 instead of 2 your function is wrong as in food argument you should pass a list of your shopping items, so when you do a for loop on it it should be as: for item in food: so your item is an each element on your shopping list so with that item you fetch prices: total += prices[item] I think now it should work Oh thank you, I got it! It was just a problem with the return part, I put it 4 spaces more........ I can't finish this one either! They say in the problem to subtract one unit for each item purchased but when we run the code, we get a message saying we changed the variable stock. why do you decrease your stock in line: stock[item] -= 1 ?? I do not remember what they asked for exactly but I do not think it was decreasing the stock. They say in point 2: If the item is in stock and after you add the price to the total, subtract one from the item's stock count. So, I have decreased the stock for each item purchased! Edited; Maybe I'm in the wrong thread! I'm trying to complete the "Stock out" problem! Something is really wrong in the site checking code... This is not right... The argument sent to the compute_bill function doesn't have 9 bananas... sorry, my bet, indeed it asks for decreasing stock. I think the problem is that you put a space between variable and its index fe. stock [item], they should be together. here's my code that worked: def compute_bill(food): total = 0 for item in food: if stock[item] > 0: total = total + prices[item] stock[item] += -1 return total Ok, this is ridiculous.... We are not supposed to use the function just yet!!! I commented out the line where I use the function and everything went right!!! Lol, they tell us to make a function and then we are not allowed to use it even for testing purposes??? This is non sense!!! that's the course, you learn by following the path but true sometimes instructions are misleading. I can not do it either!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! If you have a problem, please post this in a new topic with your question + error messages + code How come I am not getting the right total? Here is my error: Oops, try again. compute_bill(['apple']) returned 3 instead of 2 Here is my code shopping_list = ["banana", "orange", "apple", "pear"] stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } def compute_bill(food): total = 0 for food in shopping_list: total =+ prices[food] return total print compute_bill(shopping_list)
https://discuss.codecademy.com/t/making-a-purchase-11-please-help/33899/16
CC-MAIN-2018-09
refinedweb
500
71.95
2012-07-17 Code Reuse and Modularity in Python Note: You may find it easier to complete this lesson if you have already completed the previous lesson in this series. Lesson Goals Computer programs can become long, unwieldy and confusing without special mechanisms for managing complexity. This lesson will show you how to reuse parts of your code by writing Functions and break your programs into Modules, in order to keep everything concise and easier to debug. Being able to remove a single dysfunctional module can save time and effort. Functions You will often find that you want to re-use a particular set of statements, usually because you have a task that you need to do over and over. Programs are mostly composed of routines that are powerful and general-purpose enough to be reused. These are known as functions, and Python has mechanisms that allow you to define new functions. Let’s work through a very simple example of a function. Suppose you want to create a general purpose function for greeting people. Copy the following function definition into Komodo Edit and save it as greet.py. # greet.py def greetEntity (x): print("hello " + x) greetEntity("Everybody") greetEntity("Programming Historian") The line beginning with def is the function declaration. We are going to define (“def”) a function, which in this case we have named “greetEntity”. The (x) is the function’s parameter. You should understand how that works in a moment. The second line contains the code of the function. This could be as many lines as we need, but in this case it is only a single line. Note that indentation is very important in Python. The blank space before the hello Everybody hello Programming Historian This example contains one function: greetEntity. This function is then “called” (sometimes referred to as “invoked”) two times. Calling or invoking a function just means we have told the program to execute the code in that function. Like giving the dog his chicken-flavoured treat (*woof* *woof*). In this case each time we have called the function we have given it a different parameter. Try editing greet.py so that it calls the greetEntity function a third time using your own name as a parameter. Run the program again. You should now be able to figure out what (x) does in the function declaration. Before moving on to the next step, edit greet.py to delete the function calls, leaving only the function declaration. You’re going to learn how to call the function from another program. When you are finished, your greet.py file should look like this: # greet.py def greetEntity (x): print("hello " + x) Modularity When programs are small like the above example, they are typically stored in a single file. When you want to run one of your programs, you can simply send the file to the interpreter. As programs become larger, it makes sense to split them into separate files known as modules. This modularity makes it easier for you to work on sections of your larger programs. By perfecting each section of the program before putting all of the sections together, you not only make it easier to reuse individual modules in other programs, you make it easier to fix problems by being able to pinpoint the source of the error. When you break a program into modules, you are also able to hide the details for how something is done within the module that does it. Other modules don’t need to know how something is accomplished if they are not responsible for doing it. This need-to-know principle is called “encapsulation“. Suppose you were building a car. You could start adding pieces willy nilly, but it would make more sense to start by building and testing one module — perhaps the engine — before moving on to others. The engine, in turn, could be imagined to consist of a number of other, smaller modules like the carburettor and ignition system, and those are comprised of still smaller and more basic modules. The same is true when coding. You try to break a problem into smaller pieces, and solve those first. You already created a module when you wrote the greet.py program. Now you are going to write a second program, using-greet.py which will import code from your module and make use of it. Python has a special import statement that allows one program to gain access to the contents of another program file. This is what you will be using. Copy this code to Komodo Edit and save it as using-greet.py. This file is your program; greet.py is your module. # using-greet.py import greet greet.greetEntity("everybody") greet.greetEntity("programming historian") We have done a few things here. First, we have told Python to import (load) the greet.py module, which we previously created. You will also notice that whereas before we were able to run the function by calling only its name: greetEntity(“everybody”), we now need to include the module’s name followed by a dot (.) in front of the function name. In plain English this means: run the greetEntity function, which you should find in the greet.py module. You can run your using-greet.py program with the “Run Python” command that you created in Komodo Edit. Note that you do not have to run your module…just the program that calls it. If all went well, you should see the following in the Komodo Edit output pane: hello everybody hello programming historian Make sure that you understand the difference between loading a data file (e.g., helloworld.txt) and importing a program file (e.g. greet.py) before moving on. Suggested Readings Note: You are now prepared to move on to the next lesson in this series. Suggested Citation William J. Turkel and Adam Crymble , "Code Reuse and Modularity in Python," Programming Historian, (2012-07-17),
http://programminghistorian.org/lessons/code-reuse-and-modularity
CC-MAIN-2017-26
refinedweb
994
65.83
Show Table of Contents 1.31. gcc 1.31.1. RHSA-2011:0025: Low security and bug fix update Updated gcc packages that fix two security issues and several compiler gcc packages include C, C++, Java, Fortran, Objective C, and Ada 95 GNU compilers, along with related support libraries. The libgcj package provides fastjar, an archive tool for Java Archive (JAR) files. Two directory traversal flaws were found in the way fastjar extracted JAR archive files. If a local, unsuspecting user extracted a specially-crafted JAR file, it could cause fastjar to overwrite arbitrary files writable by the user running fastjar. (CVE-2010-0831, CVE-2010-2322) This update also fixes the following bugs: * The option -print-multi-os-directory in the gcc --help output is not in the gcc(1) man page. This update applies an upstream patch to amend this. ( BZ#529659) * An internal assertion in the compiler tried to check that a C++ static data member is external which resulted in errors. This was because when the compiler optimizes C++ anonymous namespaces the declarations were no longer marked external as everything on anonymous namespaces is local to the current translation. This update corrects the assertion to resolve this issue. ( BZ#503565, BZ#508735, BZ#582682) * Attempting to compile certain .cpp files could have resulted in an internal compiler error. This update resolves this issue. ( BZ#527510) * PrintServiceLookup.lookupPrintServices with an appropriate DocFlavor failed to return a list of printers under gcj. This update includes a backported patch to correct this bug in the printer lookup service. ( BZ#578382) * GCC would not build against xulrunner-devel-1.9.2. This update removes gcjwebplugin from the GCC RPM. ( BZ#596097) * When a SystemTap generated kernel module was compiled, gcc reported an internal compiler error and gets a segmentation fault. This update applies a patch that, instead of crashing, assumes it can point to anything. ( BZ#605803) * There was a performance issue with libstdc++ regarding all objects derived from or using std::streambuf because of lock contention between threads. This patch ensures reload uses the same value from _S_global for the comparison, _M_add_reference () and _M_impl member of the class. ( BZ#635708) All gcc users should upgrade to these updated packages, which contain backported patches to correct these issues.
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/5.6_technical_notes/gcc
CC-MAIN-2021-25
refinedweb
378
55.34
Python Recursion Example | Recursion In Python Programming Tutorial is today’s topic. Recursion is the method of programming or coding the problem, in which the function calls itself one or more times in its body. Usually, it is returning a return value of this function call. If the function definition satisfies the condition of recursion, we call this function a recursive function. Recursion is a process of defining something in terms of itself. A Real-world example would be to place two parallel mirrors facing each other like the movie in inception. Any object in between them would be reflected recursively and you will see infinite reflections of that object. A recursive function is the function defined in terms of itself via self-referential expressions. The recursive function has to fulfill an essential condition to be used in a program: it has to terminate. The recursive function terminates if with every recursive call the solution of the problem is downsized and moves towards the base case. The base case is a case where a problem can be solved without further recursion. The recursion can end up in an infinite loop if the base case is not met in the calls. Factorial of any number is the product of all the integers from 1 to that number. For instance, the factorial of 6 (denoted as 6!) is 12345* = 120. See the following program of Recursion in Python. # app.py def factorial(x): if x == 1: return 1 else: return (x * factorial(x-1)) number = 5 print("The factorial of", number, "is", factorial(number)) See the output. ➜ pyt python3 app.py The factorial of 5 is 120 ➜ pyt In the above example, factorial() is the recursive function as it calls itself. When we call this function with the positive integer, it will recursively call itself by decreasing a number. Each function calls multiples the number with the factorial of number 1 until the number is equal to one. When working with a recursion, we should define the base case for which we already know an answer. In an above example, we are finding the factorial of the integer number, and we already know that a factorial of 1 is 1 so this is our base case. Each successive recursive call to a function should bring it closer to the base case, which is precisely what we are doing in the above example. We use a base case in recursive function so that the function stops calling itself when the base case is reached. Without the base case, the function would keep calling itself indefinitely. To demonstrate this structure, let’s write the recursive function for calculating n!: n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1 n! = n x (n−1)! functions make a code look clean and elegant. The complex task can be broken down into simpler sub-problems using recursion. Sequence generation is more comfortable with a recursion than using the nested iteration. A logic behind recursion is hard to follow through. The recursive calls are expensive (inefficient) as they take up the lot of memory and time. Recursive functions are very hard to debug. Finally, Python Recursion Example | Recursion In Python Programming Tutorial is over. Happy Coding !().
https://morioh.com/p/0c0723d0b3ed
CC-MAIN-2020-40
refinedweb
546
56.55
Pádraig Brady wrote: ... > I'm going to use this "2.6.38" check to only enable FIEMAP_FLAG_SYNC > before Linux kernel 2.6.38. It's always worth avoiding sync if possible. > Proposed patch attached. > I'll submit my 3 outstanding fiemap patches tomorrow. ... > Subject: [PATCH] copy: with fiemap copy, only sync when needed > > * src/extent-scan.h (struct extent_scan): Add the fm_flags member to > pass to the fiemap scan. > * src/extent-scan.c (extent_need_sync): A new function used to > detect Linux kernels before 2.6.38. > (extent_scan_init): Add FIEMAP_FLAG_SYNC when needed. > * tests/cp/sparse-fiemap: Adjust comment. > * NEWS: Mention the change in behavior. > Indirectly suggested by Mike Frysinger > --- > NEWS | 4 ++++ > src/extent-scan.c | 32 +++++++++++++++++++++++++++++++- > src/extent-scan.h | 3 +++ > tests/cp/sparse-fiemap | 4 ++-- > 4 files changed, 40 insertions(+), 3 deletions(-) > > diff --git a/NEWS b/NEWS > index 9c4a16f..d1020cb 100644 > --- a/NEWS > +++ b/NEWS > @@ -31,6 +31,10 @@ GNU coreutils NEWS -*- > outline -*- > bytes from the input, and also can efficiently create a hole in the > output file when --sparse=always is specified. > > + cp now avoids syncing files when possible, when doing a FIEMAP copy. > + The sync in only needed on Linux kernels before 2.6.38. > + [The sync was introduced in coreutils-8.10] Thanks. This looks good. Minor suggestions below: > diff --git a/src/extent-scan.c b/src/extent-scan.c ... > +/* Work around Linux kernel issues on BTRFS and EXT4 before 2.6.38. */ Please add a comment here, e.g., /* FIXME: remove in 2013, or whenever we're pretty confident that the offending, unpatched kernels are no longer in use. */ > +static bool > +extent_need_sync (void) > +{ > + static int need_sync = -1; > + > + if (need_sync == -1) > + { > + struct utsname name; > + need_sync = 0; /* No workaround by default. */ > + > +#ifdef __linux__ > + if (uname (&name) != -1 && strncmp (name.release, "2.6.", 4) == 0) > + { > + unsigned long val; > + if (xstrtoul (name.release + 4, NULL, 0, &val, NULL) == > LONGINT_OK) That 3rd argument is the conversion base. Leaving it as 0 lets us accept octal and hexadecimal. No big risk, obviously, but you can tighten it up by using 10 instead. > + { > + if (val < 38) > + need_sync = 1; > + } > + } > +#endif > + } > + > + return need_sync; > +}
http://lists.gnu.org/archive/html/coreutils/2011-03/msg00055.html
CC-MAIN-2015-32
refinedweb
350
70.5
January-February San Antonio PERMIT 1001 TEXAS SAN ANTONIO PAID US POSTAGE PRST STD - Janel Tucker - 2 years ago - Views: Transcription 1 Lawyer January-February 2015 San Antonio PRST STD US POSTAGE PAID SAN ANTONIO TEXAS PERMIT 1001 2 3 January-February 2015 Features Tax Issues for Household Employers By Katy David Honors & Memories for Judge Polly Jackson Spencer By Amanda Reimherr Buckert Departments Feedback In Memoriam Fourth Court Update: Expressing Gratitude By Justice Patricia O. Alvarez Understanding the Texas Disciplinary Rules of Professional Conduct: Is Your Law Office Vulnerable? By Joseph A. Florio and Michael St. Angelo What is a Public Insurance Adjuster? By Robert W. Loree Federal Court Update By Soledad Valenciano and Melanie Fry On the Cover: Family Law Attorney, Robert F. Estrada - Courtesy photo edited by Kim Palmer. Archives of the San Antonio Lawyer are available on the San Antonio Bar Association wesite, San Antonio Lawyer is an official publication of the San Antonio Bar Association. Send address changes to the Bar Association address at the top of page 4. Views expressed in San Antonio Lawyer are those of the authors and do not necessarily reflect the views of the San Antonio Bar Association. Publication of an advertisement does not imply endorsement of any product or service. Contributions to San Antonio Lawyer are welcome, but the right is reserved to select materials to be published. Please send all correspondence to Copyright 2015 San Antonio Bar Association. All rights reserved. San Antonio Lawyer 3 January-February 2015 4 Lawyer San Antonio The San Antonio Bar Association 100 Dolorosa, San Antonio, Texas Fax: Officers/Directors President Thomas g. Keyser President-Elect James M. Marty Truss Vice President Bobby Barrera Secretary Beth Watkins Treasurer Santos Vargas Immediate Past President Rebecca Simmons Feedback Re: Gayla Corley, Judge Barbara Hanson Nellermoe: From Books to Bar to Bench Nov.-Dec Directors Rosa Cabezas-Gil Tom Crosley Dave Evans Dawn Finlayson Mexican American Bar Association Jaime Vasquez San Antonio Young Lawyers Association Patricia Rouse Vargas Bexar County Women s Bar Association Tiffanie Clausewitz San Antonio Black Lawyers Association Stephanie Boyd Editors Editor in Chief Sara Murray Articles Editor Natalie Wilson Managing Editor Kim Palmer Board of Editors Sara Murray, Chair Steve Fogle Hon. Laura Parker Hon. Richard Price Christine Reinhard San Antonio Bar Foundation Thomas g. Keyser State Bar of Texas Directors Sara E. Dysart Andrew L. Kerr Executive Director Jimmy Allison Departments Editor Leslie Sara Hyman Editor in Chief Emeritus Hon. Barbara Nellermoe Pat H. Autry, Vice-Chair Barbara: Thanks for the article. The author did an outstanding job with a good story. Bravo. Vincent R. Johnson Professor of Law and Director, Institute on Chinese Law & Business St. Mary s University School of Law I was so pleased to see Judge Nellermoe s picture grace the San Antonio Lawyer and enjoyed reading the article. She has had a distinguished career, and all of us are going to miss her sitting on the bench. Her advice to practitioners, incidentally, was right on target. A.J. Hohman, Jr. Your Honor, Well-written and well-deserved recognition of your service and the lasting legacy of the San Antonio Laywer. Kind regards, Fred Biery Ex Officio Thomas g. Keyser Kim Palmer For advertising inquiries, contact: Monarch Media 2300 Chalet Trail, #K4, Kerrville, TX (210) Chellie Thompson Roy Rector Former Lead Detective, Austin Police Department Computer Forensics Unit Reid Wittliff Former Division Chief, Texas Attorney General s Cyber Crimes Unit DIGITAL FORENSICS AND EVIDENCE SERVICES Extensive Experience and Proven Expertise in Digital Investigations (210) Texas Licensed Investigations Company, License #: A15320 Layout by Kim Palmer Managing Editor, San Antonio Bar Association San Antonio Lawyer 4 January-February 2015 5 Harry Ben Adams, III died in August at the age of 70. The San Antonio native attended San Antonio College and received his undergraduate and law degrees from St. Mary s University. In addition to being both a fine transactional attorney and litigator, he served as City Attorney for Universal City and as counsel to the Economic Development Corporation of Hollywood Park and Windcrest. Harry and his bride traveled widely throughout Europe and the Middle East. Jeffery Alan Babcock died in October at the age of 58. Babcock was born in Orlando, Florida. He received his undergraduate degree from Texas Lutheran College and his law degree from St. Mary s University School of Law. He was an Assistant U.S. Attorney with the Justice Department for more than twenty-five years, working last for the U.S. Attorney s Office in Houston. He was a member of Grace Lutheran Church in San Antonio and attended Crosspoint Lutheran Church in Houston. John Edwin Banks, Sr. died in March at the age of 91. Banks was a graduate of Thomas Jefferson High School. Following graduation from the University of Texas, he served in the Army Air Corps in the Pacific during World War II. Following military service, he earned an MBA while working on Wall Street. He obtained his law degree from Southern Methodist University School of Law and served on the editorial board of the Southwest Law Journal. Banks was SABA President from and a Director of the State Bar from He also served both as President and Board member of the San Antonio Area Foundation. Daniel Abraham Bass died in June at the age of 57. Bass studied film at the University of Texas and received his law degree from St. Mary s University School of Law. He was board certified in Civil Trial Law and practiced trial law for thirty-two years. San Antonio Lawyer 5 January-February 2015 Samuel F. Biery died in June at the age of 97. Biery was born in Streetman, Texas. He was a graduate of the Masonic Home and School of Texas. Following service both with U.S. Immigration, Border Patrol, and the Navy, Biery attended St. Mary s School of Law, from which he graduated in He and his brother Charles founded the law firm that became known as Biery, Biery, Myers and Armstrong, P.C. In its various incarnations, the firm served the area for more than fifty years. Biery held several offices with the San Antonio Bar Association and was the 1997 recipient of the Joe Frazier Brown Sr. Award of Excellence for lifetime achievement. James Edwin Bock died in July at the age of 79. Born in Waco and raised in Houston, Bock received his law degree from Southern Methodist University. He practiced trial law for fifty years and for more than half of that time was an Assistant U.S. Attorney, prosecuting criminal cases in the Western District of Texas. 6 Harry Ben Adams III Harry was a rarity in modern law practice a generalist who could do everything well. Harry was both a respected transactional attorney and a fierce courtroom advocate, who appeared in court almost up to the day that he passed. Harry s practice included representation of Red McCombs, who spoke at Harry s funeral, and various McCombs dealerships in a variety of transactions and lawsuits. When not working, Harry enjoyed cooking, fishing, and traveling. His travels took him to Europe, Africa, and the Middle East. Harry s real passion, though, was always the practice of law. He made no apologies about being a workaholic, usually arriving at his office around 4:30 a.m. He was also known as a plain talker and a person who spoke his mind. Clients and opposing counsel knew to expect Harry to pull no punches but to always keep his word. That meant that he was loved by many, disliked by some, but respected by all. Harry was married for fortyeight years to Beverly Adams, who survives him. He also has two adult children a son who lives in San Antonio and a daughter who lives in North Carolina along with numerous grandchildren. Dennis Phillip Bujnoch died in February at the age of 61. Bujnoch was one of nine children born to John and June Bujnoch in Houston. He received his undergraduate degree from the University of Houston and earned his law degree from South Texas College of Law. He was board certified by the National Board of Trial Advocacy and was acknowledged by his peers to be an exceptional trial attorney. Edward Emmanuel DeWees, Jr. died in March at the age of 81. The San Antonio native attended Austin College on a basketball scholarship. He entered military service after college and returned to earn his law degree from the University of Texas in He practiced law for more than fifty years, many of them with the Bexar County District Attorney s office. While in private practice, he concentrated his efforts on family law matters. DeWees was active in his church, First Presbyterian. He was a founding member of the Bachelor s Club of San Antonio and the Christmas Cotillion, a member of the German Club, and past president of the Conopus Club. Pepos Spiro Dounson died in February at the age of 84. Dounson was a 1951 graduate of St. Mary s Law School. The San Antonio native practiced for more than fifty years and had an affinity for things technical. He was an amateur radio operator with the nickname Old Sour Grapes. Robert F. Estrada died in April at the age of 76. Estrada attended Central Catholic High School, St. Mary s University, and St. Mary s University School of Law. He was Board Certified in Family Law and was involved in various bar sections and organizations related to family law matters. He was a member of the Texas Academy of Family Law Specialists and a founding member of the South Texas Collaborative Family Law Group. He was also an avid motorcyclist. Edward P. Fahey died in January just a few days prior to his 91st birthday. The Galveston native served in the military in the South Pacific and moved to San Antonio upon his discharge. He attended St. Edward s University in Austin and completed his education at St. Mary s University School of Law, receiving his law degree in He was a trial lawyer concentrating on insurance defense litigation and was elected to the American College of Trial Lawyers in He retired from the practice in Donald Olda Ferguson died in October at the age of 82. Ferguson was born in Breckenridge, Texas. He attended high school in Refugio and received both a BS degree Samuel F. Biery Sam Biery was one of thousands to become the first in his family to earn a degree through determination, hard work, and the GI Bill. He and brother, Charles, practiced law together for over fifty years, being in the first class of certified specialists (Family Law) in He was a precinct chair in the Democratic Party and active in the San Antonio Bar Association. Along with Charles, he received the Joe Frazier Brown Sr. Award of Excellence in Unbeknownst to his children for forty years, he struggled with panic and anxiety attacks and suicidal ideations from 1947 up to the time of his death. But three things helped defeat the fears and demons which haunted him: psychiatrists, medications, and most importantly, his wife of seventyone years, C.B., who followed him in death a few weeks later. They ran the good race. They fought the good fight and kept their faith in each other. The Honorable Fred Biery, Chief U. S. District Judge San Antonio Lawyer 6 January-February 2015 7 San Antonio Lawyer 7 January-February 2014 8 in pharmacy and a BBA degree in marketing from the University of Texas. Following military service, he got married and began work with Eli Lilly & Co. While at Eli Lilly, he took a leave of absence to attend and graduate from law school at St. Mary s University. He continued his career with Eli Lilly for a while, but ultimately he returned to San Antonio and partnered with James Gardner to form the firm of Gardner and Ferguson in Richard Ricky Hall Fox died in August at the age of 61. He attended Alamo Heights High School and the University of Texas, and received his law degree from St. Mary s University School of Law in He was an assistant criminal District Attorney for nearly twenty years and, later, a partner in the firm of Brock & Kelfer. Mike Hernandez, Jr. died in December at the age of 81. He was born in Weslaco in The family moved to San Antonio in the early 1940s. Hernandez graduated from Fox Technical High School. After high school, he worked in several different jobs and eventually moved to California to work with Beneficial Finance Company. He returned to San Robert F. Estrada When Bob first invited me to ride with his group of friends, he showed up on a gleaming purple Harley Davidson. If there was any piece of chrome made that was not on Bob s bike, it was only because Bob had not yet discovered it. Bob always kept the bike in gleaming, showroom condition, and it was a sight to behold. Eventually, he sold his beloved Harley and bought a beautiful Honda Gold Wing, but he never really bonded with the bike. He always complained that, compared to his Harley, the Honda s exhaust sounded like flatulence. Barry Snell He was a study in contrasts: pragmatic yet generous, mature yet contemporary, personable yet private. Bob cut a suave figure in his suits while in court, but he was just as happy out on his motorcycle in leather, or bicycling in shorts with his legal buddies. He was unquestionably sophisticated, yet he seemed to know every Southside taqueria by heart. A loyal husband, loving father, doting grandfather, and faithful Christian, Bob never truly looked his age but always seemed to possess a wisdom and grace well beyond his years. Elizabeth Jurenovich, Executive Director, Abrazo Adoption Associates Antonio as an area manager for that company. He enrolled at St. Mary s University, from which he received both his undergraduate (Economics) and law degrees. Hernandez joined the bar in His practice included family, criminal, and business matters. He was quite literally on his way to court when he was stricken. Lukin Taylor Gilliland, Sr. died in July at the age of 87. He attended Alamo Heights schools when all of them were located within what is now Cambridge Elementary. He attended the University of Texas, but his studies were interrupted by his enlistment in the Navy during World War II. Following military service, he earned his law degree from the University of Texas and went on to practice for more than sixty years. In addition to his success as an attorney, he excelled in both business and local politics, serving terms as councilman and Mayor of Alamo Heights. He was an informed and successful breeder of horses, both thoroughbred and quarter horses. Donald Joseph Mach died in February at the age of 67. The El Campo native attended St. John s Seminary for several years, but he attended El Campo High School his senior year. He received both his undergraduate and law degrees from St. Mary s University. He practiced law, both civil and criminal, principally in Bexar and Atascosa counties for more than forty years. He was an original member and former president of the Harp and Shamrock Irish Society, and in 1982 he was honored as Irish Man of the Year (despite his German heritage). Frank S. Manitzas died in July at the age of 80. The first-generation American was born in San Angelo to Greek immigrant parents. Following college at the University of Texas, he enlisted in the Army. He later attended law school at the University of Texas and was licensed in He worked as an attorney for the National Labor Relations Board before entering private practice. He was in the first group certified as specialized in Labor Law by the Texas Board of Legal Specialization in He was Chairman of the Labor Law Section of the State Bar from Lucian Leeds Morrison, III died in February at the age of 77. Morrison was a San Antonio native and a graduate of Alamo Heights High School. He attended the University of Texas for both his undergraduate and law degrees. Following military service, he joined his father s law firm ultimately becoming a partner in Morrison, Dittmar, Dahlgren & Kaine and its oil and gas practice. After a few years, Morrison moved on to a career in corporate banking, trust administration, and estate planning in Houston. He founded the Heritage Trust Company which, in 1990, was sold to Northern Trust of Chicago, one of the nation s largest trust institutions. He continued to counsel private trusts and individuals up to the day he died. Tillman Marc Perkins died in November at the age of 60. Perkins was born in Longview. He attended Kilgore College but later transferred to the University of Texas from which he received his undergraduate degree. He received his law degree from St. Mary s University School of Law. Perkins legal career San Antonio Lawyer 8 January-February 2015 9 began in Midland, but he returned to San Antonio to continue his practice after the birth of his first child. He returned to Longview in Carl Pipoly died in September at the age of 66. Originally from Cleveland, Ohio, Pipoly earned both his undergraduate and law degrees from the University of Denver. He began his legal career with Conoco Oil Company, negotiating and drafting joint venture agreements for mineral exploration and production. Beginning in 1988, Pipoly shifted his focus to litigation, primarily civil, where he enjoyed considerable success. He was a member of several trial-oriented organizations and was recognized as an Advocate with the National College of Advocacy. Amid all of this, he also swam the English Channel. Stephen L. Reznicek died in June at the age of 66. Reznicek was born in Omaha, Nebraska. He found himself a prime candidate for the military draft during the Vietnam War and elected to enlist in the Navy rather than be drafted. He chose wisely and found himself stationed in Japan. Following military service, he enrolled in the University of Nebraska, from which he received a BS degree in education. He later obtained an undergraduate degree in political science from Bellevue University in Omaha. In mid-life he returned to the classroom and earned a law degree from St. Mary s University in He practiced for several years with the firm of Garcia, Teneyuca and Reznicek and later worked for Standard Aero in import/export regulatory compliance. Meddie Charles Chuck Sullivan III died in November at the age of 64. Sullivan was a 1969 graduate of Alamo Heights High School. He served in the Army in Vietnam, was wounded and awarded the Purple Heart. He later attended law school at the University of Oklahoma and became licensed to practice in Texas in Sullivan practiced primarily criminal law. Sullivan was an avid motorcyclist and hunter. Ned Morris Wells, Jr. died in September at the age of 68. The San Antonio native attended Alamo Heights High School and earned both undergraduate and master s degrees from Southern Methodist University. He began law school at SMU, but his studies were interrupted by the Vietnam War and his enlistment in the Army. Following military service, Wells returned to legal studies at St. Mary s University School of Law, from which he graduated in He practiced law for forty years. He was a dedicated member of the San Antonio RoadRunners running club and a lifelong philatelist. Frank S. Manitzas Frank grew up in San Angelo the first-generation son of Greek immigrants in a country where all immigrants, legal or otherwise, were generally thought to come only from Mexico. Farmers, ranchers, school teachers, and others were accustomed to Martinez but had difficulty with Manitzas. But this son of Greek immigrants did not become embittered by his experience. Years later, he would still laugh about it. We were trying a case before an administrative law judge of the NLRB. The Board s lawyer called a witness named Frank Martinez. Frank leaned over and whispered to me, Let me cross-examine him. Frank began his cross-examination solemn and stern. Mr. Martinez, has anyone ever called you Frank Manitzas? The witness, obviously unprepared for such a question, looked first at his lawyer and then at the judge, and with a puzzled expression on his face responded, No, sir. Well, Frank replied, my name is Frank Manitzas, and all my life people have called me Frank Martinez. I was just curious if anyone had ever called you Frank Manitzas. I have nothing further, Your Honor. Pass the witness. Not only could Frank laugh about his experiences growing up in San Angelo, but he also drew strength and resolve from them. As he often said, I may be wrong, but I m never in doubt. He was proud to be a lawyer, proud to be a Texan, proud to be an Army veteran, proud to be an American. He could recite the Declaration of Independence from memory. He collected antiques, recited poetry, and loved opera. But above all else, he loved Mary Ellen and his family. Joe Harris AFFIRMED Judgment upheld. TLIE was voted best in Texas. Texas Lawyers Insurance Exchange has been voted best professional liability insurance company in Texas four years in a row by Texas Lawyer magazine. TLIE is also a Preferred Provider of the State Bar of Texas and has returned $32,800,000 to its policyholders. With all of these accolades as well as being in the business for over 35 years, doesn t TLIE make the BEST all around choice for you? / / San Antonio Lawyer 9 January-February 2015 10 Tax Issues for Household Employers By Katy David Following the rush of year-end planning, a respite from tax issues feels well deserved. We have survived the last push to complete time-sensitive tasks by December 31, and the April 15 filing deadline is not yet imminent. Nonetheless, we cannot neglect tax issues entirely. In particular, those of us fortunate enough to have paid help at home must attend to the various reporting deadlines that fall within the first months of And, for those who have been lax about household employee issues in the past, the new year is an opportunity to turn over a new leaf. Do I Really Have an Employee? That is the threshold question, and the answer is: you might. The Internal Revenue Service uses a number of factors to determine whether a person who works in your home is an employee (for whom you have tax withholding and reporting obligations) or an independent contractor (such that these requirements do not apply). In general, a worker is your employee if you control what work is done and how it is done. For purposes of determining whether a person is an employee, it does not matter whether the work is full time or part time or that you hired the worker through an agency. It also does not matter whether you pay the worker on an hourly, daily, or weekly basis, or by the job. More importantly, it does not matter whether you and the worker just agree that the worker is an independent contractor. The legal test controls, regardless of how you and the worker prefer to define your arrangement. Every situation is different, but examples illustrate the difference between an employee and an independent contractor. Example 1: A family hires a worker to clean their house once a week. The worker is scheduled to work on Wednesdays, but from time to time she reschedules to a different day. Sometimes, rather than cleaning the house herself, she unilaterally sends her sister or niece to do the work. She makes her own schedule, with the understanding that she will perform her work during the normal work day. She holds herself out as available for other work, and there is no expectation that she is available exclusively to the family. That is to say, when she is not working for the family, she is cleaning other people s houses. In this situation, I am comfortable that the worker is an independent contractor. Example 2: The same family also has a nanny. The nanny is required to arrive each morning by 8 a.m., and she stays with the children until the first parent arrives home around 6 p.m. She follows specific guidelines about the children s care. She cannot reschedule, and she cannot send another person in her stead. While she might pick up the occasional babysitting job on the side, she does not (and cannot) do other work that conflicts with her taking care of the family s children. On these facts, I would have a hard time arguing that the nanny was not an employee. Before you panic: there is a de minimis rule that prevents people who just have the occasional Saturday-night babysitter from having to deal with taxes and reporting. You have to pay federal unemployment tax (discussed below) only if you pay $1,000 or more in any calendar quarter to household employees. You have to withhold and pay social security and Medicare taxes (discussed below) only if you paid $1,900 or more in 2014 to any one household employee. If your total household worker costs are $60 a month for child care during your monthly date nights ($180 per quarter and $720 per year), you will never trip over these lines. However, if the person who works in your home is an employee and your payments are over the thresholds, you must report certain information to the Internal Revenue Service and Social Security Administration, and you must withhold and pay certain taxes to the government. What Taxes are Required? In Texas, when dealing with household employees, three types of taxes are in play: federal income tax, federal employment taxes, and unemployment taxes. Let s take them in order. Federal income tax is probably what comes to mind most readily. In general, income taxes are withheld from the pay a worker otherwise earned. The employer remits the withheld money to the government, to be applied towards the worker s current-year income tax liability. Unlike most other employers, as a household employer, you are not required to withhold federal income tax. You are allowed to withhold it if your employee asks you to. San Antonio Lawyer 10 January-February 2015 11 If you withhold, the employee s federal income taxes require some bookkeeping on your part, but because they come out of money you already owe your employee, they do not take money out of your pocket. The term federal employment taxes is a catch-all term that applies to three types of tax: social security, Medicare, and unemployment. Social security tax pays for old-age, survivors, and disability benefits for workers and their families. Medicare tax pays for hospital insurance. Together, these taxes are referred to as Federal Insurance Contributions Act ( FICA ) taxes. Both you and your employee may owe FICA taxes. Each person s share is 7.65% (6.2% for social security tax and 1.45% for Medicare tax) of the employee s wages. It is important to understand that your share does not come out of your employee s paycheck. It comes out of your pocket. You can withhold your employee s share from her wages or opt to pay it yourself (in which case, it is additional money out of your pocket). Unemployment taxes are paid at both the federal and state level. They are used to pay unemployment compensation to workers who lose their jobs. Federal unemployment taxes are referred to as Federal Unemployment Tax Act ( FUTA ) taxes. The FUTA tax is 6% of your employee s FUTA wages, up to $7,000. It s not withheld from your employee s wages, so it is on you the employer not the employee. All or a portion of the amounts you pay to the state unemployment fund by April 15 of the following year are credited against your federal liability, resulting in a net federal rate of only 0.6 percent. Do not get dizzy on the fractions. Just understand that you need to pay money to the Texas Workforce Commission by April 15 of the following year, and the money you pay will show up as a credit against FUTA liability on your personal federal return. Deciding How to Handle FICA This is the single trickiest part of the entire process: both personally and arithmetically. As a household employer, you can decide to pay your employee s FICA taxes on her behalf rather than withhold it from her pay. That is to say, in addition to paying your 7.65% employer-share of FICA taxes, you can pay your employee s 7.65% employee-share of FICA taxes, causing yourself rather than your employee to be out of pocket for this amount. Why would you do this? Perhaps you were not alert to the tax regime when you agreed to pay your employee a particular rate and you feel bad giving her a haircut you know she does not expect. Or, you might make the more deliberate decision to bear this tax burden for your employee. If you decide to pay your household employee s FICA taxes on her behalf, the amount you pay on her behalf is included in her wages on the Form W-2 you prepare (and for purposes of any income tax you withhold), but it is not itself subject to FICA or FUTA taxes. As a result, your employee s Form W-2 will show her actual wages as the social security and Medicare wages (used as the base for calculating FICA taxes) but will show her actual wages plus the FICA tax you paid on her behalf as her total wages (used to calculate her income tax liability). How to Report All of This and Pay All the Taxes? You must file a Form W-2 for each employee. You must give each employee her copy of the Form W-2 by January 31 of the following year. You must send a copy of each Form W-2, together with a Form W-3, to the Social Security Administration by February 28 of the following year. However, you do not use your Social Security Number on these forms. Instead, you need to obtain an Employer Identification Number from the Internal Revenue Service, which you can do online. Bottom line: computer systems are unpredictable; don t wait until the last minute. The Forms W-2 and W-3 are information returns. They tell the Internal Revenue Service about the employee s income (so that it can be checked against what the employee reports on her personal income tax return) and tell the Social Security Administration about the employee s Social Security payments (so that those amounts are credited to the employee s eventual Social Security benefits). The taxes (and any of your employee s income tax that you withheld) are reported using Schedule H, Household Employment Taxes, which is attached to your personal income tax return (Form 1040). The total amount on Schedule H flows through to your return and is added to your other income tax liability. If you use tax preparation software, know that Schedule H preparation is included in the Deluxe version of Turbo Tax. State unemployment taxes are reported and paid through the Texas Workforce Commission website. You will need to set up an account, but the process is very user-friendly. A Few Tips I work with the Internal Revenue Service every day and have tremendous respect for the work they do to administer our country s tax laws. Still, the first time I went through this process, I found it very challenging enough to make even the most diligent taxpayer want to throw up her hands. I have a few practical tips that might help you. First, understand that this article is for informational purposes only, to help you understand where the pitfalls are. For more information, consult Internal Revenue Service Publication 926, Household Employer s Tax Guide. If your situation is complicated or you have questions, consult your tax advisor. Second, be aware that you must file Forms W-2 and W-3 by paper, and that the forms cannot be printed off the Internet. You can contact the Internal Revenue Service to have forms mailed to you or if it is getting down to the wire pick up blank forms at the local Internal Revenue Service Taxpayer Assistance Center. Anticipate mistakes and grab multiple copies of the forms. If you use a professional tax return preparer and choose to pay FICA taxes on your employee s behalf, check the preparer s work. Like all of us, even experienced preparers can misunderstand the facts or make errors. Understand that the various taxes accrue during the year but are payable in the next year, together with your own income tax liability. To avoid coming up short, have a plan for where that cash is going to come from. One option is to estimate the liability as it accrues and tuck that amount of money away in a savings account or other place you will not casually access, so that it is there when you need it. Another (and perhaps more fool-proof) option is to provide your employer with a new Form W-4 to increase the amount withheld from your own paycheck. (Form W-4 was in the stack of paperwork you filled out when you started your job. It is the form that tells your employer how much income tax to withhold from each of your paychecks. You can adjust your withholdings by giving your employer a new one at any time.) The money will be sent to the Internal Revenue Service as it is withheld during the year. It will be reflected on your own Form W-2 and - continued on page 22 - San Antonio Lawyer 11 January-February 2015 12 Honors & Memories for Judge Polly Jackson Spencer By Amanda Reimherr Buckert ecently, Judge Polly Jackson RSpencer retired as the Judge of Bexar County Probate Court No. 1 a seat she held for twentyfour years. That court is so closely identified with Judge Spencer that it is affectionately referred to as Polly s Court. Judge Spencer has heard many complex probate cases during her tenure, but it is the personal interactions involving guardianship that she has treasured the most. Members of the San Antonio Bar are familiar not only with Judge Spencer s legal acumen, but also with her personal connection to the Probate Court, particularly guardianship actions. She is the guardian of her oldest daughter, Carrie, who became disabled after complications from a brain tumor she developed as a toddler. Judge Spencer and her husband George have three younger children, as well. At the October luncheon meeting of the San Antonio Bar Association s Elder Law Section, Judge Spencer was honored for her years on the bench with a touching and remarkable tribute that had the entire room wiping tears from their eyes. The stunning personal connection of the honor given to Judge Spencer left her choked with emotion as she recounted to a riveted room what that day recognizing her service on the bench meant to her. At this luncheon held on October 24, 2014, at the Frost Bank Plaza Club, outgoing Elder Law Section Chair Ben Wallis, III presented Judge Spencer with the Barbara F. Kishpaugh Elder Advocate Award, an award given to a person or entity who has rendered outstanding service to elders. The award is named for Colonel Kishpaugh, who was a nurse in the Army for thirty years and was later appointed by the Bexar County Probate Courts to serve as a volunteer guardian, court visitor, or guardian ad litem. She Judge Polly Jackson Spencer with the yellow roses and the Elder Law Section officers died in 2002 at the age of 79 and was posthumously awarded the first Elder Law Advocate Award in The award has carried her name with it ever since. Colonel Kishpaugh was a close personal friend of Judge Spencer and the honor of receiving this award touched the Judge very much. However, Wallis told the luncheon attendees that it just was not quite enough, and that he wanted to add a personal touch to the award by presenting her with a gift, just for Polly. The special gift that Wallis settled on was a beautiful glass vase created by the Garcia Art Glass Company filled with twenty-four yellow roses one for each of her years on the bench. This was presented by Judge Spencer s staff attorney, Karen Hogan, who has worked with her for twenty-one years and is also a member and past president of the Elder Law Section. Instantly, Judge Spencer was overcome with emotion and could no longer contain her tears. Judge Spencer slowly approached the podium to receive her award, clutching a tissue to her chest. After a few moments she said, There is no way to explain what this means to me. George and I remodeled our home and put a round table under a chandelier in our entry, that after much discussion we had decided would be a good spot for a piece from Garcia Art Glass. But since it involved spending money, George hadn t quite gotten to it yet. This is perfect. How did you know? Except nobody did know. It was a lucky coincidence, and the Elder Law Section members were quite surprised. In a moment of kismet, Judge Spencer added that she could not believe that there were yellow roses in her lovely new vase. Today, six years ago, and at exactly this time of day that I stand here, my mother passed away. Yellow roses were her absolute favorite flower. The entire room gasped and fell silent. Then most everyone cried. Judge Spencer said this connection to her mother and plans with her husband were an example of how much her retirement was really going to mean to her family. She recalled that her calling had often required her to sacrifice family time, and she worried about the toll her San Antonio Lawyer 12 January-February November-December 13 job took on her family, particularly her children. However, she knew that she could make a real difference in the lives of the residents of Bexar County, who were facing incredible struggles with which she was intimately familiar. Now as adults, her children have reassured her that those sacrifices were worth it, while simultaneously celebrating the chance to spend more time with her after retirement. Judge Spencer hopes that people will remember her and think that she listened and was fair. I also hope they think I usually got it right on the law, she said with a little laugh. Also, most people when they walk into a courtroom just want to feel like they have been heard and are usually okay with the outcome as long as they really feel they have been heard and that their case mattered. I think every case I have ever had before me mattered. Now what matters to her most is spending time with her beloved family. She said she had recently wandered the halls of her lovely home and wondered what it will be like to actually live there. Soon, she will be spend plenty of time living inside the walls of that lovely home with her family and remember her courtroom, Polly s Court, and her courthouse friends every time she looks at that beautiful vase sitting in her entry hall under the chandelier. She added that, sometimes, she will even fill it with yellow roses. Amanda Reimherr Buckert is a former newspaper reporter and the current Director of the Community Justice Program, which she has been with since Expressing Gratitude By Justice Patricia O. Alvarez Gratitude is not only the greatest of virtues, but the parent of all others. Marcus Tullius Cicero 1 This is not a legal article. This is an article about gratitude. As you develop your New Year s resolutions, consider the virtue of gratitude. What is gratitude? The word comes from the Latin word gratus, which means grace, graciousness, or gratefulness. 2 Gratitude is defined as the quality of being thankful; readiness to show appreciation for and to return kindness. 3 It is the most exquisite form of courtesy. 4 It is an art of painting an adversity into a lovely picture. 5 No one who achieves success does so without acknowledging the help of others. The wise and confident acknowledge this help with gratitude. 6 Like you, I am grateful every day for my family s unconditional love, for my faith, for my friends and colleagues. I am grateful for the opportunities people have given me. But I have not done a good job of expressing my gratitude to those who mean so much to me; after all, [s]ilent gratitude isn t much use to anyone. 7 In this short article, I address three points: (1) why gratitude is important; (2) how to express gratitude; and (3) what you can do in 2015 to show your gratitude. Benefits of Gratitude Many studies demonstrate the benefits of expressing gratitude. 8 They describe two important benefits of expressing gratitude: to feel good personally, and to make others feel good. Feeling Good I feel a very unusual sensation if it is not indigestion, I think it must be gratitude. Benjamin Disraeli 9 Expressing gratitude simply makes you feel better. This is why grateful people have higher levels of positive emotions. 10 They are happy with themselves and their environment. They are also healthier. [O]ver time gratitude leads to lower stress and depression and higher levels of social support... [and] is uniquely important to well-being and social life. 11 More importantly in our profession, feeling grateful makes people less likely to turn aggressive when provoked. 12 Gratitude is one of the sweet shortcuts to finding peace of mind and happiness inside. No matter what is going on outside of us, there s always something we could be grateful for. Barry Neil Kaufman 13 Gratitude not only makes you healthier, but it also improves your career, makes you more effective in managing people and your docket, opens network opportunities, and increases your productivity. 14 Simultaneously, gratitude blocks negative emotions because you cannot feel envious and grateful at the same time. They are incompatible feelings. 15 Making Others Feel Good More than other emotions, gratitude is the emotion of friendship.... It is part of a psychological system that causes people to raise their estimates of how much value they hold in the eyes Fourth Court Update San Antonio Lawyer 13 January-February 2015 14 of another person. Gratitude is what happens when someone does something that causes you to realize that you matter more to that person than you thought you did. 16 An expression of gratefulness sends a strong message that you value the other person. In the context of one s work environment, a supervisor s expression of gratitude in the form of thank you can increase an employee s social worth and self-efficacy behavior. Other employees will become more trusting of each other and more willing to help each other out. 17 If a thank you can have this effect, what will positive feedback or acknowledging an achievement do for your law firm? How Should We Express Gratitude? Feeling gratitude and not expressing it is like wrapping a present and not giving it. William Arthur Ward 18 Expressing Gratitude to Others The first thing that comes to mind is simply saying thank you to those who do something for you. That is certainly a start. But ask yourself whether your thank you is an automatic courteous response or really expresses your appreciation for something. We often take for granted the very things that most deserve our gratitude. 19 It does not have to be that way. Sharing with your spouse or your children your blessings for having them in your life, for their patience while you work late, or for any other matter expresses more than a thank you it expresses gratitude. Recognizing a co-worker s meaningful contribution to your final product takes thank you a step farther. Telling someone how fortunate you are to have him or her as a friend shows that person you do not take the relationship for granted. Expressing your admiration for someone s skills or talents, smiling, writing a letter, picking up the phone to simply say hello, or just showing an interest in others lives are all ways to express gratitude. Those who receive your heartfelt expressions of gratitude will feel good, appreciated, and worthy. Expressing Gratitude for What You Have He is a wise man who does not grieve for the things which he has not, but rejoices for those which he has. Epictetus 20 Epictetus s adage focuses on the things we have. Complaining about what we don t have stimulates negativism such as anxiety, dissatisfaction, stress, or envy. On the other hand, being grateful for what we do have allows us to focus on the present (versus speculate on the future) and helps maintain harmony and balance in our 21 Practicing Gratitude As we express our gratitude, we must never forget that the highest appreciation is not to utter words, but to live by them. John F. Kennedy 22 What did President Kennedy mean? He reminded us that expressing gratitude is good, but we can do better. He invited us to incorporate gratitude into every aspect of our lives to develop the virtue of gratitude by our actions. This year, I invite you to join me in developing the personal virtue of gratitude. How do we begin? In his book Thanks! How Practicing Gratitude Can Make You Happier, 23 Dr. Robert Emmons recommends starting a journal and listing five things each week for which we feel grateful. The list may include a friend s generosity; a kind word from your supervisor, employee, or opposing counsel; a kiss from your parent or spouse; or your child s smile. The purpose of the journal is to remind yourself of the gifts, grace, benefits, and good things you enjoy. 24 I suggest that next to each item in your journal, you write two things you will do to show your gratitude. During the week, perform at least one act of gratitude. For example, if you are grateful for your law degree, make a donation to your law school. If you are grateful to your paralegal for her work in your last trial, buy her a card or give her a candy bar. If you are grateful to your child s teacher, tell her why you are grateful and offer to help with the next school event. Another way of showing gratitude is through deeds. A kind deed to a homeless person or a smile to your waiter shows you are grateful for having a roof over your head or access to food. Paying for a military member s meal at a restaurant shows you are grateful for that person s service and sacrifice (I witnessed an attorney taking this action, and my admiration for her grew instantaneously). Helping a neighbor mow the lawn shows gratitude for your physical body. Volunteering for the Community Justice Program shows your appreciation for having work! We can do so many deeds if we are grateful! The gratitude principles work. I applied them in my law practice, with opposing counsel, at our court, and with my friends and family. I am still working on expressing gratitude to those who mean so much to me. My life, however, is already richer because of my commitment to developing the virtue of gratitude! It takes so little to show you are grateful, and the result is immense. Develop the expression of gratitude and make it a happy 2015! The roots of all goodness lie in the soil of appreciation for goodness. Dalai Lama 25 e ENDNOTES 1 See generally Cicero, Wikipedia, en.wikipedia.org/wiki/cicero (last visited Nov. 17, 2014) (Roman, lawyer, writer, scholar, orator, and statesman, BC). 2 See Gratitude, Dictionary.com, dictionary.reference.com/browse/gratitude (last visited Nov. 17, 2014); Gratitude, Merriam-Webster.com, (last visited Nov. 17, 2014). 3 Gratitude, Oxford Dictionaries (English), definition/american_english/gratitude (last visited Nov. 17, 2014). San Antonio Lawyer 14 January-February 2015 15 4 See generally Jacques Maritain, Wikipedia, topic/ / Jacques-Maritain (last visited Nov. 17, 2014) (French philosopher, ). 5 Attributed to Kak Sri, an unknown person. 6 See generally Alfred North Whitehead, Wikipedia, Alfred_North_Whitehead (last visited Nov. 17, 2014) (English mathematician and philosopher; ). 7 See generally Getrude Stein, Wikipedia, Stein (last visited Nov. 17, 2014) (American author ). 8 E.g., Robert A. Emmons & Michael E. Mc- Cullough, Counting Blessings Versus Burdens: An Experimental Investigation of Gratitude and Subjective Well-Being in Daily Life, 84 J. of Personality & Soc. Psychol. 377 (Feb. 2003) available at edu/ faculty/mccullough/gratitude/emmons_mccullough_2003_jpsp.pdf; Adam M. Grant & Francesca Gino, A Little Thanks Goes a Long Way: Explaining Why Gratitude Expressions Motivate Prosocial Behavior, 98 J. of Personality & Soc. Psychol. 946 (June 2010), available at com/pdfs/grant_gino_jpsp_2010.pdf; Nathaniel M. Lambert & Frank D. Fincham, Expressing Gratitude to a Partner Leads to More Relationship Maintenance Behavior, 11 Emotion 52 (Feb. 2011); Randy A. Sansone & Lori A. Sansone, Gratitude and Well Being: The Benefits of Appreciation, 7 Psychiatry 18 (Nov. 2010), available at nlm.nih.gov/pmc/articles/pmc /; Martin E.P. Seligman et al., Positive Psychology Progress: Empirical Validation of Interventions, 60 Am. Psychol. 410 (July Aug. 2005), available at net/wp-content/files/papers/pospsy Progress.pdf; see also In Praise of Gratitude, Harvard Health Publ ns, Harvard Medical School, newsletters/harvard_mental_health_letter/2011/ november/in-praise-of-gratitude (last visited Nov. 17, 2014). 9 See generally Benjamin Disraeli, Wikipedia, (last visited Nov. 17, 2014) (British Prime Minister and writer; ). 10 Alex M. Wood et al., The Role of Gratitude in the Development of Social Support, Stress, and Depression: Two Longitudinal Studies, 42 J. of Res. in Personality 854, (2007). 11 Id. at John Tierney, A Serving of Gratitude May Save the Day, New York Times (Nov. 21, 2011), com/2011/11/22/science/a-serving-ofgratitude-brings-healthy-dividends.html?_ r=1& (last visited Nov. 17, 2014). 13 See generally Son-Rise, Wikipedia, en.wikipedia.org/wiki/son-rise (describing the home-based program for children with autism spectrum disorders... developed by Barry Neil Kaufman and Samahria Lyte Kaufman for their autistic son ); Meet the Founders of the Option Institute, The Option Institute, custom:founders,single,761 (last visited Nov ) (describing the Kaufmans). 14 Robert A. Emmons, Why Gratitude is Good, item/why_gratitude_is_good (last visited Nov. 17, 2014); Amit Amin, The 31 Benefits of Gratitude You Didn t know About: How Gratitude Can Change Your Life, Happier Human, (last visited Nov. 17, 2014). 15 Robert A. Emmons, Why Gratitude is Good, why_gratitude_is_good (last visited Nov. 17, 2014). 16 John Tierney, A Serving of Gratitude May Save the Day, New York Times (Nov. 21, 2011), com/2011/11/22/science/a-serving-ofgratitude-brings-healthy-dividends. html?_r=1& (last visited Nov. 17, 2014) (quoting Dr. Michael E. McCullough, University of Miami). 17 Adam M. Grant & Francesca Gino, A Little Thanks Goes a Long Way: Explaining Why Gratitude Expressions Motivate Prosocial Behavior, 98 J. of Personality & Soc. Psychol. 946 (June 2010), available at gino_jpsp_2010.pdf. 18 See generally William Arthur Ward, Wikipedia, William Arthur Ward (last visited Nov. 17, 2014) (often quoted author of inspirational maxims). 19 See generally Cynthia Ozick, Wikipedia, Ozick (last visited Nov. 17, 2014) (American writer, novelist, essayist; born 1928). 20 See generally Epictetus, Wikipedia, (last visited Nov. 17, 2014) (Greek Stoic philosopher, AD). 21 See generally Gautama Buddha, Wikipedia, (last visited Nov. 17, 2014) (founder of Buddhism). 22 John F. Kennedy, Proclamation No. 3560, 77 Stat (1963), available at UTE-77/pdf/STATUTE-77-Pg1030.pdf. 23 Robert A. Emmons, Thanks! How Practicing Gratitude Can Make You Happier (2007). 24 Robert A. Emmons, 10 Ways to Become More Grateful, edu/ article/item/ten_ways_to_become_ more_grateful1/ (last visited Nov. 17, 2014). 25 See generally Dalai Lama, Wikipedia, (last visited Nov. 17, 2014) (head monk of Gelug school of Tibetan Buddhism). Fourth Court Update Justice Patricia O. Alvarez is an associate justice on the Fourth Court of Appeals and is Board Certified in Personal Injury Trial Law. Before joining the Fourth Court, Justice Alvarez was a defense attorney for twenty-five years. San Antonio Lawyer 15 January-February 2015 16 Understanding the Texas Disciplinary Rules of Professional Conduct: Is Your Law Office Vulnerable? By Joseph A. Florio and Michael St. Angelo In more than thirty years as a practicing attorney, many of which were with the United States government, I have seen lawyers, good lawyers, penalized for violating the Texas Disciplinary Rules of Professional Conduct ( Disciplinary Rules ). Most of these violations occurred not because the lawyer did not know the rules, but because they were subject to an interpretation of a sub-set of a rule that did not seem important... until it was. Not all disciplinary sanctions are career-killers, but all are stressful and embarrassing. Available sanctions range from private reprimand to disbarment and carry various levels of censure and restrictions on a lawyer s ability to practice. Private Reprimand A private reprimand is available only if the case is tried before an evidentiary panel of the grievance committee, as opposed to a civil action in the district court. This is a case that is tried with the lawyer as the defendant. While the trial is not before a court, it still requires a great deal of preparation. A private reprimand is the lowest level of discipline that can be given. Although the disciplinary action is not publicized, and the lawyer can continue practicing law, this sanction remains a part of the lawyer s disciplinary history and may be considered in any subsequent disciplinary proceeding. A private reprimand is not available to everyone, though. There are at least six reasons why this type of reprimand cannot be available. If a lawyer falls into one of these six categories, he or she will receive a more stringent penalty. A private reprimand is not available if: (1) a private reprimand has been imposed upon the respondent lawyer within the preceding five-year period for a violation of the same disciplinary rule; (2) the respondent lawyer has previously received two or more private reprimands, whether or not for violations of the same disciplinary rule, within the preceding ten years; (3) the misconduct includes theft; misapplication of fiduciary property; or the failure to return, after demand, a clearly unearned fee; (4) the misconduct has resulted in a substantial injury to the client, the public, the legal system, or the profession; (5) there is a likelihood of future misconduct by the respondent lawyer; or (6) the misconduct was an intentional violation of the ethics rules. Public Reprimand As its name implies, this type of discipline is public, and the reprimand is published together with the name of the respondent lawyer. As with a private reprimand, the respondent lawyer can continue to practice law without interruption. A public reprimand is not available and the respondent lawyer will receive a higher-level penalty if: (1) a public reprimand has been imposed upon the respondent lawyer within the preceding five-year period for a violation of the same disciplinary rule; or (2) the respondent lawyer has previously received two or more public reprimands, whether or not for violations of the same disciplinary rule, within the preceding five-year period. San Antonio Lawyer 16 January-February 2015 17 all other requirements for eligibility, such as payment of bar dues and compliance with continuing legal education, are current. Fully Probated Suspension This type of discipline is public and is for a term certain. The suspension, however, is probated, which means that the respondent lawyer may practice law during the period of suspension, but he or she must comply with the specific terms of probation throughout the probated suspension period. Terms of probation typically require that the respondent lawyer: (1) refrain from engaging in further misconduct; (2) not violate any state or federal criminal statutes; (3) keep the State Bar notified of current mailing, residential, and business addresses; (4) comply with continuing legal education requirements; (5) comply with the rules for maintaining trust accounts; and (6) respond to any requests by the Chief Disciplinary Counsel for information in connection with an investigation of allegations of misconduct. Depending upon the facts of a particular case, probation terms may also include: (1) additional continuing legal education; (2) a psychological evaluation; (3) substance abuse counseling; (4) practice of law under the supervision of a designated monitor; or (5) payment of restitution and attorney s fees by a certain date. A fully probated suspension is not available, and the respondent lawyer will receive a higher-level reprimand if: (1) a public reprimand or fully probated suspension has been imposed upon the respondent lawyer within the preceding five-year period for a violation of the same disciplinary rule; (2) the respondent lawyer has previously received two or more fully probated suspensions, whether or not for violations of the same disciplinary rule, within the preceding five-year period; (3) thirty days of active suspension. Partially Probated Suspension This type of discipline is a combination of an active suspension followed by a period of probated suspension and is public. Disbarment This is the most severe discipline and results, and serves the ends of justice. If such an application is granted, the disbarred lawyer is not automatically granted a law license. The disbarred lawyer must still pass the Bar Exam administered by the Texas Board of Law Examiners. Measuring and Improving Performance under the Disciplinary Rules All lawyers know that the Disciplinary Rules are for their benefit and that they are bound by those rules, but these questions remain: How do you keep the rules at the forefront of your law office? How do you make sure that everyone in the office knows how to comply? Compliance with the Disciplinary Rules requires frequent self-assessment, but how do you self-assess to a set of rules, and how do you determine where in your organization you are vulnerable? Your greatest asset is the intellectual capital represented by your employee base. If you could objectively assess that base, you would gain greater insight into, and understanding of, the Disciplinary Rules. The assessment would reveal strategic issues that affect law office performance, and it would give managers and supervising attorneys excellent insight into their vulnerabilities. This, in turn, would allow prompt identification and correction of misunderstandings of the Disciplinary Rules before an attorney is subjected to discipline. Assessment would allow you to detect problem areas in a meaningful way and identify specific areas where you or people in your office might not understand the rules. You would be able to identify the gaps between knowing that something is wrong and knowing why it is wrong. In short, you would be able to uncover business risks that could be fatal to someone s legal career or your business. So, how do you assess a law office to make sure that everyone that needs to know the Disciplinary Rules really understands them? How do you ensure that you know if there is a gap in understanding in the firm and where that gap exists? How do you know that the people you are assessing in your office are telling the truth about their knowledge of the rules? We have served as advisors to NeuraMetrics Inc. during the process of building an assessment product to accomplish these tasks and have vetted their work. NeuraMetrics Inc. is a company that specializes in business process improvement and has worked to create a formal, law-firm-wide, comprehensive, rigorous assessment of your employees knowledge of the Disciplinary Rules. This new tool uses web-based technology and an actual set of the Texas Disciplinary Rules of Professional Conduct to measure current understanding of those rules. Supervisors and managers can use the data to evaluate performance against the rules and to determine improvement potential. A comprehensive set of queries is administered over the web to the necessary employee base at all levels. Each survey is set up to be anonymous, with the understanding that confidentiality will bring about an honest and accurate assessment. The tool can be used by a firm of any size and applies to all practice areas. All of the scores in the assessment demonstrate how close the scored entities (entire firm, departments, functions, etc.) are to the standard which you have set. This tool will offer your law office - continued on page 22 - San Antonio Lawyer 17 January-February 2015 18 What is a Public Insurance Adjuster? By Robert W. Loree One of your clients or a prospective client telephones you and says that he or she needs your legal services. The client tells you that he has an insurance claim for damage to his property for one of the usual culprits fire, hail, windstorm, or water. He also tells you that the insurer is accepting coverage on the claim, but the insurer s adjuster is stringing the claim out and appears to be low-balling the cost of repairs. Your client has not obtained any estimates of his own for the cost of repairs and asks for your help with the adjustment of the claim. What should you do? As an attorney, your first inclination may be to reach a fee agreement with the client and assist him with the adjustment of the insurance claim. There are some pitfalls, however, that may not be readily apparent. First, there is the issue of payment. Your client may not be able to afford retaining counsel on an hourly basis, and taking a onethird or forty percent contingent fee interest would leave the client without the necessary funds to repair his or her property damage because insurers typically do not agree to pay any attorney s fees, even if an insured is represented by counsel during the claims adjusting process. 1 Second, when an attorney gets involved in the adjustment of an insurance claim, that attorney can easily become a fact witness on the claim by performing investigatory or adjuster type duties. When this happens, it abrogates the attorney-client privilege and can disqualify the attorney from participating in any future litigation. 2 Third, during the adjustment of the claim, the insured always needs to obtain his own estimate for the cost to repair the subject damage. It cannot be just any sort of estimate. It needs to be a Xactimate estimate, which is the industry standard for the adjustment of insurance claims. 3 Since attorneys do not prepare estimates or even know how to do so, then the attorney needs to incur additional costs with an expert to obtain that estimate. There is a very good alternative for the client that avoids all these potential problems with an attorney getting involved in the adjustment of an insurance claim. 4 That alternative is to recommend that your client retain a public insurance adjuster to assist him with the adjustment of the claim. Most clients, however, have never heard about public insurance adjusters and invariably ask: What is a public insurance adjuster? In Texas and many other states, a public insurance adjuster is a state licensed and bonded adjuster who represents only the insured concerning the adjustment and resolution of a first-party insurance claim for damage to real or personal property. Public adjusters can also represent an insured for any loss of income involved in a first-party insurance claim, often referred to as a business interruption claim. Since public adjusters represent only the insured, they even the playing field through their interaction with the insurer s adjuster in the investigation, documentation, presentation, negotiation, and settlement of the insured s claim. The insured has its own adjuster to properly work up and estimate the damage for the proper repair of his property and does not have to rely upon the insurer s adjuster for a fair evaluation. When necessary, the public adjuster will retain consultants, like roofing consultants or engineers, to determine causation-type issues or other related matters involved in the claim. Many times the public adjuster will advance these costs as part of his contract with the insured. In Texas, public adjusters are extensively regulated by the San Antonio Lawyer 18 January-February 2015 19 Texas Department of Insurance and under Chapter 4102 of the Texas Insurance Code. Section of the Texas Insurance Code requires that a public adjuster have a written contract with the insured to represent him in his insurance claim. The public adjuster s contract form must be approved by the Texas Department of Insurance and must contain a provision allowing the insured to rescind the contract by written notice within 72 hours of signature and a notice in 12-point type stating WE REPRESENT THE INSURED ONLY. Under Section of the Texas Insurance Code, a public adjuster can charge the insured for his services by an hourly rate, a flat fee, or a percentage of the total amount the insurer pays on the claim, not to exceed ten percent of the amount of the insurance settlement. Most public adjusters charge the ten percent contingent fee. The statute also prohibits a public adjuster from handling a third-party personal injury claim. Public adjusters are insurance professionals familiar with the coverages provided in property insurance policies. They are much more knowledgeable than the insured, and even most counsel, about what is covered under a property insurance policy and how to posture the claim to obtain full policy benefits. They provide the insurer with written notice of the insured s loss, which starts the clock and applicable time periods for the prompt payment of claims statute in Chapter 542 of the Texas Insurance Code and its 18% penalty if the claim is not timely paid. Public adjusters usually have estimating or construction backgrounds and are well versed in preparing estimates for property damage, including Xactimate estimates. Many of them have certifications in estimating and various construction related matters. Armed with this knowledge, public adjusters can identify the available coverages under the policy for the insured, determine causation for the loss, estimate the cost to properly repair the covered damage for the insured, and attempt to obtain a fair resolution of the insured s claim with the adjuster for the insurance company. They provide the insured with a prompt, efficient, and cost-effective service for the resolution of his insurance claim. In the event the insurer and its adjuster deny portions of the claim or low-ball the cost of repairs despite the public adjuster s efforts, the public adjuster usually refers the insured to counsel for litigation and provides counsel with his file. This file, which normally contains the subject insurance policy, the cost of repair estimates, any consultant s reports, the correspondence and s during the adjustment of the claim, and any other pertinent documents on the claim, provides counsel with the factual bases to move forward. Typically, this information is all that counsel needs to send the statutorily required notice letters under the Texas Insurance Code and the Texas Deceptive Trade Practices Act and to file suit after the sixty-day notice period. In addition, the public adjuster works with counsel during the litigation since he is both a fact and expert witness for the insured. As an expert witness, the public adjuster can testify to the reasonable and necessary cost of repairs and causation and can also comment on the insurer s claims handling since he is a licensed insurance adjuster. Currently, the Texas Department of Insurance has licensed 734 public adjusters to practice in the state. Checking with the Texas Department of Insurance website, and other Internet sources such as the Texas Association of Public Insurance Adjusters, com, should reveal the public adjusters practicing in your area. They can greatly assist your clients with the adjustment of their insurance claims, and in the event of a dispute, provide counsel with a claim ready for litigation. (Endnotes) 1 The only legal claim that may be available at this time is one under Chapter 542 of the Texas Insurance Code for the 18% per annum interest as damages for failing to timely adjust and pay the claim under the statute s various deadlines. Chapter 542 also provides for the recovery of reasonable attorney s fees, but insurers rarely pay any such 18% interest or attorney s fees without litigation. 2 See In re Tex. Farmers Ins. Exch., 990 S.W.2d 337, 341 (Tex. App. Texarkana 1999, pet. denied) (holding that if counsel acts as an investigator or an adjuster and not as an attorney, then the attorney-client privilege does not apply); Tex. Disciplinary R. Prof l Conduct 3.08 (Lawyer as a witness). 3 Xactimate is a computer program designed for estimating insurance claims, and it includes localized pricing for all the items in the scope of repairs, plus sales tax, general conditions, overhead and profit, and other factors affecting the repair job. 4 These problems are not present if the insurer has denied the claim, at which time the client or prospective client needs to consult with counsel about whether the denial was proper and what coverage issues are involved. Robert W. Loree is the senior and managing partner of the San Antonio law firm, Loree & Lipscomb. He has a general civil litigation practice and specializes in first-party insurance claims for insureds on a contingent fee basis. Mr. Loree has been practicing thirty-six years, is licensed in Texas and Colorado, and is board certified in Civil Trial Law by the Texas Board of Legal Specialization since San Antonio Lawyer 19 January-February 2015 20 Federal Court Update By Soledad Valenciano and Melanie Fry Summaries of significant decisions rendered by San Antonio federal judges from 1998 to the present are available for keyword searching at Court Web found at courtweb.pamd.uscourts.gov/ courtweb. Full text images of most of these orders can also be accessed through Court Web. If you are aware of a Western District of Texas order that you believe would be of interest to the local bar and should be summarized in this column, please contact Soledad Valenciano or Melanie Fry by phone at or or by at com or with the style and cause number of the case, and the entry date and docket number of the order. Motion to Dismiss; Private Cause of Action; 38 U.S.C Bouldin v. Wells Fargo, N.A., SA-14- CV-722-XR (Rodriguez, Oct. 16, 2014); Campbell v. Wells Fargo, N.A., SA-14- CV-723-XR (Rodriguez, Oct. 16, 2014); Ivey v. Wells Fargo, N.A., SA-14-CV-726- XR (Rodriguez, Oct. 16, 2014). Wells Fargo foreclosed on three different properties. Borrowers loans were each secured by the United States Department of Veteran Affairs ( VA ). Borrowers obtained injunctive relief, and Wells Fargo removed each action to federal court, thereafter filing motions to dismiss for failure to state a claim. In a matter of first impression for the Fifth Circuit, court granted each motion to dismiss. Borrowers do not have a private cause of action under 38 U.S.C to enforce any requirement that the VA be notified prior to instituting foreclosure proceedings on a VA-secured loan or to enforce any requirement that the VA be notified that borrower s payment was rejected after notice of default. Using a Cort analysis, 422 U.S. 66 (1975), court concluded that 3732 is designed to protect the government s interests, not the borrower s; the statute s plain language does not indicate that a private cause of action might be implied; a private cause of action is inconsistent with the statute s legislative scheme, as the statute is not intended to provide a means for veterans to prevent foreclosure when in default; and mortgage foreclosure is traditionally relegated to state law. Foreclosure; Abandonment; Review of Bankruptcy Order In re Gene R. Rosas (Rosas v. America s Servicing Co. & Deutsche Bank Nat l Trust Co., as Trustee for the Fremont Home Loan Trust Series ), SA-14- CV-601-XR (Rodriguez, Oct. 14, 2014). After bringing a series of state-court and bankruptcy proceedings in an attempt to stop the foreclosure sale of his residence, Chapter 13 debtor filed his fifth bankruptcy petition and an adversary proceeding against the servicer and holder of the note on the residence, seeking a determination as to the validity of the lien and to quiet title. Debtor appealed bankruptcy court s order granting servicer and holder s motions for summary judgment. Court held that bankruptcy court did not err in: (1) concluding that, under Texas law, forbearance agreement issued by servicer and holder and signed by debtor amounted to abandonment of all accelerations prior to specified date; (2) finding that acceptance of payments and application of such payments to the amount owed without seeking other remedies constituted abandonment; and (3) finding that defendants rights to enforce collection of the note were not time-barred. Motion to Dismiss; Temporary Restraining Order; Injunctive Relief; State Action Cokley v. Barriga, SA-14-CV-945-XR (Rodriguez, Oct. 28, 2014). Resident of private assisted living facility sued court-appointed guardian and guardian ad litem. Resident contended that she was being held against her will at the facility. Court denied resident s requests for a TRO and injunctive relief pursuant to 42 U.S.C. 1983, the Fourth and Fourteenth Amendments, and the Americans with Disabilities Act. Resident failed to allege facts to state a claim as the court-appointed guardian and guardian ad litem are not state actors and the assisted living facility in question is not a public accommodation. Remand; Improper Joinder; Pleading Practice Rajajoshiwala v. Travelers Cas. Ins. Co. of Am., SA-14-CV-715-XR (Rodriguez, Sept. 23, 2014). Court remanded insured s case against insurer and claims adjuster. Insurer had removed case based on diversity jurisdiction, arguing improper joinder because insured had no reasonable basis for his claims against claims adjuster for violations of the Texas Deceptive Trade Practices Act ( DTPA ), violations of Texas Insurance Code Chapters 541 and 542, and negligent misrepresentation. Court determined insured s Texas state court petition is not held to a federal court heightened pleading standard. Court noted that insured s DTPA and 542 claims against adjuster likely would not survive, but claims against adjuster for violating Chapter 541 for unreasonable investigation had a reasonable basis in state law. Although other federal courts in Texas have held that merely pleading that Defendants acted in violation of the law, without identifying specific actors, can lead to improper joinder, court was not convinced that the pleading at issue did not state a claim under Texas law and pleading practice. Fair Labor Standards Act; Executive Exemption Mohnacky v. FTS Int l Servs., L.L.C., SA-13-CV-246-XR (Rodriguez, Oct. 2, 2014). Court denied plaintiff s motion for partial summary judgment on his claim that defendant failed to pay him overtime under the Fair Labor Standards Act ( FLSA ). Genuine issue of material fact existed as to whether plaintiff, a field coordinator for a frac crew of ten San Antonio Lawyer 20 January-February 2015 21 to twelve members, was subject to executive exemption. Plaintiff earned a salary over $455 a week, directed crew members, provided on-the-job training, and was the highest ranking employee during fracking convoy. Plaintiff s job description included hiring, grievances, and termination of employment. Although plaintiff denied ever giving recommendations for employment decisions, court found enough evidence to let a jury decide whether executive exemption was met. Court denied plaintiff s motion for summary judgment that defendant acted willfully. Mere negligence in performing an internal audit to assess whether field coordinators were properly classified as exempt was insufficient to establish willfulness as a matter of law. While prior litigation involving the same legal issue can support a finding of willfulness against an employer, prior litigation at issue involved a position different than that held by plaintiff and was, therefore, insufficient to put defendant on notice that its policy violates the FLSA. Diversity Jurisdiction; Amount in Controversy; Eviction Federal Nat l Mortg. Ass n v. Gibson, SA- 14-CV-712-XR (Rodriguez, Sept. 3, 2014). Plaintiff sued to evict defendant from her home. Defendant removed, asserting diversity jurisdiction. Court remanded because defendant did not establish an amount in controversy greater than $75,000. Defendant pleaded that fair market value of the property was $144,280. But where plaintiff only seeks eviction and not monetary damages, the amount in controversy is the value of the right to occupy the property, not the underlying value of the property. Although foreclosure of the home was a possibility, it was not before the court. Defendant made no allegations as to fair rental value of the property and, therefore, could not establish federal diversity jurisdiction. Removal; America Invents Act; Copyright Act DEA Specialties Co., Inc. v. DeLeon, SA-14- CA-634-XR (Rodriguez, Sept. 4, 2014). Plaintiff distributor sued former supplier and employee for breach of distributor and employment agreements. Defendant supplier counterclaimed for copyright infringement under the Copyright Act, alleging that plaintiff continued to copy and use defendant s proprietary software to distribute a competitor s products. Defendant removed pursuant to 28 U.S.C as part of the America Invents Act. Court held defendant s claims arose under Copyright Act and did not merely assert a dispute over ownership of copyrighted material. Court exercised supplemental jurisdiction over plaintiff s state law claims because all parties claims arose from the distributorship agreement. Soledad Valenciano practices commercial and real estate litigation with Spivey Valenciano, PLLC. Melanie Fry practices commercial litigation and appellate law with Cox Smith Matthews. San Antonio Lawyer 21 January-February 2015 Letters of administration (usually when there is no valid will). The Probate Service What is probate? When a person dies somebody has to deal with their estate (money property and possessions left) by collecting in all the money, paying any debts and distributing) - 2 - Your appeal will follow these steps: QUESTIONS AND ANSWERS ABOUT YOUR APPEAL AND YOUR LAWYER A Guide Prepared by the Office of the Appellate Defender 1. WHO IS MY LAWYER? Your lawyer s name is on the notice that came with this guide. Organizing Your Finances After Your Spouse Has Died Organizing Your Finances After Your Spouse Has Died Page 1 of 7, see disclaimer on final page Organizing Your Finances After Your Spouse Has Died What is it? Even if you've always handled your family Consumer Legal Guide. Your Guide to Hiring a Lawyer Consumer Legal Guide Your Guide to Hiring a Lawyer How do you find a lawyer? Finding the right lawyer for you and your case is an important personal decision. Frequently people looking for a lawyer ask PRE-GRADUATION JUDICIAL INTERNSHIPS PRE-GRADUATION JUDICIAL INTERNSHIPS and Internships at the United States Attorney s Office, the Federal Public Defender s Office, and the Bexar County District Attorney s Office PROFESSOR VINCENT R. JOHNSON Effective Marketing Strategies for the Development of a Successful Law Practice By Henry J Chang Introduction Effective Marketing Strategies for the Development of a Successful Law Practice By Henry J Chang Law schools typically teach law students how to perform legal analysis but really teach them, A Reminder: Avoiding and Surviving Attorney Ethics Complaints in Texas* A Reminder: Avoiding and Surviving Attorney Ethics Complaints in Texas* A. THE BASICS FOR AVOIDING A GRIEVANCE Grievance claims in Texas have risen at a rate directly correlated to attorney growth. Child Abuse, Child Neglect. What Parents Should Know If They Are Investigated Child Abuse, Child Neglect What Parents Should Know If They Are Investigated Written by South Carolina Appleseed Legal Justice Center with editing and assistance from the Children s Law Center and the Your Personal Guide To Your Personal Injury Lawsuit Your Personal Guide To Your Personal Injury Lawsuit Know How To Do Things Right When You ve Been Wronged You have questions. And most likely, you have a lot of them. The good news is that this is completely PRE-GRADUATION JUDICIAL INTERNSHIPS PRE-GRADUATION JUDICIAL INTERNSHIPS and Internships at the United States Attorney s Office, the Federal Public Defender s Office, and the Bexar County District Attorney s Office PROFESSOR VINCENT R. JOHNSON ASBESTOS LITIGATION YOUR GUIDE TO THE LEGAL PROCESS ASBESTOS LITIGATION YOUR GUIDE TO THE LEGAL PROCESS INSIDE > About Simmons Hanly Conroy > Filing an Asbestos Lawsuit > Resources Hard at Work for You > Results That Matter > Legal FAQ > Taking the First (404) 919-9756 david@davidbrauns.com You are probably reading this guide because you were recently in an automobile accident. Now you are faced with some difficulties. The tasks of managing your care and your insurance claim can be confusing All BIS Digital, Inc. Associates: To All BIS Digital, Inc. Associates: It is with deep sorrow that I have to announce the passing of Bob Wolfe. After fighting cancer for the last several months he had called me last Friday from the hospital!!! Power of Attorney FREE REVISED 2015 Power of Attorney This publication tells you how a power of attorney can be used to give someone the legal power to take care of financial and legal matters for you. It explains the types to find a personal injury lawyer How to find a personal injury lawyer Table of contents: Introduction - page 1 The nature of personal injury cases. - page 2 How do you tell a good lawyer from a not so good one? - page 3 Where to look Chapter 35 SENIOR SUPER HERO Chapter 35 Kevin Reichard Senior Financial Network SENIOR SUPER HERO (Story told by the Reverse Mortgage Professional) I was sitting at my desk in my home office comparing two great job offers after AN INSPIRATIONAL GIFT AN INSPIRATIONAL GIFT 1949 Grad Supports Dairy Science Scholarship Iowa State meant a great deal to George Donald Graver, who passed away in spring 2012. Don grew up on a farm near Lisbon, Iowa, and 20-SOMETHINGS NEED ESTATE PLANNING, TOO 20-SOMETHINGS NEED ESTATE PLANNING, TOO Recently, we saw one Hollywood family suffer through an unthinkable tragedy. After months of lying unresponsive in a coma, Bobbi Kristina Brown passed only a few, Female client hired male Attorney for an insurance claim. While Client s husband was away in DISCIPLINARY DECISIONS IN OTHER JURISDICTIONS MISSOURI In re Howard, 912 S.W.2d 61 (Mo. 1995) Female client hired male Attorney for an insurance claim. While Client s husband was away in the Army, Attorney OUTLINE OF HOW A DECEDENT S ESTATE IS ADMINISTERED Copyright 2007-2014 F. Michael Friedman OUTLINE OF HOW A DECEDENT S ESTATE IS ADMINISTERED Copyright 2007-2014 F. Michael Friedman This memorandum outlines the general course by which a decedent s estate is handled in the Commonwealth of Pennsylvania. BEFORE THE NEVADA COMMISSION ON ETHICS STATE OF NEVADA COMMISSION ON ETHICS BEFORE THE NEVADA COMMISSION ON ETHICS IN THE MATTER OF THE REQUEST FOR OPINION CONCERNING THE CONDUCT OF JARED SHAFER, former Public Administrator, Clark County. / Networked Knowledge Media Report Networked Knowledge Prosecution Reports Networked Knowledge Media Report Networked Knowledge Prosecution Reports This page set up by Dr Robert N Moles [Underlining where it occurs is for editorial emphasis] Anthony Graves is appointed to CLIENT INFORMATION: GUIDELINES ON ADMINISTRATION & BILLING CLIENT INFORMATION: GUIDELINES ON ADMINISTRATION & BILLING As updated from time-to-time for billing rates and responsible attorney and, following actual notice to the client. This agreement forms the basis Mitchell Ceasar Attorney and Politician Mitchell Ceasar Attorney and Politician Over the years, Kingsborough Community College has had many students graduate and go on to pursue their careers at other schools. Mitchell Ceasar graduated from Ministerial Tax Issues Ministerial Tax Issues Answers to Common Questions Table of contents Introduction......................................................1 Who is a minister for tax purposes?............................... brief guide to Trusts and our Trustbuilder tool guide to guide to trusts trusts A brief guide to Trusts and our Trustbuilder tool A Brief guide to Trusts and our Trustbuilder tool Introduction This brief guide explains some of the main features PROFESSIONAL INTEGRITY, LEGAL EXPERTISE PRINCIPLES OF OUR PARTNERS, ASSOCIATES AND SUPPORT STAFF. PROFESSIONAL INTEGRITY, LEGAL EXPERTISE AND PERSONAL CHARACTER ARE THE GUIDING PRINCIPLES OF OUR PARTNERS, ASSOCIATES AND SUPPORT STAFF. PMB B Perskie Mairone Brog & Baylinson AREAS OF PRACTICE The firm: Your Roadmap to Maximize Your Settlement!!! Your Roadmap to Maximize Your Settlement!!! Helpful tips to get the most money for your injuries. The Advocates Driggs, Bills and Day PC (801) 355 5550 1 Table of Contents: Introduction: A Lofty Legal Legacy Boynton, Waldron, Doleac, Woodman & Scott, P.A. A Lofty Legal Legacy Portsmouth law firm s local experience stretches back generations By Will Courtney When Jeremy R. Waldron first opened his law Seven Things You Must Know Before Hiring a Divorce Lawyer Seven Things You Must Know Before Hiring a Divorce Lawyer Introduction Divorce is a stressful time for everyone. Whether you ve been together for 3 months or 30 years, it s important that you follow through WORKFORCE INVESTMENT BOARDS WORKFORCE INVESTMENT BOARDS ROCHELLE J. DANIELS, BROWARD WORKFORCE DEVELOPMENT BOARD 6301 NW 5 th Way, Fort Lauderdale, FL 33309 954 202 3830 - WORKFORCE INVESTMENT BOARDS - WIBS WIBs are usually organized you purchased any of these annuities in California on or before November 5, 2008: SUPERIOR COURT OF CALIFORNIA FOR THE COUNTY OF LOS ANGELES, CENTRAL CIVIL WEST If you purchased any of these annuities in California on or before November 5, 2008: Midland National Life Insurance Company 2,225 gain admission to 'very noble' profession Sign Out Front Page Trial Notebook Case Summaries In the News Calendar Photo of the Day Courts New Suits Public Notices Jobs Search Advanced Search Site Map Customer Care Contact Us LB Company Order, November 2005. 68 Tex. B. J. 960 November 2005 68 Tex. B. J. 960 BODA ACTIONS On Sept. 14, the Board of Disciplinary Appeals signed a judgment of indefinite disability suspension against Suzanne Elizabeth Mann Minx, 39, of Porter, in About See Me Communications About See Me Communications Founded in 2011, See Me Communications is dedicated to honoring and improving the lives of the frail, elderly and disabled people whose voice and essence may be hidden MAKING A WILL A guide to help you MAKING A WILL A guide to help you Death is not something we like to think about or plan for and of course no amount of planning can prevent the pain your loved ones will experience when you die.. Post-Secondary Options Post-Secondary Options This informative publication ensued from the collaborative works of Family Network on Disabilities and ASAN. Family Network on Disabilities understands and respects the beliefs and FLORIDA ESTATE PLANNING FOR NEWLYWEDS AFTER 50 Once you have your estate plan updated and all of the new issues properly addressed, you can move forward with the confidence that this new chapter will indeed have a happy ending. FLORIDA ESTATE PLANNING NETWORKING: WHY, HOW, WHO, and WHEN NETWORKING: WHY, HOW, WHO, and WHEN Professional Development Workshop Series Career Development and Internships Office (CDIO) careers@northpark.edu x5575 1 Up to 80% of jobs these days are found through Ethics Case Study for ABC Incorporated and Questions Ethics Case Study for ABC Incorporated and Questions By Renee Rampulla, CPA, Technical Manager, AICPA Professional Ethics Division and updated by Ellen Goria, CPA, Senior Manager Independence and Special
http://docplayer.net/508120-January-february-2015-san-antonio-permit-1001-texas-san-antonio-paid-us-postage-prst-std.html
CC-MAIN-2017-43
refinedweb
14,657
52.9
? A great feature! How do unitful quantities look to the CLR? Something like [Measure] struct Second : IMeasure {} and struct Mult<M1,M2> : IMeasure where M1 : IMeasure where M2 : IMeasure {} ? Great post. However, I am having issues running the "gravitionalForce" portion of it. I keep getting an error saying that "error FS0039: The namespace or module 'SI' is not defined." even though I referenced it in both ways (I also have powerpack added to the project): open SI and/or open Microsoft.FSharp.Math.SI any thoughts on this? Thanks ~sparky alexey_r: Units actually don't get seen at all by the CLR - they are "erased". They are a purely static phenomenon, which means that the performance of code with units is no worse than the performance of the code with the units removed. You can think of them as a "refinement" of usual .NET types, seen only by F#. Of course this has some downsides (no runtime inspection of units) but our experience so far has been that they are in any case extremely useful in practice. And interestingly, all the "classical" functional languages (Haskell, Caml, OCaml, Standard ML) have purely static type systems. sparky: did you include open Microsoft.FSharp.Math ? This has PhysicalConstants as a submodule. - Andrew. Would be nice to have unit of measure support as a general class library in the .net framework. Can you specify the scale and precision as well? Andrew, How can I get the following to compile?: [<Measure>] type km = static member toM = 1.0/1000.0<m/km> type m = static member toKm = 1000.0<km/m> Seems like there's a fundamental limitation I'm running up against... or hopefully I'm just missing something. The definition of m requires the definition of km, and vice versa. You can define mutually recursive measures using "and" to connect them and placing the Measure attribute immediately before the name of the measure: type [<Measure>] km = static member toM = 1.0/1000.0<m/km> and [<Measure>] m = static member toKm = 1000.0<km/m> Wonderful - thanks! I'm so excited that a practical programming language finally has units-of-measure capability. Nice work. This is incredibly annoying. [1] Reference FSharp Powerpack.dll - check [2] open Microsoft.FSharp.Math - Alt+Enter -> FSI pass [3] open SI - Alt+Enter -> FSI FAIL [error FS0039: The namespace or module 'SI' is not defined.] doing something as simple as: #light open SI let distance (d:float<m>) = d does not work -> anyone else has this problem? The VS IntelliSense and the documentation says that the SI module is installed, yet when I open and try to use it, nothing works. It seems to me that the problem is with the FSI and interpreting namespaces/modules but if anyone can give me some insights, that will really help! > As far as F# is concerned, ft and m have nothing to do with each other. It's up to you, the programmer, to define appropriate conversion factors. This is mildly annoying. There's no reason why feet cannot be converted to meters and back automatically (it's not a narrowing conversion, so no opportunity for data loss), and even less for not being able to convert between m and km. It would seem to me that boost::units approach, which differentiates between abstract measures (duration, distance etc), and specific units of measurement, is more convenient. This whole thing is seriously cool. Just today we stubmled again with unit mix up in our simulation code. But then, my most urgent question would be whether there are any plans to support this in other languages as well? F# is nice, but we have a large investment in C# and really wouldn't want to move to F# just for the unit stuff... Any ideas on that? I finally got this to work and I realized where the problem was. I was using the default F# project and .fs file to type up all the code in but when I Alt+Enter and send to FSI, that is where the problem started. Even though I added the reference via "Add Reference", I still get the error because FSI is not aware of project settings and all that. So in addition, I had to do #r "FSharp.PowerPack.dll" in the FSI window first, then Alt+Enter the rest of the code to it. Works now. Thanks for the help. It would seem to be that Microsoft is deliberately pushing for F# for scientific computing now, while C# is your typical "general-purpose" (read: system & LOB) language. C# 4.0 is expected to have 4 new language features, one of them generic variance - I wouldn't expect to see units among the other three. Nor anytime soon - DbC, for example, would probably be higher-priority for C#. Hello, One thing that I stumbled upon. The value conversion on the types get masked when you set a literal with the same name as a type. In FSI: [<Measure>] type km = static member pM = 1000.0<km/m>;; [<Measure>] type m = static member pK = 0.001<m/km>;; let km = 1.0<km>;; km;; m.pK;; km.pM;; The last line errors saying it can't find pM. Good day. Yemi Bedu Does F# support units with different zero values, e.g. Kelvin and Celsius? What I mean is that conversion of 100C to K depends on whether 100C in this case means temperature of boiling water (then the result is 373.15K) or difference between boiling water temperature and freezing water temperature (in this case the answer is 100K). One can write two converters (say C.AbsToK and C.DeltaToK), but then it is user's responsibility to do it right - F# will do no checking. Or maybe one should define two types of K and C units - absolute and delta, with rules like AbsX-AbsX=DeltaX, AbsX+DeltaX=AbsX, AbsX+AbsX=illegal, and so on? Good point regarding units with different zero values. The units supported by F# are those for which multiplication makes sense, and Celsius doesn't fit this model. It makes no sense to double an absolute temperature measured in degrees Celsius. Whereas for Kelvin, this is fine. A similar situation arises with absolute times versus time periods - it would indeed be nice to permit subtraction of absolute times, and rule out addition of absolute times, but permit either operation on time *periods*. One can do this by defining separate *types*, a little like DateTime and TimeSpan from the .NET framework. First, let me remind you that in my new ongoing quest to read source code to be a better developer , :) Kean over at AutoDesk (think AutoCAD etc.) is running an F# programming contest ! I've included his post Ostatnio ponowiłem wysiłki do opanowania nowych języków z rodziny MS w tym także implementacji znanych
http://blogs.msdn.com/andrewkennedy/archive/2008/09/02/units-of-measure-in-f-part-two-unit-conversions.aspx
crawl-002
refinedweb
1,144
66.03
- Item 37: Compose Classes Instead of Nesting Many Levels of Built-in Types - Item 38: Accept Functions Instead of Classes for Simple Interfaces - Item 39: Use @classmethod Polymorphism to Construct Objects Generically - Item 40: Initialize Parent Classes with super - Item 41: Consider Composing Functionality with Mix-in Classes - Item 42: Prefer Public Attributes Over Private Ones - Item 43: Inherit from collections.abc for Custom Container Types Item 43: Inherit from collections.abc for Custom Container Types Much of programming in Python is defining classes that contain data and describing how such objects relate to each other. Every Python class is a container of some kind, encapsulating attributes and functionality together. Python also provides built-in container types for managing data: lists, tuples, sets, and dictionaries. When you’re designing classes for simple use cases like sequences, it’s natural to want to subclass Python’s built-in list type directly. For example, say I want to create my own custom list type that has additional methods for counting the frequency of its members: class FrequencyList(list): def __init__(self, members): super().__init__(members) def frequency(self): counts = {} for item in self: counts[item] = counts.get(item, 0) + 1 return counts By subclassing list, I get all of list’s standard functionality and preserve the semantics familiar to all Python programmers. I can define additional methods to provide any custom behaviors that I need: foo = FrequencyList(['a', 'b', 'a', 'c', 'b', 'a', 'd']) print('Length is', len(foo)) foo.pop() print('After pop:', repr(foo)) print('Frequency:', foo.frequency()) >>> Length is 7 After pop: ['a', 'b', 'a', 'c', 'b', 'a'] Frequency: {'a': 3, 'b': 2, 'c': 1} Now, imagine that I want to provide an object that feels like a list and allows indexing but isn’t a list subclass. For example, say that I want to provide sequence semantics (like list or tuple) for a binary tree class: class BinaryNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right How do you make this class act like a sequence type? Python implements its container behaviors with instance methods that have special names. When you access a sequence item by index: bar = [1, 2, 3] bar[0] it will be interpreted as: bar.__getitem__(0) To make the BinaryNode class act like a sequence, you can provide a custom implementation of __getitem__ (often pronounced “dunder getitem” as an abbreviation for “double underscore getitem”) that traverses the object tree depth first: class IndexableNode(BinaryNode): def _traverse(self): if self.left is not None: yield from self.left._traverse() yield self if self.right is not None: yield from self.right._traverse() def __getitem__(self, index): for i, item in enumerate(self._traverse()): if i == index: return item.value raise IndexError(f'Index {index} is out of range') You can construct your binary tree as usual: tree = IndexableNode( 10, left=IndexableNode( 5, left=IndexableNode(2), right=IndexableNode( 6, right=IndexableNode(7))), right=IndexableNode( 15, left=IndexableNode(11))) But you can also access it like a list in addition to being able to traverse the tree with the left and right attributes: print('LRR is', tree.left.right.right.value) print('Index 0 is', tree[0]) print('Index 1 is', tree[1]) print('11 in the tree?', 11 in tree) print('17 in the tree?', 17 in tree) print('Tree is', list(tree)) >>> LRR is 7 Index 0 is 2 Index 1 is 5 11 in the tree? True 17 in the tree? False Tree is [2, 5, 6, 7, 10, 11, 15] The problem is that implementing __getitem__ isn’t enough to provide all of the sequence semantics you’d expect from a list instance: len(tree) >>> Traceback ... TypeError: object of type 'IndexableNode' has no len() The len built-in function requires another special method, named __len__, that must have an implementation for a custom sequence type: class SequenceNode(IndexableNode): def __len__(self): for count, _ in enumerate(self._traverse(), 1): pass return count tree = SequenceNode( 10, left=SequenceNode( 5, left=SequenceNode(2), right=SequenceNode( 6, right=SequenceNode(7))), right=SequenceNode( 15, left=SequenceNode(11)) ) print('Tree length is', len(tree)) >>> Tree length is 7 Unfortunately, this still isn’t enough for the class to fully be a valid sequence. Also missing are the count and index methods that a Python programmer would expect to see on a sequence like list or tuple. It turns out that defining your own container types is much harder than it seems. To avoid this difficulty throughout the Python universe, the built-in collections.abc module defines a set of abstract base classes that provide all of the typical methods for each container type. When you subclass from these abstract base classes and forget to implement required methods, the module tells you something is wrong: from collections.abc import Sequence class BadType(Sequence): pass foo = BadType() >>> Traceback ... TypeError: Can't instantiate abstract class BadType with ➥abstract methods __getitem__, __len__ When you do implement all the methods required by an abstract base class from collections.abc, as I did above with SequenceNode, it provides all of the additional methods, like index and count, for free: class BetterNode(SequenceNode, Sequence): pass tree = BetterNode( 10, left=BetterNode( 5, left=BetterNode(2), right=BetterNode( 6, right=BetterNode(7))), right=BetterNode( 15, left=BetterNode(11)) ) print('Index of 7 is', tree.index(7)) print('Count of 10 is', tree.count(10)) >>> Index of 7 is 3 Count of 10 is 1 The benefit of using these abstract base classes is even greater for more complex container types such as Set and MutableMapping, which have a large number of special methods that need to be implemented to match Python conventions. Beyond the collections.abc module, Python uses a variety of special methods for object comparisons and sorting, which may be provided by container classes and non-container classes alike (see Item 73: “Know How to Use heapq for Priority Queues” for an example). Things to Remember Inherit directly from Python’s container types (like list or dict) for simple use cases. Beware of the large number of methods required to implement custom container types correctly. Have your custom container types inherit from the interfaces defined in collections.abc to ensure that your classes match required interfaces and behaviors.
https://www.informit.com/articles/article.aspx?p=2992597&seqNum=7
CC-MAIN-2022-05
refinedweb
1,053
51.68
The script has to be saved as a Stay-open script, as it needs to monitor Mail.app in the background. It will Quit itself when the announcement is done. IMPORTANT: You need to save the script as a program, and check "Stay open" ! property announceJunk : false -- should junk mail be announced too ? property senderCntThreshold : 2 -- more than this, and the count is announced property senderCntMax : 4 -- more than this, and only the count is announced property voiceVolume : "0.7" property senderList : {} property firstRun : true -- don't do anything at first run of idle using terms from application "Mail" on perform mail action with messages theMessages repeat with thisMessage in theMessages set thisSender to extract name from sender of thisMessage set junk to junk mail status of thisMessage tell application "Mailmelding" -- We have to run ourselves :-/ -- If we didn't use "tell" the run method would never be called... newMail(thisSender, junk) end tell end repeat end perform mail action with messages end using terms from on newMail(thisSender, junk) if junk then if not announceJunk then return end if set thisSender to " junk " end if set found to false repeat with x in my senderList if sender of x is equal to thisSender then set cnt of x to (cnt of x) + 1 set found to true exit repeat end if end repeat if not found then copy {sender:thisSender, cnt:1} to end of my senderList end if end newMail on idle if firstRun then set firstRun to false return 2 end if tell application "Mail" set mailIdle to background activity count = 0 end tell if mailIdle then set senderCount to count of senderList if senderCount = 0 then set firstRun to true quit return 0 end if set sayStr to "[[volm " & voiceVolume & "]]" & "New mail:" & space if senderCount > senderCntThreshold then set sayStr to sayStr & "From " & senderCount & " different senders !" & space end if if senderCount is less than or equal to senderCntMax then -- Report the findings repeat with x in senderList set thisSender to sender of x set cnt to cnt of x set sayStr to sayStr & spokenPrefix(senderCount, cnt) & space if thisSender is " junk " then set sayStr to sayStr & "junk." & space else set sayStr to sayStr & "from " & pickFirstPart(thisSender) & "." & space end if end repeat end if say sayStr set senderList to {} set firstRun to true quit end if -- mailIdle return 2 -- Call again every 2 seconds... end idle on spokenPrefix(senderCount, cnt) if senderCount = 1 and cnt = 1 then return "" else return (cnt as text) end if end spokenPrefix on pickFirstPart(emailOrName) set oldDelim to AppleScript's text item delimiters if emailOrName contains "@" then set AppleScript's text item delimiters to {"@"} else set AppleScript's text item delimiters to {" "} end if return first text item of emailOrName set AppleScript's text item delimiters to oldDelim end pickFirstPart If you save the script as "Mail-announcer", then change this line: tell application "Mailmelding" to this: tell application "Mail-announcer" I tried to cut and paste this one and make it into an apple script but it won't compile in Jaguar using Script Editor 1.9. The error says: Expected "given", "into", "with", "without" or other parameter name but found identifier. The script looks like it would be great so any help will be appreciated. --- Mike Sorry, I'm no AppleScript expert. It works in Panther as far as I know... Visit other IDG sites:
http://hints.macworld.com/comment.php?mode=view&cid=39095
CC-MAIN-2014-42
refinedweb
564
56.02
US6728963B1 - Highly componentized system architecture with a loadable interprocess communication manager - Google PatentsHighly componentized system architecture with a loadable interprocess communication manager Download PDF Info - Publication number - US6728963B1US6728963B1 US09283818 US28381899A US6728963B1 US 6728963 B1 US6728963 B1 US 6728963B1 US 09283818 US09283818 US 09283818 US 28381899 A US28381899 A US 28381899A US 6728963 B1 US6728963 B1 US 6728963B1 - Authority - US - Grant status - Grant - Patent type - - Prior art keywords - object - thread - interprocess communication - address space - working is a utility application filing of provisional patent Ser. No. 60/099,562, filed on Sep. 9, 1998 and entitled “A Highly Componentized System Architecture With Dynamically Loadable Operating Features” (now abandoned). This application also includes subject matter related to that of U.S. patent application Ser. No. 09/282,238, filed Mar. 31, 1999.: Embedded control systems, including consumer devices, intelligent sensors and smart home controls. Communication-oriented devices such as digital cell phones and networking infrastructure. Programmable peripherals and microcontrollers.: [Bershad95] Brian Bershad, S. Savage, P. Pardyak, E. G. Sirer, M. Fiuczynski, D. Becker, S. Eggers, C. Chambers. Extensibility, safety and performance in the Spin operating system. In 15th ACM Symposium on Operating System Principles, pages 267-284, Copper Mountain Resort, Colo., December 1995. [Black92] David Black, David Golub, Daniel Julin, Richard Rashid, Richard Draves, Randall Dean, Alessandro Forin, Joseph Barrera, Hideyuki Tokuda, Gerald Malan, David Bohman. Microkernel Operating System Architecture and Mach. In 1st USENIX Workshop on Micro-kernels and Other Kernel Architectures, pages 11-30, Seattle, April 1992. [Brockschmidt95] K. Brockshmidt. Inside OLE, Second ed. Microsoft Press, Redmond Wash., 1995. [Cheriton94] David Cheriton, Kenneth Duda. A Caching Model of Operating System Kernel Functionality. In 1st Symposium on Operating Systems Design and Implementation, Seattle, 1994. [Cheriton88] David Cheriton. The V distributed system. In Communications of the ACM, pages 314-333, March 1988. [Draves97] Richard Draves, Scott Cutshall. Unifying the User and Kernel Environments. Microsoft Research Technical Report MSR-TR-97-10, 16 pages, March 1997 [Engler95] D. R. Engler, M. F. Kaashoek, J. O' Toole Jr. Exokernel: an operating system architecture for application-specific resource management. In 15th ACM Symposium on Operating System Principles, pages 251-266, Copper Mountain Resort, Colo., December 1995. [Ford97] Bryan Ford, Godmar Back, Greg Benson, Jay Lepreau, Albert Lin, Olin Shivers. The Flux OSKit: A Substrate for Kernel and Language Research. In Proceedings of the 16th ACM Symposium on Operating Systems Principles, pages 38-51. ACM SIGOPS, Saint-Malo, France, October 1997. [Golub90] David Golub, Randall Dean, Alessandro Forin, Richard Rashid. UNIX as an application program. In USENIX 1990 Summer Conference, pages 87-95, June 1990. [Helander94] Johannes Helander. Unix under Mach: The Lites Server. Master's thesis, 71 pages, Helsinki University of Technology, 1994. Available from˜jvh/lites.MASTERS.ps [Hildebrand92] D. Hildebrand. An architectural overview of QNX. In 1 st USENIX Workshop on Micro-kernels and Other Kernel Architectures, pages 113-126, Seattle, April 1992. [ISI95] Integrated Systems Inc. pSOSystem System Concepts. Part No. COL0011, May 1995, ISI, Sunnyvale Calif. [Jones96] Michael B. Jones, Joseph S. Barrera, III, Richard P. Draves, Alessandro Forin, Paul J. Leach, Gilad Odinak. An Overview of the Rialto Real Time Architecture. In Proceedings of the 7th ACM SIGOPS European Workshop, pagg. 249-256, September 1996. [Jones97] Michael B. Jones et al. CPU Reservations and Time Constraints: Efficient, Predictable Scheduling of Independent Activities. In Proceedings of the 16th ACM Symposium on Operating Systems Principles, pages 198-211. ACM SIGOPS, Saint-Malo, France, October 1997. [Jones 97b] Michael B. Jones. The Microsoft Interactive TV System: An Experience Report. Microsoft Research Technical Report MSR-TR-97-18, July, 1997. [Julin9l] Daniel Julin, Jonathan Chew, Mark Stevenson, Paulo Guedes, Paul Neves, Paul Roy. Generalized Emulation Services for Mach 3.0: Overview, Experiences and Current Status. In Proceedings of the Usenix Mach Symposium, 1991. [Lee98] Dennis Lee, Patrick Crowley, Jean-Loup Baer, Tom Anderson, Brian Bershad. Execution characteristics of desktop applications on Windows NT. In Proceedings of the 25th International Symposium on Computer Architecture, Barcelona, Spain, June 1998. [Liedtke95] Jochen Liedtke. On □-kernel construction. In 15th ACM Symposium on Operating System Principles, pages 237-250, Copper Mountain Resort, Colorado, December 1995. [Mogul87] Jeffrey Mogul, Richard Rashid, Michael Accetta. The Packet Filter: an Efficient Mechanism for User-level Network Code. In 11 th ACM Symposium on Operating System Principles, November 1987. [Rashid87] Richard Rashid. From RIG to Accent to Mach: The evolution of a network operating system. Carnegie Mellon University Technical Report, August 1987. [Rozier88] M. Rozier, A. Abrassimov, F. Armand, I. Boule, M. Gien, M. Guillemont, F. Hermann, C. Kaiser, S. Langlois, P. Leonard, W. Neuhauser. CHORUS distributed operating system. In Computing Systems, pages 305-370, Vol. 1-4, 1988. [Young89] Michael Wayne Young. Exporting a User Interface to Memory Management from a Communication-Oriented Operating System. Ph.D. Thesis CMU-CS-89-202, Carnegie Mellon University, November 1989. directed toward a loadable interprocess communication manager and generally to a computer operating system capable of supporting plural threads running in a computer having a working memory, the computer operating system including a kernel resident in the working memory at link time and a loadable interprocess communication manager resident at link time outside of the working memory and dynamically loadable into the working memory at run time upon request by one of the threads in one address space to communicate with an other thread in an other address space. The kernel includes a loader for loading the interprocess communication manager into the working memory in response to the request by the one thread. The computer further includes a storage memory separate from the working memory, the loadable interprocess communication manager residing at link time in the storage memory. The loader loads the interprocess communication manager from the storage memory to the working memory. The loadable interprocess communication manager is terminable from the working memory upon lack of a need for communication between threads in different address spaces. Preferably, the kernel of the operating system includes an interprocess communication fault handler for interprocess communication faults occurring in the absence of the interprocess communication manager in the working memory. The kernel also includes a Namespace for registering the interprocess communication manager upon the interprocess communication manager being loaded into the working memory, whereby the interprocess communication manager becomes available to each thread through the Namespace. The Namespace includes an object supporting plural interfaces exposable by the threads, the plural interfaces including a query interface through which a thread invokes the interprocess communication manager, an add reference interface by which the Namespace manages each request for the interprocess communication manager from any of the threads, and a release reference interface, by which Namespace manages termination of the interprocess communication manager from the working memory. The loader is responsive to the Namespace in maintaining the interprocess communication manager in the working memory whenever the add reference interface has a reference to the interprocess communication manager. The loadable interprocess communication manager includes an object with plural interfaces exposable to other objects, the plural interfaces of the interprocess communication manager supporting methods including an interprocess communication trap handler (IPC Trap Handler) and copy (IPC Copy). The operating system can include plural loadable interprocess communication managers resident outside of the working memory at link time, the loader being capable of loading different ones of the plural interprocess communication managers into the working memory at run time. FIG. 1A is a block diagram of an exemplary operating environment of the invention. FIG. 1B is a block diagram of an operating system embodying the present invention in the computer illustrated in FIG. 1A. FIG. 1C illustrates one application of the invention to form stacked virtual memories with a local virtual memory. FIG. 2 illustrates a page table registry structure of a virtual memory manager of the operating system of FIG. 1B. FIG. 3 illustrates the objects in the virtual memory manager. FIG. 4 illustrates the virtual memory manager of FIG. 3 with a set of interfaces. FIG. 5 illustrates the structure of an object in the operating system of FIG. 1B. FIG. 6 illustrates the structure of the virtual memory view object of the operating system of FIG. 1B. FIG. 7 illustrates the objects in a preferred implementation of the virtual memory manager. FIG. 8 illustrates the Load VMM process in the operating system of FIG. 1B. FIG. 9 illustrates the method of handling a virtual memory (VMM) fault in the operating system of FIG. 1B. FIG. 10 illustrates the operation of the VMM fault handier in the operating system of FIG. 1B. FIG. 11 illustrates the method for taking a VMM fault in the operating system of FIG. 1B. FIG. 12 illustrates the operation of the context switch process in the operating system of FIG. 1B. FIG. 13 illustrates the SwitchTo process in the operating system of FIG. 1B. FIG. 14 illustrates the operation for unloading the virtual memory manager in the system of FIG. 1B. FIG. 15 illustrates the process for handling a page fault in the system of FIG. 1B. FIG. 16 illustrates a process by which a constructor creates a thread in the operating system of FIG. 1B. FIG. 17 illustrates multiple views of memory provided by the VMView object of the operating system of FIG. 1B. FIG. 18 illustrates multiple views of memory that can be obtained in accordance with FIG. 17. FIG. 19 illustrates the basic features of a loadable interprocess communication (IPC) manager in the operating system of FIG. 1B. FIG. 20 illustrates the process of loading of the IPC manager of FIG. 19. FIG. 21 illustrates an interface between the IPC manager and other threads. FIG. 22 illustrates intercommunication provided by the IPC manager between different address spaces. FIG. 23 illustrates how an IPC trap is handled in the operating system of FIG. 1B. FIG. 24A illustrates the operation of the IPC trap handler in the operating system of FIG. 1B. FIG. 24B illustrates objects inside the loadable IPC system of a preferred embodiment of the present invention. FIG. 24C illustrates objects in different address spaces connected by the loadable IPC system of FIG. 24B. FIG. 25 illustrates the interface Imutate which provides object mutation in the operating system of FIG. 1B. FIG. 26 illustrates one application of object mutation in the operating system of FIG. 1B. FIG. 27 illustrates another application of object mutation applied to a Vtable. FIG. 28 illustrates synchronization of object mutation by mutual exclusion. FIG. 29 illustrates synchronization of object mutation by transactional synchronization. FIG. 30A illustrates the process of object mutation by swizzling in accordance with a preferred embodiment of the invention. FIG. 30B illustrates the structure of a thread relative to external objects prior to swizzling. FIG. 30C illustrates the structure of the thread relative to the external objects corresponding to FIG. 30B after swizzling. FIG. 31 illustrates an application of object mutation to achieve object interposition. FIG. 32 illustrates an application of object mutation to carry out dynamic software upgrading. FIG. 33 illustrates an application of object mutation to carry out run-time code generation. FIG. 34 illustrates how to achieve object mobility using object mutation. FIG. 35 illustrates how proxies may be used with object mutation to communicate across address spaces. FIG. 36 illustrates a mutatable structure of the virtual memory manager. FIG. 37 illustrates a method embodying the programming model of the invention. FIG. 38 illustrates operations carried out with the demand-loading NameSpace in accordance with the programming model of FIG. 37. FIG. 39 illustrates the loading of an object in accordance with the programming model of FIG. 37. FIG. 40 illustrates an application of the programming model of FIG. 37 to plug-and-play technology. FIGS. 41 and 42 illustrate an example of a conventional process for linking an executable image. FIG. 43 illustrates an example of a conventional process for linking with shared libraries. FIG. 44 illustrates a process in accordance with the present invention for linking an executable image using shared libraries. FIG. 45 illustrates a process in accordance with the present invention for forming a dynamically linked library. FIGS. 46A and 46B illustrate an example of a jump shortcutting process of the present invention. FIGS. 47A and 47B illustrate an example of a jump shortcutting process as applied to data references in accordance with the present invention. FIG. 48 illustrates an example of a post-link time compaction process of the present invention. FIG. 49 illustrates a load time code synthesis process for virtual memory in accordance with the present invention. FIG. inside various programmable peripheral interface cards such as 126, 128, 130, 144, 158, 148 in FIG. 1A, inside programmable peripherals such as disks, game controllers and accessories, speakers, modems, printers and the like, in hand-held devices, multiprocessor systems, microprocessor-based or programmable consumer electronics, network PCs, minicomputers, mainframe computers, and the like. Thus, for example, the present invention can be an operating system of an optimally minimized configuration, as described below, running inside a network interface card of the network interface 158 of FIG. 1A or in an embedded control system or in a communication-oriented device. The invention may also be practiced in distributed computing environments where tasks are performed by remote processing devices that are linked through a communications network. In a distributed computing environment, program modules may be located both in local and in remote memory storage devices. With reference to FIG. 1A, an exemplary system for implementing the invention includes a general purpose computing device in the form of a conventional personal process that helps to transfer information between elements within the personal computer 120, such as during start-up, is stored in ROM 124. The personal computer 120. Although the exemplary environment described herein employs a hard disk, dish, scanner, or the like. These and other input devices are often connected to the processing unit 121 through a serial port interface 146 that is coupled to the system bus, but may be connected by other interfaces, such as a parallel port, game port or a universal serial bus (USB). A monitor 147 or other type of display device is also connected toA. The logical connections depicted in FIG. 1A include a local area network (LAN) 151 and a wide area network (WAN) 152. Such networking environments are commonplace in offices, enterprise-wide computer networks, intranets and Internet. When used in a LAN networking environment, the personal computer 120 is connected to the local network.. An exemplary base set of system components in a preferred embodiment of the invention is now described. Referring to FIG. 1B, an exemplary operating system in accordance with an embodiment of the invention has a kernel or link-time component 202 and a set of run-time loadable resources 204. The kernel 202 includes a set of software resources including, preferably, a HEAP (physical memory manager) 302, a loader 304, a support library 306, a timer 310, an interrupt control unit 312, a scheduler 314, thread support 316 including synchronization primitives 318, NameSpace 320, filesystem 322 and a startup program 324. The set of run-time loadable resources 204 are available to the system through the loader 304. The resources 204 include, preferably, a virtual memory manager (VMM) 362, inter-process communication 364, drivers 366, applications 368 and a network program 370. A minimal multi-threaded kernel may be provided in accordance with the present invention having only the thread support 316, the scheduler 314, the library 306, the timer 310 and the startup 324. If multi-threading is not desired, the kernel may be further minimized to include only the library 306, the timer 310 and the startup 324. As illustrated in FIG. 1B, the ICU (interrupt control unit) 312 preferably includes the following software methods at link time: install VMM (virtual memory manager) trap handler 372, install IPC (inter-process communication) trap handler 374. These resources are preferably included in the interrupt control unit 312 because it is possible for such a system to take a VMM trap or an IPC trap or a page fault whether or not a VMM or IPC has been loaded. FIG. 1B. mercy Unknown: Security reasons, when a program is not trusted. The virtual memory system implements firewalls between applications. Covering for common programming errors such as NULL pointer references and memory leaks. Creating a sparse address space. This often leads to better memory utilization with fragmented heaps. Paging. This provides more memory than available, working set adaptation, and mapped files. Safe and flexible memory sharing: Copy-on-write for libraries, shared memory windows. Running non-relocatable executables as described above. Implementing garbage collection and other protection mechanisms. FIG. 1C, the invention can be used to make a collection of different machines (machine-A and machine-B) appear as a single address space by employing a local virtual memory (VM-1) while other virtual memories (VM-2 and VM-3) relating to the address spaces of the other machines but having the same interface as the local virtual memory are stacked overo and Write( ) are used for copy-paging. Share( ) is used to establish shared pages between two VMSpaces and to return pages to VMView::Fault( ). QueryAccesso. FIG. 2 illustrates how page table entries are used in providing translation between virtual memory addresses and physical memory addresses by the run-time loadable VMM 362 of FIG. 1B. Each VMSpace object stores a pointer value which is loadable into a page directory register 400 provided in the host computer's microprocessor. The pointer value, once loaded into the page directory register 400, points to a particular page table 402 which is one of many page tables available to the system. Each page table provides a particular set of address translations between virtual memory addresses and physical memory addresses. Different objects may be stored in different memory locations and therefore may require different address translations. The individual page table 402 has a set of virtual addresses 404 and physical addresses 406 correlated to corresponding ones of the virtual addresses, the addresses constituting the page table entries of the page table 402. FIGS. 3 and 4, the virtual memory manager (VMM) includes the following interfaces: IVMSpace 610, IVMMap 620, IVMView 630, IUnknown 640 and IVMFactory 650. The IUnknown interface preferably is included in every object. The purpose of this is to give every application the ability to query the object to determine if it supports a given interface. IUnknown refers to processes for querying for a given interface (“query”), for adding a reference to the object (“add”) and for releasing a reference to the object (“release”). Thus, each of the three primary interfaces of VMM includes the three processes of IUnknown, as illustrated in FIG. 4. VMFactory 650 has an interface INamespace 652 which it exports. Inamespace is used to enumerate all the objects that one virtual memory manager handles, regardless of whether they have also been registered in the common Namespace. FIG. 4 illustrates the VMM interfaces as containing particular methods. IVMSpace contains the methods Query, Add, Release, Reserve, Delete, Map, Protect, CacheControl, QueryVM, CreateShadow. IVMMap contains the methods Query, Add, Release, Read, Write, Share, Clone, QueryAccess, GetSize. IVMView contains the methods Query, Add, Release, SwitchTo, SetMapping, Fault, GetMapping. IVMFactory contains the methods or constructors CreateVMView, CreateVMSpace, CreateVMMappingFromFile, CreateVMMappingFromZero. IUnknown contains the methods Query, Add, Release. FIG. 5 illustrates the internal object architecture employed in a preferred embodiment of the invention. The object has a virtual table (V-table) 510 and a state 520. An instance pointer 530 points to the object. The state 520 can include, for example, the page table register contents, the IUnknown reference count and pointer values. The pointers of an object will be discussed below with reference to FIG. 7. FIG. 5, more than one object may point to the same interface. Of course, it is to be expected that different objects have their own unique interfaces in many instances. For any application calling the object, the object's interface provides a complete list of the processes or methods supported by the object. FIG. 6 corresponds to FIG. 5 and illustrates the object architecture of the VMView object of the VMM (virtual memory manager). In addition to the three universal IUnknown processes of query, add and release, VMView further includes the processes of fault and switch to. The “fault” process will be discussed below with reference to FIG. 10 while the “switch to” process of VMView will be discussed below with reference to FIG. 12. FIG. 7 illustrates a preferred embodiment of the Virtual Memory Manager (VMM). The VMSpace is implemented as a sequence of regions connected by a skip-list of the type well-known in the art. Each region contains a mapping, a copy mapping (for copy-on-write), a number of page lists for physical memory pages, and a set of attributes. Permanent attributes are kept in the region; any transient state is part of the page list. The VMSpace also exports a VMMap interface so that it can be directly mapped into other address spaces. FIG. 7 illustrates mappings by VMMap of various regions of VMSpace to other objects, as will be discussed in more detail below. A VMSpace is 64 bits wide in the preferred embodiment. FIG. 7, different threads 710, 715 can contain pointers pointing to the same VMView object 720. The VMView object contains pointers pointing to a page of PTEs (page table entries) 725 and to a VMSpace object 730. The VMSpace object 730 points to (defines) Region1, Region2 and Region3, corresponding to different non-contiguous memory regions linked by the skip-list. These regions are mapped to other objects in the manner illustrated in the example of FIG. 7 by pointers provided by the VMMap interface of VMSpace. Region1 is reserved (no writing permitted) and points to an empty space 735 (labelled Empty). Region2 has one pointer to a VMMap object 740 corresponding to a region in memory containing all zeroes, which is labelled ZeroVMMap. Region2 has another pointer to a page list 745. The page list 745 points to a memory 750 having allocated memory spaces in which writing is permitted. Region3 has one pointer to a VMMap object 755 which is an implementation of VMMap for mapping files and is labelled FileVMMap. The FileVMMap has a pointer pointing to a file 760. Region3 has another pointer pointing to a VMSpace object 765 (which is different from the VMSpace object 730 discussed above). The connection through Region3 between the two VMSpace objects 730, 765 supports a copy process. Region3 has yet another pointer pointing to a PageList 770. The PageList 770 has a pointer pointing to a second PageList 775. The second PageList 775 points to a Memory object 780. The linking of the two successive PageLists supports a copy-on-write function. In summary, the VMMap object can map a region to another VMMap object, examples of which are illustrated in FIG. 7 such as the pointer from Region3 to File VMMap 755 and the pointer from Region2 to Zero VMMap 740. The mapping can be to a different portion of the VMMap object itself rather than another VMMap object. The VMMap object can map to the ZeroMap object providing zero-filled physical pages, as illustrated in FIG. 7 by the pointer to the ZeroMap object 740. The VMMap object can map a region to a VMSpace object, as illustrated by the pointer from Region3 to VMSpace 765. The VMMap object can map a region to a file, as illustrated by the pointers from Region3 to the File VMMap 755 and from thence to File 760. This may include the case of the “system pager” which handles the traditional paging file. Finally, the VMMap object can map a region to a mapping filter (“CloneMap”) which, for example, restricts the protections allowed of a mapping, as illustrated by the pointer from Region3 to CloneMap. A PageList lists what pages have been called by the object. This is useful in case this information is forgotten by the PTE, for example. The state of an object, such as the virtual memory object of FIG. 7, consists of the pointer values of the various pointers in the object (such as the pointers illustrated in FIG. 7). FIG. 8 illustrates the Load VMM (load virtual memory manager) process. The first step (block 810 of FIG. 8) is to install the VMM Fault Handler method. The last step (block 830) is to register the VMM constructors, which are part of the VMFactory interface. This step is carried out by creating an object of the IVMFactory type and registering it into the NameSpace.. FIG. 9 illustrates how a virtual memory fault is handled. The first step is to save the state of the object or thread that was running at the time the fault or trap was taken (block 910 of FIG. 9). Next, the VMM Fault Handler is called (block 920). Then, the state of the object is restored (block 930). FIG. 10 illustrates the operation of the VMM Fault Handler. The first step (block 1010 of FIG. 10) is to call IVMView::Fault. The next step is to determine whether IVMView::Fault can provide a VM mapping (block 1020). If so (“YES” branch of block 1020), the page table entry is loaded (block 1030). Otherwise (“NO” branch of block 1020), an exception is taken (block 1040) and an exception handler is called (block 1050). FIG. 11 illustrates how a VM fault is taken. The first step (block 1110 of FIG. 11) is to determine whether the VM fault is due to an error. If so (“YES” branch of block 1110), then an exception is taken (block 1120). Otherwise (“NO” branch of block 1110), a determination is made whether the VM fault is due to a memory allocation postponement, sometimes referred to as “lazy memory allocation” (block 1130 of FIG. 11). Lazy memory allocation is a feature that can be implemented to guard against premature allocation of memory otherwise caused by early requests by an application. The determination of whether the VM fault is due to lazy memory allocation is made by determining whether there is any reference to the object in the PageList. If the fault was due to lazy memory allocation (“YES” branch of block 1130), then VMSpace is called to perform the memory allocation (block 1140 of FIG. 11). Otherwise (“NO” branch of block 1130), a determination is made whether the VM fault was due to a copy-on-write process (block 1150). This determination is made by asking whether the current PageList points to another PageList (as discussed above with reference to FIG. 7). If not (“NO” branch of block 1150), the reference in PageList is copied to the page table or PTE (block 1160). Otherwise (“YES” branch of block 1150), the pointer to the other PageList is taken (block 1170 of FIG. 11). This entails allocating a new page, copying the content of the old page to the new page, and then entering the mapping for the new page in the PTEs. FIG. 12 illustrates the operation of the context switch process. First, the Scheduler (shown in FIG. 1) decides to perform a context switch (block 1210 of FIG. 12). This decision may be occasioned, for example, by a thread running up to a predetermined time limit. As a result, the Scheduler selects a new thread to replace the currently-running thread (block 1212 of FIG. 12). In a preferred embodiment, the next step is to inspect the views of memory provided by IVMView of the current and new threads (block 1214) and determine whether they are different (block 1216). If so (“YES” branch of block 1216), IVMView::SwitchTo is called (block 1218). Otherwise (“NO” branch of block 1216), the system returns to the new thread (block 1220) without altering the contents of the page directory register 400 of FIG. 2. FIG. 13 illustrates the SwitchTo process, consisting of the step of loading the page directory register 400 of FIG. 2 with the new page directory value. FIG. 14 illustrates the process for unloading the virtual memory manager (VMMUnload). The first step begins whenever the last thread of the last address space using virtual memory requests termination (block 1410 of FIG. 14). The next step is to determine whether the reference count is zero (block 1420). If so (“YES” branch of block 1420), a choice (block 1430) may be made whether to terminate the virtual memory (block 1432) or to mark the VM object as “cached” (block 1434). In the preferred embodiment, the virtual memory manager is terminated (block 1432). Otherwise (“NO” branch of block 1420), the reference is released, which decrements the reference count by one (block 1440). FIG. 15 illustrates the page fault handling process. The first step is to call IVMView::Fault upon the occurrence of a page fault (block 1510). IVMView::Fault calls VMMap::Share (block 1520) which in turn calls VMSpace::CacheControl (block 1530), which in turn calls VMMap::Read (block 1540). VMMap::Read calls File::Read (block 1550), which returns data—such as the content of a file, for example—(block 1560 of FIG. 15). Finally, VMSpace adds the returned data to PageList (block 1570). FIG. 16 illustrates how a constructor creates a thread. First, VMFactory creates a VMSpace, and VMSpace creates an address space (block 1610). Next, VMFactory creates a VMMap and VMMap maps an object into the address space (block 1620). Then, VMFactory creates a VMView and VMView creates a view of the address space created in the previous step (block 1630). Finally, the scheduler creates a thread associated with the view created in the previous step (block 1640). FIG. 17 illustrates how multiple views of the same memory space are provided for multiple threads. In the example of FIG. 17, two different threads, THREAD1 and THREAD 2 are directed by the PTE to two different views, VMView1 and VMView2, respectively, of the same memory space, VMSPACE1 through the PTE. For THREAD1, VMSPACE1 has a pointer to VMMap1 which points to File1. For THREAD2, VMSPACE1 has a pointer to VMMap2 which points to File2. FIG. 18 illustrates possible results of the implementation of FIG. 17. In FIG. 17, the view of memory by THREAD1 may make the memory appear smaller than its actual physical size, which the view of THREAD2 may make the memory appear to have a wider address field than that of the actual physical memory. For example, the actual physical memory may have an address space that is 32 bits wide while it appears to be 64 bits wide in the view of memory provided to THREAD2. On the other hand, the physical memory address space may be 64 bits wide while it appears to be only 32 bits wide in the view provided to THREAD1. In a more complex case, the address space widths of the objects VMView (“THREAD1”) and VMSpace (“THREAD2”) and of the physical memory may all differ from one another, being in one example 32 bits, 64 bits and 36 bits, respectively. The address space width in VMSpace may be chosen without regard to the address space widths of the virtual memory and the physical memory.). An IPC system is needed if applications are to be run in separate address spaces. Otherwise the applications can not talk to each other or to system services. An IPC system allows: Communication between address spaces within a machine. Communication between applications in different machines in a distributed environment. Graceful termination and cleanup of applications even within one address space. FIG. 1B. The loader can load the Loadable IPC Manager at any time based upon need. The Loadable IPC Manager can also be unloaded whenever it is no longer required by any applications currently running. FIG. 19 illustrates the basic components of the Loadable IPC Manager. A trap component 1910 consists of a program to install the method IPC Trap Handler 1912, which is called whenever the system recognizes a need within the currently-running thread to communicate with another thread or a need to communicate with a thread in another machine. A copy component 1930 can be implemented with either a simple “copy” function or virtual memory or shared memory. FIG. 20 illustrates the operation of the Loadable IPC Manager, which may have the file name IPC.EXE in a preferred implementation. The first step is to load the Loadable IPC Manager (block 2010). The next step is to install the IPC Trap Handler (block 2020). Finally, the IPC constructors are registered in NameSpace (block 2030). FIG. 21 illustrates the structure of the interface between the loadable IPC and threads that use it. In the exemplary case of two threads 2110, 2120 which use a particular Loadable IPC Manager 2130, each thread has its own pointer 2110 a, 2120 a pointing to the Loadable IPC Manager 2130. The Loadable IPC Manager 2130 has interfaces for the following methods: Query Interface 2140, Add Reference 2150, Release Reference 2160 and IPC Trap Handler 2170. As will be discussed later in this specification, each one of these methods and interfaces is replaceable. FIG. 22 illustrates the intercommunication provided by the Loadable IPC Manager between threads in different address spaces. One thread (THREAD1) resides in a first address space 2210, and has a pointer to a loadable IPC Manager 2220. At some point in the running of THREAD1, it causes the Loadable IPC Manager to provide communication with another thread (THREAD2) in another address space 2230. Both THREAD1 and THREAD2 have a pointer to the Loadable IPC Manager 2220. The Loadable IPC Manager provides the requisite communication between THREAD1 and THREAD2. For example, THREAD1 may need to increment a counter controlled by THREAD2 in the other address space. The magnitude of the increment may need to be communicated to THREAD2 and the value of the count after incrementation may need to be returned to THREAD1, in some cases. The Loadable IPC Manager handles both of these communications, thus providing two-way communication between THREAD1 and THREAD2 as illustrated in FIG. 22.. FIG. 23 illustrates how an IPC trap is handled. First, the state of the currently running thread (THREAD1) is saved (block 2310). Then, a call is made (block 2320) to the IPC Trap Handler which (unlike the Loadable IPC Manager stored outside of the operating system kernel of FIG. 1) resides within the operating system kernel. FIG. 24A illustrates the operation of the IPC Trap Handler. First is the occurrence of an IPC trap (block 2410). The next step is to copy the arguments of the currently running thread (block 2420). These arguments may be, for example, the identity of a counter in another address space. The thread traps into the loadable IPC system so that its VMView is changed to the VMView that points to the new address space. (block 2430). The thread continues running in the new address space where it invokes an object or method that can produce desired information or data such as a new incremented counter stored in a register (block 2440). The next step is to return the values of the new data from the thread (block 2450). Then, the thread switches back to the original VMView (block 2460). In contrast, conventional IPC systems (which were not loadable as the IPC of the present invention) typically did not move the thread from one address space to the other. Instead, the desired information in the second address space was obtained by selecting and running a different thread in that second address space. In contrast, the preferred embodiment of the loadable IPC of the invention uses a single thread and moves between among address spaces by changing its VMView. However, an alternative embodiment of the loadable IPC of the present invention could be implemented using the conventional technique employing different threads.. FIG. 24B illustrates how instances of these interfaces are related. In the drawing, two threads belong to two different applications. Thread-B was given access to the endpoint EndP-1. FIG. 24B, Thread-A creates an EndPoint EndP-1, passing in a Signature Signature-1 and a virtual address Object-A. The EndPoint is entered in the ExportTable ETable-A of the thread's IPCSpace-A. A reference is taken on the thread's VMSpace-A (not shown). Thread-A now registers the EndPoint in the NameSpace. One reference is taken on the object and one on the EndPoint, to signify that the object is exported and visible in the NameSpace. FIG. 24B, Thread-B can either look up Object-A in the NameSpace, or invoke a method on some other object in VMSpace-A that returns Object-A as result. In either case, LIS.EXE finds that EndP-1 is the associated EndPoint, and enters it in ITable-B, the ImportTable for Thread-B's IPCSpace-B. A Proxy for Object-A is created in Thread-B's VMSpace-B (not shown). In order to create the proxy, Signature-1 is used to find the size of the necessary VTable, and for the loading (or memory mapping) of the proxy's marshalling methods. The proxy holds a copy of the EndPoint's IP. FIG. 24C illustrates the structure involved in the foregoing operations of the LIS. In the example of FIG. 24C, a first object, Object-A, resides in a first address space, Address Space 2, and a proxy object, Proxy-A, has been inserted by the LIS into a second address space, Address Space 1. LIS.EXE (corresponding to the LIS.EXE illustrated in FIG. 24B) provides communication between the the two address spaces. Proxy-A has an import index of “3” to the third entry in the import table 2472 in LIS.EXE. The import table 2472 has a pointer to an endpoint (EndPoint-1) which is exported by Address Space 2. Endpoint-1 includes the type signature and address of (i.e., a pointer to) Object-A in Address Space A. The export table for Address Space 2 in LIS.EXE (not illustrated) would have its own pointer to the same endpoint.. FIG. 24C illustrates Object-A as including a V-Table pointer and a method table, in which the second method points to the implementation code of Method 2. Endpoint-1 contains an “object address” field containing the address (“0X123) of Object-A (i.e., the pointer to Object-A) and a signature (“iii”) for Method 2 in Object-A's method table.. FIG. 25 illustrates the interface of the mutation object, IMutate, which includes the following methods: Query Interface 2510, Add Reference 2520, Release Reference 2530, MutateVTable 2540 and MutateObject 2560. The operation of the Query Interface, Add Reference and Release Reference interfaces 2510, 2520, 2530 have been described above in this specification. FIG. 26, in which the MutateObject method changes the interface pointer 2610 for method_i in the Object Interface 2620 from Implementation_A to Implementation_B. FIG. 27 illustrates an example of the operation of the MutateVTable method. In this example, the object being altered by the MutateObject method has a VTable 2710 which can point to one of two interfaces 2720, 2730. The two interfaces 2720, 2730 can list different methods or, if the same method is listed in both interfaces 2720, 2730, then their interface pointers 2750 for the corresponding method can point to different implementations, as in the case of Method_A , or to the same implementation, as in the case of Method_C. The synchronization mechanisms suitable for implementing mutation can be divided into three groups:. Transactional: Roll back the workers that are affected by mutation. Mutators and workers operate on an object transactionally and can be aborted when necessary.. FIG. 28 illustrates how object mutation is synchronized by mutual exclusion, which is the simplest synchronization embodiment. When the Mutate Object is called, the first step is to prevent any threads from accessing the object or initiating new activity with the object (block 2810). Then a determination is made whether any threads or worker threads that were already running with or within the object are still running (block 2820). If so (“YES” branch of block 2820), then the object mutation process is postponed until such threads finish running with the object. If no worker threads are running (“NO” branch of block 2820), then the Mutate Object is allowed to mutate the object (block 2830). This step may be reached immediately or reached only after waiting. After the object has been mutated, threads again are permitted to access the object (block 2840).. FIG. 29 illustrates how object mutation is synchronized by transactional synchronization. The first two steps of this method (FIG. 29, blocks 2910, 2920) are identical to that of FIG. 28 (blocks 2810, 2820). What is different is that if there are worker threads still running (YES branch of block 2920), instead of waiting, the worker threads still running are rolled back to their starting points (block 2930) and the object mutation is performed (block 2935). The threads are then reactivated (block 2940) and access by other threads to the object is re-enabled (block 2950). One limitation of transactional synchronization is that rolling back the threads entails a delay. Synchronization by swizzling ameliorates such a delay because it does not require rolling back any running threads. FIG. 30A illustrates how synchronization by swizzling operates. The first two steps (blocks 3010, 3120) are identical with the steps of blocks 2910 and 2920 of FIG. 29. What is different in FIG. 30A is that if there are threads still running (“YES” branch of block 3020), then the still-running threads are suspended temporarily (block 3030) and their states are modified to reflect the mutation of the object (block 3040). At about the same time, the object is mutated (3050). Then, the suspended threads are re-activated (block 3060) so that they continue their operations at the points at which they were suspended, except that their subsequent operations are carried out in the mutated version of the object. Access by other threads to the object is re-enabled at about this time (block 3070).. FIG. 30B illustrates one example of structure involved in the process of FIG. 30A as applied to a particular thread. The thread has a stack 3080. A stack pointer 3082 points to a Condition Wait function 3080 a on the stack 3080 at which the thread happens to be blocked in the present example. The next item on the stack 3080 is a clean point state 3080 b, followed by a clean point 3080 c, followed by data or integers 3080 d, which in turn is followed by a pointer 3080 e to the “old” object 3084. The clean point 3080 b points to a particular method 3086 of the object 3082. In this example, the method 3086 states “add 1,2” and “call condition wait” which is a call to the Condition Wait function 3080 a. The goal of the mutation process in this example is to replace the “old” object 3084 a “new” object 3088. The process identifies the stack pointer 3082. Next, the process rolls back the stack 3080 to find the bottom of the stack, which rolls back the thread. The stack 3080 is changed in place to the configuration illustrated in FIG. 30C by substituting a new Clean Point State 3080 b′, a new Clean Point 3080 c′ and a new object pointer 3080 e′ for the old ones in the stack 3080. The new Clean Point 3080 c′ points to a particular method 3089 of the new object 3086 while the new object pointer 3080 e points to the new object 3080 itself. The new method, for example, states “subtract 2,2”. One advantage of object mutation is that it enables significant changes to be made in the operating system in a manner that is transparent to the application or driver that is running. This advantage is apparent in considering various applications of object mutation. FIG. 31 illustrates an application of object mutation in carrying out object interposition. In the “BEFORE” portion of FIG. 31, an object 3110 is copied to produce a copied version 3120 of the object 3110 (in the “AFTER” portion of FIG. 31) and is mutated to produce a mutated object 3130 (also in the “AFTER” portion of FIG. 31). The copied object 3120 is preferably identical to the original object 3110. The mutated object 3130 is different in that the interface points to an implementation of an interpose method, while the pointer register 3140 of the object is changed to point to the copied object 3120.. FIG. 32 illustrates an application of object mutation in carrying out dynamic software upgrading. In the example illustrated in FIG. 32, a file manager object 3210 uses a disk driver to manage a disk drive memory, and the operating system has available two different versions 3220, 3230 of a disk driver. If the file manager object 3210 is using the low-speed disk driver 3220 and needs to upgrade to the high speed driver 3230, the MutateObject 3240 changes the object pointer of the file manager object 3210 from the low speed driver 3220 to the high speed driver 3230. Since no objects were exchanged or removed, this upgrade is transparent to the application that is running. FIG. 33 illustrates an application of object mutation in carrying out run-time code generation. In the example of FIG. 33, an object 3310 provides, in its interface 3320, a method or algorithm of dividing one number, x, by another number, y. Two versions 3330, 3340 of the algorithm are available in the object. The simplest version 3330 involves multiplying the reciprocal of y by x. The more sophisticated version 3340 involves explicitly carrying out the division of x by y. This latter version is suitable for repeated divisions of different dividends by a common divisor which can change from time to time. In such a case, it is desirable to mutate the object by moving the interface pointer 3335 from the simple version 3330 to the sophisticated version 3340. As a result, a different object code is provided to carry out the division operation. This mutation is carried out dynamically as need at any point during run time. In the sophisticated version 3340 of the algorithm, the technique of retaining the same divisor (e.g., 2) over successive division operations is typical of a class of techniques known as “constant folding”while the technique of retaining the same type of operator (e.g., the division operator) over successive operations is typical of a class of techniques known as “inlining”. The sophisticated version of the algorithm is applied as long as certain assumptions or parameters are true, namely that (1) each operation is a division of the operand and (2) the divisor is 2. Once these assumptions are no longer true, object mutation is applied to replace the current version of the algorithm (e.g, from the sophisticated version). For example, if the assumption that the divisor is 2 over successive division operations no longer applies, object mutation is invoked to return to the simpler version of the algorithm which makes no assumptions regarding the divisor. Preferably, the implementations of an object contain already-compiled machine or object code for carrying out the corresponding method. However, in an alternative embodiment, the implementation is represented only by source code, to save space for example, and it is compiled by a compiler 3350 only as needed. FIG. 34 illustrates an application of object mutation in carrying out object mobility. If the object that is the target of a method is in a different machine or a different address space, and thus can not be called directly, a proxy is interposed for delegation. Instead of calling the actual object, the client will call the (local) proxy object. The proxy marshals the parameters into a message and sends it where the actual object is located. There the message is received and dispatched to a stub object. The stub unmarshals the parameters and calls the actual method. On the return path the stub similarly marshals any return values and sends them in a message back to the proxy that in turn unmarshals and returns. Aside from taking longer to execute, the remote object call through a proxy looks exactly the same as a local call directly to the actual object. Not only is the implementation of the server transparent to the client, but the location as well. In the “before” portion of FIG. 31, threads 3110 and 3120 in Address Space 1 access an object 3130 in Address Space 2 via a proxy object 3140 in Address Space 1. That is, the threads 3110, 3120 in Address Space 1 point to a proxy object 3140 in their own address space, and the proxy object 3140 points to an object in Address Space 2. A thread 3150 in Address Space 2 points directly to the object 3130 since both the object 3130 and the thread 3150 reside in the same address space.. FIG. 35 illustrates how a thread 3510 in Address Space 1 calling upon an object 3520 in Address Space 1 (“BEFORE” portion of FIG. 35) can be diverted to an object 3530 in Address Space 2 by mutating the object 3520 into a proxy with a pointer to the object 3530 in Address Space 2. The object 3520 in Address Space 1 has a pointer register 3560 which, as a result of the object mutation, is loaded with the address of the object 3530 in Address Space 2. Address Space 1 and Address Space 2 may each reside in different machines, in which case the object 3530 in Address Space 2 must contain information identifying the other machine, as well as the memory location in the other machine. FIG. 36 illustrates one example of a mutatable structure of the Virtual Memory Manager (VMM). For each method in the interface, namely IVMSpace, IVMMap and IVMView, there are two alternatives. For each of these alternative, there is a set of corresponding implementations. Each alternative points to the corresponding implementation. By mutating the VTable pointer (using MutateVTable), any one of the three methods may be changed between its two alternative versions. Moreover, by changing the interface pointers from the methods (using MutateObject), different implementations may be chosen for each method or for some methods or for one method only.). FIG. 37 illustrates a method in accordance with a preferred programming model of the invention. An application thread currently running finds that it needs a particular object at some point. The application thread presents to NameSpace the name of the desired object (block 3710 of FIG. 37). In response, NameSpace returns the IUnknown pointer of the desired object (block 3720). The application thread then accesses the desired object in memory using the object's IUnknown pointer to find the correct memory location (block 3730). The application thread may need the object because it needs to use a method provided by that object. In such a case, the next step is for the application thread to call the QueryInterface method of the object and specify the Interface corresponding to the desired method (block 3740). For example, the application thread may need to perform a copy method provided by the object, in which case the thread may ask for an ICopy interface. A determination is first made whether the object has the desired interface (block 3750). If not, an exception is taken (NO branch of block 3750). Otherwise, the object's QueryInterface method returns a pointer to the desired interface (block 3760). The application thread then invokes the corresponding interface and implementation via the pointer to the new interface (block 3770). FIG. 38 illustrates operations carried out under control of NameSpace in support of the method illustrated in FIG. 37. The steps illustrated in FIG. 38 are generally transparent to the application thread. First, NameSpace receives the application thread's request to look up the name of the desired object (block 3810). NameSpace determines whether that name is already registered in NameSpace (block 3820). If it is already registered, then the desired object is already present in working memory and an IUnknown pointer to the object is available (YES branch of block 3820). In this case, the next step is to return the IUnknown pointer to the application thread (block 3830). Otherwise (NO branch of block 3820), the desired object has never been loaded into working memory. In this case, NameSpace requests the Loader to load the object into working memory (block 3840). The Loader, in most cases, will find the desired object on disk. If it is not found on disk, the Loader may be allowed to search other sources for the object, such as memories accessible on a network (local or global) for example. The Loader loads the object into working memory (block 3850). NameSpace registers the object's name (block 3860) and returns an IUnknown pointer specifying the object's location in memory to the application thread (block 3830).. FIG. 39 illustrates how a previously unused object stored outside of working memory (e.g., on disk) is loaded into working memory. It should be understood that the references made here to “working memory” include any other memory that may be used to supplement working memory in cases where actual working memory space is limited. For example, in some cases programs to be loaded into working memory are loaded instead into “cache” locations on the disk which are treated as part of the working memory. Before the object is loaded into working memory, space must be allocated in the working memory for the object's image. The image will contain one or more VTables, Interfaces and Implementations (block 3910 of FIG. 39). The image will also specify an EntryPoint, which is the constructor of the object. Once the image is relocated and loaded in main memory, the constructor is invoked (block 3920). Such a constructor is automatically accomodated in the C++ programming language. In a preferred embodiment, the invention is carried out in C++. The constructor allocates dynamic memory to hold the new object's state. The object's state is initialized, including the object's VTable and Interface pointers (block 3940). An IUnknown pointer to the object is produced specifying the memory location of the object (block 3950). This is the pointer that NameSpace returns to the application thread in the operation illustrated in FIGS. 37 and 38. FIG. 40 illustrates how the method of the programming model illustrated in FIG. 37 improves plug-and-play technology. When a device is plugged into a port of the computer (block 4010 of FIG. 40), it is conventional for the system to immediately load the driver for that device or to halt operations while it tells the user that a driver cannot be found. While the automatic nature of plug-and-play technology is convenient, such interruptions are time-consuming. Even if the driver is found and loaded automatically, system time is consumed in such an operation and delays operations being performed by the user. Such delays may be unnecessary, particularly if the user is not going to use the plugged-in device immediately. In the invention, such an automatic loading operation of a plug-and-play driver does not take place, at least in the preferred embodiment. The only requirement is that at some point before the plugged-in device is called for by an application, the driver for the device is made available either on the disk or on another accessible source such as a network (block 4020 of FIG. 40). Meanwhile, the system performs other tasks until an application makes a call for the plugged-in device (block 4030). Once an application calls for the device, the name of the device driver is handed to NameSpace (block 4040), and the process of FIG. 37 is carried out. The name may be handed to NameSpace by the application itself, particularly if the application was written for the programming model of FIG. 37. Otherwise, another utility may be provided to determine the name of the driver for the device, although this latter mode is not preferable.. FIG. 41 illustrates a tutorial example of an image containing an instruction in its text section to call the function CurrentTime( ). CurrentTime is a symbol. In the example of FIG. 41, an instruction invoking the function CurrentTime is represented in machine language as 0X33 (“call”), 0X99 (the four-byte address of CurrentTime). In a simple system, the compiler puts this address into the instructions in the text section of the image. In a more complex system in which the compiler can support a dynamically linked (shared) library, the compiler is capable of leaving a 0 in the text section instead of the address. In this case, which is illustrated in FIG. 41, the compiler puts a reminder or a “relocation” entry in the relocation section or table pointing to the 0 in the text section as the place to fix the value that comes from the symbol “CurrentTime”. The relocation table is a reminder of what must change before being able to execute the image. A simple minded tool set would not be able to produce anything more than an object in which the text section has a defined address for “CurrentTime”. Such a tool set at load time would want to get rid of the relocation table and find out what the implementation for CurrentTime is, which is someplace else in the image, and would want to put the address of that in the text section. The end of result would be a non-relocatable image. The present invention overcomes such problems. A conventional process of constructing an executable image from separate files is illustrated by an example shown in FIGS. 41 and 42. A C-language source file called FOO.C contains a statement T=CurrentTime( ). The compiler compiles this to make an object file FOO.OBJ having a text section containing instructions including “call” (0X33) and a zero (0) (instead of the address of the symbol “CurrentTime”). FOO.OBJ also has a relocation section or table and a symbol section. Since an implementation for CurrentTime has not been provided thus far, the compiler produces the symbol section of FOO.OBJ with a location “undefined” for the symbol CurrentTime, indicating that its location is to be determined later. The relocation table has a pointer to CurrentTime in the symbol table and to the 0 in the text section. This is pending work for the linker. In the present tutorial example, the symbol CurrentTime is defined in another file, namely an object file called KERNEL.OBJ. This definition includes, in this tutorial example, “0X99” as the address of the first instruction of CurrentTime. The linker puts together the different sections of FOO.OBJ and KERNEL.OBJ to produce a single file FOO.EXE, which is an executable image having no pending work for the linker. The new file FOO.EXE. has its own text section including the instructions “0X33” and “0X99”. “0X33” is (in this example) the machine language for “call” and was taken from the text section of FOO.OBJ while “0X99”, address of the first instruction in CurrentTime, was derived from the text section of KERNEL.OBJ. The linker, in linking the objects together, has changed the call for CurrentTime in the text section to 0X99, since that is where KERNEL.OBJ specifies the location of CurrentTime. Thus, the linker looks at all undefined symbols and finds their locations and definitions or instructions. FIG. 43. Referring to FIG. 43, in implementing shared libraries, the linker is provided at link time with more refined information that, instead of “KERNEL.OBJ”refers to a file “KERNEL.LIB”. The information in KERNEL.LIB, in the present example, indicates that the symbol “CurrentTime” is in the third entry of an export table of a shared library called KERNEL.DLL. The linker copies this information to an import table of FOO.EXE. The relocation table links this entry in the import table to the undefined (0) entry in the text section.. Referring now to FIG. 44, the munger refers to a text (ascii) file, e.g., KERNEL.DEF, which specifies the symbols to be imported from KERNEL.DLL. Files such as KERNEL.DEF have already been produced for programs running on existing machines as the precursors to the KERNEL.LIB files discussed earlier in this specification with reference to FIG. 43. KERNEL.DEF has a particular record (record 0) specifing the name (KERNEL.DLL), and a unique ID (UUID), e.g.,0X123 . . . 9. (There is a conventional tool to generate the UUID.) The munger program uses KERNEL.DEF to access information to combine with FOO.OBJ to produce FOO.EXE with an import table, without requiring the compiler to support import tables, export tables or shared libraries. Record 0 of KERNEL.DEF lists exports from KERNEL.DLL (for example, CurrentTime @1, Last @3) not listed in FOO.OBJ that must be included as entries in an import table in FOO.EXE. In FIG. 44, record 0 of KERNEL.DEF contains the information that “export=CurrentTime @1”. The munger program looks at KERNEL.DEF and sees “export=CurrentTime @1”. The munger program sees in the relocation table of FOO.OBJ that FOO.OBJ calls for CurrentTime which is undefined in FOO.OBJ (or it may bound to a fake object and needs to be redefined). The munger program does the following for that relocation: The relocation was of the type “call”, and the munger changes the type to “dll-call”, which will be described below. The munger must keep the offset, but it doesn't need to keep the symbol as the symbol is not as useful in the preferred embodiment. This is because the preferred embodiment support linking by-ordinal, not linking by name and the symbol table is therefore superfluous by this point. FIG. 43 lacks an import table because the compiler that produced it did not support import or export tables (in the present example). For an embedded system with very minimal compiler support, the invention decreases the time to market because there is no need to reform such a compiler. FIG. 45, KERNEL.DLL must have an export table. The export table is the one that looks at both the ordinals and the names. Where the system compiler does not support import/export tables, the munger program constructs the export table as follows: It builds an array of ordinals. According to record 0 of KERNEL.DEF, the symbol “CurrentTime” has ordinal number 1 while the symbol “last” has ordinal number 3. The munger counts ordinal number 1 as the first export table entry and therefore writes the location (“X99”) of CurrentTime in KERNEL.LIB as the second entry in the export table. In an alternative embodiment of the invention, the munger knows the location (“X99”) of CurrentTime because it is stated in record 0 of KERNEL.DEF In the preferred embodiment, however, the munger finds this location by inspecting KERNEL.DLL. The munger counts ordinal number 3 as the fourth export table entry and therefore writes the location (“X6”) of the symbol “Last” as the fourth entry in the export table. The first and second export table entries are left undefined in this example. The munger must put the definition of the symbol “CurrentTime”namely X99, into the export table as the second entry (ordinal 1) because, otherwise, the tool will fail. The symbol section of KERNEL.DLL defines the name “CurrentTime” with a pointer to the appropriate location in the text section (i.e., X99), and the munger copies this pointer (X99) to the corresponding entry (ordinal 1) in the new export table. What goes into the relocation section of any image such as FOO.EXE or KERNEL.DLL, is machine dependent. FIG. 45 illustrates the object KERNEL.OBJ and the new export section constructed by the munger. The munger combines the two together and thereby produces a new object, KERNEL.DLL which has a new export section, in which there are four entries: the first entry in the illustrated example is void (“ffff”), the next entry corresponds to ordinal 1 and is “X99” which is the defined symbol “CurrentTime”and a similar entry corresponding to ordinal 3 for the symbol “last”. In resolving the unknown symbols and constructing the export table, the munger looked up the values of the exported symbols, and put them in the export section at the appropriate places (ordinals) as instructed by the definition file KERNEL.DEF. Using the UUID permits the system to manage an array of multiples of export sections. In the multiple export tables illustrated in FIG. 45, the first entry is the UUID (123.99) and a number 4 which equals the number of ordinals, and then the four entries. A second export section has a UUID (456.999) and six as the number of ordinals. Thus, there can be different versions of the export table designated by different UUID's. Two versions of the dll within the same dll are provided by having two tables. This is done by giving the two versions of the dll two different UUID's. The loader at load time looks for the table with the correct UUID. FIG. 45, the call for CurrentTime involves fetching the address to jump to from a specific entry in the import section, then jumping to that address. This is an indirect call. In an alternative implementation, the entries in the import section could be themselves instructions to jump to the DLL addresses. In this case the instructions in the image are direct calls, and the import section acts as a redirector of sorts. Both implementations obtain the same result: the call instruction in the executable image (direct or indirect that it might be) can be re-directed simply by changing the import section entries. exporte). FIGS. 46A and B illustrate the jump short-cutting process as applied to instructions in the text section of an image. In FIG. 46A, the image FOO.EXE imports a symbol from the shared library file LIBRARY.DLL by first jumping from the call in the text section to a location (0X66) in the import table (JUMP 1) and then from 0X66 in the import section to 0X99 in LIBRARY.DLL (JUMP 2). The information retrieved is then returned to the text section (JUMP 3). Such indirect jumping has already been described with reference to FIGS. 43-45. In the event FOO.EXE is to run on a system having no virtual memory, the linker bypasses the import table by changing the call in the text section to 0X99 and modifying the jump instruction to a direct jump instruction. The result is illustrated in FIG. 46B, showing the direct jumps from the text section of FOO.EXE to LIBRARY.DLL and back again. Jump short-cutting is also applicable to data references. In FIG. 47A, an executable, FOO.EXE, has in its text section an instruction to move, the destination being a location 77 in the import table of FOO.EXE. Location 77 has a pointer to the real destination, namely 1010 in a data section. As illustrated in FIG. 47B, by changing the move instruction to have as its destination 1010 in the data section and modifying the move instruction to a direct move, the import table is bypassed. FIG. 48, after load time (block 4810 of FIG. 48), compaction is performed (block 4810 of FIG. 48). Compaction performed at or after load time is so thorough that the text and data sections may be merged (block 4830). A prior art linker performs compaction at link time. One embodiment of the invention also includes jump short-cutting (block 4840). Jump short-cutting eliminates the import section (block 4850) while compaction eliminates padding between images. FIG. 49. At load time, the post-link time munger determines from the relocation table of the linked file whether an indirect jump is required for a particular call (block 4910 of FIG. 49). If so, it adds an import table to the linked file (block 4920), changes the direct jump to an indirect jump to the import table (block 4930) and adds a jump (block 4940) from the import table to the final destination (e.g., an export table in a shared library file). The post-link time linker further locates the boundaries (block 4950) between sucessive sections of the linked file (e.g., the boundary between the text and symbol sections) and inserts padding at the end of each section so as to bring these boundaries in alignment with the page boundaries of the memory (block 4960). FIG. 44 in which three files (FOO.OBJ, KERNEL.DLL. and KERNEL.DEF) are synthesized into a single image (FOO.EXE), the code synthesis feature of the invention starts with the single image (e.g., FOO.EXE) and extracts code therein to form a separate dll file (e.g., KERNEL.DLL), a separate object file (FOO.OBJ) and so on. Appendix A:: creation and destruction of endpoints linking of endpoints (export/import) remote method invocation. We do not specify these, they are specific of the particular style of IPC. For example, there might be a special value in one of the machine registers that indicates what operation is desired. Appendix B:. Appendix C:. Appendix D: The following is a header file for the basic features of MMLite. This file contains all the basic interfaces and services of the MMLite “kernel”including the NameSpace. The NameSpace is the one that implements the on-demand loading programming paradigm. The Register( ) method is used to add objects to the namespace and the. As for additional interfaces, the VM manager uses the IVTLB interface. The primitives defined in mmbase.h (for Mutex_* and Condition_*, and for constraints) are sufficient in the general case. Appendix E: The following is a file for reading the foregoing header files of Appendices A-D. Explanations are provided with the code.
https://patents.google.com/patent/US6728963B1/en
CC-MAIN-2018-34
refinedweb
11,671
55.13
Introduction Question: What would the 21st century be without YouTube? Answer: Quite boring. Apart from all the funny and interesting videos on there, the main reason that 99% of people visit YouTube is because of the music videos. Today, I will show you how to make a very small YouTube application. The YouTube SDK (Software Development Kit) Before we can jump in with the code, we cannot. Why? Well, we first need to download the YouTube SDK and Google Data API. The reason why I say we need to download this is because, as with all other SDKs, we first must learn how to work with the particular technologies—we cannot just copy and paste code without understanding how they work. Make sense? We can download these here. After you have familiarised yourself with the Google GData API and what it can do and browsed through the samples, you’d have a greater idea of what we will try to accomplish today. Now, some of you might remember that I created a Facebook application or two throughout the years. You’re probably thinking why am I bringing up Facebook here? The answer is: In order for us to be able to communicate with Facebook or any social media platform from any of our programs making use of their platform(s) we must have a valid developer key. YouTube and Google is not much different. In a previous article utilising Google Maps, we also had to have a developer key. This key proves to whomever that this application is valid and not trying to do illegal stuff. This is how the programs get tracked at the end of the day, even any mobile app needs a certain type of developer key. How Do I Get a Google/YouTube Developer Key? You need to have a valid Google account and then navigate to. Here, you can set up a name for your project and get your key. This key must be present in all your programs using this framework, along with the application name you specified here. This ensures that Google can track your program’s calls and usage. Our Project The purpose of today’s little sample is to add a new playlist on your YouTube account and add a video to it. It is actually pretty easy. Let’s get started. Design Not much of a design. Create a new VB Windows Store app and add one button and a list box to your page. Name your objects anything you desire. Add the necessary references. You can find all the needed files at these locations: - C:Program Files (x86)GoogleGoogle YouTube SDK for .NETSamples - C:Program Files (x86)GoogleGoogle Data API SDKRedist Code I hope you have done some reading and browsing through the installed YouTube and Google documentation. If you haven’t, don’t stress because this app is not too complicated…. for a change! Add the needed Namespaces: Imports Google.Apis.Auth.OAuth2 Imports Google.Apis.Services Imports Google.Apis.Upload Imports Google.Apis.Util.Store Imports Google.Apis.YouTube.v3 Imports Google.Apis.YouTube.v3.Data Okay, I went a bit overboard here, but I felt it necessary to show you as much as I can. These namespaces give access to most of YouTube’s functionalities and services. Obviously, to look at each one individually through a magnifying glass is a discussion for another day. Luckily, the complete documentation also gets installed along with the libraries, so the onus is on you to delve through them. Add the following piece of code: Private Async Sub btnGet_Click(sender As Object, _ e As RoutedEventArgs) Handles btnGet.Click Dim ytCred As UserCredential Using stream = New FileStream("client_secrets.json", _ FileMode.Open, FileAccess.Read) ' This OAuth 2.0 access scope allows for ' full read/write access to the ' authenticated user's account. ytCred = Await GoogleWebAuthorizationBroker. _ AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, _ New () {YouTubeService.Scope.Youtube}, "user", _ CancellationToken.None, New FileDataStore(Me.[GetType]().ToString())) End Using Dim ytObj = New YouTubeService(New _ BaseClientService.Initializer() With { _ .HttpClientInitializer = ytCred, _ .ApplicationName = Me.[GetType]().ToString() _ }) ' Create playlist in the authorized user's channel. Dim Playlist = New Playlist() Playlist.Snippet = New PlaylistSnippet() Playlist.Snippet.Title = "HTG_PlayList" Playlist.Snippet.Description = "HTG's Playlist" Playlist.Status = New PlaylistStatus() Playlist.Status.PrivacyStatus = "public" Playlist = Await ytObj.Playlists.Insert(Playlist, _ "snippet,status").ExecuteAsync() ' Add a video to the newly created playlist. Dim PlaylistItem = New PlaylistItem() PlaylistItem.Snippet = New PlaylistItemSnippet() PlaylistItem.Snippet.PlaylistId = newPlaylist.Id PlaylistItem.Snippet.ResourceId = New ResourceId() PlaylistItem.Snippet.ResourceId.Kind = "youtube#video" PlaylistItem.Snippet.ResourceId.VideoId = "tGWVVdVbnJc" PlaylistItem = Await ytObj.PlaylistItems.Insert(newPlaylistItem, _ "snippet").ExecuteAsync() lstGet.Items.Add("Playlist item id {0} was added to playlist id _ {1}.", PlaylistItem.Id, Playlist.Id) End Sub Any layman should be able to understand most of the preceding code. Let me explain it anyway, because I am such a nice guy… 🙂 I first made use of the GoogleWebAuthorizationBroker object’s AuthorizeAsync method to determine whether or not this is a valid application. Remember, in my Facebook article I referenced earlier, that I spoke about the importance of OAuth; well, here it comes into play again. Once it is established that the application is indeed valid, it needs to check whether or not it is dealing with a valid user. If you do not have a valid YouTube account, obviously this app won’t go further, so it is crucial that you at least create a YouTube account before running this app. It then determines the application’s name, as well as its intended purpose. This was probably the most difficult part to do. Next, I created a Playlist object. This object allows you to create a new playlist. A playlist is a set of your favourite videos that you’d like to watch over and over again. You set its various (quite easy) properties, and send the request back to YouTube via the ExecuteAsync method. Obviously, a playlist is useless without any items. The next object I created was a PlaylistItem object. This identifies the physical video you’d like to add to your playlist. Conclusion Thank you for always reading my articles. Although some may be a bit shorter than others, the complexity or the technologies involved makes it all worthwhile. Until next time, cheers!
https://www.codeguru.com/visual-basic/developing-a-simple-youtube-app-with-vb-and-windows-8-1/
CC-MAIN-2021-43
refinedweb
1,054
60.31
A custom event that is designed to be fired when a layer extent has been fully calculated. More... #include <qgsproviderextentcalcevent.h> A custom event that is designed to be fired when a layer extent has been fully calculated. This custom QEvent is designed to be fired when the full extent of a layer has been calculated. It was initially included in QGIS to help the QgsPostgresProvider provide the asynchronous calculation of PostgreSQL layer extents. Events are used instead of Qt signals/slots as events can be received asynchronously, which makes for better mutlithreading behaviour and less opportunity for programmer mishap. Definition at line 42 of file qgsproviderextentcalcevent.h. Definition at line 22 of file qgsproviderextentcalcevent.cpp. Definition at line 30 of file qgsproviderextentcalcevent.cpp.
http://qgis.org/api/classQgsProviderExtentCalcEvent.html
CC-MAIN-2014-52
refinedweb
124
56.35
I'm trying to write a simple app for myself only, that can read continuous data coming into a serial port from a microcontroller. I eventually want to display it in a bunch of tachometer-like dials, but i'm a long ways from that point. At this point, my trouble is i'm trying to learn how to read the incoming data, to make sure it's coming in successfully, and it's not. I've doing a lot of surfing, and learning. I found plenty of stuff on how to read data from serial ports, including this tutorial that i followed: That seems to work, but all i get in my output box is garbage: ??%?.???????? etc... I assume that's because i can't interpret hex that way. I have been searching for how to read this data in hex, but all of the solutions i find online are too high-level for me to understand. I see people posting one-line code fixes, but i'm REALLY new, and i need more explanation on how to adjust them to match what i'm doing, and where to put them. Here's the guts of my program, just like the tutorial shows: Private Sub SerialPort1_DataReceived(sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived ReceivedText(SerialPort1.ReadExisting()) 'Automatically called every time a data is received at the serialPort End Sub Private Sub ReceivedText(ByVal [text] As String) 'compares the ID of the creating Thread to the ID of the calling Thread If Me.rtbReceived.InvokeRequired Then Dim x As New SetTextCallback(AddressOf ReceivedText) Me.Invoke(x, New Object() {(text)}) Else Me.rtbReceived.Text &= [text] End If End Sub From reading online about hex data, I think i need to edit the first sub code to be ReceivedText = Hex(SerialPort1.ReadExisting() but i get an error: "Argument not specified for parameter 'text' of 'Private Sub ReceivedText(text As String)". I'm REALLY new, and don't understand what that means, so I click the autocorrect "Generate property stub...." which generates: Private Property ReceivedText As Stringin the public class area at the top of my code. That now gives me a different error on the second sub of "ReceivedText is already declared...." I do understand that i can't declare a variable twice, but my sub has the same name as my variable, and i can't figure out how to make "Private Property ReceivedText As String" and "Private Sub ReceivedText(ByVal [text] As String)" to do both things. Sorry if this is something obvious i'm doing wrong, but i'm really new, and can't figure this out. I'm trying to learn here, so i'd appreciate low-level explanations of what i'm doing wrong, and/or how to fix it. Thanks, Mike
http://www.dreamincode.net/forums/topic/312544-total-newb-trying-to-read-incoming-serial-port-data-in-hex/
CC-MAIN-2017-39
refinedweb
471
59.33
User talk:Robstew From Uncyclopedia, the content-free encyclopedia edit Welcome! Hello, Robst!) 04:02, January 25, 2013 (UTC) edit Userspace Hello and welcome to Uncyclopedia! The thing about the sandbox is that it is not guaranteed to persist. If you want your stuff to last long enough to whip it into shape as a real Uncyclopedia article, put it in your userspace. For example, copy it out of the sandbox and create User:Robstew/Subaru and paste the text there. Cheers! Spıke ¬ 01:29 27-Jan-13 I see you call for suggestions. Here are some. - Section 1: "Is considered to be" are words that don't do anything. I wrote about stuff like this once at User:SPIKE/Cliches-1 which might help you write. - Section 2: I don't know who these guys are. Just in general, though, they should be famous people, and just putting them in a list isn't funny unless what you write is, and unless it relates to real life. - Section 3: Shit jokes and fart jokes aren't ever funny, especially if the joke is missing. - Section 4: How to avoid the STI: We have a namespace called HowTo:for this kind of writing (instruction guides). The normal article should look like an encyclopedia article and this type of writing doesn't fit. A lot to think about; I hope that helps. Spıke ¬ 01:36 27-Jan-13 Thanks^ I'll keep that in mind. Will edit. Hope you can see this, Jesus Christ this place is a mess of communication.--Robstew (talk) 03:07, January 27, 2013 (UTC) - I came over here to say almost identical things. And a “thank you” for the poem. Was that page original or has it been derived from elsewhere? (Derivations are fine, by the way. Just can't do a complete copypasta without attribution, depending in the source. And rewriting something enough to make it derivative work is a doddle.) • Puppy's talk page • 01:40 27 Jan Not a copy paste, however the pictures are basically random files I found in the dark. Unfortunately, since I am typing on mobile I can't upload my own photos or web files. Is that a no-no? The text itself is based on fact, but I have to link them to a source. What I have now is just out of what I already know. I probably will link some sources though. --Robstew (talk) 02:20, January 27, 2013 (UTC) - Uploading images from an iDevice (or similar) is not a no-no, just technically a pain in the arse. You have to first upload them to flickr, and then import them from there to here. I'd started putting together a "HowTo" on that ages ago, including a couple of rather nifty tricks, but it's complex. If you have an image found on another site somewhere then hit me on my talk page with the URL and I can get them on here. - Having said that there are a few bits of copyright law that we have to be mindful of when uploading images. For the most part, if you're using the image in an article, you can upload comfortably as being protected for the purposes of parody. (So upload away, but try not to use the site as an image host.) • Puppy's talk page • 02:54 27 Jan - Hello as well. No, everything is fine and all is allowed, except some stuff that Puppy knows about. No need to link anything to a source here, we are a satirical rendition of wikipedia and sources are for those with brains (although a few of us also edit and write at wikipedia). Good to meet you, and don't let serious notes on your talkpage make you into a serious writer, even here. Check out our Rules, and pay particular attention to number three (well, all of them, but number three). Aleister 2:58 27-1-'13 Thanks to all. I'll Definately look into all of that. Being a new member makes everything a bit confusing. --Robstew (talk) 03:07, January 27, 2013 (UTC) - We're here to confusehelp! • Puppy's talk page • 03:13 27 Jan edit Deleted article I'm not too sure about the history of the main space page, but there is a mirror site that holds a lot of our older articles. I located this: which is pretty dreadful and not much use, because it's about a different topic. You can also ask an admin to restore a deleted page so you can see what was there, but I'd advise against it. You can always get more detailed feedback via Pee review, but it takes ages for us to go through the queue there. Quicker to just ask someone directly. If you have a look at HoS you can see some of the more popular stuff that the three guys above have written. We all have different styles, so a little reading of our stuff will give you an idea of what we write like. A lot of the users listed there have moved on to other things though. Special:Recentchanges will give you a good idea of who is still around, and what's still happening. • Puppy's talk page • 04:04 27 Jan edit Subaru Just took a quick look at the article, and it appears you have something against a specific person (Ken Block, I believe). This is generally frowned upon, unless it is a famous person, in which case making fun of something that the celebrity has done in public, or is otherwise known for, is fine. I am not familiar with this person, so something describing who this person is and why they are notable or famous would be helpful (for instance, if they are a sports figure, mention that at least once). Their name should be in Wikipedia at least, or come up as notable in a Google search (that is, more than a Facebook page and a few people finder pages on them). ---- Simsilikesims(♀UN) Talk here. 04:27, January 27, 2013 (UTC) Ken Block is a rather famous rally racing driver, I'll elaborate on him in an edit. Look him up on youtube, some of his "Gymkhana" videos are pretty cool. He is not, however a good rally driver, and is known to be cocky off the track. --Robstew (talk) 04:35, January 27, 2013 (UTC) Thanks for the heads up. - I just made an edit to that page. I apologise if I edit conflicted. Often when we're editing a page we'll add comments in the edit summary, which you can see in the history tab here and will also be at the top of the page. You'll also be able to see recent edits to pages you watch on Special:Watchlist, which will also show you the summary notes. (I talk too much. Going away again now.) • Puppy's talk page • 05:44 27 Jan That's fine, like I said, any edits are welcome. I should have looked at my messages. As you can see, while I have been relatively successful in uploading pictures, I am experiencing some difficulty organizing them (Captions, etc.).--Robstew (talk) 05:50, January 27, 2013 (UTC) - WP:Wikipedia:Picture tutorial will give you the info you need, and then a whole bunch more. You're doing well with them so far though, so don't stress. • Puppy's talk page • 06:19 27 Jan Thanks, I think that's all the pictures the article can hold without looking too choppy. Anyway, i'm gonna be offline for awhile, so if anyone sees any cleanup to be done feel free to take action if you so desire. --Robstew (talk) 06:26, January 27, 2013 (UTC) edit Infobox I have looked in on the day's changes. - One thing you seem to be trying to do is cram an "Infobox" into a thumbnail. For God's sake, find a template and all you will have to do is fill out the fields, and it will work correctly on everyone's browser too. Perhaps Puppy can find you the right template for this type of article. - Another thing you seem to be trying to do is give us dollops of your own personal opinion. Subaru deserves to be bowed down to, Ken Block is an asshole, Pastrana has a name that sounds like something else, etc. This never works unless you can really make it clever. I know you're not done yet, but you need some notion about where you're taking all this--especially when we get to Section 6 and you are bandying around liberals and lesbians as if merely writing down the names of the groups were a joke. What do they have to do with Subarus? What is the point you intend to make? More stuff for you to think about; keep at it! Spıke ¬ 23:28 27-Jan-13 - Thank you for the advice, Spike. looking at wikia's page on formatting didn't mention anything on an infobox, I'll look a little harder. On the personal opinion issue, I'll try to type some more stuff about each celebrity (maybe a section for each?) and modify the liberal/lesbian/mitsubishi relationship. Over the next few days, I'm going to change my focus to the text itself as today I have been distracted by getting pictures aligned.Thanks! --Robstew (talk) 23:39, January 27, 2013 (UTC) I've recoded your initial chart using {{Infobox}} itself. Click on that link to see the instructions: There are options that let you do a whole lot more with this. Spıke ¬ 23:58 27-Jan-13 It is shaping up! I like the paragraphs of prose much more than just making a bullet point and leaving it at that. But regarding your most recent edit, please don't talk directly to the reader (unless doing so is very funny). Ordinarily, it breaks the con that this is an encyclopedia. It's like an actor "breaking the fourth wall" of the stage, that is, talking to the audience or revealing that he is in a play. It is an available technique but you have to be sure you know why you're using it. Cheers. Spıke ¬ 02:10 28-Jan-13 And here is your morning nagging! On Subaru, quotations are better if you invent a real person, and bonus points if he never would have said what you have him saying, or if he said something very similar but certainly didn't mean what you said he meant. On C-130, please learn the difference between it's and its immediately! If you cannot substitute "it is" then you cannot write it's. Happy editing! Spıke ¬ 15:48 28-Jan-13 Alright. I'll look into the grammar issue. That article is just something I whipped together, so I have a lot of refining to do. On the quotations, I'll see who I can find. Thanks again!--Robstew (talk) 15:52, January 28, 2013 (UTC) edit Subaru, again It's not quite ready for mainspace. It still reads a little too much like you are trying to sell the Subaru to other dyed-in-the-wool Subaru fans, to praise its greatness, and doesn't have enough comedy for the guy whose Subaru has just seized up. You have a lot of photos, and they are backing up and crowding because you haven't written enough text. - Given that you have an Infobox with a photo, you don't need the usual initial photo, especially when its caption refers to text somewhere else. Move this photo to where it's referenced. - Remove the heading ==Subaru== so the following paragraph just becomes the introduction. (The Table of Contents will follow it). - In Ken Block, you have a bulleted list in the middle of nowhere, a list without an introduction to tell us what it's a list of. In Pastrana, you have a list inside a list. Why? - Regarding "Rally History": I'm 11 and what's a rally? No, I'm not 11, but this jumps in with no introduction. - Beware? Go to the bookcase, pull out any encyclopedia, and show me any article that has a heading Beware. Happy more editing! Spıke ¬ 23:23 28-Jan-13 Only you moved it first! Regarding your Change Summary, you have indeed done all you could--except check this talk page!!! Now, if you had waited for me to comment, I could have moved this without creating redirects. You have created several--they make the previous names continue to succeed at retrieving the article, but you must now ask for them to be deleted. So go to UN:QVFD and add the following entries: {{Redirect|User:Robstew/Subaru}} - moved to mainspace {{Redirect|Uncyclopedia:Subaru}} - created in error I've added Subaru to {{Cars}} to fix the template at the bottom of the article. Spıke ¬ 23:32, 23:36 28-Jan-13 - Thanks for the help Spike. Still working on getting rid of those redirects. --Robstew (talk) 23:38, January 28, 2013 (UTC) - I took care of those redirects (I think). I copy/pasted the entries into today's date section.--Robstew (talk) 23:43, January 28, 2013 (UTC) Looks correct at QVFD. Welcome to mainspace! Did I mention? please start paragraphs on talk pages with one or more : characters if necessary to indent your posts from those of other people. Be seeing you! Spıke ¬ 00:00 29-Jan-13 edit Subaru2 Oh God, you are creating redirects all over the place. Having moved your article to mainspace, you could edit it right there in mainspace. Whatever; just clean up after yourself (at QVFD). Spıke ¬ 00:05 29-Jan-13 - I think I managed to clean up my tracks. Good lord this place is confusing. By redirects, I thought they meant Double links or infinite loop links. Oh well. Thanks again! --Robstew (talk) 00:17, January 29, 2013 (UTC) I think that, based on your last move, the mainspace page Subaru now contains nothing but the text #REDIRECT [[User:Robstew/Subaru2]] which we don't want to be permanent. A double redirect is one of these that points to a page that points to another page. We don't want this to ever happen. Wikis are indeed designed for the coder as well as the writer; but the result is pretty pages with universal publication, which is nice. Spıke ¬ 00:23 29-Jan-13 OK, here's more. - Please end your love affair with <br clear=all>. You are trying too hard to manage small details of the layout of the page; you should concentrate on content and let Uncyclopedia lay it out the same way as it does other pages, unless gaping problems emerge. - Please don't get chatty with the reader; it breaks the resemblance to an encyclopedia article. (See above under "fourth wall.") - As you are seeing above, please see all of the above, and do the stuff I told you to do that you haven't done yet. A global search for "it's" would be in order. Spıke ¬ 02:10 29-Jan-13 Right. I'll get on that. I did have gaping problems with photos and text, I should probably just type more. I looked up Its vs. It's on google, I get the difference now. My C-130 article is clear of those problems I think. Thanks again, will edit.--Robstew (talk) 02:24, January 29, 2013 (UTC) edit Home-made Please don't pepper your article with external links. This site is for original comedy creations, not a jumping-off point to other stuff that exists on the Web. Thanks. Spıke ¬ 01:52 31-Jan-13 - Sorry, that's just what the ICU template said. Will edit. Should I link it to other articles? Is it long enough? How do I categorize it? I so confuse... :( --Robstew (talk) 01:58, January 31, 2013 (UTC) Yeah, that message means links to other Uncyclopedia articles with the double-bracket coding. Ignore what it says about red-links (links to other articles that don't exist), as there were none when RAHB put it into your article. To make it look more like a regular Uncyclopedia article, you should use {{Q}} rather than BLOCKQUOTE for quotations; see most other articles for the correct form. No, the article doesn't seem long enough to me. And "Home-made crap" ought to go away too, as it is just a list of short things. For categories, you can certainly use Category:Phrases. Spıke ¬ 02:27 31-Jan-13 Now, over in C-130, I see you have discovered how to refer to the user's name. In my opinion, this pranks the reader (convincing him that somehow you wrote the article with him personally in mind) to amuse yourself, when you should be trying to amuse the reader. We are not all agreed here on this point, but think about it. Spıke ¬ 11:51 31-Jan-13 edit The use of templates Given SPIKE's suggestions above, and you're discovering the use of templates, I figured I'd give you a little help. There are two kinds of template. Ones that use parameters, and ones that don't. For instance: “This is a quote” Some templates have more functionality that goes beyond the standard. {{RL}} for instance is designed to clean up redlinks on a page without removing actual links. (Note when we talk about links we're talking about links on site. External links are a different matter.) - {{RL}} {{RL|This page does not exist}} - This page does not existThis page does not exist {{RL|This page does exist}} When I started editing here I barely used templates. I had a bit of HTML knowledge and did much the same as yourself. Templates do makes a bundle of things easier though. The best way to see how a page you like the look of has been formatted. Read the code and steal it for yourself. The more you learn about coding the funkier your articles can become. But these cosmetic things are tricks that can either work or fail badly. Unless your article is designed around a funky look, you need to focus on content. These few articles illustrate what I mean: - Love this uses barely any templates, but instead focuses on good writing to make the funny - Stereotype uses a couple of templates but most of the funky coding is just the table at the base (which I just stole the look from a catalogue I was reading) - Microsoft knowledge base uses very few templates, but a lot of coding, and one funky image - Twitter uses some very complex coding but mostly hidden inside a bundle of templates. - Game:Alone in the dark is lots of coding and some very complex templates, and some funky images. Each of these articles has been featured, but each of them use different techniques to make with the funny. Oddly, the most complex one is definitely the latter (and you really don't want to know how long it took to put that together), but what makes that funny is not the funky coding, but the actual text itself. All the coding does is mimic a “frame” for the content. Of them my personal favourite is Love, because it is textually funny. TL;DR version: Templates and code can help, and in some places need to be there, but the focus really needs to be on making the funny first. (And if ever you need a funky code, there are people here who can do it.) • Puppy's talk page • 12:51 31 Jan edit Hello And good to meet you. Keep up the good work as long as you're having fun. Funnybony, one of our writers, calls Uncy a playground for adults, and when I become an adult I will play here too. Aleister 12:00 31-1-'13
http://uncyclopedia.wikia.com/wiki/User_talk:Robstew
CC-MAIN-2014-49
refinedweb
3,357
72.56
Developer code plugin tutorial¶ In this chapter we will give you a brief guide that will teach you how to write a plugin to support a new code. Generally speaking, we expect that each code will have its own peculiarity, so that sometimes a new strategy for code plugin might be needed to be carefully thought. Anyway, we will show you how we implemented the plugin for Quantum Espresso, in order for you to be able to replicate the task for other codes. Therefore, it will be assumed that you have already tried to run an example of QE, and you know more or less how the AiiDA interface works. In fact, when writing your own plugin, keep in mind that you need to satisfy multiple users, and the interface needs to be simple (not the code below). But always try to follow the Zen of Python: Simple is better than complex. Complex is better than complicated. Readability counts. There will be two kinds of plugins, the input and the output. The former has the purpose to convert python object in text inputs that can be executed by external softwares. The latters will convert the text output of these softwares back into python dictionaries/objects that can be put back in the database. InputPlugin¶ In abstract term, this plugin must contain these two pieces of information: what are the input objects of the calculation how to convert the input object in an input file This is it, a minimal input plugin must have at least these two things. Create a new file, which has the same name as the class you are creating (in this way, it will be possible to load it with CalculationFactory). Save it in a subfolder at the path aiida/orm/calculation/job. Step 1: inheritance¶ First define the class: class SubclassCalculation(JobCalculation): (Substitute Subclass with the name of your plugin). Take care of inheriting the JobCalculation class, or the plugin will not work. Note The base Calculation class should only be used as the abstract base class. Any calculation that needs to run on a remote scheduler must inherit from JobCalculation, that contains all the methods to run on a remote scheduler, get the calculation state, copy files remotely and retrieve them, ... Now, you will likely need to define some variables that belong to SubclassCalculation. In order to be sure that you don’t lose any variables belonging to the inherited class, every subclass of calculation needs to have a method which is called _init_internal_params(). An example of it would look like: def _init_internal_params(self): super(SubclassCalculation, self)._init_internal_params() self.A_NEW_VARIABLE = 'nabucco' This function will be called by the __init__ method and will initialize the variable A_NEW_VARIABLE at the moment of the instancing. The second line will call the _init_internal_params() of the parent class and load other variables eventually defined there. Now you are able to access the variable A_NEW_VARIABLE also in the rest of the class by calling self.A_NEW_VARIABLE. Note Even if you don’t need to define new variables, it is safer to define the method with the call to super(). Note It is not recommended to rewrite an __init__ by yourself: this method is inherited from the classes Node and Calculation, and you shouldn’t alter it unless you really know the code down to the lowest-level. Note The following is a list of relevant parameters you may want to (re)define in _init_internal_params: self._default_parser: set to the string of the default parser to be used, in the form accepted by the plugin loader (e.g., for the Quantum ESPRESSO plugin for phonons, this would be “quantumespresso.ph”, loaded from the aiida.parsers.pluginsmodule). self._DEFAULT_INPUT_FILE: specify here the relative path to the filename of the default file that should be shown by verdi calculation outputcat --default. If not specified, the default value is Noneand verdi calculation outputcatwill not accept the --defaultoption, but it will instead always ask for a specific path name. self._DEFAULT_OUTPUT_FILE: same of _DEFAULT_INPUT_FILE, but for the default output file. Step 2: define input nodes¶ First, you need to specify what are the objects that are going to be accepted as input to the calculation class. This is done by the class property _use_methods. An example is as follows: from aiida.common.utils import classproperty class SubclassCalculation(JobCalculation): def _init_internal_params(self): super(SubclassCalculation, self)._init_internal_params() @classproperty def _use_methods(cls): retdict = JobCalculation._use_methods retdict.update({ "settings": { 'valid_types': ParameterData, 'additional_parameter': None, 'linkname': 'settings', 'docstring': "Use an additional node for special settings", }, "pseudo": { 'valid_types': UpfData, 'additional_parameter': 'kind', 'linkname': cls._get_pseudo_linkname, 'docstring': ("Use a remote folder as parent folder (for " "restarts and similar"), }, }) return retdict @classmethod def _get_pseudo_linkname(cls, kind): """ Return the linkname for a pseudopotential associated to a given structure kind. """ return "pseudo_{}".format(kind) After this piece of code is written, we now have defined two methods of the calculation that specify what DB object could be set as input (and draw the graph in the DB). Specifically, here we will find the two methods: calculation.use_settings(an_object) calculation.use_pseudo(another_object,'object_kind') What did we do? We added implicitly the two new use_settingsand use_pseudomethods (because the dictionary returned by _use_methodsnow contains a settingsand a pseudokey) We did not lose the use_codecall defined in the Calculationbase class, because we are extending Calculation._use_methods. Therefore: don’t specify a code as input in the plugin! use_settingswill accept only one parameter, the node specifying the settings, since the additional_parametervalue is None. use_pseudowill require two parameters instead, since additional_parametervalue is not None. If the second parameter is passed via kwargs, its name must be ‘kind’ (the value of additional_parameters). That is, you can call use_pseudoin one of the two following ways: use_pseudo(pseudo_node, 'He') use_pseudo(pseudo_node, kind='He') to associate the pseudopotential node pseudo_node(that you must have loaded before) to helium (He) atoms. The type of the node that you pass as first parameter will be checked against the type (or the tuple of types) specified with valid_types(the check is internally done using the isinstancepython call). The name of the link is taken from the linknamevalue. Note that if additional_parameteris None, this is simply a string; otherwise, it must be a callable that accepts one single parameter (the further parameter passed to the use_XXXfunction) and returns a string with the proper name. This functionality is provided to have a single use_XXXmethod to define more than one input node, as it is the case for pseudopotentials, where one input pseudopotential node must be specified for each atomic species or kind. Finally, docstringwill contain the documentation of the function, that the user can obtain by printing e..g. use_pseudo.__doc__. Note The actual implementation of the use_pseudo method in the Quantum ESPRESSO tutorial is slightly different, as it allows the user to specify a list of kinds that are associated with the same pseudopotential file (while in the example above only one kind string can be passed). Step 3: prepare a text input¶ How are the input nodes used internally? Every plugin class is required to have the following method: def _prepare_for_submission(self,tempfolder,inputdict): This function is called by the daemon when it is trying to create a new calculation. There are two arguments: tempfolder: is an object of kind SandboxFolder, which behaves exactly as a folder. In this placeholder, you are going to write the input files. This tempfolder is gonna be copied to the remote cluster. 2. inputdict: contains all the input data nodes as a dictionary, in the same format that is returned by the get_inputdata_dict() method, i.e. a linkname as key, and the object as value. Note inputdict should contain all input Data nodes, but not the code. (this is what the get_inputdata_dict() method does, by the way). In general, you simply want to do: inputdict = self.get_inputdata_dict() right before calling _prepare_for_submission. The reason for having this explicitly passed is that the plugin does not have to perform explicit database queries, and moreover this is useful to test for submission without the need to store all nodes on the DB. For the sake of clarity, it’s probably going to be easier looking at an implemented example. Take a look at the NamelistsCalculation located in aiida.orm.calculation.job.quantumespresso.namelists. How does the method _prepare_for_submission work in practice? You should start by checking if the input nodes passed in inputdictare logically sufficient to run an actual calculation. Remember to raise an exception (for example InputValidationError) if something is missing or if something unexpected is found. Ideally, it is better to discover now if something is missing, rather than waiting the queue on the cluster and see that your job has crashed. Also, if there are some nodes left unused, you are gonna leave a DB more complicated than what has really been, and therefore is better to stop the calculation now. create an input file (or more if needed). In the Namelist plugin is done like: input_filename = tempfolder.get_abs_path(self.INPUT_FILE_NAME) with open(input_filename,'w') as infile: # Here write the information of a ParameterData inside this # file Note that here it all depends on how you decided the ParameterData to be written. In the namelists plugin we decided the convention that a ParameterData of the format: ParameterData(dict={"INPUT":{'smearing':2, 'cutoff':30} }) is written in the input file as: &INPUT smearing = 2, cutoff=30, / Of course, it’s up to you to decide a convention which defines how to convert the dictionary to the input file. You can also impose some default values for simplicity. For example, the location of the scratch directory, if needed, should be imposed by the plugin and not by the user, and similarly you can/should decide the naming of output files. Note it is convenient to avoid hard coding of all the variables that your code has. The convention stated above is sufficient for all inputs structured as fortran cards, without the need of knowing which variables are accepted. Hard coding variable names implies that every time the external software is updated, you need to modify the plugin: in practice the plugin will easily become obsolete if poor maintained. Easyness of maintainance here win over user comfort! copy inside this folder some auxiliary files that resides on your local machine, like for example pseudopotentials. return a CalcInfoobject. This object contains some accessory information. Here’s a template of what it may look like: calcinfo = CalcInfo() calcinfo.uuid = self.uuid calcinfo.cmdline_params = settings_dict.pop('CMDLINE', []) calcinfo.local_copy_list = local_copy_list calcinfo.remote_copy_list = remote_copy_list ### Modify here and put a name for standard input/output files calcinfo.stdin_name = self.INPUT_FILE_NAME calcinfo.stdout_name = self.OUTPUT_FILE_NAME ### calcinfo.retrieve_list = [] ### Modify here ! calcinfo.retrieve_list.append('Every file/folder you want to store back locally') ### Modify here! calcinfo.retrieve_singlefile_list = [] return calcinfo There are a couple of things to be set. - stdin_name: the name of the standard input. - stdin_name: the name of the standard output. - cmdline_params: like parallelization flags, that will be used when running the code. - retrieve_list: a list of relative file pathnames, that will be copied from the cluster to the aiida server, after the calculation has run on cluster. Note that all the file names you need to modify are not absolute path names (you don’t know the name of the folder where it will be created) but rather the path relative to the scratch folder. - local_copy_list: a list of length-two-tuples: (localabspath, relativedestpath). Files to be copied from the aiida server to the cluster. - remote_copy_list: a list of tuples: (remotemachinename, remoteabspath, relativedestpath). Files/folders to be copied from a remote source to a remote destination, sitting both on the same machine. - retrieve_singlefile_list: a list of triplets, in the form ["linkname_from calc to singlefile","subclass of singlefile","filename"]. If this is specified, at the end of the calculation it will be created a SinglefileData-like object in the Database, children of the calculation, if of course the file is found on the cluster. If you need to change other settings to make the plugin work, you likely need to add more information to the calcinfo than what we showed here. For the full definition of CalcInfo(), refer to the source aiida.common.datastructures. That’s what is needed to write an input plugin. To test that everything is done properly, remember to use the calculation.submit_test() method, which creates locally the folder to be sent on cluster, without submitting the calculation on the cluster. OutputPlugin¶ Well done! You were able to have a successful input plugin. Now we are going to see what you need to do for an output plugin. First of all let’s create a new folder: $path_to_aiida/aiida/parsers/plugins/the_name_of_new_code, and put there an empty __init__.py file. Here you will write in a new python file the output parser class. It is actually a rather simple class, performing only a few (but tedious) tasks. After the calculation has been computed and retrieved from the cluster, that is, at the moment when the parser is going to be called, the calculation has two children: a RemoteData and a FolderData. The RemoteData is an object which represents the scratch folder on the cluster: you don’t need it for the parsing phase. The FolderData is the folder in the AiiDA server which contains the files that have been retrieved from the cluster. Moreover, if you specified a retrieve_singlefile_list, at this stage there is also going to be some children of SinglefileData kind. Let’s say that you copied the standard output in the FolderData. The parser than has just a couple of tasks: - open the files in the FolderData - read them - convert the information into objects that can be saved in the Database - return the objects and the linkname. Note The parser should not save any object in the DB, that is a task of the daemon: never use a .store() method! Basically, you just need to specify an __init__() method, and a function parse_with_retrieved(calc, retrieved)__, which does the actual work. The difficult and long part is the point 3, which is the actual parsing stage, which convert text into python objects. Here, you should try to parse as much as you can from the output files. The more you will write, the better it will be. Note You should not only parse physical values, a very important thing that could be used by workflows are exceptions or others errors occurring in the calculation. You could save them in a dedicated key of the dictionary (say ‘warnings’), later a workflow can easily read the exceptions from the results and perform a dedicated correction! In principle, you can save the information in an arbitrary number of objects. The most useful classes to store the information back into the DB are: ParameterData: This is the DB representation of a python dictionary. If you put everything in a single ParameterData, then this could be easily accessed from the calculation with the .resmethod. If you have to store arrays / large lists or matrices, consider using ArrayData instead. ArrayData: If you need to store large arrays of values, for example, a list of points or a molecular dynamic trajectory, we strongly encourage you to use this class. At variance with ParameterData, the values are not stored in the DB, but are written to a file (mapped back in the DB). If instead you store large arrays of numbers in the DB with ParameterData, you might soon realize that: a) the DB grows large really rapidly; b) the time it takes to save an object in the DB gets very large. StructureData: If your code relaxes an input structure, you can end up with an output structure. Of course, you can create new classes to be stored in the DB, and use them at your own advantage. A kind of template for writing such parser for the calculation class NewCalculation is as follows: class NewParser(Parser): """ A doc string """ def __init__(self,calc): """ Initialize the instance of NewParser """ # check for valid input if not isinstance(calc,NewCalculation): raise ParsingError("Input must calc must be a NewCalculation") super(NewParser, self).__init__(calc) def parse_with_retrieved(self, retrieved): """ Parses the calculation-output datafolder, and stores results. :param retrieved: a dictionary of retrieved nodes, where the keys are the link names of retrieved nodes, and the values are the nodes. """ # check the calc status, not to overwrite anything state = calc.get_state() if state != calc_states.PARSING: raise InvalidOperation("Calculation not in {} state" .format(calc_states.PARSING) ) # retrieve the whole list of input links calc_input_parameterdata = self._calc.get_inputs(type=ParameterData, also_labels=True) # then look for parameterdata only input_param_name = self._calc.get_linkname('parameters') params = [i[1] for i in calc_input_parameterdata if i[0]==input_param_name] if len(params) != 1: # Use self.logger to log errors, warnings, ... # This will also add an entry to the DbLog table associated # to the calculation that we are trying to parse, that can # be then seen using 'verdi calculation logshow' self.logger.error("Found {} input_params instead of one" .format(params)) successful = False calc_input = params[0] # Check that the retrieved folder is there try: out_folder = retrieved[self._calc._get_linkname_retrieved()] except KeyError: self.logger.error("No retrieved folder found") return False, () # check what is inside the folder list_of_files = out_folder.get_folder_list() # at least the stdout should exist if not calc.OUTPUT_FILE_NAME in list_of_files: raise QEOutputParsingError("Standard output not found") # get the path to the standard output out_file = os.path.join( out_folder.get_abs_path('.'), calc.OUTPUT_FILE_NAME ) # read the file with open(out_file) as f: out_file_lines = f.readlines() # call the raw parsing function. Here it was thought to return a # dictionary with all keys and values parsed from the out_file (i.e. enery, forces, etc...) # and a boolean indicating whether the calculation is successfull or not # In practice, this is the function deciding the final status of the calculation out_dict,successful = parse_raw_output(out_file_lines) # convert the dictionary into an AiiDA object, here a # ParameterData for instance output_params = ParameterData(dict=out_dict) # prepare the list of output nodes to be returned # this must be a list of tuples having 2 elements each: the name of the # linkname in the database (the one below, self.get_linkname_outparams(), # is defined in the Parser class), and the object to be saved new_nodes_list = [ (self.get_linkname_outparams(),output_params) ] # The calculation state will be set to failed if successful=False, # to finished otherwise return successful, new_nodes_list Example¶ In this example, we are supporting a code that performs a summation of two integers. We try to imagine to create a calculation plugin that supports the code, and that can be run using a script like this one. First, we need to create an executable on the remote machine (might be as well your localhost if you installed a scheduler). Therefore, put this script on your remote computer and install it as a code in AiiDA. Such script take an input file as input on the command line, reads a JSON file input and sums two keys that it finds in the JSON. The output produced is another JSON file. Therefore, we create an input plugin for a SumCalculation, which can be done with few lines as done in this file aiida/orm/calculation/job/sum.py. The test can now be run, but the calculation Node will only have a RemoteData and a retrieved FolderData which are not querable. So, we create a parser ( aiida/parsers/plugins/sum.py) which will read the output files and will create a ParameterData in output. As you can see, with few lines we can support a new simple code. The most time consuming part in the development of a plugin is hidden for simplicity in this example. For the input plugin, this consists in converting the input Nodes into some files which are used by the calculation. For the parsers, the problem is opposite, and is to convert a text file produced by the executable into AiiDA objects. Here we only have a dictionary in input and output, so that its conversion to a from a JSON file can be done in one line, but in general, the difficulty of these operations depend on the details of the code you want to support. Remember also that you can introduce new Data types to support new features or just to have a simpler and more intuitive interface. For example, the code above is not optimal if you want to pass the result of two SumCalculation to a third one and sum their results (the name of the keys of the output dictionary differs from the input). A relatively simple exercise you can do before jumping to develop the support for a serious code, try to create a new FloatData, which saves in the DB the value of a number: class FloatData(Data): @property def value(self): """ The value of the Float """ return self.get_attr('number') @value.setter def value(self,value): """ Set the value of the Float """ self._set_attr('number',value) Try to adapt the previous SumCalculation to acceps two FloatDatas as input and to produce an FloatData in output. Note that you can do this without changing the executable (a rather useless note in this example, but more interesting if you want to support a real code!).
https://aiida.readthedocs.io/projects/aiida-core/en/v0.4.1/developer_guide/devel_tutorial/code_plugin.html
CC-MAIN-2020-50
refinedweb
3,529
52.8
There sure is a lot of $if 0 in Mozilla. Some of these blocks contain code which will land in the future, while others contain long since dead code. My intent is to prune the latter, thereby clarifying the source code a bit. I will produce patches for each top level source code directory. Here's a prime candidate from nsTextHelper in widget/gtk: 186 //------------------------------------------------------------------------- 187 NS_IMETHODIMP nsTextHelper::GetSelection(PRUint32 *aStartSel, PRUint32 *aEndSel) 188 { 189 #if 0 190 XmTextPosition left; 191 XmTextPosition right; 192 193 if (XmTextGetSelectionPosition(mTextWidget, &left, &right)) { 194 *aStartSel = (PRUint32)left; 195 *aEndSel = (PRUint32)right; 196 } else { 197 printf("nsTextHelper::GetSelection Error getting positions\n"); 198 return NS_ERROR_FAILURE; 199 } 200 #endif 201 return NS_OK; 202 } Is that Motif? Yes, it is! The whole method is commented out. It's actually something of a shame that we even bother to push a stack frame to enter this method. Hopefully the compilers are optimizing this away. before you go out and kill all of the motif code, you might want to ask the guy who's trying to resurrect motif if any of it is of any use to him. I think the real answer is that most of the widgets in widget/src/* aren't actually used by mozilla at all (they might be used by the *embed apps). -- I keep running into that when i try to figure out what stuff actually needs implementation for BeOS. I'm slightly wrong, as the only client in this case isn't *embed, it's viewer (aka the app everyone wants to kill). After an exhaustive lxr investigation, I conclude that there are no consumers of nsTextHelper::GetSelection() at all. Good thing, since it doesn't fulfill its interface. Oh I forgot to mention that I don't condone "#if 0" as a history mechanism. That's why we have CVS. For cripes sake, this same commented out block of Motif code is even present in the Mac source.
https://bugzilla.mozilla.org/show_bug.cgi?id=87248
CC-MAIN-2017-39
refinedweb
329
62.58
UDP(7P) UDP(7P) NAME UDP - Internet User Datagram Protocol SYNOPSIS #include <<<<sys/types.h>>>> #include <<<<sys/socket.h>>>> #include <<<<netinet/in.h>>>> s = socket(AF_INET, SOCK_DGRAM, 0); DESCRIPTION UDP is a simple, unreliable datagram protocol used to support the SOCK_DGRAM socket type for the internet protocol family. UDP sockets are connectionless, and are normally used with the sendto() and recvfrom() calls (see send(2) and recv(2). The connect() call can also be used to simulate a connection (see connect(2). When used in this manner, it fixes the destination for future transmitted packets (in which case the send() or write() system calls can be used), as well as designating the source from which packets are received. The recv() and read() calls can be used at any time if the source of the message is unimportant. UDP address formats are identical to those used by TCP. In particular, UDP requires a port identifier in addition to the normal Internet address format. Note that the UDP port domain is separate from the TCP port domain (in other words, a UDP port cannot be connected to a TCP port). The default send buffer size for UDP sockets is 65535 bytes. The default receive buffer size for UDP sockets is 2147483647 bytes. The send and receive buffer sizes for UDP sockets can be set by using the SO_SNDBUF and SO_RCVBUF options of the setsockopt() system call or the XTI_SNDBUF and XTI_RCVBUF options of the t_optmgmt() system call. The maximum size for these buffers is 2147483647 bytes. The maximum receive buffer size may be lowered using the ndd parameter udp_recv_hiwater_max. The maximum message size for a UDP datagram socket is limited by the lesser. ERRORS One of the following errors may be returned in errno if a socket operation fails. For a more detailed list of errors, see the man Hewlett-Packard Company - 1 - HP-UX Release 11i: November 2000 UDP(7P) UDP(7P) pages for specific system calls. [EISCONN] Attempt to send a datagram with the destination address specified, when the socket is already connected. [ENOBUFS] No buffer space is available for an internal data structure. [EADDRINUSE] Attempt to create a socket with a port which has already been allocated. [EADDRNOTAVAIL] Attempt to create a socket with a network address for which no network interface exists. AUTHOR The socket interfaces to UDP were developed by the University of California, Berkeley. SEE ALSO ndd(1M). getsockopt(2), recv(2), send(2), socket(2), t_open(3), t_optmgmt(3) inet(7F), socket(7), RFC 768 User Datagram Protocol RFC 1122 Requirements for Internet hosts Hewlett-Packard Company - 2 - HP-UX Release 11i: November 2000
http://modman.unixdev.net/?sektion=7&page=udp&manpath=HP-UX-11.11
CC-MAIN-2017-13
refinedweb
439
55.44
# MVCC in PostgreSQL-3. Row Versions Well, we've already discussed [isolation](https://habr.com/ru/company/postgrespro/blog/467437/) and made a digression regarding [the low-level data structure](https://habr.com/ru/company/postgrespro/blog/469087/). And we've finally reached the most fascinating thing, that is, row versions (tuples). Tuple header ============ As already mentioned, several versions of each row can be simultaneously available in the database. And we need to somehow distinguish one version from another one. To this end, each version is labeled with its effective «time» (`xmin`) and expiration «time» (`xmax`). Quotation marks denote that a special incrementing counter is used rather than the time itself. And this counter is *the transaction identifier*. (As usual, in reality this is more complicated: the transaction ID cannot always increment due to a limited bit depth of the counter. But we will explore more details of this when our discussion reaches freezing.) When a row is created, the value of `xmin` is set equal to the ID of the transaction that performed the INSERT command, while `xmax` is not filled in. When a row is deleted, the `xmax` value of the current version is labeled with the ID of the transaction that performed DELETE. An UPDATE command actually performs two subsequent operations: DELETE and INSERT. In the current version of the row, `xmax` is set equal to the ID of the transaction that performed UPDATE. Then a new version of the same row is created, in which the value of `xmin` is the same as `xmax` of the previous version. `xmin` and `xmax` fields are included in the header of a row version. In addition to these fields, the tuple header contains other ones, such as: * `infomask` — several bits that determine the properties of a given tuple. There are quite a few of them, and we will discuss each over time. * `ctid` — a reference to the next, more recent, version of the same row. `ctid` of the newest, up-to-date, row version references that very version. The number is in the `(x,y)` form, where `x` is the number of the page and `y` is the order number of the pointer in the array. * The NULLs bitmap, which marks those columns of a given version that contain a NULL. NULL is not a regular value of data types, and therefore, we have to store this characteristic separately. As a result, the header appears pretty large: 23 bytes per each tuple at a minimum, but usually larger because of the NULLs bitmap. If a table is «narrow» (that is, it contains few columns), the overhead bytes can occupy more space that the useful information. Insert ====== Let's look in more detail at how the operations on rows are performed at a low level, and we start with an insert. To experiment, we will create a new table with two columns and an index on one of them: ``` => CREATE TABLE t( id serial, s text ); => CREATE INDEX ON t(s); ``` We start a transaction to insert a row. ``` => BEGIN; => INSERT INTO t(s) VALUES ('FOO'); ``` This is the ID of our current transaction: ``` => SELECT txid_current(); ``` ``` txid_current -------------- 3664 (1 row) ``` Let's look into the contents of the page. The `heap_page_items` function from the «pageinspect» extension enables us to get information on the pointers and row versions: ``` => SELECT * FROM heap_page_items(get_raw_page('t',0)) \gx ``` ``` -[ RECORD 1 ]------------------- lp | 1 lp_off | 8160 lp_flags | 1 lp_len | 32 t_xmin | 3664 t_xmax | 0 t_field3 | 0 t_ctid | (0,1) t_infomask2 | 2 t_infomask | 2050 t_hoff | 24 t_bits | t_oid | t_data | \x0100000009464f4f ``` Note that the word «heap» in PostgreSQL denotes tables. This is one more weird usage of a term: a heap is a known [data structure](https://en.wikipedia.org/wiki/Heap_(data_structure)), which has nothing to do with a table. This word is used here in the sense that «all is heaped up», unlike in ordered indexes. This function shows the data «as is», in a format that is difficult to comprehend. To clarify the things, we leave only part of the information and interpret it: ``` => SELECT '(0,'||lp||')' AS ctid, CASE lp_flags WHEN 0 THEN 'unused' WHEN 1 THEN 'normal' WHEN 2 THEN 'redirect to '||lp_off WHEN 3 THEN 'dead' END AS state, t_xmin as xmin, t_xmax as xmax, (t_infomask & 256) > 0 AS xmin_commited, (t_infomask & 512) > 0 AS xmin_aborted, (t_infomask & 1024) > 0 AS xmax_commited, (t_infomask & 2048) > 0 AS xmax_aborted, t_ctid FROM heap_page_items(get_raw_page('t',0)) \gx ``` ``` -[ RECORD 1 ]-+------- ctid | (0,1) state | normal xmin | 3664 xmax | 0 xmin_commited | f xmin_aborted | f xmax_commited | f xmax_aborted | t t_ctid | (0,1) ``` We did the following: * Added a zero to the pointer number to make it look like a `t_ctid`: (page number, pointer number). * Interpreted the status of the `lp_flags` pointer. It is «normal» here, which means that the pointer actually references a row version. We will discuss other values later. * Of all information bits, we selected only two pairs so far. `xmin_committed` and `xmin_aborted` bits show whether the transaction with the ID `xmin` is committed (rolled back). A pair of similar bits relates to the transaction with the ID `xmax`. What do we observe? When a row is inserted, in the table page a pointer appears that has number 1 and references the first and the only version of the row. The `xmin` field in the tuple is filled with the ID of the current transaction. Because the transaction is still active, both `xmin_committed` and `xmin_aborted` bits are unset. The `ctid` field of the row version references the same row. It means that no newer version is available. The `xmax` field is filled with the conventional number 0 since the tuple is not deleted, that is, up-to-date. Transactions will ignore this number because of the `xmax_aborted` bit set. Let's move one more step to improving the readability by appending information bits to transaction IDs. And let's create the function since we will need the query more than once: ``` => CREATE FUNCTION heap_page(relname text, pageno integer) RETURNS TABLE(ctid tid, state text, xmin text, xmax text, t_ctid tid) AS $$ SELECT (pageno,lp)::text::tid AS ctid, CASE lp_flags WHEN 0 THEN 'unused' WHEN 1 THEN 'normal' WHEN 2 THEN 'redirect to '||lp_off WHEN 3 THEN 'dead' END AS state, t_xmin || CASE WHEN (t_infomask & 256) > 0 THEN ' (c)' WHEN (t_infomask & 512) > 0 THEN ' (a)' ELSE '' END AS xmin, t_xmax || CASE WHEN (t_infomask & 1024) > 0 THEN ' (c)' WHEN (t_infomask & 2048) > 0 THEN ' (a)' ELSE '' END AS xmax, t_ctid FROM heap_page_items(get_raw_page(relname,pageno)) ORDER BY lp; $$ LANGUAGE SQL; ``` What is happening in the header of the row version it is much clearer in this form: ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+------+-------+-------- (0,1) | normal | 3664 | 0 (a) | (0,1) (1 row) ``` We can get similar information, but far less detailed, from the table itself by using `xmin` and `xmax` pseudo-columns: ``` => SELECT xmin, xmax, * FROM t; ``` ``` xmin | xmax | id | s ------+------+----+----- 3664 | 0 | 1 | FOO (1 row) ``` Commit ====== When a transaction is successful, its status must be remembered, that is, the transaction must be marked as committed. To this end, the XACT structure is used. (Before version 10 it was called CLOG (commit log), and you are still likely to come across this name.) XACT is not a table of the system catalog, but files in the PGDATA/pg\_xact directory. Two bits are allocated in these files for each transaction — «committed» and «aborted» — exactly the same way as in the tuple header. This information is spread across several files only for convenience; we will get back to this when we discuss freezing. PostgreSQL works with these files page by page, as with all others. So, when a transaction is committed, the «committed» bit is set for this transaction in XACT. And this is all that happens when the transaction is committed (although we do not mention the write-ahead log yet). When some other transaction accesses the table page we were just looking at, the former will have to answer a few questions. 1. Was the transaction `xmin` completed? If not, the created tuple must not be visible. This is checked by looking through another structure, which is located in the shared memory of the instance and called ProcArray. This structure holds a list of all active processes, along with the ID of the current (active) transaction for each. 2. If the transaction was completed, then was it committed or rolled back? If it was rolled back, the tuple must not be visible either. This is just what XACT is needed for. But it is expensive to check XACT each time, although last pages of XACT are stored in buffers in the shared memory. Therefore, once figured out, the transaction status is written to `xmin_committed` and `xmin_aborted` bits of the tuple. If any of these bits is set, the transaction status is treated as known and the next transaction will not need to check XACT. Why does not the transaction that performs the insert set these bits? When an insert is being performed, the transaction is yet unaware of whether it will be completed successfully. And at the commit time it's already unclear which rows and in which pages were changed. There can be a lot of such pages, and it is impractical to keep track of them. Besides, some of the pages can be evicted to disk from the buffer cache; to read them again in order to change the bits would mean a considerable slowdown of the commit. The reverse side of the cost saving is that after the updates, any transaction (even the one performing SELECT) can begin changing data pages in the buffer cache. So, we commit the change. ``` => COMMIT; ``` Nothing has changed in the page (but we know that the transactions status is already written to XACT): ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+------+-------+-------- (0,1) | normal | 3664 | 0 (a) | (0,1) (1 row) ``` Now a transaction that first accesses the page will need to determine the status of the transaction `xmin` and will write it to the information bits: ``` => SELECT * FROM t; ``` ``` id | s ----+----- 1 | FOO (1 row) ``` ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+-------+-------- (0,1) | normal | 3664 (c) | 0 (a) | (0,1) (1 row) ``` Delete ====== When a row is deleted, the ID of the current deleting transaction is written to the `xmax` field of the up-to-date version and the `xmax_aborted` bit is reset. Note that the value of `xmax` corresponding to the active transaction works as a row lock. If another transaction is going to update or delete this row, it will have to wait until the `xmax` transaction completes. We will talk about locks in more detail later. At this point, only note that the number of row locks is not limited at all. They do not occupy memory, and the system performance is not affected by that number. However, long lasting transactions have other drawbacks, which will also be discussed later. Let's delete a row. ``` => BEGIN; => DELETE FROM t; => SELECT txid_current(); ``` ``` txid_current -------------- 3665 (1 row) ``` We see that the transaction ID is written to the `xmax` field, but information bits are unset: ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+------+-------- (0,1) | normal | 3664 (c) | 3665 | (0,1) (1 row) ``` Abort ===== Abort of a transaction works similarly to commit, except that the «aborted» bit is set in XACT. An abort is done as fast as a commit. Although the command is called ROLLBACK, the changes are not rolled back: everything that the transaction has already changed, remains untouched. ``` => ROLLBACK; => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+------+-------- (0,1) | normal | 3664 (c) | 3665 | (0,1) (1 row) ``` When accessing the page, the status will be checked and the hint bit `xmax_aborted` will be set. Although the number `xmax` itself will be still in the page, it will not be looked at. ``` => SELECT * FROM t; ``` ``` id | s ----+----- 1 | FOO (1 row) ``` ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+----------+-------- (0,1) | normal | 3664 (c) | 3665 (a) | (0,1) (1 row) ``` Update ====== An update works as if the current version is deleted first and then a new one is inserted. ``` => BEGIN; => UPDATE t SET s = 'BAR'; => SELECT txid_current(); ``` ``` txid_current -------------- 3666 (1 row) ``` The query returns one row (the new version): ``` => SELECT * FROM t; ``` ``` id | s ----+----- 1 | BAR (1 row) ``` But we can see both versions in the page: ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+-------+-------- (0,1) | normal | 3664 (c) | 3666 | (0,2) (0,2) | normal | 3666 | 0 (a) | (0,2) (2 rows) ``` The deleted version is labeled with the ID of the current transaction in the `xmax` field. Moreover, this value has overwritten the old one since the previous transaction was rolled back. And the `xmax_aborted` bit is reset since the status of the current transaction is unknown yet. The first version of the row is now referencing the second, as a newer one. The index page now contains the second pointer and second row, which references the second version in the table page. The same way as for a delete, the value of `xmax` in the first version indicates that the row is locked. Lastly, we commit the transaction. ``` => COMMIT; ``` Indexes ======= We were talking only about table pages so far. But what happens inside indexes? Information in index pages highly depends on the specific index type. Moreover, even one type of indexes can have different kinds of pages. For example: a B-tree has the metadata page and «normal» pages. Nevertheless, an index page usually has an array of pointers to the rows and rows themselves (just like table pages). Besides, some space at the end of a page is allocated for special data. Rows in indexes can also have different structures depending on the index type. For example: in an B-tree, rows pertinent to leaf pages contain the value of the indexing key and a reference (`ctid`) to the appropriate table row. In general, an index can be structured quite a different way. The main point is that in indexes of any type there are no row *versions*. Or we can consider each row to be represented by only one version. In other words, the header of the index row does not contain the `xmin` and `xmax` fields. For now we can assume that references from the index point to all versions of table rows. So to make out which of the row versions are visible to a transaction, PostgreSQL needs to look into the table. (As usual, this is not the whole story. Sometimes the visibility map enables optimizing the process, but we will discuss this later.) Here, in the index page, we find pointers to both versions: the up-to-date and previous: ``` => SELECT itemoffset, ctid FROM bt_page_items('t_s_idx',1); ``` ``` itemoffset | ctid ------------+------- 1 | (0,2) 2 | (0,1) (2 rows) ``` Virtual transactions ==================== In practice, PostgreSQL takes advantage of an optimization that permits to «sparingly» expends transaction IDs. If a transaction only reads data, it does not affect the visibility of tuple at all. Therefore, first the backend process assigns a virtual ID (virtual xid) to the transaction. This ID consists of the process identifier and a sequential number. Assignment of this virtual ID does not require synchronization between all the processes and is therefore performed very quickly. We will learn another reason of using virtual IDs when we discuss freezing. Data snapshots do not take into account virtual ID at all. At different points in time, the system can have virtual transactions with IDs that were already used, and this is fine. But this ID cannot be written to data pages since when the page is accessed next time, the ID can become meaningless. ``` => BEGIN; => SELECT txid_current_if_assigned(); ``` ``` txid_current_if_assigned -------------------------- (1 row) ``` But if a transaction begins to change data, it receives a true, unique, transaction ID. ``` => UPDATE accounts SET amount = amount - 1.00; => SELECT txid_current_if_assigned(); ``` ``` txid_current_if_assigned -------------------------- 3667 (1 row) ``` ``` => COMMIT; ``` Subtransactions =============== Savepoints ---------- In SQL, *savepoints* are defined, which permit rolling back some operations of the transaction without its complete abortion. But this is incompatible with the above model since the transaction status is one for all the changes and no data is physically rolled back. To implement this functionality, a transaction with a savepoint is divided into several separate *subtransactions* whose statuses can be managed separately. Subtrabsactions have their own IDs (greater than the ID of the main transaction). The statuses of subtransactions are written to XACT in a usual way, but the final status depends on the status of the main transaction: if it is rolled back, all subtransactions are rolled back as well. Information about subtransactions nesting is stored in files of the PGDATA/pg\_subtrans directory. These files are accessed through buffers in the shared memory of the instance, which are structured the same way as XACT buffers. Do not confuse subtransactions with autonomous transactions. Autonomous transactions in no way depend on one another, while subtransactions do depend. There are no autonomous transactions in the regular PostgreSQL, which is, perhaps, for the better: they are actually needed extremely rarely, and their availability in other DBMS invites abuse, which everyone suffers. Let's clear the table, start a transaction and insert a row: ``` => TRUNCATE TABLE t; => BEGIN; => INSERT INTO t(s) VALUES ('FOO'); => SELECT txid_current(); ``` ``` txid_current -------------- 3669 (1 row) ``` ``` => SELECT xmin, xmax, * FROM t; ``` ``` xmin | xmax | id | s ------+------+----+----- 3669 | 0 | 2 | FOO (1 row) ``` ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+------+-------+-------- (0,1) | normal | 3669 | 0 (a) | (0,1) (1 row) ``` Now we establish a savepoint and insert another row. ``` => SAVEPOINT sp; => INSERT INTO t(s) VALUES ('XYZ'); => SELECT txid_current(); ``` ``` txid_current -------------- 3669 (1 row) ``` Note that the `txid_current` function returns the ID of the main transaction rather than of the subtransaction. ``` => SELECT xmin, xmax, * FROM t; ``` ``` xmin | xmax | id | s ------+------+----+----- 3669 | 0 | 2 | FOO 3670 | 0 | 3 | XYZ (2 rows) ``` ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+------+-------+-------- (0,1) | normal | 3669 | 0 (a) | (0,1) (0,2) | normal | 3670 | 0 (a) | (0,2) (2 rows) ``` Let's rollback to the savepoint and insert the third row. ``` => ROLLBACK TO sp; => INSERT INTO t VALUES ('BAR'); => SELECT xmin, xmax, * FROM t; ``` ``` xmin | xmax | id | s ------+------+----+----- 3669 | 0 | 2 | FOO 3671 | 0 | 4 | BAR (2 rows) ``` ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+-------+-------- (0,1) | normal | 3669 | 0 (a) | (0,1) (0,2) | normal | 3670 (a) | 0 (a) | (0,2) (0,3) | normal | 3671 | 0 (a) | (0,3) (3 rows) ``` In the page, we continue to see the row that was added by the rolled back subtransaction. Committing the changes. ``` => COMMIT; => SELECT xmin, xmax, * FROM t; ``` ``` xmin | xmax | id | s ------+------+----+----- 3669 | 0 | 2 | FOO 3671 | 0 | 4 | BAR (2 rows) ``` ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+-------+-------- (0,1) | normal | 3669 (c) | 0 (a) | (0,1) (0,2) | normal | 3670 (a) | 0 (a) | (0,2) (0,3) | normal | 3671 (c) | 0 (a) | (0,3) (3 rows) ``` It is clearly seen now that each subtransaction has its own status. Note that SQL does not permit explicit use of subtransactions, that is, you cannot start a new transaction before you complete the current one. This technique gets implicitly involved when savepoints are used and also when handling PL/pgSQL exceptions, as well as in some other, more exotic situations. ``` => BEGIN; ``` ``` BEGIN ``` ``` => BEGIN; ``` ``` WARNING: there is already a transaction in progress BEGIN ``` ``` => COMMIT; ``` ``` COMMIT ``` ``` => COMMIT; ``` ``` WARNING: there is no transaction in progress COMMIT ``` Errors and operation atomicity ------------------------------ What happens if an error occurs while the operation is being performed? For example, like this: ``` => BEGIN; => SELECT * FROM t; ``` ``` id | s ----+----- 2 | FOO 4 | BAR (2 rows) ``` ``` => UPDATE t SET s = repeat('X', 1/(id-4)); ``` ``` ERROR: division by zero ``` An error occurred. Now the transaction is treated as aborted and no operations are permitted in it: ``` => SELECT * FROM t; ``` ``` ERROR: current transaction is aborted, commands ignored until end of transaction block ``` And even if we try to commit the changes, PostgreSQL will report the rollback: ``` => COMMIT; ``` ``` ROLLBACK ``` Why is it impossible to continue execution of the transaction after a failure? The thing is that the error could occur so that we would get access to part of the changes, that is, the atomicity would be broken not only for the transaction, but even for a single operator. For instance, in our example the operator could have updated one row before the error occurred: ``` => SELECT * FROM heap_page('t',0); ``` ``` ctid | state | xmin | xmax | t_ctid -------+--------+----------+-------+-------- (0,1) | normal | 3669 (c) | 3672 | (0,4) (0,2) | normal | 3670 (a) | 0 (a) | (0,2) (0,3) | normal | 3671 (c) | 0 (a) | (0,3) (0,4) | normal | 3672 | 0 (a) | (0,4) (4 rows) ``` It's worth noting that psql has a mode that allows continuing the transaction after failure, as if the effects of the erroneous operator were rolled back. ``` => \set ON_ERROR_ROLLBACK on => BEGIN; => SELECT * FROM t; ``` ``` id | s ----+----- 2 | FOO 4 | BAR (2 rows) ``` ``` => UPDATE t SET s = repeat('X', 1/(id-4)); ``` ``` ERROR: division by zero ``` ``` => SELECT * FROM t; ``` ``` id | s ----+----- 2 | FOO 4 | BAR (2 rows) ``` ``` => COMMIT; ``` It's easy to figure out that in this mode, psql actually establishes an implicit savepoint before each command and initiates a rollback to it in the event of failure. This mode is not used by default since establishing savepoints (even without a rollback to them) entails a significant overhead. [Read on](https://habr.com/ru/company/postgrespro/blog/479512/).
https://habr.com/ru/post/477648/
null
null
3,591
56.89
Everographs. Later, they did a live coding broadcast related to this. You can watch the video here. 38 of these logographs and related documents are available in this Github Repo. These logographs look like this: This image means ‘Time’. Then I thought about creating my own set of logographs. I started with creating some set of rules and procedure. 1) Only English letters will be considered. 2) Assigned weights to each English alphabet according to their freqency ranging from 0 to 10. 3) Applied standard mathematical function to each alphabet in the letter. 4) Plot the final function. The frequency values were like this: I tried functions (sin(x)), (cos(x)), (log(x)), (e^x), and (x^n) with different values of n. Tried summing up, multiplying and composite of functions. But nothing worked. Everything lead to unstable and weird plots. When I tried composite function for some word, I got an interesting plot like this one below: It looks like pulses. When I checked for the function, it was the following one: [frac{1}{sin(cos(x))}] But of course, it had different coeffiecients. Then I checked for the actual plot of this function. That looked like this. It looks very interesting. So, I created a method to generate pulsegraphs from text using the frequency of the alphabet and this function. For now on in this we call this function (ozii). [ozii(x) = frac{1}{sin(cos(x))}] Here (x) is in degrees. The Method [ x in (0, 1] ] [ p = sum_{i=1}^n weight(a_i) * x^i ] [ y = ozii(p) ] (a_i) is the ith alphabet and p is a polynomial generated from weight values defined the above table. For each unique word we will get unique polynomial. I scaled down (y) value to maximum of 0.5, Then plot a graph between x and y. There you have your pulse graph. For example, lets take the input as ‘time’: [ p = 9.62x + 8.46x^2 + 5x^3 + 10x^4 ] [ y = ozii(p) ] Scale down (y) to maximum of 0.5 If you plot this you will get the following pulsegraph: And for sentences I took the sum of each (y) to make the plot. Full Code import os import numpy as np import matplotlib.pyplot as plt # Weight Values alphabet = { , 'E': 10.0+(1e-7), 'T': 9.62+(1e-7), 'A': 9.23+(1e-7), 'O': 8.85+(1e-7), 'I': 8.46+(1e-7), 'N': 8.08+(1e-7), 'S': 7.69+(1e-7), 'R': 7.31+(1e-7), 'H': 6.92+(1e-7), 'D': 6.54+(1e-7), 'L': 6.15+(1e-7), 'U': 5.77+(1e-7), 'C': 5.34+(1e-7), 'M': 5.00+(1e-7), 'F': 4.62+(1e-7), 'Y': 4.23+(1e-7), 'W': 3.85+(1e-7), 'G': 3.46+(1e-7), 'P': 3.08+(1e-7), 'B': 2.69+(1e-7), 'V': 2.31+(1e-7), 'K': 1.92+(1e-7), 'X': 1.54+(1e-7), 'Q': 1.15+(1e-7), 'J': 0.77+(1e-7), 'Z': 0.34+(1e-7), '.': 4.9e-7, '?': 5.1e-7, ' ': 0 } def cos(x): return np.cos(180 * x / np.pi) def sin(x): return np.sin(180 * x / np.pi) def inverse(x): return 1/x # Ozii Function def transformer(x): y = cos(x) y = sin(y) y = inverse(y) return y # X x = np.linspace(0, 1, 1001) x = x[1:] # Return y for a single word def transform(text): n = len(text) y = 0 for i in range(len(text)): y += alphabet[text[i]] * (x ** (i+1)) y = transformer(y) max_y = np.max(np.abs(y)) y = (0.5/max_y) * y return y # y for a sentence def sentence_transformer(sentence): words = sentence.split() y = np.zeros(x.shape) for i, word in enumerate(words): y += transform(word) max_y = np.max(np.abs(y)) y = (0.5/max_y) * y return y # Create plot and generate image. def generate_image(sentence, pixels=500, dir="output"): y = sentence_transformer(sentence) size = pixels / 10 fig = plt.figure(figsize=(10, 10)) plt.plot(x, y, linewidth=1, c='k') plt.axis([0, 1, -0.5, 0.5]) plt.axis('off') words = sentence.split() if not os.path.isdir(dir): os.makedirs(dir) filename = dir + "/" + sentence + ".png" plt.savefig(filename, dpi=size) plt.close('all') return filename You might have noticed that I have added weight values to capital letters too. More Examples ozii Time There is no linear time Batman I am Batman Human Humanity Let me know what you think.
https://hackerworld.co/generate-pulsegraphs-from-text-using-python
CC-MAIN-2018-34
refinedweb
755
81.09
Object Hierarchy GBoxed ╰── GFileAttributeInfoList GEnum ├── GFileAttributeStatus ╰── GFileAttributeType GFlags ╰── GFileAttributeInfoFlags Description File attributes in GIO consist of a list of key-value pairs. Keys are strings that contain a key namespace and a key name, separated by a colon, e.g. "namespace::keyname". Namespaces are included to sort key-value pairs by namespaces for relevance. Keys can be retrived using wildcards, e.g. "standard::*" will return all of the keys in the "standard" namespace. The list of possible attributes for a filesystem (pointed to by a GFile) is available as a GFileAttributeInfoList. This list is queryable by key names as indicated earlier. Information is stored within the list in GFileAttributeInfo structures. The info structure can store different types, listed in the enum GFileAttributeType. Upon creation of a GFileAttributeInfo, the type will be set to G_FILE_ATTRIBUTE_TYPE_INVALID. Classes that implement GFileIface will create a GFileAttributeInfoList and install default keys and values for their given file system, architecture, and other possible implementation details (e.g., on a UNIX system, a file attribute key will be registered for the user id for a given file). Default Namespaces "standard": The "Standard" namespace. General file information that any application may need should be put in this namespace. Examples include the file's name, type, and size. "etag: The Entity Tag namespace. Currently, the only key in this namespace is "value", which contains the value of the current entity tag. "id": The "Identification" namespace. This namespace is used by file managers and applications that list directories to check for loops and to uniquely identify files. "access": The "Access" namespace. Used to check if a user has the proper privileges to access files and perform file operations. Keys in this namespace are made to be generic and easily understood, e.g. the "can_read" key is TRUEif the current user has permission to read the file. UNIX permissions and NTFS ACLs in Windows should be mapped to these values. "mountable": The "Mountable" namespace. Includes simple boolean keys for checking if a file or path supports mount operations, e.g. mount, unmount, eject. These are used for files of type G_FILE_TYPE_MOUNTABLE. "time": The "Time" namespace. Includes file access, changed, created times. "unix": The "Unix" namespace. Includes UNIX-specific information and may not be available for all files. Examples include the UNIX "UID", "GID", etc. "dos": The "DOS" namespace. Includes DOS-specific information and may not be available for all files. Examples include "is_system" for checking if a file is marked as a system file, and "is_archive" for checking if a file is marked as an archive file. "owner": The "Owner" namespace. Includes information about who owns a file. May not be available for all file systems. Examples include "user" for getting the user name of the file owner. This information is often mapped from some backend specific data such as a UNIX UID. "thumbnail": The "Thumbnail" namespace. Includes information about file thumbnails and their location within the file system. Examples of keys in this namespace include "path" to get the location of a thumbnail, "failed" to check if thumbnailing of the file failed, and "is-valid" to check if the thumbnail is outdated. "filesystem": The "Filesystem" namespace. Gets information about the file system where a file is located, such as its type, how much space is left available, and the overall size of the file system. "gvfs": The "GVFS" namespace. Keys in this namespace contain information about the current GVFS backend in use. "xattr": The "xattr" namespace. Gets information about extended user attributes. See attr(5). The "user." prefix of the extended user attribute name is stripped away when constructing keys in this namespace, e.g. "xattr::mime_type" for the extended attribute with the name "user.mime_type". Note that this information is only available if GLib has been built with extended attribute support. "xattr-sys": The "xattr-sys" namespace. Gets information about extended attributes which are not user-specific. See attr(5). Note that this information is only available if GLib has been built with extended attribute support. "selinux": The "SELinux" namespace. Includes information about the SELinux context of files. Note that this information is only available if GLib has been built with SELinux support. Please note that these are not all of the possible namespaces. More namespaces can be added from GIO modules or by individual applications. For more information about writing GIO modules, see GIOModule. <!-- TODO: Implementation note about using extended attributes on supported file systems --> Default Keys For a list of the built-in keys and their types, see the GFileInfo documentation. Note that there are no predefined keys in the "xattr" and "xattr-sys" namespaces. Keys for the "xattr" namespace are constructed by stripping away the "user." prefix from the extended user attribute, and prepending "xattr::". Keys for the "xattr-sys" namespace are constructed by concatenating "xattr-sys::" with the extended attribute name. All extended attribute values are returned as hex-encoded strings in which bytes outside the ASCII range are encoded as escape sequences of the form \x nn where nn is a 2-digit hexadecimal number. Functions g_file_attribute_info_list_new () GFileAttributeInfoList * g_file_attribute_info_list_new ( void); Creates a new file attribute info list. Returns a GFileAttributeInfoList. g_file_attribute_info_list_ref () GFileAttributeInfoList * g_file_attribute_info_list_ref ( GFileAttributeInfoList *list); References a file attribute info list. Returns GFileAttributeInfoList or NULL on error. g_file_attribute_info_list_unref () void g_file_attribute_info_list_unref ( GFileAttributeInfoList *list); Removes a reference from the given list . If the reference count falls to zero, the list is deleted. g_file_attribute_info_list_dup () GFileAttributeInfoList * g_file_attribute_info_list_dup ( GFileAttributeInfoList *list); Makes a duplicate of a file attribute info list. g_file_attribute_info_list_lookup () const GFileAttributeInfo * g_file_attribute_info_list_lookup ( GFileAttributeInfoList *list, const char *name); Gets the file attribute with the name name from list . Returns a GFileAttributeInfo for the name , or NULL if an attribute isn't found. g_file_attribute_info_list_add () void g_file_attribute_info_list_add ( GFileAttributeInfoList *list, const char *name, GFileAttributeType type, GFileAttributeInfoFlags flags); Adds a new attribute with name to the list , setting its type and flags . Types and Values enum GFileAttributeStatus Used by g_file_set_attributes_from_info() when setting file attributes. GFileAttributeInfo typedef struct { char *name; GFileAttributeType type; GFileAttributeInfoFlags flags; } GFileAttributeInfo; Information about a specific attribute. GFileAttributeInfoList typedef struct { GFileAttributeInfo *infos; int n_infos; } GFileAttributeInfoList; Acts as a lightweight registry for possible valid file attributes. The registry stores Key-Value pair formats as GFileAttributeInfos.
https://developer.gnome.org/gio/unstable/gio-GFileAttribute.html
CC-MAIN-2019-22
refinedweb
1,023
59.19
ASP.NET MVC Practical Hands-On Lab Tutorial (Free from the Software University) this lab you will create a web based event management sytem, from zero to fully working web application. Enjoy this free practical ASP.NET MVC tutorial for beginners. The source code is intentionally given as images to avoid copy-pasting. ASP.NET MVC Lab (May 2015) – Web Based Events Management System The goal of this lab is to learn how to develop ASP.NET MVC data-driven Web applications. You will create MVC application to list / create / edit / delete events. The recommended development IDE to use for this Lab is Visual Studio 2013 with the latest available updates + SQL Server 2012. Let’s start building the event management system in ASP.NET MVC step by step. Project Assignment Design and implement a Web based event management system. · Events have title, start date and optionally start time. Events may have also (optionally) duration, description, location and author. Events can be public (visible by everyone) and private (visible to their owner author only). Events may have comments. Comments belong to certain event and have content (text), date and optional author (owner). · Anonymous users (without login) can view all public events. The home page displays all public events, in two groups: upcoming and passed. Events are shown in short form (title, date, duration, author and location) and have a [View Details] button, which loads dynamically (by AJAX) their description, comments and [Edit] / [Delete] buttons. · Anonymous users can register in the system and login / logout. Users should have mandatory email, password and full name. User’s email should be unique. User’s password should be non-empty but can be just one character. · Logged-in users should be able to view their own events, to create new events, edit their own events and delete their own events. Deleting events requires a confirmation. Implement client-side and sever-sidevalidation data validation. · A special user “admin@admin.com” should have the role “Administrator” and should have full permissions to edit / delete events and comments. Step 1. Empty Visual Studio Solution Create a new empty Visual Studio Solution named “Events-Lab“: This VS solution will hold your projects: data layer project and ASP.NET Web application project. Step 2. Empty MVC Project with User Accounts Create and empty ASP.NET MVC project by the default Visual Studio template with built-in user accounts and authentication. First, click on the solution, choose [Add] à [New Project…]: Choose [Visual C#] à [Web] à [ASP.NET Web Application]. Name the application “Events.Web“. It will hold your ASP.NET MVC Web application (controllers, views, view models, etc). The data access layer (entity classes + Entity Framework data context) will be separated in another application. Next, choose the “MVC” project template + “Individual User Accounts” as authentication type. Visual Studio will generate an ASP.NET MVC application by template, which will serve as start (skeleton) for your Events management system. The application uses a typical Web development stack for .NET developers:ASP.NET MVC 5 as core Web development framework, Bootstrap as front-end UI framework, Entity Framework as data layer framework, ASP.NET Identity system as user management framework, and SQL Server as database. Step 3. Customize the MVC Application The project generated by the Visual Studio template needs many adjustments. Let’s customize the generated code for your Events management system. 1. Edit the connection string in the Web.config file to match your database server settings. In our case, we will use a database “Events” in MS SQL Server 2014 Local DB: (LocalDb)\MSSQLLocalDB: 2. Delete some unneeded files: o AssemblyInfo.cs – holds application metadata (not needed at this time) o App_Data folder – holds the application database (not needed, we will use SQL Server Local DB) o favico.ico – holds the Web application icon used in the browser location bar. We will not use it. We can add it later. o Project_Readme.html – holds instructions how to start out MVC project 3. Build and run the application to check whether it works, e.g. by clicking [Ctrl + F5]: 4. Test the user registration functionality. You should have out-of-the-box user registration, login and logout: You have a problem. By default, the MVC application is configured to use too complex passwords. This will make hard the testing during the development. 5. Let’s change the password validation policy: · Modify the PasswordValidator in the file App_Start\IdentityConfig.cs: · Modify the password minimum length in the class RegisterViewModel. It is located in the file Models\AccountViewModels.cs: · Modify the password minimum length in the SetPasswordViewModel and ChangePasswordViewModel classes, located in the file Models\ManageViewModels.cs: 6. Recompile and run the application again. Test the user registration, login and logout again. E.g. try to register user “test@test.com” with password “1“: After a bit of waiting, Entity Framework will create the database schema in SQL Server and the MVC application will register the user in the database and will login as the new user: 7. Open the database to ensure it works as expected. You should have a database “Events” in the MS SQL Server Local DB, holding the AspNetUsers table, which should hold your registered user account: 8. Now let’s edit the application layout view. Edit the file \Views\Shared\_Layout.cshtml. · Change the application’s title: · Change the navigation menus. Change the home page link. Replace the “About” and “Contact” links with the code shown below. The goal is to put “My Events” and “Create Event” links for logged-in users only. Anonymous site visitors will have only “Events” link to the home page, while logged in users will be able to see their events and create new events: · Change the application footer text as well: · Remove the junk code from the home controller’s default view \Views\Home\Index.cshtml: · Remove the unneeded HomeController‘s actions “About” and “Contacts“: · Delete the unneeded Home controller’s views About.cshtml and Contact.cshtml: 9. Now run the application to test it again. It should look like this for anonymous users: After login, the application should display the user’s navigation menus. It should look like this: Now you are ready for the real development on the Events management system. Let’s go. Step 4. Separate the EF Data Model from the MVC Application The application structure is not very good. It mixes the entity data models with the Entity Framework data context and the MVC view models for the views and MVC input models for mapping the forms. Let’s restructure this. 1. Create a new Class Library project “Events.Data” in your solution in Visual Studio: 2. Delete the unneeded files from the Events.Data project: 3. Move the file Events.Web\Models\IdentityModels.cs to the new project Events.Data. You can use [Edit] à [Cut] à [Paste]. 4. Now the Visual Studio Solution will not compile. Many errors will be shown if we rebuild with [F6]: We need to fix some issues: class names, file names, library references, project references, etc. 5. Extract the class ApplicationUser into a file named “ApplicationUser.cs“. Change its namespace to “Events.Data“. Your code should look like this: 6. Rename the IdentityModel.cs file to ApplicationDbContext.cs. This file will hold your Entity Framework database context – the class ApplicationDbContext. Change its namespace to Events.Data. Your code should look like this: 7. Your code will still not compile. Now you should add NuGet references to the missing libraries: Entity Framework, Microsoft.AspNet.Identity.Core and Microsoft.AspNet.Identity.EntityFramework: It is enough to reference the package “Microsoft.AspNet.Identity.EntityFramework“. The others depend on it and will be installed by dependency. 8. Fix the missing “using …” in the code. The project Events.Data should compile without errors. 9. The project Events.Web will not compile due to missing classes: ApplicationUser and ApplicationDbContext. Let’s fix this. 10. Add project reference from Events.Web project to Events.Data project: 11. Fix the missing “using Events.Data;” statements in the Events.Web project. Now the project should compile correctly. If not, check your library and project references and “using” statements. 12. Test the MVC application. It should work correctly. Test the Home Page, Register, Login and Logout: Step 5. Define the Data Model Now you are ready to define the data model for the Events management system: entity classes + Entity Framework database context + data migration classes. Let’s define the entity classes: 1. First, add a full name in the ApplicationUser class. It will hold the name of the event’s author: 2. Next, create your Event class. It will hold the events and their properties: Compile your code. It should compile without errors. 3. Create your Comment class. It will hold the comments for each event: Compile your code. It should compile without errors. 4. Add comments to the Event class: Compile again your code. It should compile without errors. 5. Modify the ApplicationDbContext class to include the events and comments as IDbSet<T>: Compile again your code. It should compile without errors. 6. Run the MVC application. It will fail at the Login action. Think why! You need a migration strategy for the database, right? How shall changes in the DB schema be handled? Step 6. Configure Database Migrations Now you will configure automatic migration strategy for the database to simplify changes in the database schema during the project development. 1. First, enable the database migrations from the Package Manager console for the Events.Data project: The command “Enable-Migrations” will generate a file Migrations\Configuration.cs in the Events.Data project: 2. The generated DB migration class has non-informative name. It is a good practice to rename it: Configuration à DbMigrationsConfig. Rename the file that holds this class as well: Configuration.cs àDbMigrationsConfig.cs. 3. Edit the DB migration configuration: make the class public (it will be used by the MVC project); enable automatic migrations; enable data loss migrations: 4. Set the database migration configuration in the database initializer in your Global.asax file in your MVC Web application: 5. Now run the MVC application to test the new database migration strategy. Rebuild the application and run it. The application will fail! Seems like the database migration has not been executed, right? You could also check the database: The new tables (Events and Comments) are missing. 6. Let’s fix this problem. The easiest way is just to drop the database: 7. Let’s run the MVC Web application again and try to login. It will say “Invalid login“: This is quite normal: we dropped the entire database, right? Let’s see what the database holds now: 8. Let’s register a new account. The application will fail with “Entity Validation Errors“: The problem comes from the field “FullName” in the ApplicationUser class. It is required but is left empty. 9. We need to change the RegisterViewModel, the Register.cshtml view and the Register action in the AccountController to add the FullName property: 10. Now run the application and try to register a new user account. It should work correctly: Step 7. Fill Sample Data in the DB (Seed the Database) You are ready to fill the database with sample data. Sample data will help during the development to simplify testing. Now let’s fill some data: create admin account and a few events with few comments. The easiest way to do this is to create a Seed() method in the database migration strategy. 1. In the Seed() method check whether the database is empty. If it is empty, fill sample data. The Seed() method will run every time when the application starts, after a database schema change. You can use sample code like this: In this example, the default administrator user will be “admin@admin.com” with the same password. This will simplify testing, because some actions require administrator privileges in the system. 2. Now, let’s create the admin user and the administrator role and assign administrator role to the admin user: 3. Next, create some events with comments: 4. Add some code to create a few more events: · Few upcoming events · Few passed events · Few anonymous events (no author) · Events with / without comments 5. Drop the database and restart the Web application to re-create the DB. If you get “Cannot open database” error, stop the IIS Server, rebuild and run the MVC application again: Stopping the IIS Express web server (Internet Information Services): 6. Check the data in the Events database. It should hold few records in the Events, Comments, AspNetUsers, AspNetRoles and AspNetUserRoles: Now you have sample data in the Events database and you are ready to continue working on the Events management MVC Web application. Step 8. List All Public Events at the Home Page Listing all public events at the home page passes through several steps: · Create EventViewModel to hold event data for displaying on the home page. · Create UpcomingPassedEventsViewModel to hold lists of upcoming and passed events. · Write the logic to load the upcoming and passed events in the default action of the HomeController. · Write a view to display the events at the home page. 1. Create a class Models\EventViewModel.cs to hold event data for displaying on the home page: 2. Create a class Models\UpcomingPassedEventsViewModel.cs to hold lists of upcoming and passed events: 3. Create a class Controllers\BaseController.cs to hold the Entity Framework data context. It will be used as base (parent) class for all controllers in the MVC application: 4. First extend the BaseController from the HomeController to inherit the DB context: 5. Now write the code in the default action Index() of the HomeController to load all public events: The idea of the above code is to select all public events, ordered by start date, then transform them from entity class Event to view model class EventViewModel and split them into two collections: upcoming and passed events. 6. Finally, create the view to display the events at the home page – \Views\Home\Index.cshtml: 7. The above code shows the upcoming events only. Add similar code to list the passed events as well. 8. You need to define a display template for the EventViewModel class. It will be used when the Razor engine renders this code: @Html.DisplayFor(x => x.UpcomingEvents). Create the display template in the file\Views\Shared\DisplayTemplates\EventViewModel.cshtml: 9. Build and run the project to test whether it works correctly. If you have a luck, the code will be correct at your first attempt. The expected result may look like this: 10. Now let’s add some CSS styles to make the UI look better. Append the following CSS style definitions at the end of the file \Content\Site.css: 11. Refresh the application home page to see the styled events: 12. Good job! Events are displayed at the home page. Now let’s optimize a bit the HomeController. It holds a code that loads an Event object into a new EventViewModel object: This code can be moved to the EventViewModel class to make the HomeController cleaner: Looks complex, but it is not really. This static property is used in .Select(…) queries to transform Event into EventViewModel. Such transformations are boring and work better encapsulated in the view model class. Now the HomeController can use this static property as follows: 13. Build and test the project again to ensure it woks correctly after the refactoring. Step 9. List Events Details with AJAX The next step in the development of the Events management application is to display event details dynamically with AJAX. The goal is to achieve the following functionality: 1. First, let’s define the EventDetailsViewModel class that will hold the event details: It will internally refer the CommentViewModel class: 2. Next, let’s write the AJAX controller action, that will return the event details when users click the [View Details] button: The above logic is not quite straightforward, because event details should be shown only when the user has permissions to access them: · The event author can view and edit its own events (even private). · System administrators can view and edit all events (even private). · Public events are visible by everyone, but not editable by everyone. 3. It is quite good idea to extract the check whether the current user is administrator in the BaseController: 4. Next, let’s create the partial view that will be returned when the AJAX request for event detail is made. The partial view for the above AJAX action should stay in \Views\Home\_EventDetails.cshtml. First, display the event description: Next, list the event comments: Finally, show [Edit] and [Delete] buttons when the user has edit permissions: 5. Now, let’s edit the events display template \Views\Shared\DisplayTemplates\EventViewModel.cshtml and add the AJAX call in it: 6. Let’s test the new functionality. Everything works fine, except that the AJAX action link is executed as normal link without AJAX: 7. What is missing? The script that handle the AJAX calls are not loaded in the page. Let’s add it. · First, install the NuGet package Microsoft.jQuery.Unobtrusive.Ajax in the project Events.Web: · Register the Unobtrusive AJAX script in the bundles configuration file App_Start\BundleConfig.cs, just after the jQuery bundle registration: · Include the unobtrusive AJAX script in the view which needs AJAX: \Views\Home\Index.cshtml This code will render the “~/bundles/ajax” bundle in the section “scripts” in the site layout: 8. Now the AJAX functionality should work as expected: The network requests in the Web browser developer tools shows that the AJAX call was successfully executed: Step 10. Create New Event The next feature to be implemented in the Events management system is “Create New Event“. This will require creating a “New Event” form (Razor view) + input model for the form + controller action to handle the submitted form data. 1. First, let’s define the input model for the create or edit event form. It will hold all event properties that the user will fill when creating or editing an event. Let’s create the class Models\EventInputModel.cs: It is a good idea to attach validation annotations like [Required] and [MaxLength] for each property to simplify the validation of the form. 2. Next, let’s create the “New Event“ form. The easiest way to start is by using the Razor view generator in Visual Studio. Create a folder “\Views\Events“. Right click on the “Events” folder and choose [Add] à [View…]: Enter a view name “Create“. Select template “Create“. Select the model class “EventInputModel (Events.Web.Models)“. Click [Add] to generate the view: Visual Studio will generate the “Create Event” form: 3. Now customize the generated form. Change several things: · Change the Title à “Create Event” · Remove the “Back to List” link: · Add [Cancel] link to “My Events”, just after the [Create] button: 4. Create EventsController to handle the actions related to events: create / edit / delete / list events. 5. Add the “Create” action (HTTP GET) to display the “New Event” form: 6. Build the project, run it and test the new functionality (login and click [Create Event]). The “New Event” form should be rendered in the Web browser: Create New Event Logic After the “Create New Event” form is ready, it is time to write the logic behind it. It should create a new event and save it in the database. The correct way to handle form submissions in ASP.NET MVC is by HTTP POST action in the controller behind the form. Let’s write the “Create New Event” logic. 1. First, extend the BaseController to inherit the database context: 2. Next, write the action to handle POST \Events\Create: 3. Run and test the code. Now creating events almost works: When the form is submitted, the result will be like this: This is quite normal. The “My” action in the EventsController is not missing. 4. Let’s define the action “My” and the view behind it in the EventsContoller: Create an empty view \Views\Events\My.cshtml (it will be implemented later): 5. Now run and test the application again: Check the database to see whether the new event is created: 6. At the home page the new event is not listed. Why? The event is not public. Let’s make the “Is Public?” check box in the “New Event” form checked by default: Step 11. Notification System (Info / Error Messages) The next big step will be to add a notification system to display informational and error messages like these: Typically, MVC controller actions that modify DB objects (e.g. EventsController.Create) work as follows: · Check the model state. If the validation fails, the model state will be invalid and the controller will re-render the form. The form will show the errors for each incorrect field. · If the model state is correct, create / edit the database object behind the form. · Add a notification message to be shown at the top of the next page shown in the Web application. · Redirect to another page that lists the created / modified DB object. As the “Post-Redirect-Get” pattern says, in Web applications it is highly recommended to redirect to another page after executing an action that changes something at the server side:. The missing part in ASP.NET MVC is the notification system, so developers should either create it, or use some NuGet package that provides notification messages in ASP.NET MVC. Let’s install and use the NuGet packageBootstrapNotifications: 1. From the package management console in Visual Studio install the NuGet package BootstrapNotifications in the Events.Web project: NuGet will add the class Extensions\NotificationExtensions.cs: NuGet will also add a partial view \Views\Shared\_Notifications.cshtml: 2. To display the notification messages (when available) at the top of each page in the MVC project, render the _Notifications partial view in the site layout, just before the @RenderBody(): 3. Put notifications in the controller actions after successful database change. Use NotificationType.INFO for information messages (success) and NotificationType.ERROR for error messages. Not that these notifications will render after the first redirect to another page, because the implementation relies on the TempData dictionary in ASP.NET MVC. Add notification messages after db.SaveChanges() in the actions that change the database, followed by RedirectToAction(…): 4. Run and test the application. Create an event to see the “Event created.” notification message: This looks a bit ugly, so add a fix in the \Content\Site.css: 5. Save the changes, refresh the site with [Ctrl + F5] and create a new event to test the changes: Step 12. Date / Time / Duration UI Controls The “New Event” form displays fields for entering date + time and duration. Currently the editor for these fields is not user-friendly. The date format is unclear and there is not calendar control. Let’s fix this. Let’s add “date-time picker” for the date and duration fields: 1. Install the NuGet package “Bootstrap.v3.Datetimepicker.CSS“: It will add the following files to your MVC project: · \Scripts\bootstrap-datetimepicker.js · \Scripts\moment.js · \Content\bootstrap-datetimepicker.css These files should be includes in all pages that use the date-time picker. 2. Create CSS and JavaScript bundles for the date-time picker: 3. Create a placeholder for the CSS bundles in the _Layout.cshtml: It will be used later to inject the date-time picker’s CSS from the events editor form. 4. Add the date-time picker’s scripts and CSS files in the “New Event” form, in \Views\Create.cshtml: This code will inject the specified CSS from the bundles in the page header: It will also inject the specified JavaScript from the bundles at the end of the page: 5. Now the site is ready to add the date-time picker in the “New Event” form. Let’s try to attach the date-time picker for the field “StartDateTime” in \Views\Events\Create.cshtml: 6. Now rebuild the project and run the code to test the new functionality. It does not work due to JavaScript error: 7. Seems like jQuery is not loaded. This is because the script for attaching the datetimepicker for the StartDateTime field uses jQuery, but the jQuery library loads later, at the end of the HTML document. This is easy to fix, just move the jQuery reference at the start of the HTML code in _Layout.cshtml: 8. Now rebuild the project and run the code to test again the new functionality. It should now work correctly: 9. In similar way, add a time picker for the “Duration” field: 10. Test the new duration picker by starting the Web application: Step 13. Client-Side Unobtrusive Validation Now the “New Event” form works as expected. There is a small UI problem: when invalid data is entered, the form validation is executed at the server side and the user sees the validation errors after post-back, with a small delay. Let’s try to add client-side form validation. This is really easy, just insert the Microsoft jQuery Unobtrusive validation JavaScript bundle at the page holding the form: Test the “New Event” form to ensure the validation is now client side. Step 14. List My Events Now let’s list current user’s events at its personal events page: \Events\My. 1. First, add [Authorize] attribute in the EventsController: The [Authorize] attribute will redirect the anonymous users to the login form. It says that all controller actions of the EventsController can be accessed by logged-in users only. 2. Next, add the HTTP GET controller action “My” in EventsController that will display current user’s events: 3. Finally, create the view My.cshtml behind the above action. It is essentially the same like the Index.cshtml view of the HomeController, right? Duplicating code is very bad practice, so let’s reuse the code. First, extract a partial view \Views\Shared\_Events.cshtml, then reference it from \Views\Events\My.cshtml and again from \Views\Home\Index.cshtml: 4. Test the new functionality “My Events“, as well as the old functionality “Home Page“: 5. Try also to access “My Events” for anonymous user. The application should redirect you to the login page: Step 15. Edit Existing Event Form The “Edit Event” functionality is very similar to “Create Event“. It uses the same input model Events.Web.Models.UpcomingPassedEventsViewModel. Create a view \Views\Events\Edit.cshtml and reuse the logic from \Views\Events\Create.cshtml by extracting a partial view \Views\Events\_EventEditorForm. Step 16. Edit Existing Event Logic Write the controller action for editing events in the EventsController. 1. Write a HTTP GET action “Edit” to prepare the form for editing event. In case of invalid event ID, show an error message and redirect to “My Events“: 2. The logic in LoadEvent(id) method loads an existing event in case the user has permissions to edit it: 3. Write a HTTP POST action “Edit” to save the changes after submitting the event editing form. It should first check the event ID and show an error of case of non-existing event or missing permissions. Then it checks for validation errors. In case of validation errors, the same form is rendered again (it will show the validation errors). Finally, the Edit method modifies the database and redirects to “My Events“: 4. Run and test the new functionality “Edit Event” by opening \Events\Edit\3. Step 17. Handling HTML Special Characters Try to create an event named “<New Event>“: It will fail, because by default ASP.NET MVC does not allow forms to send HTML tags in the fields values. This is to help protecting from Cross-Site Scripting (XSS) attacks. You will see an ugly error page: This is very easy to fix, just add [ValidateInput(false)] attribute in the BaseController: Step 18. Delete Existing Event Form Create a form and controller action, similar to “Edit Event”. The form should load the event data in read-only mode with [Confirm] and [Cancel] buttons. Step 19. Delete Existing Event Logic The logic behind the “Delete Event” from is similar to “Edit Event”. Try to implement is yourself. Step 20. Add Comments with AJAX For each comment implement [Add Comment] button that shows (with AJAX) a new comment form. After the form is submitted, it creates a comment and appends it after the other comments for the current event. Comments can be added by the currently logged-in user and anonymously (without login). Step 21. Delete Comments Comments can be deleted only by their author (owner) and by administrators. Display [Delete] button right after each comment in the events (if deleting is allowed). Clicking [Delete] should delete the comment after modal popup confirmation. Step 22. Add Paging Implement paging for the events. Display 15 events per page. At each page display the pager holding the number of pages as well as [Next Page] / [Previous Page] links. Step 23. Upload and Display Event Image Modify the “Create Event” form to upload an image for the event (optionally). The image should be at most 100 KB, max width 400, max height 400, min width 100 and min height 100 pixels. Images should be gif, png orjpeg files, stored in the file system, in files named like this: event-185.png. Hold the images in a directory “~/Images“. Protect the directory to disable direct HTTP access to it. Create an action /event/image/{id} to download and display an event image. It should read the image from the file system and display it if the user is allowed to view it (owner or administrator or public event). Modify the event listing views to display the image for each event (when available). Use max-width and max-height attributes to ensure the image will resize correctly for different sizes of its container. The Full Source Code of the Events MVC Application Download the fully-functional application source code here: (see section “Lab”). 27 Responses to “ASP.NET MVC Practical Hands-On Lab Tutorial (Free from the Software University)” Може би е добра идея да се включи и AngularJs към един такъв туториал, и там да се разгледа пак фронт-енд MVC дизайна на ангулар и как може да се ползва той за хибридни mobile apps с asp.net. Това би запалило повече хора по ASP.NET MVC 🙂 Да, има още какво да се добави, включително за AngularJS, нали имаме цял курс за него в СофтУни… Това са първите 55 страници. За повече не стигне времето. Написах ги само за 4 дни усилена работа. Гледам за всеки курс да пускам по един такъв лаб, за да може хората да минат през него и да почувстват технологията в ръцете си. Много по-силно е сам да си напишеш проекта (макар и следвайки готови стъпки), вместо да гледаш как някой друг пише код пред тебе на живо. Лека полека в СофтУни ще правим все повече такива практически step-by-step учебни материали, лабове и самоучители, за да се вдигне нивото на успеваемост сред студентите. Загрижен съм, че само 30% от нашите студенти завършват. Останалите се отказват защото им е трудно или не им стига времето. good idea to have — I went to the LAB section , and download the zip folder a few time but somehow it cannot even about to unzip, then copy and paste to another folder successfully — it is kind of SCAM so it is BAD < very BAD This is an excellent tutorial. Would you please re-submit the code download as the files cannot be unzipped. Thanks. The ZIP file with the Lab source code works perfectly fine: Thanks nakov for re-submitting the download. The issue is not with the code. I simply cannot unzip the zip file – there is an ‘unexpected error’ preventing the file from unzipping. Any ideas? Kind Regards. Walter. Thanks for this great post, but it looks like i have a problem too with unzipping the file 🙁 I just unzipped it successfully with 7zip, with winrar im getting errors, so @Walter, you can try the same if you havent got the file by now. Thanks again for this. @V Thank you. 7Zip worked for me too. Thanks for sharing your discovery. Thanks @nakov for the Lab. Hi there, thanks for the lab, it has been a great help. Just wondering, when i change the code in CreateSeveralEvents method in DbMigrationsConfig, it is not implementing once I launch the solution on any browser. I.e. if I change “Party @ Softuni” to “test”, it does not change. Any suggestions for a beginner? Many thanks. The CreateSeveralEvents() method in the database migrations runs once, when the database is first created. The easiest way to re-create the events is to DROP the entire database and it will be created again. U said that code duplicating is very bad practice but u have duplicated code in Home controller’s Index method and Events controller’s My method. What if i have 10 view pages then i have to put same code in all 10 controller to show on view page.how to resolve this ??? The object-oriented programming says that common logic should be moved to base classes and specific logic should stay in child classes. In our case you should have BaseController (base, parent class) to hold the shared code and seveal child cntroller (child, derived classes) to hold the page-specific code. Hi, I really appreciate the way you present the thing but it would looks more fine if you’ll consider update your article using a DI container like (Ninject, Unity). hi.. 🙂 pls send me a link to create comment pls. in Step20. Details Of The Md Science Lab Max Load […] ²Ð¸ ÑÑÑпкР[…] Thanks nakov for your time. God bless. Sorry, I meant Nakov*. Practical Microsoft Visual Studio 2015 […] µÑки step-by-step ÑÑебни маÑеÑиали, лабове и ÑÐ°Ð¼Ð¾Ñ […] Thank you for this tutorial, I have one question : where can I find the Events databases ? Opps sorry, It will be create automatically Beginning Aspnet 20 Databases […] ¸Ñе код п […] i am hvaing this error. System.Exception: Name admin@admin.com is already taken. Practical Aspnet Web Api […] ли, лабове и самоучители, за да се вдигне нив […] Thank you for sharing. How I can add Event Attendee and too users can registering for a event as Attendee Any Idea?? Please Thanks when I Build and run Step 8.9 Not display Events only Id of Upcoming and Passed Events. please solve the issue Your blog is very nice… Thanks for sharing your information…
http://www.nakov.com/blog/2015/05/28/free-asp-net-mvc-hands-on-lab/
CC-MAIN-2018-34
refinedweb
5,776
67.15
24 April 2009 10:23 [Source: ICIS news] Correction: In the ICIS news story headlined “Sinopec finalises higher PTA, MEG prices for Mar in ?xml:namespace> SHANGHAI (ICIS news)--China’s Sinopec has finalised its prices for purified terephthalic acid (PTA) and monoethylene glycol (MEG) sold within the domestic market in April at sharply higher levels due to strong demand and tight supply, company officials said on Friday. The PTA price was pegged at yuan (CNY) 7,300/tonne ($1,069/tonne) DEL (delivered), while the MEG price was CNY4,600/tonne DEL. These numbers represented jumps of CNY1,050/tonne and CNY900/tonne respectively from the previous month’s final values. “Demand has been strong, and we don’t have too much to sell anyway,” said one of the Sinopec officials. Sinopec is ($1 = CNY6.83) Clytze Yan and Freya Tang of CBI China contributed to this article For more information on MEG
http://www.icis.com/Articles/2009/04/24/9210739/corrected-sinopec-finalises-higher-april-pta-meg-prices-in-china.html
CC-MAIN-2014-42
refinedweb
154
68.4
App::AltSQL - A drop in replacement to the MySQL prompt with a pluggable Perl interface .). There are a few key issues that this programmer has had with using the mysql client every day. After looking for alternatives and other ways to fix the problems, reimplementing the client in Perl seemed like the easiest approach, and lent towards the greatest possible adoption by my peers. Here are a few of those issues: All of the shells that we used on a daily basis allow you to abandon the half-written statement on the prompt by typing Ctrl-C. Spending all day in shells, you expect this behavior to be consistent, but you do this in mysql and you will be thrown to the street. Let's do what I mean, and abandon the statement. We are grateful that mysql at least uses ASCII art for table formatting (unlike sqlite3 for some reason). But there are some tables that I work with that have many columns, with long names (it's often easier to keep adding columns to a table over time). As a result, when you perform a simple `select * from fim limit 4` you quickly find your terminal overwhelmed by useless ASCII art attempting (and mostly failing) to provide any semblance of meaning from the result. You can throw a '\G' onto the command, but if it took 10 seconds to execute and you locked tables while doing it, you could be slowing down your website or letting your slave fall behind on sync. Suffice it to say, it's a much better experience if, just like with git diff, wide output is left wide, and you are optionally able to scroll horizontally with your arrow keys like you wanted in the first place. Most other modern programs we developers use on a daily basis (vim, ls, top, git, tmux, screen) offer to provide additional context to you via color. By consistently setting colors on a variable type or file type, programs can convey to us additional context that allows us to better grasp and understand what's happening. They help us be smarter and faster at our jobs, and detect when we've made a mistake. There's no reason we shouldn't use color to make it obvious which column(s) form the primary key of a table, or which columns are a number type or string type. The DBI statement handler contains lots of context, and we can interrogate the information_schema tables in mysql for even more. The usage of '|', '+' and '-' for drawing tables and formatting data seems a bit antiquated. Other tools are adopting Unicode characters, and most programmers are now using terminal programs that support Unicode and UTF8 encoding natively. The Unicode box symbol set allows seamless box drawing which allows you to read between the lines, so to speak. It is less obtrusive, and combining this with color you can create a more useful and clear user experience. I've thought of a number of other features, but so too have my coworkers and friends. Most people I've spoken with have ideas for future features. Next time you're using your DB shell and find yourself irritated at a feature or bug in the software that you feel could be done much better, file a feature request or, better yet, write your own plugins. The command line arguments inform how to connect to the database, whereas the configuration file(s) provide behavior and features of the UI. The following options are available. Basic connection parameters to the MySQL database. By default, upon startup and whenever the database is changed, the information_schema tables will be read to perform tab completion. Disable this behavior to get a faster startup time (but no tab complete). We are using Config::Any for finding and parsing the configuration file. You may use any format you'd like to write it so long as it's support in Config::Any.: "%u@%h[%d]> " # 'username@hostname[database]> ' prompt: "%c{red}%u%c{reset} %t{%F %T}> ' # 'username' (in red) ' YYYY-MM-DD HH:MM:SS> ' Provide a custom prompt. The following variables will be interpolated: The username used to connect to the model The current database or '(none)' The hostname the model is connected to An escaped percent sign A Term::ANSIColor color name. The value will be passed directly to the color method. A block to be eval'ed. You may use $self to refer to the App::AltSQL::Term object The argument to this option will be passed to DateTime strftime for the current time An array of plugin names for the main namespace. An array of View plugin names to be applied to each View object created. Hash of the command line arguments Hash of the file configuration Called in bin/altsql to collect command line arguments and return a hashref . Return a config value of the given key in the namespace. Returns empty list if non-existant. Will read in all the config file(s) and return the config they represent Called in altsql to read in the command line arguments and create a new instance from them and any config files found. Start the shell up and enter the readline event loop. Perform any cleanup steps here. The user has just typed something and submitted the buffer. Do something with it. Most notably, parse it for directives and act upon them.. Call App::AltSQL::View new(), mixing in the app and command line view arguments and loading any requested plugins. Your basic logging methods, they all currently do the same thing.>
http://search.cpan.org/~ewaters/App-AltSQL-0.05/lib/App/AltSQL.pm
CC-MAIN-2015-18
refinedweb
936
60.65
Mission: Attempt to explain recursive functions in the way that helped me understand them. Intro When I learned about recursive functions, they made absolutely no sense to me. I understood what output was expected and when to use them, but I didn’t know how they got there and I don’t like using things unless I fully understand them, not least because it makes debugging a nightmare. When I looked for explanations online, all I could find were things along the lines of: Ah, you see, it works on two sides. It works out the left side, and then the right. It’s a function that calls itself until it doesn’t. I was still none the wiser. Of course, these explanations make sense to me now, but sometimes you need things explained to you in a different way, which is what I’m aiming to do for you today. The way I finally understood how they worked was to write my own recursive function on this old fashioned device called a piece of paper. Knowing what the output would be, I worked backwards to see if I could figure it out… and I did! … then I felt stupid for not understanding it in the first place, but hey, that’s programming! What are recursive functions used for? A recursive function is a way of iterating over a block of code until a certain condition is met. If this sounds like a for loop or a while loop, it’s because their use cases are the same, they’re just different ways of achieving the same result. Our function Let’s create a recursive function in Python that prints the sum of all positive integers between 1 and the number we pass it. For example: if we pass our function the number 5, it should output 15 because 5 + 4 + 3 + 2 + 1 = 15. def machine(n): if n == 1: return 1 else: return n + machine(n - 1) What is happening?! In order to explain how this works, I’m going to refer to our function by its name, machine. When we feed the machine a number (n), it first checks if n is equal to 1, and if it does it outputs (returns) 1. Basic stuff so far. If, however, n does not equal 1, the machine outputs n + [ feed the machine (n - 1) ]. This is where it gets a bit confusing. In order for the machine to complete its calculation, it first needs to work out what the result would be if it was fed n - 1. With this in mind, let’s run through the machine’s entire process one step at a time. Step 1: Process 1 The machine is given the number 3. Does 3 = 1? No, move on. Output 3 + [ give machine 2 ]. Stop and give the machine 2. Step 2: Process 2 The machine is given the number 2. Does 2 = 1? No, move on. Output 2 + [give machine 1] . Stop and give the machine 1. Step 3: Process 3 The machine is given the number 1. Does 1 = 1? YES! Output 1! Step 4: Back to Process 2 Now that the machine knows the answer to [ give machine 1 ], it can finish its output calculation. Output 2 + 1 = 3. Step 5: Back to Process 1 Now the machine knows the answer to [ give machine 2 ], it can finish its output calculation. Output 3 + 3 = 6. The Result The machine will output 6! One more example Let’s run the machine with the number 5 this time. Just to remind you of the code: def machine(n): if n == 1: return 1 else: return n + machine(n - 1) machine(5) Feed machine 5 Output 5 + feed machine 4 Feed machine 4 Output 4 + feed machine 3 Feed machine 3 Output 3 + feed machine 2 Feed machine 2 Output 2 + feed machine 1 Feed machine 1 Output 1. Feed machine 2 = 2 + 1 = 3. Feed machine 3 = 3 + 3 = 6. Feed machine 4 = 4 + 6 = 10. Feed machine 5 = 5 + 10 = 15. Result = 15! The Pattern You might start being able to see a really nice symmetrical pattern with how this works, and you may even start to see why people explain it as working on ‘2 sides’. If we wrote the above a bit differently, the ‘sides’ explanation might make more sense. Read the left column from top to bottom, then the right column from bottom to top. This process is referred to as ‘The Call Stack’: a stack of functions that need to be solved in turn, so the next function in the stack can be completed. Can’t we just use a for loop? Yep! Our machine function utilising a for loop might look something like this: def machine(n): sum = n for x in range(n): sum += x return sum What we’re doing here is setting a variable sum equal to the number we pass the function (n), then looping through numbers 0 - n (exclusively), then adding the current iteration to the value of sum. Then we return sum. Pitfalls Much like a for loop, we can set a recursive function to easily loop infinitely - not a good thing. Always make sure there is a ‘base case’ in a recursive function which will cause the recursion to stop. In our recursive machine function, our ‘base case’ is: if n == 1: return n. We are also decrementing n with each recursive call with else: return n + machine( n - 1 ). This means that with each function call, we call the function with a number 1-less than the previous iteration, and we stop when n is equal to 1. Where are all my Javascript homies? I’ve written this post using Python as my language of choice, however, please see below the 2 functions I’ve written in Javascript. // Recursive function machine(n) { if (n === 1) { return n; } else { return n + machine(n - 1); } } // Iterative function machine(n) { let sum = n; for (let i = 0; i < n; i++) { sum += i; } return sum; } Wrap it up wrap it up I hope that this has helped you understand recursive functions. There are obviously a million and one use cases and examples we could go through, but by understanding how they work and the fundamentals behind them, hopefully you’ll be able to use them in a future project in your own way. For further reading on recursive functions, I would highly recommend this article by Beau Carnes on Free Code Camp: Happy coding :) Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/kaxmoglan/recursive-functions-explained-5hie
CC-MAIN-2021-25
refinedweb
1,093
80.01
Domain Model Learning Outcomes Why domain models are better for storing application state. How to structure our application to use a domain model. What are Domain Models? A good practice when writing Angular code is to try to isolate the data structures you are using from the component code. Right now our data structure is just an array of objects which we initialised on the component. We also have this toggle function which doesn’t do anything other than modify a property of the object passed in, i.e. the function could exist outside of the component completely and still do it’s job just fine. Imagine if this was a much larger application, if all the data was stored inside components as plain objects it would be hard for a new developer to find out where the data is stored and which function to edit. To solve this, let’s create a class that represents a single joke and attach the toggle function to that class. This class is what we call a Domain Model, it’s just a plain class which we will use to store data and functions. Our Domain Model We create a simple class with 3 properties, a constructor and a toggle function, like so: class Joke { setup: string; punchline: string; hide: boolean; constructor(setup: string, punchline: string) { this.setup = setup; this.punchline = punchline; this.hide = true; } toggle() { this.hide = !this.hide; } } As we’ve mentioned before we can instantiate a class by using the new keyword and when that happens javascript calls the constructor function where we can have code that initialises the properties. However the constructors we’ve used so far have not had any arguments, the one for the joke class above does. It initialises the properties of the joke instance from the arguments passed into the constructor. We can pass those arguments in when we instantiate a joke like so: let joke = new Joke("What did the cheese say when it looked in the mirror?", "Hello-Me (Halloumi)"); We also added a toggle function which just flips the value of the hide property. Note thisin a class function to distinguish between properties that are owned by the class instance vs. arguments that are passed in or declared locally by the function. So this.jokein our toggle function is explicitly saying the jokeproperty on the class instance. Now lets change our JokeListComponent so it uses our domain model, like so: class JokeListComponent { jokes: Joke[]; (1) constructor() { this.jokes = [ (2)’"), ]; } toggle(joke) { joke.hide = !joke.hide; } } The final thing to do is to change the markup in the template so we call the joke.toggle() function on the joke instance and not the toggle(joke) function on the component, like so: <a class="btn btn-warning" (click)="joke.toggle()">Tell Me</a> Summary Although its possible to store all your data as objects it’s both recommend and simple to encapsulate your data into domain models in Angular. Using a domain model clarifies for all developers where you should put functions that need to act on the data, like our toggle function. Listing import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {NgModule}-list', template: ` <div class="card card-block" * <h4 class="card-title">{{joke.setup}}</h4> <p class="card-text" [hidden]="joke.hide">{{joke.punchline}}</p> <a class="btn btn-warning" (click)="joke.toggle()">Tell Me</a> </div> ` })’"), ]; } } @NgModule({ imports: [BrowserModule], declarations: [JokeListComponent], bootstrap: [JokeListComponent] }) export class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule);
https://codecraft.tv/courses/angular/quickstart/domain-models/
CC-MAIN-2018-34
refinedweb
578
54.93
On Monday, TiVo announced a Java SDK called the Home Media Engine (HME) and a corresponding simulation tool, all for writing PC applications that target their digital recorder box. The announcement has been heralded in many forums, notably slashdot , the New York Times, EWeek, Yahoo News, etc. You'd be hard pressed to discover the fact that TiVo's new SDK is a set of Java APIs and a new J2SE-based tool in most of the coverage, so naturally I'll try to fill that embarrassing lacuna here. The TiVo SDK and simulator tool run on J2SE 1.4.2 or 1.5 and they're available for free on now. The documentation appears to be comprehensive enough and there are enough examples to kick-start development. Plus the source code for the entire SDK is provided. The only thing lacking for yours truly is a TiVo box at home to really complete the experience. Sadly, that will have to wait. Fortunately one can obtain a reasonable TiVo developer experience facsimile by running applications against the simulator screenshot here ). Just for the record, I wasn't able to run the samples "right out of the box" on my Java Desktop System laptop due to some confusion about the IP address for my machine's ethernet port. The symptom was a "java.net.MalformedURLException". The fix was to lookup the eth0 address using ifconfig and pass that as well as a port number to the sample app on the command line: > /sbin/ifconfig eth0 | fgrep "inet addr" inet addr:129.145.161.189 Bcast:129.145.161.255 Mask:255.255.254.0 > java -cp simulator.jar:samples/samples.jar com.tivo.hme.sim.Simulator com.tivo.hme.samples.hello.HelloWorld -i "129.145.161.189" -port 7288 TiVo's developer forum on sourceforge.net was helpful for sorting this little snafu out. What may be becoming clear from all of this is that TiVO HME applications are actually servers that the TiVo box or the simulator tool discover and connect to. You don't download applications into the box, the application or application service running on your PC sends commands to the box and receives events, roughly like an X11 client would. Unlike an X11 client, an HME service includes a factory that generates a new instance of your application for each TiVo box that connects to it. This aspect of the HME SDK will not be much of a concern while you're prototyping an app for the TiVo box in your living room. If you wanted to turn your creation into a service for all, then you'd have to think carefully about the sorts of scaling issues that application server folks worry about. The HME SDK is a small API. It makes it possible for an app running on your PC to map data from the internet to a visualization that's appropriate for your TV. HME applications build hierarchies of translucent rectangular View objects where each View contains one image, text, or color resource. A View corresponds to the essence of a GUI component, it just defines a 2D coordinate system and a clip rectangle. There's an HME Application class which defines a root view and you override its init() method to add your own views to that, e.g.: public class MyApplication extends Application { protected void init(Context context) { View v1 = new View(this.root, 0, 100, this.width, 100); View v2 = new View(this.root, 0, 200, this.width, 200); Resource text = createText("default-36.ttf", Color.white, "Hello")); v1.setResource(text); ImageIcon icon = new ImageIcon("myImageFile.png"); Resource image = createImage(icon.getImage()); v2.setResource(image); } } In this example the Resource createXXX methods create text and image resources on the TiVo box synchronously. It's also possible to stream images resources from an arbitrary URI to the box. At the moment there's no support for streaming or playing videos, an unusual limitation for a TV device. There's no way to gain access to the TiVo's archive of recorded material either; of course this is only an "early access" release of the SDK. Event dispatching is a similarly no-frills affair. The TiVo box sends events for everything from the TV keyboard and remote control to progress reports per downloading a streamed resource, back to the application. The application can deal with them by overriding an Application method called handleEvent(). One novel feature of the HME SDK is support for animation. Some of the methods that set View properties take an extra string argument that specifies how to animate the transition from the properties current value to the new one. For example to "fade in" a View over a period of 500 milliseconds one could write: myView.setTransparency(1.0f); // initially transparent myView.setTransparency(0.0f, "*500"); // 500ms, linear ramp One can animate changes in a View's bounds, origin, scale, and transparency. One can also specify a second animation parameter (also part of the string) that defines how fast the animation accelerates and decelerates to/from the linear ramp. I suspect that's enough of an introduction to this new SDK. I didn't cover the support for loading/streaming audio clips however it was nice to see that the TiVo folks picked up the JLayerME MP3 decoder (featured in the Swing Sightings column back in April 2002) from JavaZoom, see for the latest information about that. It's cool that TiVo are doing this, don't get me wrong, but does anyone know if you can write java extensions of MythTV ? I'm currently setting up a box for home purposes and would love to write some extras in Java. Otherwise I'd need to learn whatever it is that MythTV is written in . Posted by: luggypm on February 02, 2005 at 12:51 AM I wrote a quick tutorial on how develop TiVO apps in NetBeans - it's trivial to get set up so pressing F6 runs the app in the emulator, etc. Posted by: timboudreau on February 03, 2005 at 04:54 PM
http://weblogs.java.net/blog/hansmuller/archive/2005/02/inside_tivos_ne.html
crawl-002
refinedweb
1,017
54.73
Fractional second support up to microseconds has recently been added in MySQL 5.6.4 and higher. I was hoping that MySQLdb will add support for this feature with timedelta. Currently, to bypass this issue I have modified MySQLdb/times.py and it seems to be working for my purposes. def format_TIMEDELTA(v): microseconds = v.microseconds seconds = float(v.seconds) % 60 minutes = int(v.seconds / 60) % 60 hours = int(v.seconds / 3600) % 24 return '%d %d:%d:%d.%06d' % (v.days, hours, minutes, seconds, microseconds) Although my patch seems to be working, to be more robust I expect that timedelta millisecond support might also be needed.
http://sourceforge.net/p/mysql-python/feature-requests/24/
CC-MAIN-2014-23
refinedweb
106
71.61
Encoding and Decoding non-ASCII text using EMA and RFA C++/.NET Overview This article explains how to encode and decode RMTES String containing non-ASCII text using EMA and RFA C++ and .NET edition. Currently, our APIs does not provide RMTES encoder, therefore, it has been a question from developers when they want to publish data containing non-ASCII text such as Chinese and Korea language to Elektron Real-Time network. Moreover, a user usually found the issue that their application unable to display non-ASCII text properly. This is because the data that the application receives containing garbage characters at the beginning of a string. We will be talking about the background of these issues and its solution in this article. A problem in the Consumer application There are some fields in the data dictionary that using RMTES_String data type and it was designed for use with the local language. The problem that the user often see is that it containing garbage string like "%0" at the beginning of the text. And below is a sample output from API example which contains the garbage character. It's data from field DSPLY_NML which represents local language instrument name for RIC ".HSI" and "0005.HK" Note that FID DSPLY_NMLL is RMTES_STRING as indicate in RDMFieldDictionary file. DSPLY_NMLL "LCL LANG DSP NM" 1352 NULL ALPHANUMERIC 32 RMTES_STRING 32 .HSI FieldEntry [ 1080] PREF_DISP 2191 FieldEntry [ 1352] DSPLY_NMLL "%0恒生指數" FieldEntry [ 1709] RDN_EXCHD2 HSI (456) 0005.HK FieldEntry [ 1080] PREF_DISP 5780 FieldEntry [ 1352] DSPLY_NMLL "%0匯豐控股" FieldEntry [ 1404] ODD_VOLUME 18364 Considering raw data from RFA and EMA tracing log below, The garbage string from above sample texts usually contains three bytes character at the beginning of the text and there are 0x1B, 0x25 and 0x30 which is garbage characters "", "%" and "0". .HSI <fieldEntry fieldId="1080" data="088F"/> <fieldEntry fieldId="1352" data="1B25 30E6 8192 E794 9FE6 8C87 E695 B8"/> <fieldEntry fieldId="1709" data="01C8"/> 0005.HK <fieldEntry fieldId="1080" data="1694"/> <fieldEntry fieldId="1352" data="1B25 30E5 8CAF E8B1 90E6 8EA7 E882 A1"/> <fieldEntry fieldId="1404" data="0E47 BC"/> Actually, these three bytes character are not garbage character. There is an escape sequence used by our data feed component for the text encoded with UTF-8. You may also see difference format of garbage character at the beginning of the string and it could be other character sets used by our internal publisher application. If the application calls DataBuffer.getAsString() method in RFA or using getAscii in EMA, it would return the actual string including the escape sequence. This is because the method does not have a built-in RMTES decoder. Normally RFA application can use RMTES Converter interface in order to get an actual UTF-8 text from the DataBuffer or just calling fieldEntry.getRmtes().toString() in EMA. We will provide more details about the background of the escape sequence in the next section. RMTES Encoding Basically, RMTES uses ISO 2022 escape sequences to select the character sets used. RMTES provides support for Reuters Basic Character Set (RBCS), UTF-8, Japanese Latin and Katakana (JIS C 6220 - 1969), Japanese Kanji (JIS X 0208 - 1990), and Chinese National Standard (CNS 11643-1986). RMTES also supports sequences for character repetition and sequences for partial updates. These characters set or format internally used by various infra components. Unfortunately, there is no open RMTES encoder library provide for external user or customer. There are many questions from application developers who want to create publishing or contributing application, and it has to publish RMTES string which contains non-ASCII text such as Japanese and Chinese characters. Implementing their own RMTES encoder is not easy and it's a very complex format. However, there is an alternative choice for this case as the developer can use the switching function provided for encoding RMTES string and switching from default ISO 2022 scheme to UTF-8 character set. It could say that the developer can use the UTF-8 character set to publish data for RMTES field type. They can use the function to encode the UTF-8 string into RMTES string and then publish the string to the system. The switching function is permitted only at the very start of a field and it contains three bytes of characters that are 1B 25 30. 0x1B 0x25 0x30 The function is permitted only at the very start of a field. The application could prepend 0x1B, 0x25, 0x30 to the UTF8 string and encode that way as an RMTES type. The escape sequence characters indicate to the RMTES parser or decoder that it’s supposed to be a UTF-8 string. As a result, there is a reason that the samples data from field DSPLY_NMLL for RIC ".HSI" and "0005.HK" start with the three bytes escape sequence character 0x1B 0x25 and 0x30. Please note that you need to be very careful with using that three-byte string, as it can cause the UTF-8 string to be longer than the cached dictionary values which are the size of RWF LEN column in a byte from RDMFieldDictionary. It can cause display issues if they’re going through the infra. The non-ASCII character such as Chinese, Thai, Japanese and Korea language can be used UTF-8 character set, therefore, the application can use this way to encode the non-ASCII text instead. We will talk about the implementation in RFA and EMA C++/.NET in the next section. Publishing non-ASCII RMTES string in RFA application As described earlier, the publishing or contributing application can encode the non-ASCII text with UTF-8 instead of implementing RMTES encoder. The application can just prepend the three bytes escape sequence 0x1B, 0x25, and 0x30 to the UTF8 string and encode in the DataBuffer class as RMTES string. Below is sample codes for RFA C++ and you can add the codes to our provider example such as Provider_Interactive example provided with the RFA C++ package in order to test the codes. You can modify codes in file MarketByPriceStreamItem.cpp method MarketPriceStreamItem::encodeMarketPriceFieldList to publish additional FID which use RMTES_String data type. In this case, we will add FID 1352 DSPLY_NMLL which holds local language instrument name to the codes. Below sample codes use u8 literal from C++ 11 to create UTF-8 string. You can use another library or a different approach to create a UTF-8 string. Note that u8 literal requires Visual Studio 2013 or later version and you may need to add -std=c++11 when compiling the example on Linux. // Setup DSPLY_NMLL field field.setFieldID(1352); // Local lanaguage instrument name for Hang Seng Index std::string utf8Str = u8"恒生指數"; unsigned char displayNameBytes[50]; memset(displayNameBytes, 0, 50); //set three bytes escape sequences displayNameBytes[0] = 0x1B; displayNameBytes[1] = 0x25; displayNameBytes[2] = 0x30; //Add UTF-8 String to the buffer memcpy(displayNameBytes + 3, utf8Str.c_str(),utf8Str.length()); //Create RFA Buffer and set it to DataBuffer. The type should be StringRMTESEnum Buffer bf; bf.setFrom(displayNameBytes, (int)utf8Str.length()+3); dataBuffer.setBuffer(bf, DataBuffer::StringRMTESEnum); field.setData(dataBuffer); pfieldListWIt->bind(field); And the following codes are for RFA.NET Provider application. You can try sample C# codes with Provider_Interactive from RFA.NET package. Just modify the codes in file MarketPriceStreamItem.cs method EncodeMarketPriceFieldList. // Setup DSPLY_NMLL field field.FieldID = 1352; // Local language instrument name for Hang Seng Index var utf8Str = Encoding.UTF8; //using Encoding class from System.Text List<byte> displayNameBytes = new List<byte>(); //Set three bytes escape sequences displayNameBytes.Add(0x1B); displayNameBytes.Add(0x25); displayNameBytes.Add(0x30); //Add bytes data for the UTF-8 string to displayNameBytes bytes array displayNameBytes.AddRange(utf8Str.GetBytes("恒生指數")); //create buffer and set it to data buffer, the type should be StringRMTESEnum RFA.Common.Buffer bf=new RFA.Common.Buffer(); bf.SetFrom(displayNameBytes.ToArray(),displayNameBytes.Count); dataBuffer.SetBuffer(bf, DataBuffer.DataBufferEnum.StringRMTES); field.Data = dataBuffer; fieldListWIt.Bind(field); Below is sample outgoing RSSL tracing log generated by the RFA Provider application. Comparing the data with sample data we described earlier, it's the same and identical one. <fieldEntry fieldId="1352" data="1B25 30E6 8192 E794 9FE6 8C87 E695 B8"/> An output from RFA StarterConsumer which has RMTES decoder, it can display the Chinese text correctly without garbage character. We will describe decoding RMTES string in Decoding RMTES section. FieldEntry [ 2] RDNDISPLAY 100 FieldEntry [ 4] RDN_EXCHID SES (155) FieldEntry [ 38] DIVPAYDATE 12/10/2005 FieldEntry [ 1352] DSPLY_NMLL "恒生指數" FieldEntry [ 6] TRDPRC_1 1.00 FieldEntry [ 22] BID 0.99 Publishing non-ASCII RMTES string in EMA application Using the same approach in EMA C++ is easier than RFA. You can just add the UTF-8 string like the RFA C++ to FieldList and then publish the data to the wire. In order to test the codes, you can use Provider interactive example from EMA C++ package. For testing the codes, we use example 200MarketPriceStreaming to publish the same Chinese text. You can modify and use below codes in file IProvider.cpp method AppClient::processMarketPriceRequest. // Local lanaguage instrument name for Hang Seng Index std::string utf8Str = u8"恒生指數"; char displayNameBytes[50]; memset(displayNameBytes, 0, 50); //set three bytes escape sequences displayNameBytes[0] = 0x1B; displayNameBytes[1] = 0x25; displayNameBytes[2] = 0x30; //prepend UTF-8 string memcpy(displayNameBytes + 3, utf8Str.c_str(), utf8Str.length()); EmaBuffer emaBuffer; emaBuffer.setFrom(displayNameBytes, (int)utf8Str.length() + 3); event.getProvider().submit( RefreshMsg().name( reqMsg.getName() ).serviceName( reqMsg.getServiceName() ). state( OmmState::OpenEnum, OmmState::OkEnum, OmmState::NoneEnum, "Refresh Completed" ).solicited( true ). payload( FieldList(). addRmtes(1352, emaBuffer ). // Add fid 1352 DSPLY_NMLL to FieldList addEnum( 15, 840 ). ... complete() ). complete(), event.getHandle() ); The outgoing message from EMA tracing log shows the same value as RFA. You should get the same result as RFA C++ when using OMM Consumer which has RMTES decoder subscribe the data from the Provider example. <fieldEntry fieldId="1352" data="1B25 30E6 8192 E794 9FE6 8C87 E695 B8"/> Decoding RMTES RFA and EMA generally provided RMTES converter or parser interface for converting the encoded RMTES string payload received as part of the OMM data to a Unicode string. It helps display news in international languages with UCS2 format or transfer data through the network in ISO 2022 and UTF-8. The following section will provide a guideline for applications that want to display non-ASCII string correctly. Displaying non-ASCII RMTES string in RFA Consumer application RFA provides RMTESConverter interface to convert RMTES string back to a readable string. The interface is useful for converting the encoded RMTES string payload received as part of the OMM data to a Unicode string. It helps display news in international languages with the UCS2 format or transfer data through the network in ISO 2022 and UTF-8 format. The RMTESConverter interface provides the following major functions: - setBuffer(): binds a buffer to a converter (with a heap allocation). If the offset passed into the function is -1, the buffer passed in contains full field data and RFA will internally cache the buffer in memory. If the offset is equal to or greater than 0, the buffer passed in contains partial field data and RFA will internally apply the partial field data on the earlier cached buffer based on offset. The cached buffer should contain full field data. - getAsCharString(): returns a UTF-8-formatted string as an RFA_String. - getAsShortString(): returns a UCS2-formated string as an RFA_Vector in RFA C++ or List in RFA.NET. Each item in the vector is a short which holds a char and each item in List is a char which holds a character. The size of the vector or List is the total number of characters. Sample Codes for RFA C++ RFA C++ example such as StarterConsumer cannot decode data buffer which contains non-ASCII text. However, the user can add RMTESConverter to StarterConsumer when it decoding the data buffer. You can open StarterConsumer project and add below codes to StandardOut.cpp in method void StandardOut::out( const DataBuffer& dataBuffer ). Note that below codes are just sample codes for decoding generic RMTES string and it does not support partial RMTES update. If you want to decode partial RMTES update, an application has to cache the RMTESConverter object and apply all received changes to them. You can find more details about RMTESConverter from RFA C++ Development guide. #include "Common/RMTESConverter.h" ... case DataBuffer::StringRMTESEnum: { RMTESConverter converter; //set DataBuffer to RMTESConverter converter.setBuffer(dataBuffer.getBuffer()); //get UTF-8 string from RMTESConverter RFA_String utf8Str = converter.getAsCharString(); int buffSize = utf8Str.size(); sData = new char[buffSize + 1]; strncpy(sData, (char*)utf8Str.c_str(), buffSize); sData[buffSize] = '\0'; write("\"%s\"", sData); delete[] sData; } break; Open StarterConsumer_Log on a text editor, you should see chinese text displayed correctly. FieldEntry [ 1051] GV2_DATE 5/5/2017 FieldEntry [ 1080] PREF_DISP 2191 FieldEntry [ 1352] DSPLY_NMLL "恒生指數" FieldEntry [ 1709] RDN_EXCHD2 HSI (456) FieldEntry [ 3263] PREV_DISP 0 Sample Codes for RFA.NET Like the RFA C++, we use StarterConsumer to demonstrate the codes for decoding the RMTES string and shows the non-ASCII text returned by DSPLY_NMLL fid. You can open StarterConsumer project from RFA.NET package and then open file StandOut.cs and then add below codes to method public void Out(DataBuffer dataBuffer) case DataBuffer.DataBufferEnum.StringRMTES: { RMTESConverter conv = new RMTESConverter(); //set DataBuffer to RMTESConverter conv.SetBuffer(dataBuffer.GetBuffer()); //get UTF-8 string from RMTESConverter var utf8Str = conv.GetAsCharString(); RFA_String sData = new RFA_String(utf8Str.ToArray()); Console.Write("\""+sData.ToString()+"\""); if (fileWriter != null) { fileWriter.Write("\"" + sData.ToString() + "\""); } } break; If the application has to works with a partial RMTES update message, it has to catch the RMTESConverter object as explained in RFA C++. Please refer to the RFA.NET Development guide for more details about RMTES Usage. Displaying non-ASCII RMTES string in EMA C++ Consumer application Using RMTES on EMA C++ is easier than RFA C++/.NET. This is because EMA provides a built-in RMTES decoder. If needed, the application can cache RmtesBuffer objects and apply all received changes to them. Please refer to EMA C++ Documents for more information about RmtestBuffer class. Sample Codes for EMA C++ Below are sample codes that the application can cache the RmtesBuffer object and apply all received changes to them. // Create RMtesBuffer object and caches it in application thomsonreuters::ema::access::RmtesBuffer rmtesBuffer; ... //Decoding FieldEntry const FieldEntry& fe = fl.getEntry(); cout << "Name: " << fe.getName() << " Value: "; rmtesBuffer.apply( fe.getRmtes() ); cout << rmtesBuffer.toString() << endl; In case that application wants to decode RMTES field and do not need to works with the partial update, it can just call thomsonreuters::ema::access::FieldEntry::getRmtes() to get RMTESBuffer object when it decoding the FieldEntry which has DataType as RmtesEnum. Conclusions In this article, we explain the details of how to decode and encode non-ASCII text in field type RMTES using EMA and RFA C++ or .NET edition. We also provide a snippet of codes to demonstrate the API usages. The developer can try the codes with the examples application provided in the RFA or EMA package. References For further details, please check out the following resources:
https://developers.uat.refinitiv.com/en/article-catalog/article/encoding-and-decoding-non-ascii-text-using-ema-and-rfa-cnet
CC-MAIN-2022-27
refinedweb
2,485
55.74
The HTTP clients provided by many libraries (httplib in the Standard Library, asynchttp, Twisted) do not deal with absolute URLs but instead with the three component parts of host, port, and request URL. However these are not the parts returned by either urlparse.urlsplit or urlparse.urlparse. I therefore suggest it might be useful to have in the Standard Library a function that splits an absolute URL into host, port, and request URL. So for the following URL: "" the function would return ("", 80, "/cgi-bin/moinmoin/FrontPage?action=edit") An optional parameter could specify which port to use as default. Hamish Lawson
https://mail.python.org/pipermail/python-dev/2004-February/042600.html
CC-MAIN-2018-05
refinedweb
102
63.9
#include "inflating_fetch.h" This Fetch layer helps work with origin servers that serve gzipped content even when request-headers do not include accept-encoding:gzip. In that scenario, this class inflates the content and strips the content-encoding:gzip response header. Some servers will serve gzipped content even to clients that didn't ask for it. Depending on the serving environment, we may also want to ask backend servers for gzipped content even if we want cleartext to be sent to the Write methods. Users of this class can force this by calling EnableGzipFromBackend. Adds accept-encoding:gzip to the request headers sent to the origin. The data is inflated as we Write it. If deflate or gzip was already in the request then this has no effect. Analyzes headers and depending on the request settings and flags will either setup inflater or not. Reimplemented from net_instaweb::SharedAsyncFetch. If inflation is required, inflates and passes bytes to the linked fetch, otherwise just passes bytes. Reimplemented from net_instaweb::SharedAsyncFetch. Resets the 'headers_complete_' flag. Reimplemented from net_instaweb::AsyncFetch.
http://modpagespeed.com/psol/classnet__instaweb_1_1InflatingFetch.html
CC-MAIN-2017-09
refinedweb
176
59.6
09 September 2011 11:03 [Source: ICIS news] Correction: In the ICIS story headlined “?xml:namespace> SINGAPORE (ICIS)-- Compared to July, vehicles sales last month were up 8.29%, the China Association of Automobile Manufacturers (CAAM) said. Meanwhile, the country’s vehicle production rose by 8.72% year on year to 1.39m units in August, CAAM said. Vehicle production grew by 6.66% month on month in August. Passenger car sales rose 7.3% year on year to 1.10m units, while production was up 14.13% at 1.12m units, CAAM data showed. In the January-August period of this year, Total passenger car sales rose 6.05% year on year to 9.22m units in the January-August period, while production grew by 6.39% to 9.21m units,
http://www.icis.com/Articles/2011/09/09/9491263/corrected-china-august-vehicle-sales-up-4.15-output-grows-8.72.html
CC-MAIN-2014-42
refinedweb
132
73.03
As an example: Const OPERATIONS = []for (var i = 0; i < 5; i++) { Operations.push (() = { Console.log (i) })}for (const Operation of Operations) { operation ()} It basically loops 5 times and adds a function to the operations array. This function can print out the index value of the cyclic variable i. The expected result after running these functions should be: 0 1 2) 3 4 But what actually happens is this: 5 5 5) 5 5 Why is this happening? Because Var is used. Because the Var variable is promoted, the above code is equivalent to var i;const operations = []for (i = 0; i < 5; i++) { Operations.push (() = { Console.log (i) })}for (cons T operation of Operations) { operation ()} Therefore, in the for-of loop, I is still visible, it is equal to 5, and each time I is involved in the function, this value will be used. So what should we do to make it what we think it is? The simplest scenario is to declare with let. As described in ES2015, they are a great help to avoid some strange questions about using Var declarations. It is simple to turn Var into a let in the loop variable, which works well: Const OPERATIONS = []for (Let i = 0; i < 5; i++) { Operations.push (() = { Console.log (i) })}for (const Operation of Operations) { operation ()} Here is the output: 0 1 2) 3 4 How does this work? This is because each time the loop repeats, I is recreated, and when each function adds a operations array, it can get the I of itself. Remember that you cannot use const in this case, because this causes the for in the second loop to attempt to assign a new value to the error. Another very common solution to this problem is to use the PRE-ES6 code, which is called an instant call function expression (iife). In this case, you can wrap the entire function and bind I to it. From this way, you are creating a function that can execute immediately, and you return from it with a new function. So we can execute it later. Const OPERATIONS = []for (var i = 0; i < 5; i++) { Operations.push ((j) = { return () = Console.log (j) c6/>}) (i))}for (const operation of Operations) { operation ()}
http://topic.alibabacloud.com/a/parsing-the-relationship-between-javascript-loops-and-scopes-with-code_4_87_30002459.html
CC-MAIN-2019-18
refinedweb
375
62.38
Displaying 3D objects with Tao Presentations is very easy. Thanks to the GLC-Lib library and to the Taodyne ObjectLoader module, Tao Presentations can directly read a large number of common 3D file formats. We will use this capability to read a 3DS file representing a 3D model of the NASA space shuttle. Here is the entire code required for this very simple demo: import ObjectLoader clear_color 0,0,0,0 light 0 light_position 1000,1000,1000 adjust mouse_x, mouse_y adjust MX:real, MY:real -> rotatex 0.5 * MY + 180 rotatey 0.5 * MX scale 0.5, 0.5, 0.5 shuttle X -> "models/shuttle/" & X object shuttle "shut.3ds" object shuttle "door-prt.3ds" object shuttle "door-stb.3ds" translatex -500 object shuttle "eng.3ds" locally translatez 50 object shuttle "rcs.3ds" locally translatez -50 object shuttle "rcs.3ds" Here is a useful tip for 3D geeks: a large number of 3D models of NASA space vehicles are available for download with a rather liberal usage licence. This allows us to give a direct download link for a presentation that includes not just the code above, but also the 3D model itself. As a matter of fact, the original model will show up without textures, because the file names in the archive don't seem to match the names in the 3DS file exactly. There are a number of applications for 3D models in presentations: product introductions, architecture, or simply to create a unique slide design. Just invent your own and share with us in the comments area.
http://www.taodyne.com/shop/dev/en/blog/117-displaying-3d-objects
CC-MAIN-2014-35
refinedweb
259
65.83
ncl_wmgetc man page WMGETC — Retrieves the current character value of an internal parameter of type character. Synopsis CALL WMGETC (PNAM,CVAL) C-Binding Synopsis #include <ncarg/ncargC.h> void c_wmgetc (char *pnam, char *cval, int len) Description - PNAM (an input constant or variable of type CHARACTER) specifies the name of the parameter to get. The name must appear as the first three characters of the string. - CVAL (an output variable of type CHARACTER) is the name of Wmap parameters. For a complete list of parameters available in this utility, see the wmap_params man page. Access To use WMGETC or c_wmgetc, load the NCAR Graphics libraries ncarg, ncarg_gks, and ncarg_c, preferably in that order. See Also Online: wmap, wmdflt, wmgetr, wmgeti, wmlabs, wmsetc, wmseti, wmsetr, wmap_params Hardcopy: WMAP - A Package for Producing Daily Weather Maps and Plotting Station Model Data University Corporation for Atmospheric Research The use of this Software is governed by a License Agreement.
https://www.mankier.com/3/ncl_wmgetc
CC-MAIN-2017-26
refinedweb
155
52.29
Woo-hoo, another release of Allegro! This release brings lots of fixes for annoying bugs and a few new features. Enjoy! In terms of packaging, I've once again changed what the msys2 binaries contain. They now contain dlls with dynamically linked runtime. Statically linked runtime proved to be too hard to use. I've also fixed the Nuget package a bit. MSYS2 binaries are available here with the dependency packages available here. You can grab the MSVC Nuget package here. Ubuntu and homebrew will be updated in the coming days. The main developers this time were: Elias Pschernig, Trent Gamblin, SiegeLord, Ryan Roden-Corrent, Boris Carvajal and Peter Hull. Optimize bitmap holding a bit (Bruce Pascoe). Add al_get/set_depth/samples (OpenGL only for now). Optimize destruction performance when you have thousands of objects (e.g. sub-bitmaps). Use low floating point precision for the OpenGL fragment shaders, which helps performance a lot on mobile platforms. Don't stop and join the timer thread when stopping the last timer (prevents unnecessary delay in this situation on some platforms). Add al_backup_dirty_bitmap and al_backup_dirty_bitmaps to more finely control when bitmap context backup is performed. Fix Android app issues when woken up during sleep. Specify the Android toolchain file on the command line now. ANDROID_NDK_TOOLCHAIN_ROOT now has to be specified in an environment variable. Improve joystick enumeration (Todd Cope). Make al_set_new_window_title work correctly. Don't send duplicate mouse move events. Fix mouse warping behavior. Exit fullscreen mode if ALLEGRO_FULLSCREEN_WINDOW is set when destroying a display (otherwise if you destroy and recreate display without terminating the program, a white window kicks around). Make it compile again. Don't backup textures as it is unnecessary. Update minimum iOS to version to 6.1. Disable the native png loader in favor of libpng, as it is broken on Apple's end. Create library when creating the archive. Fix the D3D target bitmap bug. Clear display to black right away to avoid an ugly white flash. Fix system cursor support. Use PROJECT_SOURCE_DIR and PROJECT_BINARY_DIR instead of CMAKE_SOURCE_DIR and CMAKE_BINARY_DIR. This lets you use Allegro as a sub-project in your CMake project. Fix GDIPlus finding in cmake-gui (Bruce Pascoe). Add .gitignore and ignore build/ dir (Mark Oates). Fix building examples with non-Allegro dependencies with the monolith build. Various documentation updates (Daniel Johnson and others). Add more #include statements in Allegro headers, so it's easier to use them in isolation (Jordan Woehr). Allow marking tests as being hardware only. Prefix some private Allegro macros and types to not pollute the namespace. Make set_shader_uniform api const-correct (Bruce Pascoe). Adjust loop end position when calling al_set_sample_instance_length. Allow file-backed audio streams to be restarted after they finish. Add Opus codec support. Fail gracefully if not built with PNG/JPG loaders. Make al_get_text_dimensions and al_get_glyph_dimensions return exact bounding boxes (koro). Add ALLEGRO_GLYPH structure and al_get_glyph, allowing for some additional optimization when drawing fonts. Add more controls to ex_audio_props. Add an example of using Enet with Allegro. SHA256SUMS 34acb0346780b9d262c7e459701646a6046bec88db6056e17244c558fa1adfcc Allegro.5.2.1.0.nupkg d229402acca828882baa48e77a5ae3405d2d53565db4b2c834b3a7db1da66323 allegro-5.2.1.7z 9e88cda6bbe2b56fb47fe253f9b22868c821e78a19004b5742a90f66ac4fe927 allegro-5.2.1.tar.gz 124bb7892e37c8fe10c903264480ac1bc50771a8fdeefc030811eaedc4fbb0ec allegro-5.2.1.zip c9f6104a7125c76c78c1ec049a774402b003ac91ac2049f8906200333f09a1bf allegro-mingw-gcc5.3.0-x64-5.2.1.zip d94446f458bf0cde3d2fdec3e0057b13001bf30a24415e5fe5916eb8ec6c947f allegro-mingw-gcc5.3.0-x86-5.2.1.zip 6bf48e4d4c7922f70a4d34bb5216ee169b6c415b5a77e18b868628108aa6aa90 allegro-mingw-gcc5.3.0-x64-dynamic-5.2.1.zip f1da3d793481f08e89b392c3b4fe0ae612ae7ec31087f843f7e8ef7b5937b289 allegro-mingw-gcc5.3.0-x64-static-5.2.1.zip 319743507b87772632122ffceff1dc79eea53df7a1fe48ab2840042831591594 allegro-mingw-gcc5.3.0-x86-dynamic-5.2.1.zip 0179b124e796f015a4b9c74da73bf5941350306805b804faec37fe43b173fe1a allegro-mingw-gcc5.3.0-x86-static-5.2.1.zip "For in much wisdom is much grief: and he that increases knowledge increases sorrow."-Ecclesiastes 1:18[SiegeLord's Abode][Codes]:[DAllegro5]:[RustAllegro] Thank you developers, for all your hard work on this great library! Hou pinaise je vais tester cette après midi pour le bug D3D !!! Cool, I think the fix might help some of my progs which were acting strange (i.e only OGL working in windows) "Code is like shit - it only smells if it is not yours"Allegro Wiki, full of examples and articles !! Awesome. Great work guys. Will be working on putting together a binary distribution of MinGW 5.3.0.2 and Allegro 5.2.1 and all the dependencies here in the next few tried updating the pre-built Allegro monolith included in jalleg from the zip I downloaded at, but it does not work. It looks like it might depend on some (new?) libraries, when I try to load it, I get the error "Can't find dependent libraries". Looking at the output from Dependency Walker, I see two new DLL dependencies on 5.2.1 that were not on 5.2.0: LIBGCC_S_SEH-1.DLL and LIBSTDC++-6.DLL. It looks like Allegro was compiled in C++ mode, or at least with structured exceptions handling turned on? GilliusGillius's Programming -- That's this change: In terms of packaging, I've once again changed what the msys2 binaries contain. They now contain dlls with dynamically linked runtime. Statically linked runtime proved to be too hard to use. Is it difficult for your use case to bundle those two extra binaries? I rarely get feedback for these msys binaries (the only one I got was that the statically linked versions were too hard to use). Good job. I'll test it right now. Anyway, did you read this? I'll really appreciate a comment from the development team. Pretty pleeeeeease? -----------------Current projects: Allegro.pas | MinGRo The library loader I use can't automatically load dependent libraries. There might be a workaround I can try to see if the dynamic linker can resolve symbols from the current process first, then I can load libraries manually in order. But I don't understand it, because 5.2.0 binaries worked perfectly, and I don't understand why I need to include the entire C++ runtime and structured exceptions support library for a pure C library (it looks like Allegro doesn't even call any public members of the C++ runtime). I would also need to be able to find the exact versions of those DLLs needed, as they aren't in the ZIP. It's been quite a few years since I've used gcc, but I thought with a certain flag you can turn off C++ support? C++ under windows is non-optional due to how much DirectX we use. The issue for bundling the runtime into the dll is that when linking the library manually in a native language (C/C++ etc), you'll need to be very careful with flags... which is a royal pain. For runtime loading, it of course doesn't matter. Anyway, the issue was mostly a naming issue, as always. It's trivial for me to make both kinds of dlls, I just need to come up with a way to either include them in the same archive, or come up with the names of two archives. OK, I didn't know about that requirement. I assume it wasn't needed because I saw hardly no symbols from libstdc++ in use. Ultimately, all I need is a DLL that can be loaded without dependencies on Windows 64 bit, however that is compiled. If that is something the Allegro team can provide it would be greatly appreciated. I re-package allegro-monolith into a JAR form and publish to a standard repository for any jalleg or Java user using JNA. If you prefer to keep only the dynamic link version published, that's doesn't matter, if I can get a copy of the static build for my package. Thanks for the great work on Allegro and all the support! Thank you so much. Especially SiegeLord for those NuGet packages. Never used NuGet before and now it is soooo easy to add Allegro to a project. Awesome work! I just got back to some C++ and Allegro after dabbling with Unity. Alright, I added the statically linked runtime versions of Allegro. They should be named in a self-explanatory fashion. God Job!!!!;D Great! I downloaded the static library, and it worked. Then I released an updated jalleg-rt package for 5.2.1. YAAAAAAAAAAAA! ALLEGRO_UNSTABLE is still required for al_set_new_bitmap_samples and al_set_new_bitmap_depth? --Streaming KrampusHack 2020 LIVE on Twitch - (status: ⭕️ OFFLINE) -)AllegroFlare • allegro.cc markdown • Allegro logo Yep, we still haven't gotten around to implementing it for Direct3D. The way you'll be able to tell when it won't be necessary is that it won't have the 'unstable API' in the docs, and it'll be in the changelog (if I remember it ). Awesome
https://www.allegro.cc/forums/thread/616406/1024171
CC-MAIN-2021-17
refinedweb
1,444
68.57
Are you in the mood for a lightweight and fun project? We are going to build a custom-styled console logging class that you can use in place of console.log()! We’re going to add some color and variation to our consoles. It will be similar in functionality to the debug npm package. This should take no more than 10 minutes. To make things simpler, we can use CodeSandbox. It’s especially good for quick projects like this. We’ll be using the Vanilla template, which utilizes Parcel to give us features like bundling, importing, ES6 classes, etc. Check out this post for an introduction to Parcel if you’re curious to know more. I like to outline what my code should look like before I get started. Something like: index.js import CustomLogging from './CustomLogging'; const custom = new CustomLogging; const error = new CustomLogging('error'); error.setBodyStyle({ color: 'red', size: '2rem' }); // the output console.log('Regular log.'); custom.log('Hello there!'); error.log('Something bad happened!'); In the console tab (at the bottom of CodeSandbox), this outputs: Our Strategy We’re going to use an ES6 class to deliver this functionality. Because of Parcel, we can import/export this class to be used as a “package” of sorts. At it’s core this project will utilize the %c feature in the regular console.log() method. See our article on the JavaScript console API for more details. If you’re feeling adventurous, try to see what you can come up with on your own! Tweet your results to @alligatorio to show it off. Let’s Get Coding First, clear the initial code in index.js so we’re starting fresh. Be sure to save as you go. Create a new CustomLogging.js file in the src directory. Here’s a basic outline: CustomLogging.js class CustomLogging { log() { console.log("Hey, good lookin`!"); } } export default CustomLogging; You’ll notice that this isn’t dynamic - we’re simply trying to make sure it works. To get this to be logged to the console, head over to the index.js file where you’ll import the class, instantiate it, and then call the log() method. index.js import CustomLogging from './CustomLogging'; const custom = new CustomLogging; custom.log(); Add Message and Styling Now let’s pass in any message we want and begin some styling: CustomLogging.js class CustomLogging { log( body = "" // defaults to empty string ) { console.log( `%c${body}`, // everything after the %c is styled `color: green; font-weight: bold; font-size: 2rem;` ); } } export default CustomLogging; …which is fired by: index.js // ... custom.log('May the Force be with you.'); Dynamic Styling Let’s create a constructor to set defaults. We’ll then add a method to modify the styling on the fly: CustomLogging.js class CustomLogging { constructor() { // choose whatever defaults you'd like! this.body = { color: "#008f68", size: "1rem" }; } setBodyStyle({ color, size }) { // this will only set a value that is passed-in if (color !== undefined) this.body.color = color; if (size !== undefined) this.body.size = size; } log(body = "") { // adds dynamic styling via the template literals console.log( `%c${body}`, `color: ${this.body.color}; font-weight: bold; font-size: ${ this.body.size }; text-shadow: 0 0 5px rgba(0,0,0,0.2);` ); } } export default CustomLogging; And again, we’ll use it: index.js // ... custom.setBodyStyle({ color: 'red' }); custom.log('Anger, fear, aggression; the dark side of the Force are they.'); What’s the Title? Lastly, we’ll add a title into the constructor so that different instances can display their label: CustomLogging.js class CustomLogging { constructor(title) { this.title = { body: title || "---", color: "darkgrey", size: "1rem" }; this.body = { color: "#008f68", size: "1rem" }; } setTitleStyle({ color, size }) { if (color !== undefined) this.title.color = color; if (size !== undefined) this.title.size = size; } setBodyStyle({ color, size }) { if (color !== undefined) this.body.color = color; if (size !== undefined) this.body.size = size; } log(body = "") { // the second line is now the body because the first references the content after the first %c for the title console.log( `%c${this.title.body} | %c${body}`, `color: ${this.title.color}; font-weight: bold; font-size: ${ this.title.size };`, `color: ${this.body.color}; font-weight: bold; font-size: ${ this.body.size }; text-shadow: 0 0 5px rgba(0,0,0,0.2);` ); } } export default CustomLogging; Invoke it with: index.js import CustomLogging from './CustomLogging'; const custom = new CustomLogging; const error = new CustomLogging('error'); error.setBodyStyle({ color: 'red', size: '2rem' }); console.log('Regular log..'); custom.log('Hello there!'); error.log('Something bad happened!'); 🎉 Whoo! 🎉 We did it! Your console should now match the example at the top of the post. Pat yourself on the back, show a friend, or do whatever floats your boat. Extra-Cool Functionality What functionality can you add to this? Here are some ideas: - More styling options - Detect if body of log()method is an array or object and print them out in a styled way - Track time between each log and tag that onto the end - Review the ‘debug’ npm package for more ideas.
https://alligator.io/js/custom-styled-console-logging/
CC-MAIN-2020-34
refinedweb
833
61.73
- Tutorials - 2D UFO tutorial - Creating Collectable Objects Creating Collectable Objects Checked with version: 5.2 - Difficulty: Beginner In this assignment we'll add collectable objects to our 2D UFO game in progress. We'll use Prefabs, 2D trigger colliders to do this, and add a one line C# script to make the collectable objects rotate. Creating Collectable Objects Beginner 2D UFO tutorial Transcripts - 00:02 - 00:05 So far we have created a play field - 00:05 - 00:07 and a Player game object - 00:07 - 00:09 and we have the player moving - 00:09 - 00:11 under our control. - 00:11 - 00:13 In this lesson we'll create - 00:13 - 00:16 the collectable objects - 00:16 - 00:18 for our player to pick up. - 00:19 - 00:21 First open the Sprites folder. - 00:22 - 00:24 Drag the sprite Pickup - 00:24 - 00:26 in to the hierarchy. - 00:30 - 00:32 You'll notice after dragging in - 00:32 - 00:34 the Pickup sprite that we - 00:34 - 00:35 still can't see it. - 00:36 - 00:38 That's because it's being rendered - 00:38 - 00:42 behind both the Player - 00:42 - 00:44 and Background sprites. - 00:44 - 00:46 To bring it forward we - 00:46 - 00:49 need to set the sorting layer - 00:49 - 00:51 in the sprite renderer component. - 00:53 - 00:56 Set the sorting layer to Pickups. - 00:58 - 01:00 Now the Player game object - 01:00 - 01:02 is still in the way. - 01:03 - 01:06 This is because the Player - 01:06 - 01:08 sorting layer is in front - 01:08 - 01:10 of the Pickups sorting layer. - 01:11 - 01:13 Let's temporarily deactivate - 01:13 - 01:15 the Player game object. - 01:16 - 01:18 Select the Player game object - 01:18 - 01:20 and deselect the checkbox - 01:20 - 01:22 in front of the Name field. - 01:22 - 01:25 This is the game object's Active checkbox. - 01:26 - 01:28 Deselecting it will deactivate - 01:28 - 01:30 the game object in the scene. - 01:30 - 01:32 This will give us a clear working space - 01:32 - 01:34 for our new pickup object - 01:34 - 01:36 which we can now see. - 01:37 - 01:39 Focus the scene view camera on the - 01:39 - 01:41 pickup object by highlighting it - 01:41 - 01:43 and pressing the F key whilst - 01:43 - 01:45 the cursor is over the scene view. - 01:46 - 01:48 So that we can collide with the pickup - 01:48 - 01:50 let's add a circle collider 2D - 01:50 - 01:52 component to it. - 01:52 - 01:54 With the pickup highlighted click - 01:54 - 01:58 Add Component - Physics 2D - 01:58 - 02:00 then Circle Collider 2D. - 02:01 - 02:03 Adjust the Radius property - 02:03 - 02:05 of the circle collider 2D - 02:05 - 02:09 so that it fits the sprite artwork visually b - 02:09 - 02:11 by dragging in the Radius field. - 02:13 - 02:15 To be effective the collectable - 02:15 - 02:18 must attract the attention of the player. - 02:18 - 02:21 So let's make the object more attractive. - 02:22 - 02:24 There's one thing I feel certainly - 02:24 - 02:26 attracts the attention of a player - 02:26 - 02:27 and that is movement. - 02:27 - 02:29 So let's rotate our pickup. - 02:29 - 02:32 One way to do this is with a script. - 02:33 - 02:35 With the pickup object still selected - 02:35 - 02:37 use the Add Component button - 02:37 - 02:39 in the inspector. - 02:40 - 02:43 Let's create a new script called Rotator. - 02:44 - 02:46 Click Create and Add to confirm - 02:46 - 02:48 and let's organise the script by - 02:48 - 02:50 placing it in the Scripts folder. - 02:52 - 02:54 Open the Scripts folder and - 02:54 - 02:56 double click to open it for editing. - 02:58 - 03:00 We want the sprite to spin and we want - 03:00 - 03:02 to do it with this script. - 03:02 - 03:04 Let's remove the sample code - 03:04 - 03:06 we don't need. - 03:07 - 03:09 We will not be using forces - 03:09 - 03:11 so we can use Update - 03:11 - 03:13 rather than Fixed Update. - 03:14 - 03:17 We want to rotate the object every frame. - 03:17 - 03:19 To make the pickups spin we - 03:19 - 03:22 don't want to set the transform rotation - 03:22 - 03:24 but we want to rotate the transform. - 03:25 - 03:28 Type Transform inside Update. - 03:31 - 03:33 Select it and hold down the - 03:33 - 03:36 control key on windows or the command - 03:36 - 03:38 key on mac and type ' - 03:40 - 03:42 Again this brings up the page - 03:42 - 03:44 with a search term Transform. - 03:44 - 03:46 Select Transform. - 03:48 - 03:53 Scroll down until you see Transform's public functions. - 03:54 - 03:57 There are two main ways to affect the transform. - 03:57 - 04:00 These are Translate and Rotate. - 04:01 - 04:03 Translate moves the game object - 04:03 - 04:05 using it's transform. - 04:06 - 04:08 Rotate rotates the game object - 04:08 - 04:10 using it's transform. - 04:11 - 04:13 We will use rotate. - 04:14 - 04:16 So let's click on the link. - 04:16 - 04:19 This brings up the page for Transform.Rotate. - 04:20 - 04:23 Note again the two signatures. - 04:24 - 04:27 One is using a vector3 - 04:27 - 04:29 and the other is using 3 - 04:29 - 04:33 float values for X, Y or Z. - 04:34 - 04:36 Both have the optional parameter - 04:36 - 04:38 Space which we will - 04:38 - 04:40 leave at default for this lesson. - 04:41 - 04:43 Again we will choose the most simple - 04:43 - 04:46 form that only uses the vector3 for direction. - 04:47 - 04:49 Let's return to our code. - 04:51 - 04:53 After transform, - 04:53 - 04:55 making sure that transform is written to - 04:55 - 04:57 begin with a lowercase t, - 04:57 - 05:06 write .rotate (new Vector3 (0, 0, 45)) - 05:07 - 05:09 This means we'll rotate - 05:09 - 05:12 around the Z axis. - 05:12 - 05:14 Now this action also needs - 05:14 - 05:17 to be smooth and frame rate independent - 05:18 - 05:21 so we need to multiply the vector3 value - 05:21 - 05:23 by Time.deltaTime. - 05:25 - 05:27 It is worth noting that even - 05:27 - 05:29 though we are working with a 2D - 05:29 - 05:32 sprite we are using a vector3 - 05:32 - 05:34 to rotate the collectable's transform. - 05:35 - 05:37 This is because the transform - 05:37 - 05:39 of the 2D sprite - 05:39 - 05:42 still exists in the 3D volume. - 05:43 - 05:45 When using the transform component - 05:45 - 05:47 with 2D objects we simply - 05:47 - 05:49 ignore the axis we don't need. - 05:50 - 05:53 Now that we are done with our Rotator script - 05:53 - 05:55 save this script and return to Unity. - 05:56 - 05:59 Let's test by entering play mode. - 06:00 - 06:03 And we can see our pickup object rotates. - 06:04 - 06:06 Let's exit play mode. - 06:07 - 06:10 Okay, we have the start of a working - 06:10 - 06:12 pickup object. - 06:12 - 06:14 Next we want to place these pickups - 06:14 - 06:16 around the game area. - 06:16 - 06:18 But before we do this we need to do - 06:18 - 06:20 one important step. - 06:20 - 06:22 We need to make our pickup object - 06:22 - 06:24 in to a prefab. - 06:25 - 06:27 Remember, a prefab is an - 06:27 - 06:29 asset that contains a template - 06:29 - 06:31 or blueprint of a game object - 06:31 - 06:33 or game object family. - 06:34 - 06:36 We create a prefab from an - 06:36 - 06:39 existing game object or game object family - 06:40 - 06:42 and once we create it - 06:42 - 06:44 we can use it in any scene - 06:44 - 06:46 in our current project. - 06:47 - 06:49 With a prefab of our pickup object - 06:49 - 06:51 we will be able to make changes to - 06:51 - 06:53 a single instance in our scene - 06:53 - 06:55 or to the prefab asset itself. - 06:55 - 06:57 And all of the pickup objects in our - 06:57 - 07:00 game will be updated with those changes. - 07:01 - 07:03 You'll notice we already have a folder - 07:03 - 07:05 to hold our prefabs. - 07:05 - 07:07 Let's drag the Pickup game object - 07:07 - 07:09 from our hierarchy and place - 07:09 - 07:12 it in to our Prefabs folder. - 07:13 - 07:15 When we drag and item from our hierarchy - 07:15 - 07:17 in to our project view - 07:17 - 07:19 we create a new prefab - 07:19 - 07:21 asset in our project. - 07:22 - 07:24 Before we spread our collectables - 07:24 - 07:26 around the game area we should create - 07:26 - 07:28 a new game object - 07:28 - 07:30 to hold our pickups and - 07:30 - 07:32 to help organise our hierarchy. - 07:33 - 07:35 Let's create a new game object. - 07:37 - 07:39 And call it Pickups. - 07:41 - 07:43 Check the transform to make sure our - 07:43 - 07:45 Pickups holder object - 07:45 - 07:48 is at origin, or (0, 0, 0). - 07:48 - 07:50 And if not use the component - 07:50 - 07:52 context menu to reset it. - 07:53 - 07:57 Next drag our Pickup game object on to it. - 07:58 - 08:00 Now we want to spread a - 08:00 - 08:02 number of these pickup objects - 08:02 - 08:03 around the play area. - 08:03 - 08:05 Make sure the pickup game object is - 08:05 - 08:07 selected, and not the parent. - 08:09 - 08:11 Now let's back out a little - 08:11 - 08:13 so we can see the entire game area. - 08:15 - 08:17 Click and drag the pickup game object - 08:17 - 08:19 to move it in to the - 08:19 - 08:21 first pickup position. - 08:21 - 08:23 I'm going to place mine at the top of the playing area. - 08:24 - 08:26 With the game object still selected - 08:27 - 08:28 duplicate it. - 08:28 - 08:30 This can be done either by selecting - 08:30 - 08:34 Edit - Duplicate, or by using the hot key combination. - 08:35 - 08:37 This is command-D on mac, - 08:37 - 08:39 or control-D on windows. - 08:40 - 08:42 Now let's position the - 08:42 - 08:44 second instance of the prefab. - 08:47 - 08:49 Using the hot keys we will - 08:49 - 08:51 create a few more, placing them - 08:51 - 08:53 around the play area. - 09:08 - 09:10 Okay, I've created 12. - 09:11 - 09:13 Let's hit play and test. - 09:14 - 09:16 Excellent, these pickup prefabs - 09:16 - 09:18 are working great. - 09:18 - 09:20 In the next assignment we'll learn how to - 09:20 - 09:22 pick them up and to count them. Code snippet using UnityEngine; using System.Collections; public class CompleteRotator : MonoBehaviour { //Update is called every frame void Update () { //Rotate thet transform of the game object this is attached to by 45 degrees, taking into account the time elapsed since last frame. transform.Rotate (new Vector3 (0, 0, 45) * Time.deltaTime); } } Related tutorials - Introduction to 2D UFO Project (Lesson) - Setting Up The Play Field (Lesson) - Controlling the Player (Lesson) - Adding Collision (Lesson) - Following the Player with the Camera (Lesson)
https://unity3d.com/learn/tutorials/projects/2d-ufo-tutorial/creating-collectable-objects?playlist=25844
CC-MAIN-2019-04
refinedweb
2,120
79.4
Q:? A: It's not clear if it's legal or portable, but it is rather popular. An implementation of the technique might look something like this: #include <stdlib.h> #include <string.h> struct name *makename(char *newname) { struct name *ret = malloc(sizeof(struct name)-1 + strlen(newname)+1); /* -1 for initial [1]; +1 for \0 */ if(ret != NULL) { ret->namelen = strlen(newname); strcpy(ret->namestr, newname); } return ret; }This function allocates an instance of the name structure with the size adjusted so that the namestr field can hold the requested name (not just one character, as the structure declaration would suggest). Despite its popularity, the technique is also somewhat notorious: Dennis Ritchie has called it ``unwarranted chumminess with the C implementation,'' and. The above example could be rewritten like this: #include <stdlib.h> #include <string.h> #define MAXSIZE 100 struct name { int namelen; char namestr[MAXSIZE]; }; struct name *makename(char *newname) { struct name *ret = malloc(sizeof(struct name)-MAXSIZE+strlen(newname)+1); /* +1 for \0 */ if(ret != NULL) { ret->namelen = strlen(newname); strcpy(ret->namestr, newname); } return ret; . Of course, to be truly safe, the right thing to do is use a character pointer instead of an array: #include <stdlib.h> #include <string.h> struct name { int namelen; char *namep; }; struct name *makename(char *newname) { struct name *ret = malloc(sizeof(struct name)); if(ret != NULL) { ret->namelen = strlen(newname); ret->namep = malloc(ret->namelen + 1); if(ret->namep == NULL) { free(ret); return NULL; } strcpy(ret->namep, newname); } return ret; }(Obviously, the ``convenience'' of having the length and the string stored in the same block of memory has now been lost, and freeing instances of this structure will require two calls to free; see question 7.23.) When the data type being stored is characters, as in the above examples, it is straightforward to coalesce the two calls to malloc into one, to preserve contiguity (and therefore rescue the ability to use a single call to free): struct name *makename(char *newname) { char *buf = malloc(sizeof(struct name) + strlen(newname) + 1); struct name *ret = (struct name *)buf; ret->namelen = strlen(newname); ret->namep = buf + sizeof(struct name); strcpy(ret->namep, newname); return ret; } However, piggybacking a second region onto a single malloc call like this is only portable if the second region is to be treated as an array of char. For any larger type, alignment (see questions 2.12 and 16.7) becomes significant and would have to be preserved. Hosted by
http://c-faq.com/struct/structhack.html
CC-MAIN-2018-13
refinedweb
413
51.48
Euler problems/61 to 70 From HaskellWiki Revision as of 12:16, 17 August 2007:)^3: Problem 69 Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum. Solution: import Data.Ratio import Data.List primePowerFactors n = rle (takeFactors n primes) where rle = map (\xs -> (head xs, length xs)) . group takeFactors n (p:ps) | n == 1 = [] | p * p > n = [n] | n `mod` p == 0 = p : takeFactors (n `div` p) (p:ps) | otherwise = takeFactors n ps eulerTotient n = product (map (\(p,i) -> p^(i-1) * (p-1)) factors) where factors = primePowerFactors n problem_69 = snd . maximum . map (\n -> (n % eulerTotient n, n)) $ [1..1000000] Note: credit for arithmetic functions is due to David Amos. 10 Problem 70 Investigate values of n for which φ(n) is a permutation of n. Solution: problem_70 = undefined
https://wiki.haskell.org/index.php?title=Euler_problems/61_to_70&diff=15119&oldid=15104
CC-MAIN-2015-18
refinedweb
137
66.44
Agenda See also: IRC log -> Accepted -> Accepted. Norm must give regrets. Henry to chair Henry reminds us of the two deliverables from our charter. <ht> Henry: Those are Tim's thoughts on this issue. ... Tim's ideas are driven largely by the combination of XML elements from different namespaces in vocabularies like HTML ... Tim frames the question in terms of "what is the meaning of this document"? He likes to think about it in a way that I'll characterize informally as "compositional semantics" ... If you have a tree structured thing, you can talk about its semantics as being compositional in so far as the meaning of a bit of the tree is a function of the label on that node and the meaning of its children. ... So a simple recursive descent process will allow you to compute the meaning of the whole tree. ... It's not surprising that we switch between a processing view and more abstract statements about the meaning of nodes ... Tim's perspective is that if the fully qualified names of elements can be thought of as functions, then the recursive descent story is straightforward. ... That is the "XML functions" story about the document's meaning. ... Another bit of the background is the kind of issue that crops up repeatedly "now that we have specs like XML encryption and XInclude, when another spec that's supposed to deal with generic XML ... is created, just what infoset is it that those documents work with if you hand them a URI. Is it the result you get from parsing with a minimal parser, or a maximal parser, or one of those followed by ... name your favorite set of specs ... ... until nothing changes". People keep bumping up against this and deciding that there should be some generic spec to answer this question. ... That's where the requirement in our charter comes from So GRDDL could have said "You start with a blurt infoset" where a spec such as ours could define what blurt is. Henry: I ran with this ball in the TAG for a while. <ht> Henry: This document is as far as I got. ... It uses the phrase "elaborated infoset" to describe a richer infoset that you get from performing some number of operations. ... That document doesn't read like a TAG finding, it reads like a spec. ... So one way of looking at this document is as input into this discussion in XProc. ... I think the reasons this stalled in the TAG are at least to some extent outside the scope of our deliverable. ... They have to do with the distinction between some kind of elaborated infoset and the more general question of application meaning of XML documents. ... Fortunately, we don't have to deal with the latter. ... Hopefully, folks can review these documents before next week. Norm: They make sense to me Norm: My concern with my chair's hat on is that there are lots of ways to approach this. Perhaps the right thing to do is start by trying to create a requirements and use cases document? Murray: Can we do that by pointing to all the existing documents? Henry: I think we could benefit from a pointer to Murray's discussion on the GRDDL working group mailing list. ... I'm thinking that what this is primarily is a way of defining a vocabulary that other specs can use. Murray: Would I be way off base thinking that a net result of this process will be a pipeline written in XProc? Henry: The process I described above requires you to repeat the process until nothing changes. Norm: You could do it, you'd end up doing it n+1 times, but you could do it with p:compare. Henry: It'd have to be recursive, it'd be a little tricky, but I guess you could do it. Murray: It seems to me that if we can't answer part 2 by relying on part 1, then we didn't complete part 1 properly. ... If you can't produce an elaborated infoset by running it through a pipeline, then you did something wrong in the pipeline. ... Otherwise, what hope does anyone else have in accomplishing this.. ... I'm not yet convinced that there aren't things in that category that you need. Murray: Maybe that'll provide the imputus for XProc v.next ... If I have a document that purports some truth, but I have to go through lots of machinations to get there, but there's a formulaic way then we should be able to use the tools to do it. Henry: I believe, thoughI I'm not sure, that you could implement XInclude by writing an XProc pipeline that didn't use the XInclude step. Doing so might reveal something about the complexity of XInclude. ... If someone said you don't need to do that, you can always write a pipeline, I'd say "No, wrong, you could but you wouldn't want to." Norm: If we get to the point where we think we could do it, but we needed a few extra atomic steps, I think we could call that victory. Henry: Let me introduce one other aspect, in attempting to do this in a way that doesn't require a putative spec to be rewritten every time some new bit of XML processing gets defined, ... the elaborated infoset proposal has this notion of "elaboration cues" and attempts to define the process independent of a concreate list of these cues. ... I'm not sure how valuable that attempt to be generic is. Norm: I think one possibility is to define a concrete pipeline that does just have a limited set of steps. Henry: Doesn't that mean that if we add a new obfuscation step, that de-obfuscation requires us to revisit the elaborated infoset spec? Norm: Yes. Murray: Right, we're talking about the default processing model. Henry's talking about the obfuscated processing model which would be different. ... You can petition later to become part of the default. Henry: Another way of putting it is, should the elaboration spec be extensible? Norm: Right. And one answer is "no". <MoZ> Scribe : MoZ Murray: it looks like it has been done in other spec. What we need to do is to define the processing model for the most common cases Henry: my experience is that it will be easier to have agreement on elaboration to allow people to control what is elaboration and what isn't ... The default is to have XInclude but not external stylesheet ... Some want to have XInclude, some wants external stylesheet and other wants both Norm: I agree, but will it make any progress on the problem ? Henry: it will depends on the conformance story ... what I had in mind was : if GRRDL is coming out, and has the ability to say that the input of the processing is a GRDDL elaborated infoset Murray: what happen to XML document that is not anymore an XML Document (Encryption, Zipping, etc...) Henry: I agree, that's all we talking about <Norm> scribe: Norm Some discussion about which technologies preserve the "XMLness" of a document. Encryption and Henry's obfuscation example both produce XML documents Mohamed: It's an interesting discussion. There is, I think, a common base on which we can at least agree. ... These are more technical than logical, for example, XInclude, encryption, where the behavior is clearly defined. ... On top of that, there's a layer of user behavior. I think we'll have a hard time at that layer. ... Defining the use caes and requirements is probably the only place we can start. Norm: Yeah, I don't want to make us do work that's already been done. But I think there would be value in collecting the use cases together ... to see if we have agreement that some, all, or none of them are things we think we could reasonably be expected to achieve. Murray: Hopefully more than none. Norm: Indeed. ... Ok, for next week, let's plan to have reviewed the documents that Henry pointed to and spend some time on use cases and requirements. Henry: Agreed. None heard. Adjourned.
http://www.w3.org/XML/XProc/2009/05/07-minutes
CC-MAIN-2016-44
refinedweb
1,369
70.53
Feature #7435 Exceptions should have backtrace_locations Description Further to def boom raise "boom" end begin boom rescue => e p e.backtrace end ["t.rb:2:in boom'", "t.rb:6:in'"]¶ It seems exceptions still store backtraces in strings, shouldn't the backtrace be stored in RubyVM::Backtrace::Location objects and then optionally grabbed using backtrace_locations or backtrace depending on how you feel? This means exceptions could be more efficient as filenames could easily be pinned in memory leading to significantly reduced allocation for exceptions. History Updated by sam.saffron (Sam Saffron) about 7 years ago ouch, this was meant to be a feature req not a bug ... cant figure out how to change Updated by zzak (Zachary Scott) about 7 years ago - Tracker changed from Bug to Feature - Category set to core - Status changed from Open to Assigned - Assignee set to ko1 (Koichi Sasada) - Target version set to 2.0.0 Updated by zzak (Zachary Scott) about 7 years ago - Target version changed from 2.0.0 to 2.6 Updated by ko1 (Koichi Sasada) about 7 years ago (2012/11/26 7:02), sam.saffron (Sam Saffron) wrote: This means exceptions could be more efficient as filenames could easily be pinned in memory leading to significantly reduced allocation for exceptions. Current implementation does not make String array. Please run the following code: def foo raise end begin foo rescue => e # e.backtrace # (X) ObjectSpace.each_object(Array){|ary| if ary.find{|obj| obj.is_a?(String) and /foo/ =~ obj} p ary end } end If you run (X), then the code prints out backtrace object. -- // SASADA Koichi at atdot dot net Updated by ko1 (Koichi Sasada) about 7 years ago - Status changed from Assigned to Rejected Updated by ko1 (Koichi Sasada) about 7 years ago One more comment. Exception class has Exception#set_backtrace method, which set backtrace using string array. It conflicts with locations. We need to solve this issue to support Exception#backtrace_locations. Updated by headius (Charles Nutter) almost 7 years ago I wish I had seen this before 2.0.0! Perhaps set_backtrace should just cause backtrace_locations to return an empty array? I really, really wish backtrace_locations had gotten into 2.0.0, so let's try to make this happen for 2.1. Updated by sawa (Tsuyoshi Sawada) over 6 years ago Why is this issue closed? Is this problem solved? I think it is a very important feature that is missing. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/7435
CC-MAIN-2019-51
refinedweb
409
66.84