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 |
|---|---|---|---|---|---|
HTML/next
From W3C Wiki
HTML.next
HTML.next in W3C bugzilla
Ideas for HTML.next. — Sam Ruby
Do not hesitate to make lists. A good source of ideas are the bugs resolved LATER.
See also (and copy from there to here)
- - Proposed HTML elements and attributes
Ideas List
New Semantics
Decompress Element <decompress> to integrate files from ZIP folders into webpages directly
Goal: To allow files from compressed folders (primarily .ZIP, and so forth) to be accessible in web browsers. This could have many uses, such as reducing bandwidth for computer and mobile platforms by distributing large HTML or image files through a ZIP folder and allowing them to be accessible through a web browser.
First, specify the ZIP folder that carries the files that you wish to be displayed on your webpage.
Example: <decompress href=””>
This informs the browser that the zip folder “familyreunion.zip” contains files that may need to be used in the HTML document. After the decompress element has been used, files from the ZIP folder can be integrated into the webpage like the following examples:
<a href=”familyreunion.zip/html/activities.html”>Activities from our family reunion</a> <img src=”familyreunion.zip/img/familyreunion1.jpg”>
In the first line of code from the example, the anchor tag provides a link to an HTML document inside the file “familyreunion.zip”. Since the ZIP folder has already been specified in the decompress tag, the anchor tag automatically is aware of where to go inside the ZIP folder if the user clicks on the link “Activities from our family reunion.”
On the second line of code from the example, the image tag works likewise but grabs a photo from the specified “familyreunion.zip” and sticks it on the current page the user is browsing.
Just as note, it is imperative that each ZIP file that contains files to be integrated into a webpage is called through the decompress tag. Not doing so might have the browser prompt the user to save the ZIP folder to the user’s hard drive instead of displaying the contents directly in the webpage.
--Jace Voracek November 5, 2011
Isn't this already achieved through the
Content-Encoding and
Transfer-Encoding headers of HTTP/1.1?
Semantics for expressing titles and authors
Being able to identify the title of a book, blog posts, movie, etc. and to relate to it the authors even if the markup is being spread over a few paragraph. In a pseudo markup to illustrate what could be the links in between the items. That would not be mandatory to establish the relations in between them.
[title: The praise of Shadow id:praise by:junichiro] is a book written by [author: Junichiro Tanizaki id:junichiro] explaining … etc.
<location> element (like <time>) for expressing geo information, eg with attributes lat, long, altitude
Eg <location lat=54.3 long=32 altitude=540>Bill's mother's house</location
<datagrid> element
<teaser> Element
I've made this proposal elsewhere, but here seems a good place to reiterate it. The <teaser> element is intended to be a wrapper around a summary block of content with an associated link to a fuller block of content. You see similar structures all over the web, from search result listings to front pages for blogging sites, in which you generally have a title (often linked), a summary block with or without some kind of media resource, and either a _more_ link or a URL to the full article. In general it would be a sectional element that might be placed in another sectional element, such as <nav> pages:
<nav> <teaser> <header> <h1><a href="">My First Cool Article</a></h1> </header> <p>This is my first article on the page, and it's really cool.</p> <footer> <time>3 Days Ago</time> <div><a href="" ></a></div> </footer> </teaser> <teaser> <header> <h1><a href="" >My Second Cool Article</a></h1> </header> <p>This article is on superconducting fields, and is even cooler than my first article.</p> <footer> <time>1 Days Ago</time> <div> <a href="" ></a </div> </footer> </teaser> </nav>
There are a number of good reasons for adopting the <teaser> element:
- It describes a common, frequently used structure in HTML.
- There are currently no elements that serve the same purpose (the closest may be <cite>, but that more commonly is used specifically as a footnote citation mechanism, and is not specifically aware of the <header>/<footer> structure of HTML5).
- It increases search engine optimization and component control optimization, as different widgets could be used to render this structure in different ways from a list of items to a shoutbox or similar component.
- It doesn't necessarily participate in the list numbering mechanism.
- It can be used with internal named anchorst to make a fast TOC.
- It works well in the blogging model that HTML5 seems to be adopting as the foundation for sectional content.
Importing font file formats using a "fontsrc" tag attribute
Being able to integrate specific font file formats into a webpage using a "fontsrc" attribute. Such would be used for purposes of allowing a "special" font to be displayed on a page that would typically be unrecognized by other web browsers. This would allow a developer to use unique special characters on the page, or developers to customize the font of languages that are sometimes difficult to read because of jumbled pixels. (Arabic, Farsi, etc.) It may be best to use this element with the common .TTF, .FNT, and .TF formats.
For example, the font format could be called using the font tag:
<font fontsrc="" size="5"> Text written here will be displayed according to the font file format specified. </font>
--Jace Voracek April 2011
This functionality is already supported via the CSS @font-face rule [1].
--Glenn Adams November 2011
Is necessary a CSS atribute to informate a break line, because no all break lines are semantics. Additionally this change will make the BR tag consistent. Example "BR definition":
BR { breakline:right; } breakline: none | left | right ; none : = default left : = insert a breakline before the element right : = insert a breakline after the element
Another example ;
<LABEL><INPUT><LABEL><INPUT>
Today show all in same line. If you desire one input for line, you need use this:
<LABEL><INPUT><BR><LABEL><INPUT>
My sugestion is:
<LABEL><INPUT><LABEL><INPUT> INPUT { breakline:right; }
or:
INPUT { breakline:left; }
--Edson Carli 22:23, 20 September 2012 (UTC)
Forms
Automatic capitalization in input fields
See the proposal for use cases and details.
Enhancing Authentication Forms
Today most browsers include heuristics for guessing when a page includes a form that represents an authentication or login form with variable accuracy. These heuristics are sometimes confused by password change forms, for example. Adding annotations to forms and fields representing authentication would allow user agents to more accurately recognise these scenarios and improve interoperability in this area.
--Adrian Bateman [MSFT] 11 May 2011
Localising Form Controls
Web developers frequently ask for the ability to localise form controls that include text such as the Browse or Pick button on <input type=file> and the strings that make up date/time controls.
--Adrian Bateman [MSFT] 28 June 2011
ComboBox
Web developers need a inputable dropdown select like other UI system.
<select name="age" inputable="inputable"> <option value="11"></option> <option value="12"></option> </select>
--Yanming Zhou 1 Feb 2012
Multimedia
Games
Implement a pseudo-cursor attribute or possibly element, such that once animated it would fire events identically to the cursor. In many situations such as screencast, or game-replay, it is helpful to be able to review behaviour,
Responsive Images
See the documentation of Responsive Images on this wiki. Please add to that, including incorporating other ideas like the below (Adaptive Images etc.).
Adaptive Images
Read more about Adaptive Images or see Adaptive Image Element.
Adaptive Streaming
See and for some initial work.
There are a number of different adaptive streaming formats (just like there are a number of different progressive download media formats). Many uses cases for adaptive streaming also require some form of protected content. The current HTML5 media elements support selecting from different formats and defining these formats is outside the scope of the HTML working group. Nevertheless, there are aspects of adaptive streaming and protected content that do require enhancement in the scope of HTML to support common use cases (especially those from popular video distribution networks). Specifically, these include:
- Additional media element states to allow the UA to display status (for example negotiating acquisition with the server)
- Additional media element errors (for example failed negotiation)
- Additional media element events (for example bit-rate change)
- Additional media element properties (for example current bit-rate - this may be related to the other QOS metrics)
Audio Balance
HTML5 Audio balance adjustment (left/right) for stereo tracks.
Video enhancements
(fast/slow) rewind, previous/next frame
Fullscreen and Screenshots
domElement.fullScreen(); and
domElement.getImageData(0, 0, domElement.offsetWidth, domElement.offsetHeight);
For fullscreen, see Fullscreen
Authoring
<editor> element
An editor element which allows saving back to the same page one is editing without all the hassle we have to go through today.
<textarea type="wysiwyg">
It could be <textarea type="wysiwyg"> or some such. It should support "flat" yet simplified HTML.
Main purpose of the editor: WYSIWYG editing of structured (semantic) text. Intended usage: blogs, emails, WYSIWYG wiki editing.
Proposed list of supported elements:
- blocks p, ul/li,ol/li,dl/dt/dd,blockquote,pre
- spans: strong/em/a/sup/sub/u/code/strike.
- inline-blocks: img and br(with proper visualization).
- simple tables: table/tr/th/td
Features:
- shall support copy/paste of images from/to system clipboard (can be disabled by attribute)
- shall support copy/paste of text and HTML from/to system clipboard (can be disabled by attribute)
- shall not support inline styles of any kinds.
- may have attribute content-style="some.css" defining styles of elements inside the editor.
- only simple "tag" and "tag.class" selectors in some.css shall be used.
Serialization: It shall be serializeable (set/get) into markup with structure close to this:
<envelope> <head> <image cid="1234" name="..." type=mime/type>base-64-encoded body</image> <image cid="5678" name="..." type=mime/type>base-64-encoded body</image> </head> <body>... mini-html markup ... <img alt=... </body> </envelope>
cid's (content id's) shall support unique naming that allows to do simple body.replace("cid=1234","src=final.url") when content needs to be rendered outside the editor.
Form submission of such input element shall be done as a whole: images, if any, are part of the content. Value of the input element is either plain text, HTML fragment (with images having only external urls) and <envelope> - for JavaScript it is a JSON map {"head":[],body:""}. --Andrew Fedoniouk 05:46, 11 April 2011 (UTC)
copy-paste-ability
Imagine a list like this one:
<ol><li>Lorem<li>Ipsum<li>Dolor<li>sit<li>et cetera</ol>
It will render like this:
- Lorem
- Ipsum
- Dolor
- sit
- et cetera
Now, if you as user/author copy the entire list item with 'Dolor', and paste it into a normal WYSIWYG text editor, its "3." will be replaced with "1." But I want to be able to copy it as number "3."
Components and ECMAScript
"behaviors"
Also known as dynamic subclassing of DOM elements.
This feature is greatly useful for UI component frameworks and toolkits.
Consider this JavaScript code:
document.behaviors["ul.some>li"] = { // the behavior class: attached: function() {...}, detached: function() {...}, onmousedown: function() {...}, onclick: function() {...}, ... };
The behavior is a collection of methods that is assigned (mixed-in) to all elements satisfying the selector used in declaration. When the element gets the behavior then the attached function is invoked. onmousedown and others will be default event handlers for such elements.
For the same purposes we can reuse binding property from CSS (See BECSS at )
document.behaviors["some.name"] = { // registration of the behavior class: attached: function() {...}, detached: function() {...}, onmousedown: function() {...}, onclick: function() {...}, ... };
And in CSS:
ul.some>li { color: red; binding: "some.name" [optional js source url]; }
Example of its use, in CSS we can define
input[type="masked"] { binding:"jquery-ui.masked"; }
And so in markup it will be enough to define
<input type="masked" >
to insert and activate it in place (assuming that behavioral jquery-ui implementation is included).
--Andrew Fedoniouk 06:14, 11 April 2011 (UTC)
include("url");
For the sake of modularity it should be window.include("url"[,mime/type]) method available in JavaScript.
Similar to what @import url(...) does in CSS.
If to assume that behaviors are there then the include() should able to include CSS resources too.
--Andrew Fedoniouk 06:25, 11 April 2011 (UTC)
Allow or require script element to be placed outside <body></body>
script elements or any other inclusion tag (like included css files) should be placed outside the body of a document.
<html> <head> scripts, css etc </head> <body> the place for html </body scripts etc </html>
--Marco Kotrotsos 09 Juli 2012
JavaScript: namespaces and classes
(I don't know is this the right place for JavaScript improvement proposals or not, anyway...)
JavaScript code is getting more and more complex these days. Many libraries can be used on the same page. But lack of namespaces [and classes] is just non-acceptable. May I suggest to consider namespaces and classes in JavaScript from my TIScript? TIScript uses similar (to JS) runtime and syntax so I am pretty sure they can be added to JS as they are.
--Andrew Fedoniouk 06:37, 11 April 2011 (UTC)
Syntax highlighting for <code> elements
I believe this has already been hinted on before, but here goes. Browsers usually already have a syntax highlighting code path, used when viewing HTML, CSS or JavaScript source code. It would be neat to enable syntax highlighting on <code> elements, without the need for crazy server-side or client-side parsers. It should be possible to specify the programming language through an attribute (although I’m not sure @lang should be used for this). The presence of this special attribute could imply that syntax highlighting is desired, but it can still be disabled by attribute. Native code highlighting for HTML, CSS and JS would be great start, but maybe there could be a standardized way for authors to include new programming languages. I’d imagine this would use the shadow DOM to render, and styles could be tweaked through the use of pseudo-elements in CSS.
--Mathias Bynens 05:56, 12 April 2011 (UTC)
Code Formatting for <code> elements
Regarding the proposal above me 'Syntax Highlighting' I would like to extend this with Code Formatting. Same rules and standards but to include formatting.
--Marco Kotrotsos 15:14, 09 May 2012 (UTC)
Document Organisation
Modular Enhancements
Thinking about enhancing HTML after the HTML5 specification moves into Last Call, we believe that an approach similar to the CSS3 structure is favourable. The CSS working group works on a number of different modules in parallel, each progressing at a different rate, some being successful and some falling by the wayside. They all depend on the framework defined by CSS 2.1, the large monolithic spec that they all reference. Most of the modules are additive but some may modify or extend the behaviour of the underlying 2.1 spec.
Applying this notion to HTML, we would like to see new HTML features proposed as cohesive modules with a dependency back to the monolithic HTML5 spec that provides the overall framework. One of the problems with a large specification is that different features stabilise at different rates. Adopting a more modular approach would allow the features with most interest and support to move forward more quickly. This allows implementers to ship without vendor prefixes and yet avoid some of the versioning issues we've seen recently.
--Adrian Bateman [MSFT] 11 May 2011 | http://www.w3.org/wiki/index.php?title=HTML/next&oldid=63383 | CC-MAIN-2013-48 | refinedweb | 2,637 | 52.8 |
Web sites need to be able to handle requests for missing content and deal with misspelled or bad URL formats. But how would you handle this in code? In Microsoft Web Forms, a typical solution enforced by the ASP.NET framework defines custom routes for common HTTP codes such as 404 and 403. Whenever users type, or follow, a badly formatted URL, they are redirected to another page where they are informed of the problem that has occurred. The trick works just fine and there's nothing you can complain about from a purely functional perspective. The rub lies with the behavior of such applications when their URLs are requested by search engines.
More Insights
White PapersMore >>
ReportsMore >>
Webcasts
- Agile Service Desk: Keeping Pace or Getting out Paced by New Technology?
- Innovations in Integration: Achieving Holistic Rapid Detection and Response
Imagine a search engine requesting a URL that doesn't exist in an application that implements custom error routing. The application first issues an HTTP 302 code which tells the caller that the resource has been temporarily moved to another location. The caller makes another attempt and finally lands on the error page. This approach is great for humans who ultimately get a pretty message; it is wrong for search engines which form the idea that the content is not missing at all just harder than usual to retrieve. And an error page is cataloged as regular content and related to similar content.
This approach is good from a coding perspective in that it doesn't require much work. One alternative is writing a runtime filter an HTTP module to validate the incoming URL, then return HTTP 404 right away. Starting with .NET 3.5 Service Pack 1, Microsoft incorporated the routing module with the ASP.NET platform. The routing module is just an HTTP module that can be used for many different purposes, including filtering incoming requests based on routes. Honestly, the routing module is more helpful in ASP.NET MVC than in Web Forms when it comes to handling missing content. In Web Forms, in fact, it has to redirect to another resource. In ASP.NET MVC, it can serve a 404 status code right away with no additional roundtrip.
What's the best practice in ASP.NET MVC? I recommend completing the route collection in global.asax with a catch-all route that traps any URLs being sent to your application that haven't been captured by any of the existing routes. For obvious reasons, the catch-all rule must be placed at the very bottom of the list since routes are evaluated from top to bottom and parsing stops at the first match. The catch-all route simply maps the request to an
Error controller. The controller, in turn, looks at content and headers and decides about which HTTP code to return.
The
Error controller must be manually added to the project and to some extent its structure is still a matter of preference. The
Error controller code here is a minimal implementation:
public class ErrorController : Controller { public ActionResult Missing() { HttpContext.Response.StatusCode = 404; return View("Missing"); } }
The missing .aspx view will contain any UI you want to show to users. This approach weds the best of SEO with coding effectiveness. Search engines quickly get a 404 and can use that information for the best. Users get a pretty message and can check if they did something wrong. For developers, it's not a huge amount of work.
Dino Esposito is a consultant and author who specializes in Windows development. | http://www.drdobbs.com/windows/when-urls-point-to-missing-content/222300733 | CC-MAIN-2014-23 | refinedweb | 594 | 63.7 |
Before we move to Spark Dataframes and its benefits, it is imperative to look at the concept of Dataframe. A Dataframe is based on the concept of a statistical table. It is a data structure comprising rows (cases/tuples) and columns (measurements). A row is a single observation of multiple variables and it can comprise heterogeneous data types. However, a column needs to be homogeneous. Additionally, a dataframe contains some metadata like row names and column names.
Dataframes have a wide variety of applications in data analysis. However, there are two primary benefits:
- They support a wide variety of API for slicing and dicing of data, filtering out rows, normalizing the data, create new columns, aggregations, etc.
- They provide a way to manage the integrity constraints of the incoming data. This is significant because raw statistical data is usually messy. Common examples of messy data are data type mismatch and missing values. Dataframes implement type enforcement for the former, while the latter can be dealt with cleansing API.
Besides the above benefits, Dataframes are a boon to developers and programmers entering the realm of big data from the relational world, since it gives a SQL experience to data. For more on Dataframes, refer to this link: What is a Data Frame?
Pandas Dataframe
Dataframes have been implemented in multiple languages like Python, R, Julia, F#, octave etc. Amongst them, Python’s pandas Data frames have taken precedence. However, I strongly recommend you to explore other languages like R and their Data frames. Before we compare the performance benefits of spark dataframe over pandas, let’s take the scenario which I encountered recently. I had a client who wanted to write dataframe data to an Azure SQL Database from Azure Machine Learning services.
a. Creating ODBC connection and reading the source in a dataframe
Firstly, let’s read some data from an Azure SQL database table named creditdata into a pandas dataframe using ODBC connection:
import pyodbc import pandas as pd server = '<myserver>' database = '<mydatabase>' username = '<myusername>' password = '<my password>' driver= '{ODBC Driver 13 for SQL Server}' cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) query = "SELECT * FROM [dbo].[creditdata]" df = pd.read_sql(query, cnxn)
b. Writing the read dataframe back to Azure SQL database
Now let us write back the dataframe df into another table named creditdata_test2 using SQL Alchemy:
import sqlalchemy import urllib.parse as ul params = ul.quote_plus("DRIVER={ODBC Driver 13 for SQL Server};SERVER= <myserver>;DATABASE= <mydatabase>;UID= <myusername>;PWD= <my password> ") engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params) df.to_sql("creditdata_test2 ", engine, if_exists = 'replace')
c. Reviewing SQLAlchemy performance
When we run the code with SQL Alchemy, which by the way is faster than using a cursor, the results are:
The total number of records in creditdata i.e. the original table is 112994.
When the number of records transferred at 12:45:20 was measured, we had 124 rows.
One minute later, at 12:46:20, only 420 rows were transferred!
Spark Dataframe
Now, to demonstrate the performance benefits of the spark dataframe, we will use Azure Databricks. For more on Azure Databricks: Azure Databricks tutorial: end to end analytics.
The primary advantage of Spark is its multi-language support. Let’s take a similar scenario, where the data is being read from Azure SQL Database into a spark dataframe, transformed using Scala and persisted into another table in the same Azure SQL database. Here is a step by step guide:
a. Creating a JDBC connection
Firstly, we redact credentials for Azure SQL Database from key vault secrets. Secrets are a key vault feature for storing sensitive credential information. In Databricks, it is achieved using the key-vault backed secret scope. Here is the comprehensive documentation for setting up the same.
val jdbcUsername = dbutils.secrets.get(scope = "AvroScope", key = "username") val jdbcPassword = dbutils.secrets.get(scope = "AvroScope", key = "password")
Now we create a JDBC connection using the below code:
val jdbcHostname = "<Your Server name>" val jdbcPort = 1433 val jdbcDatabase = "<Your Database Name>" //}")
b. Reading data into spark dataframe
Once the connection string is formed, a simple spark.read.jdbc function helps us read the data from the table source table creditdata.
val df = spark.read.jdbc(url=jdbcUrl,table="creditdata", properties=connectionProperties)
c. Writing the spark dataframe to Azure SQL database
Finally, we write the data read into df, as is in the Azure SQL database table creditdata_test2.
df.write.mode("Overwrite").jdbc(jdbcUrl, "creditdata_test2", connectionProperties)
d. Reviewing spark dataframe performance
Below snapshot shows that all the 112994 rows in creditdata were written in creditdata_test2 in a time frame of 2.13 minutes!
We have all the data!
Conclusion
This article is not meant to deride python’s pandas dataframe. I personally love pandas with its rich API for data exploration and manipulation. However, it has its own limitation with row by row insert. This is overcome by spark dataframe in its native scala language. Please note that I am not commenting on the famous PySpark and R data frames. I encourage the readers to try them as well.. | https://www.data4v.com/spark-dataframe-performance-benefits/ | CC-MAIN-2022-05 | refinedweb | 852 | 57.67 |
Versioning Options
Scott Seely
Microsoft Corporation
October 15, 2002
Summary: Scott Seely walks through the steps of implementing a new version of a Web service, showing how to add extra methods, change method signatures, and update the data model. (11 printed pages)
Download Ays15oct2002-setup.msi.
Introduction
Back in August, a few of you wrote in asking me to explain how to version an interface. When implementing a new version of an interface, there are some instances where you can simply enhance the existing class, and others where you need to implement a new class that may use the previous version. I want to address the combinations that I believe most readers will encounter. Here are the most common tasks you will face when updating a Web service:
- Adding extra methods. The new methods are conceptually related to the existing Web service and should be implemented on the same endpoint.
- Changing method signatures. In this instance, the number and or types for input elements changes.
- Updating the data model. In this instance, data types will be expanded and data members may change names.
To set the stage, I want to lay out a simple Web service capable of undergoing all sorts of changes. This Web service represents version 1. Classes and the Web service will start out synchronized with one namespace. Everything will evolve throughout the article.
Version 1
I want to present a starting point for the modifications that will be made later. Each section builds on this initial Web service. The following sections do not, however, build on each other. The service is set up to handle messages to add two numbers together and to convert some basic personal data to a string.
[WebServiceAttribute(Namespace = NamespaceConsts.AYS15Oct2002)] public class VersionOne : System.Web.Services.WebService { [WebMethodAttribute] public string GetDisplayValue( Person person ) { return person.ToString(); } [WebMethodAttribute] public int Add( int a, int b ) { return a + b; } }
The namespace strings are stored in one location, the NamspaceConsts class, to reduce problems with typos. I'll be reusing the namespace value a lot, and I want to reduce the chances of typing in the wrong string.
public class NamespaceConsts { /// <summary> /// This value contains the string used for the XML Namespace /// /// </summary> public const string AYS15Oct2002 = ""; /// <summary> /// This value contains the string used for the XML Namespace /// /// </summary> public const string AYS22Oct2002 = ""; }
Finally, the first version of the Web service uses a few other classes:
- PersonName: This class contains three string member variables for a person's first, middle, and last name.
- USAddress: This class contains other member variables representing the street address, city, state, and zip code.
- Person: This class contains two public members, a PersonName and a USAddress. (Big surprise, right?)
All the classes use the System.Xml.Serialization.XmlTypeAttribute to make sure that when the class is serialized to XML, the classes are in the same XML namespace. For example, here is the Person class.
[XmlTypeAttribute(Namespace=NamespaceConsts.AYS15Oct2002)] public class Person { public PersonName Name; public USAddress Address; public override string ToString() { return string.Format( "{0}\n{1}", Name.ToString(), Address.ToString() ); } }
This pretty much details version 1 of the Web service.
Adding Extra Messages
One of the ways to update a Web service is to add extra messages that the Web service is able to accept. The Web service supports addition of numbers. How about adding the ability to subtract as well? How do we add this new message without breaking existing clients? First, let's see what happens if we try the naïve approach and just add the new Web method. For this experiment, I created a new Web service endpoint called Service2a.asmx. In this situation, the Version2a Web service was created only to show how to implement the changes. These changes could have also been applied to the VersionOne Web service. I then copied the code from ServiceOne.asmx.cs and added the new Web method. Here's the result.
[WebServiceAttribute(Namespace = NamespaceConsts.AYS15Oct2002)] public class Version2a : System.Web.Services.WebService { [WebMethodAttribute] public string GetDisplayValue( Person person ) { return person.ToString(); } [WebMethodAttribute] public int Add( int a, int b ) { return a + b; } [WebMethodAttribute] public int Subtract( int a, int b ) { return a - b; } }
If I then point the client at this new endpoint, the Microsoft® .NET client continues to run just fine. What does this tell me? This tells me that if I add new messages without altering the existing ones, the deployed clients will continue to work without any modifications. A more important question to ask: "Is this the right thing to do?" From my point of view, the answer to that question is "No." I am speaking strictly from the point of view of a fully deployed Web service, not how you choose to work through a beta.
So, what is the right thing to do? In general, you should change the qualified name of the portType whenever you change the definition of a message. A "qualified name" is the XML Namespace plus portType name.
In this situation, the operations are all still logically related. It makes perfect sense to have an Add and Subtract operation as part of the same WSDL portType and binding. A user of the Web service would expect any proxy generation tools to keep the operations together. In this instance, we want to manage the XML namespaces used by the input and output messages while keeping all the operations in one binding. We also want to keep Add and GetDisplayValue accessible to existing clients. Finally, we want to indicate that the Web service is using a new XML Namespace. To do this, we need to add some attributes to set the namespace used by the request and response messages.
[WebServiceAttribute(Namespace = NamespaceConsts.AYS22Oct2002)] public class Version2a : System.Web.Services.WebService { [WebMethodAttribute] [SoapDocumentMethodAttribute( NamespaceConsts.AYS15Oct2002 + "GetDisplayValue", RequestNamespace=NamespaceConsts.AYS15Oct2002, ResponseNamespace=NamespaceConsts.AYS15Oct2002 )] public string GetDisplayValue( Person person ) { return person.ToString(); } [WebMethodAttribute] [SoapDocumentMethodAttribute( NamespaceConsts.AYS15Oct2002 + "Add", RequestNamespace=NamespaceConsts.AYS15Oct2002, ResponseNamespace=NamespaceConsts.AYS15Oct2002 )] public int Add( int a, int b ) { return a + b; } [WebMethodAttribute] [SoapDocumentMethodAttribute( NamespaceConsts.AYS22Oct2002 + "Subtract", RequestNamespace=NamespaceConsts.AYS22Oct2002, ResponseNamespace=NamespaceConsts.AYS22Oct2002 )] public int Subtract( int a, int b ) { return a - b; } }
By default, Microsoft® ASP.NET Web services route the message based on the SOAPAction. The SOAP action is created by concatenating the Web service XML Namespace with the operation being invoked. So, if a Web service uses the XML Namespace and contains an operation named foo, the default SOAPAction is. Each exposed operation sets the SOAPAction and namespaces to create a more up-to-date set of operations. The WSDL generated by ASP.NET will place all of the operations in the same binding. As a reader of the WSDL, I can tell that Subtract was added sometime after Add and GetDisplayValue. As a user of the old WSDL, the original client will continue to function. Any new clients will be able to call Subtract as well, and will use the updated XML Namespaces. The endpoint is able to correctly respond to old and new clients without breaking. The endpoint does, however, fail to do one important thing: To document the fact that the one endpoint supports two bindings. How do we do this?
Because of how we chose to build the Web service, the existing attribution methods, which allow the developer to specify which binding a particular operation belongs to, do not work in this situation. The Add and GetDisplayValue messages did not change in any way, meaning that I cannot just attribute things "correctly" and move on. At this point, you have two options:
- Write some more code and give up on having one endpoint support both versions.
- Save the binding information to separate files for both versions, write a custom WSDL file for the endpoint, and turn off documentation for the Web application.
Let's take a look at these two options in turn.
Writing More Code
The code for this option lives in Version2b.asmx. If the idea of writing WSDL by hand repulses you, you can choose to write more code instead. (Hey, writing WSDL by hand is not exactly an easy thing to do, and you just may not want to bother.) If you would rather let ASP.NET do the work for you, the option of writing more code requires you to deploy a new endpoint. This option does not maintain namespace compatibility with existing clients, meaning that the Web application will have two .ASMX endpoints: one for version 1 and one for version 2.
When I went to do this, my first instinct was to derive the version 2 Web service class from VersionOne, add methods in the new XML namespace, then redirect requests to Add in the new namespace to Add in the base class. For better or worse, the methods in VersionOne are made available through inheritance, and the message names for Add and GetDisplayValue in both namespaces wind up clashing. Why? ASP.NET winds up with some problems around clashes in identical message names. I could change the message name, but setting the message name to Addv2 is completely unappealing to me. The targetNamespace of the WSDL file indicates the version. I don't want to take that information into the operation name—it clutters things up.
My next attempt used delegation. Since functionality is not changing, the Web service should make use of the previous version methods. Delegation wound up working. The code has the three functions: Add, GetDisplayValue, and the new Subtract.
[WebServiceAttribute(Namespace = NamespaceConsts.AYS22Oct2002)] public class Version2b : WebService { [WebMethodAttribute] public string GetDisplayValue( Person person ) { // Call the original function VersionOne v1 = new VersionOne(); return v1.GetDisplayValue( person ); } [WebMethodAttribute] public int Add( int a, int b ) { // Call the original function VersionOne v1 = new VersionOne(); return v1.Add( a, b ); } [WebMethodAttribute] public int Subtract( int a, int b ) { return a - b; } }
As you can see, the calls to Add and GetDisplayValue delegate the requests to the original version.
Custom WSDL
Let's take a look at what we could do to show that Service2a.asmx really does implement the version 1 and 2 bindings. A WSDL file indicates its version in the /documentation/@targetNamespace attribute. For version 1, the value of the targetNamespace attribute is. Version 2 uses.
As far as I could tell, there is no way I could see to make ASP.NET generate the right WSDL automatically. Here are the steps we will follow:
- Save the WSDL for the VersionOne.asmx Web service.
- Save the WSDL for the Version2a.asmx Web service.
- Remove the service elements from the WSDL documents.
- Place the schema for the version 1 namespace into a separate XSD file.
- Write and save the WSDL file for the Version2a.asmx Web service.
- Turn off documentation.
Steps 1–3 can be done by navigating to the .ASMX page, viewing the WSDL, and saving the presented WSDL to disk. Then just open the saved file and remove the service element. For step 4, I created a new file, MessageTypes.xsd. I saved the contents of the types section from VersionOne.wsdl to this file, and added namespace declarations for the XSD XML Namespace and for the version 1 XML Namespace. In the end, the types section for VersionOne.wsdl was reduced to the following:
<import namespace="" location="" /> <types />
The new WSDL for the Web service is:
<?xml version="1.0" encoding="utf-8" ?> <definitions xmlns: <import namespace="" location="" /> <import namespace="" location="" /> <types /> <service name="Version2a"> <port name="Version1" binding="s0:Version1"> <soap:address </port> <port name="Version2aSoap" binding="s1:Version2aSoap"> <soap:address </port> </service> </definitions>
Notice that the location for both ports is the same. Finally, the documentation was turned off. To do this, use the /configuration/system.web/webServices/protocols section of web.config and add the following line:
<webServices> <protocols> <remove name="Documentation" /> </protocols> </webServices>
So, what did this option accomplish? We edited WSDL that accurately reflects the messages accepted by both versions of the Web service. A new WSDL was created to show that the endpoint understands the messages defined in both documents. The underlying Web service is able to accept messages for both versions due to the way it was coded.
Adding new methods isn't the only way to evolve a Web service. Next, let's take a look at what to do if you change the signature of a method.
Changing Method Signatures
For this case, I am assuming that you want to leave the existing version operational, and that you want to change the contents of a specific message. Let’s take a look at changing the Add message to take an array of integers and return the sum of those integers. This new Add message and the old one are incompatible.
I could get both messages to operate on the same endpoint by giving them different names, but that isn't what I want to do. The WSDL needs to reflect that this method is a newer, better form of Add. To make the break clean and keep the other functions together, I created a new Web service, Version2c. I also chose to move GetDisplayValue into the new XML Namespace. This function still calls into the internal GetDisplayValue method to take advantage of the existing code and any future bug fixes.
[WebServiceAttribute(Namespace=NamespaceConsts.AYS22Oct2002)] [WebServiceBinding("Version2", NamespaceConsts.AYS22Oct2002 )] public class Version2c : System.Web.Services.WebService { [WebMethodAttribute] [SoapDocumentMethodAttribute(Binding="Version2")] public string GetDisplayValue( Person person ) { VersionOne v1 = new VersionOne(); return v1.GetDisplayValue( person ); } [WebMethodAttribute] [SoapDocumentMethodAttribute(Binding="Version2")] public int Add( int[] values ) { int retval = 0; if ( ( values == null ) || ( values.Length < 1 ) ) { // No values passed in, return 0. return retval; } foreach( int val in values ) { retval += val; } return retval; } }
In this situation, the version 1 and version 2 client run side-by-side at different URLs. Add methods cannot be confused, since one version takes an array of integers whereas the older version takes two integers.
To wrap up, let's take a look at what to do when you add new derived types and want the Web methods to handle the new data.
Updating the Data Model
In case you were wondering why GetDisplayValue was in the Web service, you are about to find out. In our scenario, we decide to add a new type of Person called Penpal. Penpal extends Person by adding an e-mail address. The definition for Penpal is:
[XmlType(Namespace=NamespaceConsts.AYS22Oct2002)] public class Penpal : Person { public string Email; public override string ToString() { return string.Format( "{0}\n{1}", base.ToString(), Email ); } }
I'd like to enable the Web service to accept either a Person or a Penpal for GetDisplayValue. For the Web service, I do the following:
- Add a new type.
- Change the types GetDisplayValue accepts.
Considering my requirements, it appears I am somewhere between where I was when I added a new method and where I changed the signature. However, I did change the set of data types that the GetDisplayValue method accepts. If versioning is truly important (and it is), this change requires GetDisplayValue to be in a new XML Namespace. So, once again, this new version should go to a separate URL and class.
[WebServiceAttribute(Namespace=NamespaceConsts.AYS22Oct2002)] [WebServiceBindingAttribute("Version2", NamespaceConsts.AYS22Oct2002)] public class Version2d : System.Web.Services.WebService { [WebMethodAttribute] [SoapDocumentMethodAttribute(Binding="Version2")] public string GetDisplayValue( [XmlElement("Person", typeof(Person))] [XmlElement("Penpal", typeof(Penpal))] Person person ) { VersionOne v1 = new VersionOne(); return v1.GetDisplayValue( person ); } [WebMethodAttribute] [SoapDocumentMethodAttribute(Binding="Version2")] public int Add( int a, int b ) { VersionOne v1 = new VersionOne(); return v1.Add( a, b ); } }
Internally, the revision calls into the old Web service since the functionality didn't change—just the WSDL.
Conclusion
When creating a new version of a Web service, you will need to make one or more changes:
- Add a new method.
- Change the signature of a method.
- Update the data model.
In every case, it's easiest to create a new Web service endpoint that delegates to the previous version when possible, and implements the new functionality otherwise. This isn't the first time I've discussed versioning, but it is the first time I've actually shown what I was doing in code to get the job done. A few readers posted some great questions that drove most of the content in this article. Thanks for the great feedback!
On another note, this is the last At Your Service column that I will write. My job duties have changed and I will no longer have the time to devote to this column. I've really enjoyed being able to present in this space and show my readers some of the neat things I've learned about ASMX and SOAP interoperability. Adios, amigos.). | https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/aa480518(v%3Dmsdn.10) | CC-MAIN-2019-43 | refinedweb | 2,771 | 57.27 |
This is your resource to discuss support topics with your peers, and learn from each other.
12-19-2012 01:21 AM
This seems like it should be about as basic as it gets, but I haven't had any luck.
I'm trying to get gyroscope data using the blackberry.sensors api. I tried using one of the demo apps which make the following call:
blackberry.sensors.setOptions("devicecompass", { delay: 1000 });
But that just gives me an error: Uncaught TypeError: cannot call setOptions of undefined
I figured this must just mean that the sensors api wasn't loaded. According to the docs I just need to add
<feature id="blackberry.sensors" />
to the config.xml file, but that doesn't seem to help.
Can anyone explain what I've done wrong? Here's my config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns=""
xmlns:
<author href=""
rim:Author</author>
<name>myapp</name>
<content src="index.html"/>
<description>
My Description
</description>
<icon src="icon-150.png"/>
<rim:splash
<rim:splash
<feature id="blackberry.app" />
<feature id="blackberry.sensors" />
</widget>
12-19-2012 01:47 PM
It sounds like you might be missing the webworks.js file. Try adding the script src="local:///chrome/webworks.js" in the head of your HMTL document.
12-19-2012 02:02 PM
I wondered if that might be the case, but the reference to webworks.js is already there.
The network inspector shows that the GET for webworks.js fails, but the console does indicate that webworks has loaded:
webworks.bb10 :: Initialization Finished (Make it so.) ripple.js:475
I also have a listener on the webworksready event that does fire correctly, so webworks must be loading, mustn't it?
Yet, when anything tries to use a part of webworks, like the following I get errors. The following:
12-19-2012 02:04 PM
If the GET for webworks.js fails then that isn't good. It sounds like an API loading issue in Ripple maybe? If your webworks.js can be loaded, then it will try and load the sensor API that you have requested. Is this what the GET fails on?
12-20-2012 03:09 AM
The GET failure was definitely happening on the webworks.js file.
To try to eliminate any possible mistakes that I could have been making I uninstalled Ripple and reinstalled it with a fresh download. Then I grabbed the BB10 WebWorks samples archive and loaded up the mediacards example. Exactly the same problem - can't GET webworks.js.
Here's my console output when trying to load the example files which are being served by the internal Ripple webserver on localhost:9910
But I can package this just fine and deploy to the simulator without any issue.
12-20-2012 05:36 AM
12-20-2012 10:49 AM
This is submittted. Here's the link:
To try to eliminate more variables I've disabled every other Chrome extension, the problem remains.
12-20-2012 10:53 AM
Awesome, Bryan raised a couple good points this morning about how perhaps the device namespace is not implemented in Ripple yet. This could be part of the problem coupled with the local:///chrome not being found. Let's let the issue in the repo play out. It will get some attention for sure. | https://supportforums.blackberry.com/t5/Web-and-WebWorks-Development/Unable-to-load-API-features-with-lt-feature-gt-tag/m-p/2049209/highlight/true | CC-MAIN-2017-13 | refinedweb | 557 | 68.16 |
This is for any+all of you new to Zope.. and for those like me who have been struggling with DMTL for too long. I just found a perfect *gemstone* burried in 'Chapter6 - Advanced DTML' of the online sample of the O'Reilly Zope Book at """ The REQUEST namespace is very useful in Zope since it is the primary way that clients (in this case, web browsers) communicate with Zope by providing form data, cookies and other information about themselves. A very simple and enlightening example is to simply print the REQUEST out in an HTML page: <dtml-var standard_html_header> <dtml-var REQUEST> <dtml-var standard_html_footer> """" Try it...beautiful and yes very enlightening. This should be on PageZero in my opinion I never saw a single line of ZopeDTML which so well demonstrates what it is capable of and why it _is_ cool when you know what to type. Get this book in Print asap please! thanks - Jason PS. Be warned: <8-() if you try put the code above in a DTML methods named 'showREQUEST' or 'show_REQUEST' it will not work = 'Id already in use' ________________________________________________________________ Jason CUNLIFFE = NOMADICS.(Interactive Art and Technology).Design Director _______________________________________________ Zope maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - )
- [Zope] 'showREQUEST' or 'show_REQUEST' ? Jason Cunliffe
- [Zope] 'showREQUEST' or 'show_REQUEST' ? Chris Withers
- Re: [Zope] 'showREQUEST' or 'show_REQUEST' ? Steve Alexander
- Re: [Zope] 'showREQUEST' or 'show_REQUEST' ? Evan Simpson | https://www.mail-archive.com/zope@zope.org/msg07428.html | CC-MAIN-2016-44 | refinedweb | 234 | 64.61 |
If you stand in a queue at a grocery store (or anywhere else), the first customer in the queue will be served, and then the next, and so on.
In programming terminology, especially in data structure, this concept is called FIFO (first in first out) queue.
In C++, Queue is an important part of a STL (Standard Template Library).
Apart from the typical FIFO queue, there are few other types of queue. For example, priority queue.
In a priority queue, apart from the FIFO characteristics, certain customers (or elements in a queue) might have a higher priority, and they might receive immediate service irrespective of their location in the queue.
In this tutorial, we’ll discuss the following aspects of STL Queue:
- Create a Queue
- Check Queue Status
- Access Next Element
- Access Last Element
- Add New Element to the Queue
- Create and Insert Element to the Queue
- Remove Element from the Queue
- Swap the Content of an Element
If you are new to C++ STL concept, the following might help:
- 3 Example Programs to Understand C++ STL Stack Implementation
- STL Tutorial: How to use C++ Vector with Example Program
The following are few important functions/statements required to create your queue program:
- #include <queue>- In order to use STL queue, add this include. This will include some important files to the code we are writing.
- queue <type> ourQueue; – Declare queue of some type
- ourQueue.empty(); – Check if the queue is empty. If queue is empty the answer will be true, otherwise the answer is false.
- ourQueue.size(); – Figure out the number of elements in your queue. Just like size, you also have sizeof() operation as well.
- ourQueue.front() and ourQueue.back(); – You can access the first element in the queue, or the last element in the queue using front and back function respectively.
- ourQueue.push(); – When you are creating the queue, you can use push to add new elements to the queue.
- ourQueue.pop(); – If you would like to remove the element from the queue, use the pop function:
- You also have emplace and swap. Emplace is used to construct and insert element into the queue. Swap is used when you need to swap the content. The syntax for these two functions are similar to the above functions.
STL Queue Basic Example Code
Our task is to create a queue and add some elements( 3, 6 and 7) to it. After that, we’ll remove the elements from the queue.
In order to make it more simple I will use one ciphered numbers, and there will be few public member functions applied.
#include <iostream> #include <queue> using namespace std; int main( void ) { queue < int > ourQueue; cout<<"The occupied place in the memory is = " <<ourQueue.size() <<endl; ourQueue.emplace( 3 ); ourQueue.emplace( 6 ); ourQueue.emplace( 7 ); cout<<"The occupied place in the memory is = " <<ourQueue.size() <<endl <<"And with the bits it is =" <<ourQueue.size() * sizeof( int ) <<endl; while( ! ourQueue.empty() ) { int iTemp = ourQueue.front(); cout<<iTemp<<endl; ourQueue.pop(); } return EXIT_SUCCESS; }
In general, in the above code we did the following:
- Create a queue
- Calculate the size of the queue before any elements were added
- Construct and insert few elements,
- Calculate the size after the elements were added
- Empty the content of the queue
The following are few suggestions to improve the above basic code:
1) First, probably you can add some meaningful comments in the above program to explain what it does.
2) Second, add few lines of code to understand how front and pop works.
Probably you can add the following line to the above sample code, after you have emplaced those elements into our queue.
int iTempFront = ourQueue.front(); cout<<iTempFront;
After that add one more time the same two lines of code. Now, use method pop in between those added lines of code, something like this:
int iTempFront = ourQueue.front(); cout<<iTempFront; ourQueue.pop(); iTempFront = ourQueue.front(); cout<<iTempFront;
3) Third, add few lines of code to understand how back works. Replace the above few lines of code with the following.
int iTempFront = ourQueue.back(); cout<<iTempFront; ourQueue.pop(); iTempFront = ourQueue.back(); cout<<iTempFront;
So, now you understand the back member function and you should be able to figure out what is difference between front and back, as well as why pop is used for.
4) Fourth, remove those three emplace member functions and replace that part of the code with this one:
do { char cChoice; cout<<" More elements (y)es / (n)o ->"; cin>>cChoice; if( ( cChoice == 'N' ) || ( cChoice == 'n') ) { break;} else if( ( cChoice == 'Y' ) || ( cChoice == 'y')) { int iNextOne; cout<<"Next element->"; cin>>iNexOne; ourQueue.push( iNexOne); } else { cout<<"Wrong choice!!!"; systm("clear"); } } while( 1 );
Additional Thoughts on Queue
Now that you have some basic idea about queue, you should also understand the following two types of queues that you might encounter.
- Limited Queue – Limited queue is implemented with simple array. This implementation is mostly not interesting and it is more useful in C.
- Unlimited Queue – This uses struct(class) and pointers. While practically there is no limit to this, it is limited by the physical resources you have on your system.
When you start creating serious programs in C++, you could have queue of objects or you might have queue of something in your class.
In the world of C, deciding when to use queue over array is simple. If you don’t know how many objects you will need to store, the array was not useful. Now, there are vectors and you could add elements at the end of it and even swap them.
Two most basic dynamic data structures are: stack and queue. They are similar. Stack will return last added element. On the other hand, queue will return first added element. So, if you add elements on one side and later remove them from your particular container, those two data structures could be good pick.
If you need to add elements at the beginning and at the end of structure deque might be considered. This could be reason why to pick deque over the vector. However, if you need to add elements in the middle of our data structure, you might be needing list. Bad side of list could be felt in situations when you need to access first, second, third or n-th element of the list. In order to improve original list you could deploy few tricks.
Additional Queue Exercises
- Create the queue that will store active processes one your computer. It would be good idea to type ps aux into terminal and figure what you might need.
- Create a queue for music playlist. Your task is to create part of the code that will store names of song, locations on the disk, and few additional information about the song.
- Create two queues, one will have grater priority and the second one will have lower priority. The strategy of consuming elements from those queues it this: if queue with greater priority is not empty take element from that queue, and if the queue with higher priority is empty get elements from the queue with lower priority.
- Same as above #3, but use the stack for lower priority data structure.
- Your task is to crate the part of the program that will store messages to be encrypted.
- Create the page, it will have sentences of one conversation. Those sentences will be kept as the stings and added from the file. After you have completed reading from the file, display these sentences on the screen. Try to limit the size of the queue, so that your program won’t crash.
- Create a program to manage printer queue. | http://www.thegeekstuff.com/2017/01/cpp-stl-queue/ | CC-MAIN-2017-09 | refinedweb | 1,275 | 72.76 |
A Publisher's Journey Into His Former Life
A while back I wrote a post about lambda expressions in C# 3.0 and how they are one of the enabling technologies behind Linq. I would like to continue that discussion today with a quick overview of something called extension methods. First, I want to say up front that I believe extension methods are one of those features that will be useful for framework developers – but bring a very high risk of abuse if used widely in a general sense. So with that out of the way, I'll cover what extension methods are, how they can be used, and what are some of the "gotchas".
First, an extension method is simply a new technique for extending a class without inheriting from the class, making a partial class, etc… The really interesting thing about this technique is in the implementation details. In C# 3.0, extension methods are implemented by creating a static class (which implies that the methods will be static methods) and using the 'this' modifier on the first method parameter. For example, consider the following.
1: namespace LinqTestsHarness.Extensions {
2: public static class TestExtensions {
3: public static void SayHelloFromInt(this int arg) {
4: Console.WriteLine("Hello " + arg.ToString());
5: }
6: }
7: }
As we have described, the extension method is identified by the fact that it is a static method (in a static class) and that it has the 'this' modifier on its first parameter. OK – so now we've go this extension method – what do we do with it? If you remember our working definition of an extension method from above, the method allows us to extend an existing type – and that's exactly what our new method does. For example, we can now run the following code.
using LinqTestsHarness.Extensions;
...
int n = 5;
n.SayHelloFromInt();
And how did this work again? 2 things. First, we imported the namespace containing our extension method. Every time you import a namespace, you bring in every extension method that is defined within that namespace. The second important thing that allowed the above code to work is that we declared our variable (n) of type int – which is of course the type expected by our extension method. The following would not compile because of the type mismatch.
using LinqTestsHarness.Extensions;
...
string s = "howard";
n.SayHelloFromInt();
So by now you should have a pretty decent understanding of how extension methods work – so let's take a look at how they are used by Linq. Consider the following Linq expression.
IEnumerable<string> expr = from s in names
where s.Length == 5
orderby s
select s.ToUpper();
The Linq keyword such as 'where', 'orderby', etc… are simply shortcuts to extension methods defined in the System.Linq namespace. Therefore, the following is equivalent to the previous Linq expression.
IEnumerable<string> expr = names
.Where(s => s.Length == 5)
.OrderBy(s => s)
.Select(s => s.ToUpper());
So hopefully, you are now starting to see that Linq is not some sort of compiler magic. It is built on the very same language features that you have access to as you design and construct your solutions. Now, as we look at one potential application of extension methods, let me be quite clear that this is not a design pattern that I support – I am mentioning it here because I know that this is a pattern that many people do support, and if it is going to continue being used, extension methods are not a bad way to go about separating concerns. Let's consider object persistence. While there is significant debate over the "proper" architectural pattern for layer interactions, there is a school of thought that advocates the inclusion of persistence operations (Create, Read, Update, Delete) on business objects. One of the counter arguments to this approach is that you are then required to mix persistence code with business code and subsequently tie the business layer to a specific data access provider. In this context (let's forget about all of the other arguments both for and against this technique right now), extension methods provide a creative solution to the problem. For example, consider the following business entity class.
1: public class Person {
2: private string _name;
3: private int _age;
4: private bool _canCode;
5:
6: public Person() { }
7:
8: public Person(string name) {
9: Name = name;
10: }
11:
12: public Person(string name, int age) : this(name) {
13: Age = age;
14: }
15:
16: public string Name {
17: get { return _name; }
18: set { _name = value; }
19: }
20:
21: public int Age {
22: get { return _age; }
23: set { _age = value; }
24: }
25:
26: public bool CanCode {
27: get { return _canCode; }
28: set { _canCode = value; }
29: }
30:
31: public override string ToString() {
32: return Name;
33: }
34: }
If you wanted to maintain your data access code in a separate assembly, yet still have the appearance of data access methods on this class, you could create your data access class as a static class and use extension methods for the data access functionality. This extension class would look like the following.
namespace LinqTestsHarness.DataAccess {
public static class DataAccessExtensions {
public static void Save(this Person arg) {
// ...
}
public static void Delete(this Person arg) {
// ...
}
}
}
Just like in the previous case, using the extension method is a simple matter of importing the LinqTestsHarness.DataAccess namespace. The first parameter on the extension method constrains the method to only instances of the 'Person' class. Of course, all of the usual OO capabilities apply to extension methods. Were I using an ORM tool for my persistence, I could also create a marker interface and constrain the extension method to that interface rather than the concrete type. You can also create generic extension methods. However, my goal with this post is to simply give you an overview.
Now – a word of caution. While extension methods can be a very handy tool for allowing frameworks to add functionality to existing object models, they should probably be approached with a degree of caution. Like any cross-cutting technique, extension methods can be a real pain when it comes to tracing and debugging. One thing that you absolutely must keep in mind with extension methods is that they are given the lowest priority in terms of method invocation. Practically, this means that if the object instance already contains a method (virtual or otherwise) with the same name as your extension method, that method will always be give precedence over your extension method. Therefore, there's always going to be some degree of brittleness if you design a solution that makes heavy use of extension methods because your extension methods and the object model on which the methods are applied will probably evolve quite independently.
Secondly, and even more dangerous is the fact that although it appears as an instance methods, extension methods are of course static. What that means in IL terms is that extension methods use the 'call' instruction rather than the 'callvirt' instruction. Why is this important? Because the 'callvirt' instruction, the instruction called whenever you call an instance method on an object (in C#), checks for null and throws a 'NullReferenceException' if the object is null – the 'call' instruction does not. Therefore, the following code is perfectly legal.
Person howard = null;
howard.Save();
Now, obviously, there are a lot of cool things that you can do with extension methods, and I'm not trying to say that you should never use them. Obviously, the Linq team has gained tremendous value from them. However, like with all things in development – just because you have a new hammer, don't turn everything into a nail!
If you would like to receive an email when updates are made to this post, please register here
RSS
Ohad's Weblog - IE7Pro - a must have add-in if you use IE7 ! Simple Living Simple Thinking - Zip and
Hi Howard,
Nice intro and connection of LINQ and extensions. I have one problem with extensions. I couldn't find a way to make an extension method that would change an instance value. i.e.
public static void AddThis(this int source, int val)
{
source += val;
}
This method doesn't throw an exception when it is called, but it doesn't change a value either. Do you have a solution for this?
Hi Milan - extension methods don't allow ref or out parameters. Therefore, you can't do what you're trying to do for value types like int. You can of course, change the state of reference types. As an example, in the following 2 tests, the first test (which is the same as your code) will fail because i cannot be passed as a ref param. The second test will pass because you are simply changing the state of a reference type.
[Test]
public void testExtensionMethod_ValueType() {
var i = 5;
i.AddMe(3);
Assert.AreEqual(8, i);
public void testExtensionMethod_RefType() {
var howard = new Person {Name = "Howard"};
howard.ChangeName("Howard Modified");
Assert.AreEqual("Howard Modified", howard.Name);
Hi Howard.
I thought so, but was hoping that's not true :(
Thanks for the insights in this article. What I'd hoped to see, however, is a (small) explanation of the obviousness of the extension methods being static and why it isn't possible to create an extension instance method (i.e. Int32.MyExtension()).
I'd understand that the method already being static means that it cannot be "more" static (über-static???). Or do I misunderstand something and is it perfectly possible to create instance method extensions?
Thanks again,
Abel
Hi Abel - so in terms of the obviousness of extension methods being static, it's related to the next part of your question.
Extension methods are static because for many types that you would want to create them for, you don't have access to the source code that would enable you to create instance methods (e.g. - Int32).
That said, from a syntactic perspective, extension methods behave in the same manner as instance methods - enabling you to to call an Int32 extension method using the syntax you specified Int32::MyExtension
essentially, the 'this' argument modifier enables a an extension method (which is static) to behave like an instance method in the code that uses it.
So the short answer to your question is this - an extension method is absolutely a static method from the compiler's perspective. However, the extension method syntax enables it to be used as if it were an instance method on the type specified for the 'this' argument.
hth | http://blogs.msdn.com/howard_dierking/archive/2007/02/09/more-c-3-0-extension-methods.aspx | crawl-002 | refinedweb | 1,754 | 60.35 |
Why are my plots printing out of order?
Here is my code:
def lam(n): m = 1 while (n+1 - m >= 0): m = 2*m return m/2 def inter(n,l): return [(n+1-l)/l, (n+2 - l)/l] def f(a,b,x): if x>=a and x<=b: return 1 else: return 0 for n in range(1,15): I = inter(n,lam(n)) lst = [] for i in range(101): lst.append([i/100, f(I[0],I[1],i/100)]) scatter_plot(lst,markersize=20,aspect_ratio=0.1)
I know that the plots are printing correctly, they are just out of order for some reason. Any ideas?
Also, I know this is a terrible way to plot this. I wanted to use:
plot(f(I[0],I[1],x),(x,0,1))
but that doesn't seem to be working (it just gives me the zero function), so if you have any suggestions for that as well, that would be great. Thank you.
For reference, can you mention what interface (command-line, sagenb, Jupyter notebook, CoCalc Sage worksheet) you are using? It's conceivable the answer may be different depending on this. | https://ask.sagemath.org/question/43666/why-are-my-plots-printing-out-of-order/ | CC-MAIN-2020-50 | refinedweb | 196 | 69.72 |
System wide hotkeys
System Hotkey
Multi platform system wide hotkeys for python 3,
Currently no mac or python2 support :(
Installation
the old
pip3 install system_hotkey
should do the trick
Windows
install pywin32
Usage
Input Keysyms
System hotkeys uses the keysym names from xlib for everything besides modifiers.(although case insensitive) grep for vk_codes for a list of available chars. If you are unable to bind to a certain key please let us know.
You can bind directly to symbols such as [“’,. etc Numpad keys can be binded by prefixing with kp_.
Supported modifiers include:
- control
- shift
- super (windows key)
- alt
InvalidKeyError will be raised if a key was not understood
from system_hotkey import SystemHotkey hk = SystemHotkeys() hk.register(('control', 'shift', 'h'), callback=lambda:print("Easy!"))
A SystemRegisterError will be raised if a hotkey is already in use.
To unregister a hotkey
hk.unregister(('control', 'shift', 'h'))
A KeyError will be raised if the combination is not already grabbed.
A UnregisterError will be raised if unregistering failed for any other reason.
If you want you can pass in a custom consumer:
def some_func(self, event, hotkey, args): pass hk = SystemHotkeys(consumer=some_func) hk.register(hotkey, arg1, arg2, arg3)
So you have a master function that receives all hotkey presses and can delegate as desired.
Note Modifier keys are independent of order i.e control + alt + del is the same as alt + control + del
Features
- Support for up to 3 modifiers and a key
Limitations
- I have only mapped most common keys, i have not experimented with Unicode/Japanese characters etc. It’s only a matter of mapping a name to the keysym on Linux and virtual key code on windows.
- binding to kp_left (key pad left) will also bind to kp_4, there is a flag (unite_kp) to toggle this behaviour but it is experimental
To be done
Mac support
eta > 8 months
Version Release Notes
1.0.3
- Documented the fact that xlib shouldn’t really be used
1.0.2
- Fixed a linux bug where spurious events got passed through
1.0.0
- calls to the unregister and register are now thread safe
- kp keys work properly
- kp_unite option
0.1.4
- Bug fix on linux where pressing numlock would crash us..
0.1.3
- Custom args can now be passed to a custom consumer
Download Files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/system_hotkey/ | CC-MAIN-2017-43 | refinedweb | 406 | 63.29 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
Generic loops are problematic to reason about and understand when you read the code, and therefore prone to cause bugs. I think it would be beneficial to forbid generic loops, and only have iterators.
Recursions can also be problematic since the stack usage can become unpredictable. The exception is of course tail recursions, since those can re-use that current stack frame.
If the language would prohibit generic loops and recursions except for tail recursions, would it still be useful as a generic programming language or would those restrictions make some common designs impossible?
(1) I see no problem with eliminating loops in favor of tail-recursion: I rarely/rarely/rarely use loops in OCaml, preferring almost always tail-recursion or "inductive" iter/fold/map/whatever combinators instead.
(2) eliminating non-tail-recursion completely doesn't change the expressive power of the language either: you can always CPS-translate (as we've seen in Node.JS and other languages, via the "control" monad) away non-tail recursion into tail-recursion.
BUT: (3) there is a performance penalty to be paid for only having tail-recursion: I know of no widely-used compilers that can re-infer the stack-like nature of the continuation-chain, and thereby recover the efficiency of stack-allocation of frames. And this is a serious issue if you're writing performance-sensitive code.
If those are a problem depends on what parallelism the language will support, I've got some other ideas there that I really have no idea whether they will make the situation any better...
tail recursion is the same thing as a generic loop.
And since a loop with a manual stack can do the same things as recursive functions, what have you gained from prohibiting recursive functions?
The idea was to promote better coding without sacrificing expressivity. General loops are generally looked down upon because they are hard to read and understand. Iterators and recursions are usually seen as easier to understand. The reason for limiting to trail recursions was to avoid hard to predict stack consumption.
General loops are generally looked down upon
Perhaps they are looked down upon by religious extremists, but I almost never meet real programmers who complain about loops.
...recursions are usually seen as easier to understand
This would surprise me. I would posit that fewer than a third of programmers (professional, $100k+/yr jobs) can understand most recursive examples without a significant amount of effort.
Loops are ugly. That's the real complaint. They're easy to understand, but ugly. And they leak all sorts of details. But they work, and people grok them.
I would posit that fewer than a third of programmers (professional, $100k+/yr jobs) can understand most recursive examples without a significant amount of effort.
I'd hazard that it will be the same amount of effort it took to them to get comfortable with loops. Seems to me, this difficulty is largely due to a lack of exposure since they learn imperative languages first (and often, only), not due to any inherent difficulty with recursion over loops.
Basing on the abstraction tier model.
The general recursion over concrete types has the same abstraction tier as a loop. One need to use the first order logic to reason about both. On other hand loops are more local than generic recursion, since one does not need to switch lexcial context from loop to caller of the loop if there are only global functions (like Prolog predicates or C functions/procedures). There is also a need to aggregate context and pass it to loop function. So programs with concrete recursion are harder to understand, and this was one of major issues with Prolog program understandability for me.
If there are objects, local functions, and lambdas, this is a usage of the existensial types, so it requires the second order logic to reason about, and the code the heavier to reason about per code element since concepts belongs to the next abstraction tier. Collection operations (like map, flatMap, filter, etc.) might be easier to understand for trained mind in some cases, but they are inherintly harder to learn than loops due to the higer abstraction tier. Generally higher abstraction tiers concepts are like ammunition of higher caliber. They are more powerful, but they tax mind more.
So, the loops are easier to learn in both cases, since they are either have lower abstraction tier or they are more local. Note, I consider there a case when software engineer really understands what the code is doing and able to reason about it. And not the case when code is copied and modified from tutorials and stack overflow.
On other hand loops are more local than generic recursion, since one does not need to switch lexcial context from loop to caller of the loop if there are only global functions (like Prolog predicates or C functions/procedures).
I'm not sure what you're trying to say here, or what "more local" means. Loops also "switch lexical context" when they update the bound variables, check the loop condition, then either resume or exit.
There is also a need to aggregate context and pass it to loop function. So programs with concrete recursion are harder to understand, and this was one of major issues with Prolog program understandability for me.
I don't see how this follows. Whatever context you need to aggregate and pass in a recursive call, you also need to accumulate in the equivalent loop.
they are inherintly harder to learn than loops due to the higer abstraction tier.
Yes, the fact that recursion can extent to higher levels of abstraction means those more abstract instantiations are more difficult to understand. I don't see how that makes recursion at the same "abstraction tier" less understandable though.
If anything, haven't you just argued that recursion is strictly superior since the same concept extends to more abstract domains?
Let's consider the random example from web:
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}. Just another random example from web example with Prolog:
mergesort([],[]). /* covers special case */
mergesort([A],[A]).
mergesort([A,B|R],S) :-
split([A,B|R],L1,L2),
mergesort(L1,S1),
mergesort(L2,S2),
merge(S1,S2,S).
split([],[],[]).
split([A],[A],[]).
split([A,B|R],[A|Ra],[B|Rb]) :- split(R,Ra,Rb).
merge(A,[],A).
merge([],B,B).
merge([A|Ra],[B|Rb],[A|M]) :- A =< B, merge(Ra,[B|Rb],M).
merge([A|Ra],[B|Rb],[B|M]) :- A > B, merge([A|Ra],Rb,M).
There is no clear lexical context guiding for loops. One needs to switch attention between different lexical contexts.
But this context lives in the same lexical scope, there is no need to switch back and forth between different functions. And there is no need to aggregate local variables into an additional structure. Context switches are expensive for brain too.
Higher-tier abstractions are not necessarily better, because the brain need to spend more efforts to learn, use, and understand them. For example, in Java one has to use a class context just to write a hello world program. In Haskell, one needs understand and use the concept of Monad for a hello world program. In Groovy, the print statement could be at the top level.
The monad and classes might be useful for other tasks, but for a hello world program they are just extra cognitive cost that an engineer has to pay. The monads and classes require the second order logic to understand.
If the task does not require higher-level abstractions, why to use them? They start to make sense only when their usefulness outweighs their cost for the specific task. And this is one of reasons why I do not use Haskell for pet projects..
Is it more cognitive effort overall though, or is it less because each function requires less context individually? This assertion of extra cognitive effort sounds like an empirical question for which I've seen no evidence.
I will also note a strange contradiction that seems among programmers, which is that almost everyone agrees that it's wise is to build programs with small reusable functions, but then they immediately invent reasons and languages that discourage this very thing. So when you say recursion makes us "refactor [sum] out as a separate function", my immediate thought was "good!", and I've seen no convincing reason so far to change that conclusion. The sum function you describe is immediately reusable where the embedded loop is not reusable. If your language encourages loops over recursion, then it sounds to me like it's encouraging code duplication and the subsequent maintenance problems that brings.
But this context lives in the same lexical scope, there is no need to switch back and forth between different functions.
I don't see why 1 context switch somehow dominates all other software engineering considerations. Your loop has some inputs and computes a (possibly compound) result. The equivalent recursive function has some inputs and computes a (possibly compound) result. In either case, you're reasoning from inputs to outputs, but in the recursive function you need to consider less context at any given point, eg. with the loop you have to be aware of any state updates along every possible control flow path, where with the recursive function, updates to the calling context are encapsulated in the return value.
The vast majority of code people write operates on fewer than 6 variables at any given point. If loops encourage entangling partially overlapping but disjoint contexts, that sounds like a terrible idea for any real code. If recursive functions instead encourage separating contexts so you need only consider the relevant information to the problem at hand, that sounds like a win.
I'm sure we could go back and forth on this all week, so absent any empirical evidence I don't see any reason to accept your claims. You see the different lexical scope as a disadvantage, where I instead see it as an advantage.
And there is no need to aggregate local variables into an additional structure.
I still don't see how this follows. Any local variable in a loop would be lifted into a function parameter in the recursive equivalent. There's literally no additional structure, you're just moving the location of the bindings.
If the task does not require higher-level abstractions, why to use them?
Then don't use them if they're not appropriate. But if the same thought pattern for less general abstractions can be extended to more general abstractions, then that's useful. Why would I learn 3 different concepts to achieve a given level of abstraction if I can simply learn 1 that smoothly generalizes to cover all of them?
For instance, what is the loop-based equivalent of defining a recursive type? If you can't imagine how this could be expressed, then you must acknowledge that programmers need to understand how to apply recursion anyway. You speak of cognitive load, but you don't seem to apply it evenly in different contexts.
Inner-outer-block context switch has less cost because of visual locality. Also, there is no indirection step, and there is no cognitive effort to resolve this indirection. Any indirection has additional resolution cost. If there is a reuse of code, indirection cost is compensated by learning what function does and reusing that knowledge. For a single use, indirection cost may or not be offset by cost of having larger procedure.
The particular variant of sum in the example has about zero reuse potential, since it is a very specific variant of sum. So, it does not make sense to separate it into function basing on reuse. Also, separating to function does not reduce complexity of main(...) noticeably, so there is no reason to move it out basing on it.
Also, too many procedures or functions have own cost as they pollute global namespace in the tier 3 languages like C.
Separating context and creating a good abstraction is an effort. It might help or not later, but the ultimate goal of programming is not creating a good code. The goal is 'getting things done'. Generally, the code with total cost of 2h is better than code with total cost of 6h (including creation, maintenance, etc.), if the code works the same. Balancing different costs is a major part of the art of programming. Good engineering is not only about the code, it is about how the code solves real-life problems.
Some tasks worth investing time to optimize form or performance, some do not..
Software is not written once except for few cases. It is evolving entity, so it does not have to be perfect. The particular piece of code might be as well dropped in the future, so all extra efforts spent on it will be wasted. The quality of the code should be just sufficient for the task. Overengineering might be a bigger problem than sloppy code in the long run.
For instance, what is the loop-based equivalent of defining a recursive type? If you can't imagine how this could be expressed, then you must acknowledge that programmers need to understand how to apply recursion anyway.
Böhm–Jacopini theorem says that recursion could be replaced by iteration. And considering stack-size limitations it has to be done quite often.
Inner-outer-block context switch has less cost because of visual locality. Also, there is no indirection step, and there is no cognitive effort to resolve this indirection. Any indirection has additional resolution cost.
Maybe, maybe not. Again, this is an empirical question, not a claim you can validate via introspection about how your mind works. We're all guilty of too much hand waving in programming language debates.
This is also why your arguments aren't convincing. Even if I accepted your conclusion of this example, as you yourself basically just stated, it's trivial code that's not representative of anything realistic.
I want to be clear that I'm not saying recursion is superior in every language. You should use the idioms that are common to whatever language you're using, but if you're designing a language per the posted topic, recursion seems superior for anything but contrived examples.
Separating context and creating a good abstraction is an effort. It might help or not later, but the ultimate goal of programming is not creating a good code. The goal is 'getting things done'.
...with an eye towards ensuring you can continue to get things done later. I agree abstraction requires effort. Even if recursion has more cognitive load, it would be negligeable. Recursion vs. iteration will simply not make or break your project..
Code is read far more often than it is written, so I could very easily object to your arguments that any language defaults that encourage you to organize your code around small functions will pay large dividends down the road. I have presented just as much evidence of this claim as you have about your claims for recursion, so neither of us should have convinced a skeptic. Like I said, I could do this all week, and we'll ultimately end up in exactly the same place: with no way to resolve who's right because we're debating an empirical question without any data.
Of course it could be. That's rather beside the point I was making, which is that recursion appears in many different contexts and you can reuse the the same operational thinking in all of them. If your language has loops and type-level recursion, well you've just doubled your conceptual load for no good reason that I can see, unless you have some notion of what would constitute a type-level loop.
I would disagree about negligible. Understanding recursion requires a mind shift, after that it is easier. Inductive reasoning is a skill that need to be seriously trained. If brain is trained along the line, each usage of the recursion reduces cost a bit.
I do see this when doing code reviews. The cost of recursion is hard to estimate and boundaries (like the stack size) are harder to control, and people do make mistakes there. Tail recursion optimization is only applicable for linear structures, and it is easy to disable it. In contrast, cost of loop is more apparent for beginners, as it is easier to compile in the brain to lower-level constructs.
Also, consider the compiler complexity for efficient recursive functions and loops. This compilation need to be done not only by software before execution, but by brain as well to understand a general idea how it runs.
The code is realistic in sense that there are a lot of such small processing pieces spread along of typical enterprise application. And such pieces are rarely reusable, because they are dependent on data-type, task, and context. And it demonstrate precisely the thing that does not worth creating a separate abstraction, and it lives just fine as a loop. But in case of recursion, one will be forced to create a separate named abstraction for it, paying extra cognitive cost.
Code is read far more often than it is written, so I could very easily object to your arguments that any language defaults that encourage you to organize your code around small functions will pay large dividends down the road.
There is a difference between forcing and encouraging. Forcing would just create a language with the high development cost. One of reasons why Haskell is not popular is because too much things are forced: immutability, monads, recursion, etc.
Even for reasoning about simple imperative tasks like IO, one need to translate imperative-looking DSL to 'pure functional code' and then translate functional code to imperative machine code in the mind, just to understand performance implications and the operation order. Scala or Kotlin allow writing imperative code for imperative tasks, there is no artificial pure-functional step in the reasoning. Brain will eventually short-circuit this reasoning, but this extends time needed to learn the language and makes critical early adoption stages more problematic.
For a new language it is important to support paying only for things you need, rather than forcing high upfront costs. Simple things should be done in a simple way. If one needs to spend more cognitive efforts to get simple things done, one would just use some other language. Doing it in another way might lead to repeating the fate of Haskell, that failed to get a noticeable market share despite all hype.
IMHO Kotlin is a good example of a well-balanced language: simple things are simple, higher-tier abstractions might be gradually introduced when needed. Kotlin allows evolving program on complexity hotspots, rather than doing abstraction optimization everywhere upfront.
When I code recursion, I see the recursive call as just a function call, and the appropriate function to call just happens to be the same function I call from.
While this might seem like it makes recursion easy to understand, I have had some other problems with it. It makes me forget that there might be stack costs associated, and that there might be cases where the recursion never ends.
I guess this is the reason I came up with the idea that the language should only allow tail recursions, since I at least do not need to worry about stack explosions. What is left is whether the compiler can detect cases where the recursion will never end?
I'll just close by reiterating that I disagree with just about everything you've asserted here, and I've still seen no evidence for these claims. Perhaps your conclusions grew out of experience reviewing code written by people with more experience with imperative JVM languages, but I see no reason to generalize this as if it's representative of human cognition or programming in general, which is essentially what you're asserting.
About the only thing we seem to agree on in this thread is that Kotlin is a nice language, at least compared to what's generally available and supported for the JVM.
You might like Guy Steele's presentation about replacing many kinds of loops map-reduce
There were also some interesting things about parallelism.
I'm trying to wrap my head around the connection, if any, between the questions of general loops versus iterators, iteration versus recursion, and general recursion versus tail recursion.
The difference between general loops and iterators is an imperative-versus-declarative thing, I think? That is, a general loop is inherently sequence-oriented and can draw on the entire logic of the context in which decisions are to be made, while an iterator is parallelizable (if the language design chooses to go that way) and is more regulated in what it can draw on for its decisions. The iterators' constraints on what they can use for their decisions seems to me to be unique amongst all the constructs mentioned, in that both general iteration and both kinds of recursion would seem to draw on the full context for their decisions. The matter of serial/parallel (or is it imperative/declarative) seems quite left open by recursion; general iteration is the only one of these devices that takes a strong position on the matter (solidly in the imperative camp).
Iterators, in concert with syntactic sugar in some languages, encapsulate the loop mechanics.
It's mainly a matter of taste.
Traditional loop constructs tend to require an L-Value (e.g. the CX register, or some variable named "i"), a starting value (e.g. 0), a test (e.g. the loop's stop point), and an increment size (e.g. add 1).
for (int i = 0; i < count; ++i) {
Person person = people[i];
// ...
}
Iterators look nicer:
for (Person person : people) {
// ...
}
My plan was to try to make it as functional as is practical, but I'm not sure if I'll be able to go all the way. This might have affected my impression that general loops are harder to reason about.
But since I'm an old time C programmer I can certify that loops has a tendency to be wrong, misleading or at least hard to understand. It can be hard to spot those infamous of by one errors. Coders also seem to like to do all kind of irrelevant things in the loop to save a few lines of code...
I think you're onto something:
(1) [general loops vs iterators] general loops are .... general. But that also means that we cannot regulate and express the pattern of induction [chose that word on purpose] we actually mean. Using iteration combinators (and fold, map, etc) allow us to express the pattern more visibly, and that's good for program comprehension/correctness/debuggability. It also means we can get by with fewer/no imperative operations: again good for those things.
(2) [iteration vs. recursion] In _The Science of Programming_, Gries talks about invariants and convergence bounds. Using [tail] recursion makes these things more-explicit: instead of having to figure out which variables change during an iteration of a loop, we can see what the tail-call's arguments are, and match them up to the arguments of the function. Again, it makes something visible, that for the sake of correctness, we really want to know.
(3) [general vs. tail recursion] I think this simply boils down to whether you think stack-recursion is good or bad. That's it. We all know that you can convert between the two (Felleisen & Sabry taught us how).
I think I'll actually try using those restrictions then, seems like it might work.
I just want iterators that give me a magic "i" variable. In the case of nested loops, a magic "j" variable. To override the variable name, just declare magic x.
magic x
I think that would solve most of my situations where I convert from a foreach loop to a for loop. The remaining problem is filling a buffer and doing bi-directional seeks, since that's not an iterator but a stream; in that regard cursors are more powerful than iterators and "iteratees" could potentially be structured to use extra memory to accomodate look-behind (but could create unbounded consumption - I am not sure if anyone has studied how to minimize allocations and do the look-behind lazily). An example use case is opening a file in read mode with share access, and the same file with a different handle in write mode with share access, and replacing strings.
I feel like this covers a huge array of problems that most Standard Libraries give the programmers way too many function calls to solve.
Another example on top of this is that boundary detection is often limited, so people often write imperative code to do boundary detection and manage their read buffer. A primitive to detect a pattern in a stream and use that as a boundary would be a great wait to delimit control flow.
I realize these are not really theoretical concepts, but I have often wondered why our standard libraries are so painful to use and don't concisely express what I want to say.
In this regard, I have found the terse q language for the kdb+ database to be spot on. I can imagine a less terse version of an array processing language that is as easy to write (with auto-code completion) and easier to read. I have not done much q / apl in a few years, and I can't remember all the idioms any more.
Your boundary detection sounds interesting. Could you give an example?
could you provide examples of how using the q language would make the tasks you describe easier/more-transparent? That would be interesting.
When I finally grokked that calls and returns are the same thing, I immediately started thinking about the implications of returning several results the same way most languages allow calls with several arguments, and return addresses overloaded by the type signature of the return, the same way many languages overload function calls.
So, if the function is returning an integer, the program counter goes to this address, and if it's returning a string, the program counter goes to that address. Sort of like a "goto" except with a call stack to provide context. Also the simplest possible implementation of "exceptions" as a separate type of return value.
Each call frame would determine a *set* of possible return addresses depending on what is eventually to be returned.
It's an interesting idea, and has expressive power roughly equal to scheme's call/cc. From time to time I've thought that a new programming language really ought to adopt it, with syntactic support, as a relatively simple approach that more coders could easily understand.
Anyway, this topic reminded me of it, because with overloaded calls and returns, the semantics of recursion are at the very least interesting. A tail recursion can always be represented as a loop, but the loop could wind up being very complex.
I don't really follow what you have in mind, but I'd be interested to.
You can think of a normal continuation passing style as a singleton dictionary like `(return: (result -> k))`. Then a multi-continuation might have the form `(return: (result->k), exception: (ExceptionArgs->k), ...)`. Although the syntax might be expressed as returning vs. raising an exception, a transformation to CPS could model this as calling a choice of continuation functions.
The main benefit would be removing the 'magic' of stuff like exception handling. However, the practical benefit even for exceptions is relatively limited because, in practice, too many call frames will have stack unwind actions (e.g. C++ RAII, Haskell 'bracket').
I've tried to explore this idea for potential performance benefits, but I found that construction, maintenance, and communication of multiple continuations costs more than any gains achieved compared to simply returning a value then matching on it (and applying normal optimizations).
Well, it seems that either you understand what feature is being described, or at least you think you understand... but I still don't think I understand. It sounds as if we're not talking about "multiple-value returns" here, but beyond that I'm just not getting it. :S
Ray was not talking about "multiple-value returns". That's unrelated. He was speaking instead about providing a choice of continuations, i.e. a choice of multiple return addresses with different result types, pick one.
In his words, "Each call frame would determine a *set* of possible return addresses depending on what is eventually to be returned". Where he emphasizes 'set' I would emphasize the 'possible' and 'depending'. Instead of one 'return' continuation with no options, the function picks one continuation from a collection depending on the function's internal choice of results (e.g. integer, string, exception).
Aside: when thinking about this subject, I find it useful to understand 'the stack' in conventional PLs as a representation of the data needed for a program's continuation, albeit specialized for a singular 'return' continuation.
Good, so we're solid on what this isn't. I'm not making sense of the words used to describe what it is. How about this:
the function picks one continuation from a collection depending on the function's internal choice of results (e.g. integer, string, exception).
This seems like the most specific description I've seen. I don't get it, but optimistically I suppose I might if I had (and understood) an example. You did try to give an example earlier, I think, but I didn't understand it. :S
(I'm really not trying to be obtuse, here; it seems I'm managing to be obtuse without trying.)
It sounds like continuation-passing style.
You know the way C-descended languages use 'return(value)' to send 'value' back to the caller? The first part of what I was talking about is where 'return' takes multiple arguments and therefore the function returns a 'tuple' rather than a single value.
This is exactly the same way functions (in most languages) take a 'tuple' of arguments rather than a single argument, so I could call 'return(45,"Impeached Twice")' to return a tuple of two values.
The second part is folding up the classic 'call a function then explicitly check the return type' pattern from latent-typed languages with the same kind of type dispatch that many languages do on function calls, making it possible to do similar constructions in a language with strict type checking.
As I imagine it you'd declare 'return sites' at chosen points in the program,
(some language statement that says 'function foo may return to this place as though it had been called from here, if it returns a string+integer tuple' and says what to do with the values returned.)
and then when you actually call foo, (using some language statement having semantics like 'call function foo, and if foo returns an integer then continue from this site'.) the return would dispatch either to the same site if foo returned an integer, or to the closest frame in scope containing a matching return site for foo otherwise.
It would look first in the scope of the calling function itself, and then either to its dynamic scope (which could have implicit call-frame-stack-unwinding or or call-frame-tree-traversing semantics) or to the most closely enclosing type-matching return site. the lexical scope (which probably can't be done simply unless I have some inspiration when I spend more time thinking about it).
It doesn't really buy you the idea of 'freezing' a copy of the stack and returning to it later with an arbitrary function, which is the powerful and fundamental thing that call/cc does. But it does give you most of the things that call/cc actually gets used for.
Hmm, a trivial pseudocode example might be something like this:
def divide(dividend, divisor, onOK, onErr):
if 0 == divisor:
(tailcall) onErr("divide by zero")
else:
(tailcall) onOK(dividend / divisor)
def divideOrZero(dividend, divisor, cc):
(tailcall) divide(dividend, divisor, cc, lambda() => cc(0))
This example uses an explicit continuation-passing style, i.e. 'returns' are replaced by tail-calls to continuations. This relates to Ray's first sentence, "I finally grokked that calls and returns are the same thing" - returns are implicit continuation tail-calls.
The divide function clearly accepts "multiple continuations", where 'multiple' is just two - one for a valid result and another for divide-by-zero errors. But we could extend this, e.g. have a separate continuation for type errors.
..
To be clear, I'm not advocating this approach. I've experimented with this feature before and rejected it as impractical (compared to conventional approach: construct a variant return value then branch on it).
Even if continuations are represented by cheap compile-time constructs like 'return addresses' instead of lambdas, at least half would have a fate to be discarded unused. This is exacerbated considerably by stack-unwind operations (such as C++ RAII destructors or Java's try/finally) that would require all continuations share an unwind step, thus requiring a whole new set of continuations per frame.
CPS with multiple continuations is mostly useful as an intermediate representation for compiler optimizations (cf. Cogen in Six Lines), Church-encodings of programs or data (where the lambda argument is an interpreter), and other esoteric applications.
Explicit continuations like that are extremely powerful, and yes that's a very good syntax construction for them.
But I was looking for something that could work without passing around explicit continuations, because as you note they are expensive to construct and keep.
I wanted to encode the much simpler, easier-to-understand-but-not-as-powerful idea of an explicitly labeled 'return site' within whose scope a call to some function could return depending on its return types.
I think it would require that the function within whose scope the return site was found would, when returning, unwind the stack to the most recent frame where that function was called, possibly saving the unwound frames for inspection (in an error handler) or for building an explicit continuation (which I don't prefer). Otherwise the 'return site' would act very much as a goto label, but one that's restricted to being a target site for the return of some particular function and some definite tuple of types to be returned from that function.
The explicit syntax is just to illustrate. Making them implicit won't significantly affect their cost. But greatly restricting expressiveness could reduce the cost. IIUC, you're speaking of some sort of mixed call-match control-flow structure like this:
foo(x) =>
s : string -> return (len(s))
i : int -> return (i + 42)
(s,i) : (string,int) -> ...
...
Presumably, you would implicitly compile this call as something closer to `foo(x, dict{ onstr: addr1, onint: addr2, onsi: addr3, ... })`, using a potentially static dict pointer.
foo(x, dict{ onstr: addr1, onint: addr2, onsi: addr3, ... })
I think that the main benefit, in this case, is that you can avoid the semantics for boxing values of different types and constructing tuples for multi-type function returns.
The disadvantage is that this structure is relatively awkward to use by hand, and if expanded by compiler - e.g. `f(g(x),y) + h(z)` where f, g, h return `int | float` - will easily result in very large code.
From all this discussion, looks to me as if it's adjacent to multiple-value returns. In the usual functional arrangement, calling specifies an operator and a tuple, and polymorphism allows selection of which function handles the call, while returning merely provides a single value. I maintained in the R-1RK (rationale of §4.9.1, $define!) that multiple-value returns are an illusion: a single value is passed into a function call, and a single value is returned; the value passed in can be parsed, in the Kernel dialect of Lisp, using a generalized definiend tree to distribute its parts into bindings in the local environment, while the value returned can likewise be parsed using a generalized definiend tree to distribute its parts into bindings in the dynamic environment. However Lisps usually, and Kernel particularly, don't do polymorphism. The proposal, if I'm finally grokking it, involves polymorphism in both directions.
$define!
This is about how to express things, after all. I'm not quite sure how it would work (and wouldn't be surprised to hear Ray isn't quite, either; one tries to push these sorts of ideas forward, and thereby learns what one didn't know before trying). When specifying a call, there's an operator that serves as a first-cut selector, and then a value (typically a tuple) for polymorphic refinement of the target of the call. When specifying a return, though, the value usually goes back to where the call came from, essentially a stack-based arrangement. Seemingly, where the call came from ought to have something to do with selecting a destination for the return, which would be an apparent asymmetry of return versus call; and it's not clear that there is any operator involved in the return.
Here's an example of what I was imagining, using a completely fictitious pseudocode to express a function that iterates a polyvalent function named 'foo' until a relevant condition is achieved.
And FWIW, John is right: this is all fairly woolly and I haven't taken it in detail. I just thought it could be relevant to a discussion about how to handle loops and recursions.
# univalent function takes 2 int args and has a single return type, int.
function fooloop (int arg1, int arg2)!int{
#local variables and initialization
int total = 0, string errmsg = '';
repeat{
#landing clauses are not executed unless foo returns to them.
errmsg=landing(foo!string){
# foo returns a string to signal an error.
print(errmsg, stderr);
halt(2);
}
addend,arg1,arg2 = landing(foo!int,int,int){
# a 3-int return updates the args and sends a message to a monitor
total += addend;
updateBoard(arg1, arg2);
}
# function call and handling of 1-int return.
# note that this has no effect on total unless foo returns to here.
total += foo(arg1,arg2)!int;
}
until (arg1 == arg2);
return(total);
}
Anyway, I was thinking of uses like this: de-cluttering the pattern of checking and dispatching on return types of polyvalent functions. And then thought, this also allows specifying types closely enough for full type checks, so there's more to it than that.
Each "landing clause" specifies an additional possible return address for foo when foo is called from this function, and the actual call restricts itself to handling one of the cases. But this means the whole thing can be statically type checked and compiled.
Ah! A variant on how the caller specifies how to handle what it gets back. An interesting variant. Invites tinkering.
Multi-valued variables would be fun. Might be a way of abstracting out concurrency by allowing the compiler to slice up the control flow however it sees fit.
If your PL can model a stack data type, then it's just as powerful under the constraint of tail recursion. Simply model a continuation stack as one of the recursion parameters (within each mutually recursive group that needs it). Defunctionalize as needed.
An explicit stack parameter and potential defunctionalization of the continuation is certainly less convenient to express than general recursion. But being explicit does have potential advantages. You certainly have much safer access to 'the stack' and more options to decide how to proceed with modeling exceptions, stack logging, etc..
However, if your PL has first-class functions, including function pointers or conventional 'objects', then it's very difficult to prevent general recursion even using static analysis. I doubt the idea is tenable in these conditions.
I would really like to have both... I haven't given it much thought, but would it be entirely impossible to solve this using the type system?
You can easily have both first class functions and tail recursion. It's just difficult to also avoid general recursion. | http://lambda-the-ultimate.org/node/5616 | CC-MAIN-2021-25 | refinedweb | 6,790 | 52.9 |
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
Hi,
fields_view_get() method will be called whenever you clicked your form view.
This is a sample:
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
res = super(class_name, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar)
#your modification
return res
Hi,
If you want to do something while opening a form view, you may either override the fields_view_get() method or you may go for a functional field.
Overriding the fields_view_get() method would be better, and you may find some example references in Odoo addons folder.
Refer this link! | https://www.odoo.com/forum/help-1/question/what-event-is-triggered-when-a-form-view-is-called-or-shown-98255 | CC-MAIN-2016-50 | refinedweb | 128 | 63.09 |
I'm trying to use Inkcut v1.0 on Inkscape on a Ubuntu16.10 machine. My vinyl cutter is a Redsail RS500C. Plugged with the USB cable.
lsusb gives:
Bus 002 Device 003: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter
Inkcut is installed in the Inkscape extentions.
I drawed a simple 3d box, converted to paths and ungrouped. Selecting the hole thing and selecting Inkcut gives :
Traceback (most recent call last):
File "inkcutext.py", line 71, in <module>
effect.affect()
File "/usr/share/inkscape/extensions/inkex.py", line 268, in affect
self.effect()
File "inkcutext.py", line 47, in effect
from app.main import InkscapePlugin
ImportError: No module named app.main
What's wrong?
Thanks | http://www.inkscapeforum.com/viewtopic.php?f=31&t=31976&p=97098 | CC-MAIN-2018-30 | refinedweb | 118 | 64.27 |
Geb Tutorial – Automated Browser Testing
In this example we’ll look at the Groovy alternative to automated browser testing (integration testing) using Geb. Geb is built on top of Selenium drivers and brings the tests into a very readable format. selector syntax!
Getting Ready
These tests are built on the Spring Data JPA example in a previous post. The full source code for the testing series is at the bottom of the page.
For this example we add the required dependencies to the pom.xml. This includes JUnit, Groovy, Spock, Geb and Selenium Drivers.
<!--Testing--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--Geb Integration Tests--> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.1.5</version> </dependency> <!--Spock support--> <dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>0.7-groovy-2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.gebish</groupId> <artifactId>geb-spock</artifactId> <version>0.9.0</version> <scope>test</scope> </dependency> <!-- Selenium Drivers (all the desired browser drivers here) --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-firefox-driver</artifactId> <version>2.33.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-support</artifactId> <version>2.33.0</version> <scope>test</scope> </dependency>
Geb Configuration
Create a groovy class in the test source package src/test/resources/GebConfig.groovy. Geb will automatically find this file by convention so name is important and it must be in the root class path. More details on the ConfigSlurper is available in the Geb manual.
import org.openqa.selenium.firefox.FirefoxDriver driver = { new FirefoxDriver() } baseUrl = "" reportsDir = new File("target/geb-reports") reportOnTestFailureOnly = true
- driver is the default driver which is set here as FireFox.
- baseUrl is the root URL that all tests will pull from. This is a convenience so the pages can be agnostic to the root domain which helps facilitate multi environment testing.
- reportsDir is required and tells the test runner where to save the test results.
- reportOnTestFailureOnly does what it says and is used here to shorten the reports to just the stuff we need to act on.
The ConfigSlurper supports environment definitions. To enable an environment specify -Dgeb.env=test-ie
The Geb manual is very good and covers all the options. I point it our here to show it is possible and is useful even in simple setups to test multiple browsers.
environments { 'test-ie' { baseUrl = "" driver = { new RemoteWebDriver(new URL(""), DesiredCapabilities.internetExplorer()) } } 'test-firefox' { baseUrl = "" driver = { new FireFoxDriver(); } } }
Define Geb Page Objects
Geb allows you to use page objects to separate the what from the how. That means all the logic about the page layout lives in its own file. The test drives against that file and then you just assert that the stuff you care about is there. The big benefit is that any changes to the page can but updated once and not impact all the tests.
The first page we will setup is the signup form (show below)
Now we create the page object for the Signup Form:
class SignupPage extends Page { static url = "/" static at = { title == "Sample App Sign-up Page" } static content = { heading { $("h1").text() } errorHeading { $(".alert-error h4").text() } signupForm { $("form[id=signupForm]") } emailField { $("input[name=email]") } lastNameField { $("input[name=lastName]") } firstNameField { $("input[name=firstName]") } submitButton(to: SignupResultPage) { $("button[type=submit]") } } }
This class defines what is on our page and how to access it.
- url is the location of the page. If you use a relative path then it will be appended to the BaseUrl in the GebConfig.
- at is used to assert that the driver is on the correct page. Usually this is the title or something unique and static about the page.
- content can be anything on the page that you want a simple accessor for. In this case we want the heading deigned by a simple “H1”, errors, the form fields and the submit button. If a content element is associated with an action (link, button, navigation…) then you can set a “to:” attribute that tells Geb to expect a new page when called.
There are other really cool features you can do here. Some of my favorite is caching, modules, timeouts and the groovy .collect option. The Geb manual has more details and I can post an advanced Geb Page Object if there is any interest.
Now it’s time for the Confirmation Page Object:
class SignupResultPage extends Page { static url = "/create" static at = { title == "Sample App Sign-up Result Page" } static content = { heading { $("h1").text() } } }
All the static vars are the same. This page is at “/create” and has a unique title. The only content we need is the heading since there is nothing really in this page.
Create the Geb Tests
The pages are defined and it’s time to get testing!
Create the test class: src/test/groovy/com/luckyryan/sample/integration/test/SignupPageIT.groovy. I used the *IT.groovy file naming convention for the failSafe maven plugin. This is used later in the example and does not mean anything specific for Geb.
@Stepwise class SignupPageIT extends GebReportingSpec { def "Signup Test Happy Path"() { given: "I'm at the sign up form" to SignupPage when: "I signup as a valid user" emailField = "geb@test.com" firstNameField = "firstname" lastNameField = "lastname" submitButton.click() then: "I'm at the result page " at SignupResultPage } }
@Stepwise is a Spock annotation that will share the browser state and run the tests in order.
Tests are defined in Spock format. They start with a normal groovy closure “def”, then a descriptor of the test as the function name. The core of the test is given:,when:,then:. Each declaration takes a description of the action for reference if the test fails. It also gives an indication to what is happening in the test without needed to read the code.
The first test is the happy path.
- given: … to SignupPage is a Geb command which directs the web driver to the page url declared in the SignupPage object.
- when: … is where we put page interactions. In this case it fills out the form the clicks the submit button. Notice how there is no reference to anything directly on the page, just to the abstracted names. This will help with readability and insulate page layout changes.
- then: … is just making sure we made it to the right place. We could add any other assertions here.
Next we add a test for an invalid user. This tests the layout when an error is displayed.
class SignupPageIT extends GebReportingSpec { def "Signup Test for Invalid User"() { given: "I'm at the sign up form" to SignupPage when: "I signup as an invalid user" emailField = "geb@test.com" firstNameField = "dave" lastNameField = "lastname" submitButton.click(SignupPage) then: "I'm at the sign up page again " at SignupPage errorHeading == "Error!" } }
- when: … We fill out the form with our invalid user “dave”. Even though we already set the destination for the submit click, it is overridden here since we expect an error and should be redirected to the signup page.
- then: … is where the assertions live. For the failed test we assert we are at the correct page and the errorHeading was set to the expected text.
Run the Geb Tests
The tests can be run from your IDE since the test runner is built on JUnit or via maven. Normally I like SureFire for Maven to run the units tests and it can definitely be used here for integration tests but takes some setup. The conflict comes with the execution scope. Normally SureFire will kick off with mvn test and for that we only want unit tests. You can always exclude the integration tests but then you need to define a 2nd SureFire just for Integration tests. An alternative is the FailSafe maven plugin. FailSafe is designed for integration tests and will automatically find any tests ending with *IT and run them. To setup just add the following to the pom in the build section.
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>integration-test</id> <phase>integration-test</phase> <goals> <goal>integration-test</goal> </goals> </execution> </executions> </plugin>
Now you can run the test from the command line with mvn integration-test
Sample Spring MVC + Test Suite (9290 downloads)
This post is one in a series about end to end testing of Spring MVC applications. If you are interested in other levels of application testing then check out the series index here.
Hi,
do you have any video tutorials ?
I cloned this project into intelliJ and have a few questions as I am trying to learn Geb:
Why can I only run from command line and not from GebConfig.groovy? I would like to debug to understand how the project flows because I have no idea how we get from the base url to the GebishOrgTest.groovy file and am getting errors when trying to run project from the IDE.
How do I click on OK button on a browser alert window in Geb? Since I cannot look up the page element name using firebug, is there a direct code that can just identify this OK button and click on it? | https://www.luckyryan.com/2013/08/28/browser-testing-geb/ | CC-MAIN-2017-47 | refinedweb | 1,545 | 57.27 |
In the last essay, we took a higher level view of the design principles of JPA. In this essay, we examine how the JPA-annotated plain-old Java object (POJO) fails to separate persistence-level concerns from our domain classes.
As we discussed in the previous essay, part of the allure of using JPA is that we expect to map between our domain entities and our persistence model purely with configuration, such as in XML or Java annotations. This is exposed most strongly in the JPA concept of the POJO - the “plain old Java object”. These POJOs, so the story goes, can be used to define our entities in our domain model, and at the same time, with the aid of the configuration, can be used to perform persistence operations. But this is far from the case, as we will see here.
Let’s take as our example, perhaps the simplest entity we can imagine. Suppose we want to model a customer in our system, and at this stage in development, the only property we are interested in keeping track of is the customer’s first name. In a UML class diagram, the customer would look like this:
Converting this into a POJO would in turn look something like this:
public class Customer {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
But this is not what we end up with when we create a POJO for JPA! Instead, we end up with something like the version below. (We’ll leave aside all the JPA annotations for now, since they are not important for the sake of this example.)
public class Customer {
private Long customerId;
private String firstName;
private User createdBy;
private Date createdDate;
private User lastModifiedBy;
private Date lastModifiedDate;
private Long version;
public Long getUserId() {
return userId;
}
public void setUserId(userId: Long) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public User getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModified(User lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
As we can see, there is a lot here that does not reflect anything in our domain model. Let’s review these briefly:
- userId: The database primary key.
- createdBy, createdDate, lastModifiedBy, and lastModifiedDate: These are database columns that are included for diagnostic purposes. We use these fields to help us work out the history of our data when we are performing database queries, either to troubleshoot and fix database problems, or track system usage. We typically configure Spring/JPA to set these values automatically.
- version: This column is used to perform optimistic locking, or the prevention of overlapping edits to a single entity, which would otherwise overwrite the changes made by the earlier edit.
There are two major problems with having these fields directly in our domain classes. First, it blurs the line between domain and persistence concerns. It’s very common for people to fail to differentiate between the database schema and the domain model, and we want to draw a clear distinction between these two whenever possible. Second, it exposes persistence concerns throughout the application, including right at the heart of our domain. Ideally, we want these things to be isolated within our persistence layer and repository classes. If we don’t do this, we will find ourselves dealing with persistence issues throughout every layer of our application.
Let’s look at each of the three cases in a bit more detail. If we expose our database primary keys directly in your domain classes, nearly every layer of our application has direct access to this data. And it’s hard for, say, an API developer to know that she is simply not supposed to use it. If she has a problem to solve, and accessing the database ID helps her solve it, what’s to stop her? Maybe she doesn’t know any better, or maybe she does, but she has a tight deadline to meet and goes ahead and makes the change anyway.
Before you know it, this ID has become an integral concern of the service layer, the front end API, and can even end up displayed prominently in the user interface! And if you have a web UI, simply having it in the URIs, to a certain extent, means it is exposed to your users. What was once merely persistence state has become part of your domain. It sounds absurd, and it is absurd, but in my experience, this is the norm rather than the exception when using JPA. And I’ve seen multiple projects where what was once a database ID inadvertently became an official part of the domain model.
If this seems like an odd objection to make, that is simply because most or many of the applications you have worked on were built this way. But this isn’t the way to do DDD. Consider that an engineering team is in early discussions with the domain experts on designing a UI for showing customer accounts. The software engineer says, “Okay, we have a rough layout for this page, but how is the administrator going to locate a specific user account in the first place?” The domain expert does not reply, “Can’t they just look it up by the database ID?” The domain expert is not thinking about database IDs at all. Instead, they might answer something like: “Well, they could look them up by first and last name, but that could turn up more than just one account, so we would need a way to select between the different matching accounts. Or they could look them up by account number. That would provide a unique record.” If you apply this kind of thinking consistently, you won’t even need a findById method in your repository classes any more.
Exposing diagnostic data, such as lastModifiedBy and lastModifiedDate, similarly risks those fields becoming a permanent part of the domain model. To be sure, there are times when this kind of information is a natural part of the domain. For instance, our administrative users have the ability to add and edit notes to a customer account. We want to keep track of which administrator last edited the note, and when. But it would be a mistake to try to use these diagnostic data for dual purposes.
Supposing we did. At a later point, we might have a complex data migration, or perhaps our data was corrupted in some way that we are trying to fix. The fix involves applying some of our domain business logic, and as such, we find it much easier to write a script to do the fix through JPA than to craft database update commands to do the job. But if we do so, the fields that keep track of the administrator that made the change, and what time the change was made, will get overwritten by the user running the script, and the time the script was run. Maybe we could disable the Spring/JPA configurations for updating these columns just for the purposes of running the script, but this may not be possible, depending on the conditions the script needs to run under.
Exposing the version used for optimistic locking is less of a problem, as there seems little opportunity for an ill-informed developer to misuse this information. But its presence in the domain classes can give rise to confusion, especially if there is some sort of versioning information stored in the domain itself.
As we will discuss in the next essay, there are various things we can do to properly encapsulate these kinds of persistence concerns in our persistence layer, and prevent them from leaking in to the rest of the application. We can resolve these issues to some extent while working with our Java/JPA toolset, but there is more we can do if we are willing to reconsider our toolset. For example, the longevity project applies all these principles of encapsulation in a Scala/NoSQL context.
Thank you for sharing this point of view.
I completely agree with you and I'm sharing a similar message within my DDD experience: you have to separate the conceptual model (only domain classes and its relationships) to the logical model of the persistent stores (database schemas).
This is especially true for NoSQL solutions such as Cassandra or Redis where Data Modeling is an important and dedicated activity with query driven schema design (you have to model your data among your data access patterns).
From a DDD point of view, it is the responsability of the infrastrcture layer to define mappers (or converters) between these two different models and call them in the repository implementations.
Regarding the DDD identifier, I agree of the importance to find a right unique domain identifier (and make it part of the ubiquitous language), despite to fall back to a technical identifier from the persistence store.
Regarding diagnostic fields, there are no issues from my point of view. At the begining, these technical fields are not part of the ubiquitous language (and so not part of the domain model)
Either you need to define another Bounded Context (BC), maybe a dedicated Diagnostic BC, either these technical fields are hidden by the infrastructure layer. Therefore, this use case of mixing diagnotic fields with true domain fields in the domain model can't take place in an unique BC (into POJO domain model).
Thanks for your insightful comment Gregory!
If you are doing DDD with a NoSQL database please consider longevity, a Persistence Framework for Scala and NoSQL with a Domain Driven Design Orientation.
Best, John
Hello John,
Thanks for this article.
I would like to know, if foreign key relationships are mapped with domain keys as opposed to database keys in the schema.
Thank you
Hi pinkpanther,
I'm glad you liked the article. You ask a good question about the foreign key relationship. In later articles in this series - starting with "Reinstating the Aggravate" - we distinguish between between two kinds of relationships that are typically represented as foreign key relationships in relational databases: those internal to a single entity aggregate, and relationships between aggregates. Relationships between entities within the same aggregate should generally not be represented as key-based relationships in the domain model. They are better modelled by _containment_, or objects nested within other objects. Relationships between aggregates should be represented at the domain level via domain keys. These domain keys can be mapped onto a database model in different ways; for relational databases, a foreign key relationship is appropriate. | http://scabl.blogspot.com/2015/03/aeddd-3.html | CC-MAIN-2018-39 | refinedweb | 1,809 | 50.36 |
Opened 4 years ago
Closed 4 years ago
#22531 closed New feature (fixed)
Q objects lack a useful repr
Description
>>> from django.db.models.query_utils import Q >>> a = Q() >>> b = Q(a=1, b=2) >>> c = b & Q(c=3) >>> d = c | Q(d=4) >>> e = Q(d) & Q(e=5) >>> f = e | ~Q(f=6) >>> repr(f) # actually just typing f<enter> into ipython/pdb/python REPL '<django.db.models.query_utils.Q at 0x103184050>'
That's not exactly useful, given a Q object may represent a complex tree. As it turns out, Q objects do implement str, which is the SQL output for the Node subclass, which would be more useful than the above repr, and possibly more useful than the nested repr of .children
The simplest repr implementation would probably be something like:
def __repr__(self): return '{obj.__class__!r} {obj!s}'.format(obj=self)
Change History (3)
comment:1 Changed 4 years ago by
comment:2 Changed 4 years ago by
comment:3 Changed 4 years ago by
Note: See TracTickets for help on using tickets.
PR: | https://code.djangoproject.com/ticket/22531 | CC-MAIN-2017-51 | refinedweb | 180 | 55.27 |
Cache Service
This page is obsolete. For up to date documentation see
This page describes technical details of the ARC Cache Service. The software is still in the development stage and may have bugs or missing functionality. Please report problems to.
Contents
Description and Purpose
The ARC caching system automatically saves to local disk job input files for use with future jobs. The cache is completely internal to the computing element and cannot be accessed or manipulated from the outside. The ARC Cache Service exposes various operations of the cache and can be especially useful in a pilot job model where input data for jobs is not known until the job is running on the worker node.
Installation
The cache service is designed to run alongside any standard production (>= 0.8.x) installation of the ARC computing element and comes in the package nordugrid-arc-cache-service, available in the usual NorduGrid or EMI repositories.
Configuring and Running
ARC 1.x and 2.x (releases 11.05 and 12.05)
The cache service runs as a separate process in a separate HED container, listening on port 60001 on path /cacheservice. It is assumed that there is an existing arc.conf configuration file for A-REX, which is read to get information on the caches. There is no other configuration needed for the cache service. It can be started with
$(ARC_LOCATION)/etc/init.d/arc-cache-service start
Messages are logged to /var/log/arc/cache-service.log.
ARC >= 3.x (releases 13.02 and above)
The cache service runs inside the same HED container as A-REX, and so is accessible at the same hostname and port as the A-REX web-service interface, at path "/cacheservice". The following option in the [grid-manager] section of arc.conf enables it
enable_cache_service=yes
The A-REX web-service interface must also be enabled through the arex_mount_point option. No other configuration is needed. The cache service is automatically started when A-REX is started and so does not need to be started separately. Messages are logged to the A-REX log. The same instance of the DTR data staging framework is used by both A-REX and the cache service so DTR must be enabled for the cache service to run (it is enabled by default).
Setting up the Runtime Environment
The Runtime Environment (RTE) advertises to clients that the cache service is available and sets up the environment for the job to use it, by setting an environment variable pointing to the service. The following template can be used to create an RTE in <your rte directory>/ENV/ARC-CACHE-SERVICE
#/bin/sh! case "$1" in 0) export ARC_CACHE_SERVICE= ;; 1) return 0;; 2) return 0;; *) return 1;; esac
The only thing you need to change is to substitute your real host name for hostname. The proxy certification is also required on the worker node and so another runtime environment (eg ENV/PROXY) is needed for that, for example
#!/bin/bash x509_cert_dir="/etc/grid-security/certificates" case $1 in 0) mkdir -pv $joboption_directory/arc/certificates/ cp -rv $x509_cert_dir/ $joboption_directory/arc cat ${joboption_controldir}/job.${joboption_gridid}.proxy >$joboption_directory/user.proxy ;; 1) export X509_USER_PROXY=$RUNTIME_JOB_DIR/user.proxy export X509_USER_CERT=$RUNTIME_JOB_DIR/user.proxy export X509_CERT_DIR=$RUNTIME_JOB_DIR/arc/certificates ;; 2) : ;; esac
Client Usage
A Python client for the cache service is available in the nordugrid-arc-python package and in the source tree. It requires the ElementTree module which is available by default in Python versions 2.5 and higher. For Python 2.4 it is available in the elementtree module which must be installed separately. Python versions 2.3 or lower are not supported. To use it you may need to add the system-dependent installation path to PYTHONPATH.
from cache import cache
Three methods are defined:
- cache.cacheLink(): Tells the cache service to link the given URLs from the cache to the specified job directory on the worker node
- cache.cacheCheck(): Queries the cache service for the existence of the given URLs in the cache
- cache.echo(): Call the echo service - useful for testing
For full API description see the doc in the code:
from cache import cache print cache.cacheLink.__doc__
Small example script to call the service (this would be run on the worker node at the start of the job to prepare the input files):
run.py: #!/usr/bin/env python import sys import os import time import pwd from cache import cache endpoint = 'os.environ['ARC_CACHE_SERVICE'] proxy = os.environ['X509_USER_PROXY'] username = pwd.getpwuid(os.getuid())[0] # job id from GRID_GLOBAL_JOBID or cwd if 'GRID_GLOBAL_JOBID' in os.environ: gridid = os.environ['GRID_GLOBAL_JOBID'] # Assuming GridFTP job submission jobid = gridid[gridid.rfind('/')+1:] else: cwd = os.getcwd() jobid = cwd[cwd.rfind('/')+1:] urls = {'srm://srm.ndgf.org/ops/jens1': 'file1', 'lfc://lfc1.ndgf.org/:guid=8471134f-494e-41cb-b81e-b341f6a18caf': 'file2'} stage = False try: cacheurls = cache.cacheLink(endpoint, proxy, username, jobid, urls, stage) except cache.CacheException, e : print('Error calling cacheLink: ' + str(e)) print(cacheurls) print(os.listdir('.'))
and a job description file to submit this script:
cache.xrsl: & ("executable" = "run.py") ("jobname" = "cache service test" ) ("runtimeenvironment" = "ENV/PROXY") ("runtimeenvironment" = "ENV/ARC-CACHE-SERVICE") ("inputfiles" = ("run.py" "") ) ("walltime" = "3600" ) ("cputime" = "3600" ) ("stderr" = "stderr") ("stdout" = "stdout") ("gmlog" = "gmlog") )
Note that the ENV/PROXY runtime environment is needed in order to have access to the proxy on the worker node.
If successful and the requested files are in cache, the output should list the links to those files.
Issues and Notes
- The HED service container which hosts the cache service does not accept legacy proxies. This type of proxy is created by default with grid/voms-proxy-init, but an RFC-compliant proxy can be generated using the -rfc option.
- The cache service links files to the session dir. If a scratch directory is used for executing the job, the cache files are moved there from the session directory. This requires that the scratch dir is accessible from the cache service host, so the cache service cannot be used in situations where the scratch directory can only be accessed by the underlying LRMS. | https://wiki.nordugrid.org/wiki/Cache_Service | CC-MAIN-2020-29 | refinedweb | 1,017 | 58.58 |
Asked by:
Script to scan XML file for info
Question
All,
I have run into an issue with some code that I have. The code scans an XML file and pulls some information out of it. It was working for a while and then I started getting the error below. I know that I should check to see if object exists first, but the objects are there, so my bigger issue is why the script is not finding it.
---------------------------
Windows Script Host
---------------------------
Script: D:\IFC\Load-Xref.vbs
Line: 92
Char: 61
Error: Object required: 'objNode.Attributes.getNamedItem(...)'
Code: 800A01A8
Source: Microsoft VBScript runtime error
---------------------------
OK
---------------------------
Code:'This code goes through all archived XML files and pulls out the needed information to be loaded into
'the Invoice table of the database
'****************************************************************************************************
filex = "xml"
ifcfolder = "D:\IFC\" & trim(Plant) & "\Archive"
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(ifcfolder) Then
Set iFolder = FSO.GetFolder(ifcfolder)
Else
Msgbox("Folder " & ifcfolder & " does not exist")
WScript.Quit
End If
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("D:\IFC\" & trim(Plant) & "-Inv.txt", True)
For Each f2 In fso.GetFolder(ifcfolder).Files
Do
Inv_Total = 0
Inv_Date = ""
Inv_Number = ""
Series = ""
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "True"
xmlDoc.Load(f2.path)
Set colNodes=xmlDoc.selectNodes("cfdi:Comprobante")
For Each objNode in colNodes
Inv_Total = objNode.Attributes.getNamedItem("total").Text
Inv_Date = objNode.Attributes.getNamedItem("fecha").Text
Inv_Number = objNode.Attributes.getNamedItem("folio").Text
Series = objNode.Attributes.getNamedItem("serie").Text
a.WriteLine (Inv_Total & "," & Inv_Date & "," & Inv_Number & "," & Series)
Loop While False
Part of file where data is taken:<?xml version="1.0" encoding="utf-8"?><cfdi:Comprobante
</cfdi:Comprobante>
Thanks!
David
- Moved by Bill_Stewart Monday, March 12, 2018 8:33 PM This is not "fix/debug/rewrite my script for me" forum
All replies
I do not understand. What is it about the XML that indicates that it has nothing to do with the code?
I have provided the code that is used the segment of file that was read and the error.
BTW I am the one that wrote the original script. It was working. I will look at the previous XML files.
I am at a loss here. I feel as though your response adds more confusion to me.
If there is something more that you need to help, please let me know.
This is what you XML looks like when correctly formatted:
<?xml version="1.0" encoding="utf-8"?> <cfdi:Comprobante" </cfdi:Comprobante>
It does not match the code. Notice there are no nodes with the names the code is using.
\_(ツ)_/
I have reviewed the old code and it looks as if NameSpace has been introduced. I am not sure how this is read in differently than the previous XML format.
If there are links to how this is done, please let me know.
It would be easier to do in PowerShell.
Also all references to objects in the XML are case sensitive. You MUST use the case that is in the XML for all tags and names.
\_(ツ)_/
Unfortunately, the XML is not under my control. Your mock up of how the data should look is understandable. This is an invoice from Mexico and the format is dictated by the government. I have been trying to modify the code to fix the errors that cropped up for some time now and have come up empty. I now know that it is the change to namespace, but that information is not getting me any closer to a solution since I know I cannot change the format of the inbound file.
A Simple search would solve your problem:
\_(ツ)_/
This is how easy it is in PowerShell:
[xml]$xml = cat "C:\Users\jvierra\Documents\SAPIEN\Scripts\Untitled.xml" $xml.Comprobante| select Total,FEcha,Folio,Serie $xml.Comprobante| select Total,FEcha,Folio,Serie | Export-Csv output.csv -NoType
\_(ツ)_/ | https://social.microsoft.com/Forums/en-US/06df6da2-9f57-462c-8a7d-2d40448638bd/script-to-scan-xml-file-for-info?forum=Offtopic | CC-MAIN-2020-50 | refinedweb | 650 | 60.31 |
Next: String Ports, Up: Port Types:
- ‘r’
- Open an existing file for input.
- ‘w’
- Open a file for output, creating it if it doesn't already exist or removing its contents if it does.
- ‘a’
-:
- ‘+’
- Open the port for both input and output. E.g.,
r+: open an existing file for both input and output.
- ‘0’
-
- ‘l’
- Add line-buffering to the port. The port output buffer will be automatically flushed whenever a newline character is written.
- ‘b’
- Use binary mode. On DOS systems the default text mode converts CR+LF in the file to newline for the program, whereas binary mode reads and writes all bytes unchanged. On Unix-like systems there is no such distinction, text files already contain just newlines and no conversion is ever made. The
bflag is accepted on all systems, but has no effect on Unix-like systems.
(For reference, Guile leaves text versus binary up to the C library,
bhere just adds
O_BINARYto the underlying
opencall, when that flag is available.)
If a file cannot be opened with the access requested,
open-filethrows an exception.
In theory we could create read/write ports which were buffered in one direction only. However this isn't included in the current interfaces.
Open filename for input. Equivalent to(open-file filename "r")
Open filename for output. Equivalent to(open-file filename "w")
Open filename for input or output, and call
(proc
port)with the resulting port. Return the value returned by proc. filename is opened as per
open-input-fileor
open-output-filerespectively, and an error is signalled if it cannot be opened.
When proc returns, the port is closed. If proc does not return (eg.or
open-output-filerespectively, and an error is signalled. This function returns the strings "standard input", "standard output" and "standard error" when called on the current input, output and error ports respectively.
port must be open,
port-filenamecannot be used once the port is closed.
Change the filename associated with port, using the current input port if none is specified. Note that this does not change the port's source of data, but only the value that is returned by
port-filenameand reported in diagnostic output. | http://www.gnu.org/software/guile/docs/docs-1.8/guile-ref/File-Ports.html | CC-MAIN-2017-04 | refinedweb | 366 | 66.54 |
Before getting into an example, we should know what is a countdown timer in android. Count down timer as simple as we see in watches and mobile phones. we can set count down time after completion of time it will stop and get 0 values.
There are four methods are available to use countdown timer as shown below -
onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking.
onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish().
start() - It is used to call countdown timer.
cancel() - It is used to cancel countdown timer.
This example demonstrates how to integrate countdown timer with textview.="" android: <TextView android: </LinearLayout>
In the above code, we have declared a text view. it going to print countdown timer.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public int counter; @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView counttime=findViewById(R.id.counttime); new CountDownTimer(50000,1000) { @Override public void onTick(long millisUntilFinished) { counttime.setText(String.valueOf(counter)); counter++; } @Override public void onFinish() { counttime.setText("Finished"); } }.start(); } }
In the above code, we have declare 50s and time interval is 1s. It going to print ms time in textview as shown onTick method and after done time intervals it will print the result as "Finished".
Step 4 − No need to change manifest.xml
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run Icon
from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above screen, it shows time counting points. After done counting time means 50 sec it will show the result as shown below- | https://www.tutorialspoint.com/how-to-make-a-countdown-timer-in-android | CC-MAIN-2021-49 | refinedweb | 386 | 53.37 |
Base texture class. More...
#include <StelTexture.hpp>
Base texture class.
For creating an instance, use StelTextureMgr::createTexture() and StelTextureMgr::createTextureThread()
Definition at line 41 of file StelTexture.hpp.
Destructor.
Bind the texture so that it can be used for openGL drawing (calls glBindTexture).
If the texture is lazyly loaded, this starts the loading and return false immediately.
Return whether the texture can be binded, i.e. it is fully loaded.
Definition at line 74 of file StelTexture.hpp.
Return the width and heigth of the texture in pixels.
Get the error message which caused the texture loading to fail.
Definition at line 85 of file StelTexture.hpp.
Return the full path to the image file.
If the texture was downloaded from a remote location, this function return the full URL.
Definition at line 89 of file StelTexture.hpp.
Returns whether the texture has an alpha channel (GL_RGBA or GL_LUMINANCE_ALPHA format) This only returns valid information after the texture is fully loaded.
Definition at line 81 of file StelTexture.hpp.
Return whether the image is currently being loaded.
Definition at line 92 of file StelTexture.hpp.() | http://www.stellarium.org/doc/head/classStelTexture.html | CC-MAIN-2015-27 | refinedweb | 185 | 53.17 |
Tree Tags
Introduction
The following topic explains the tree tags and classes and how they are used to create and render trees. A tree is rendered in an HTML page based upon an object representation of the tree. NetUI defines a set of classes which create the tree structure which is rendered. The object representation may be created either through NetUI JSP tags found in a JSP or may be created programmatically in a page flow or shared flow. This means that there are parallel representations of a tree. In a JSP, a set of JSP tags represent the tree. This representation is then transformed into a tree data structure defined by a set of tree classes.
Simple Example
This section presents a sample of the most basic tree. The tree is created in a JSP and displays a simple tree on the page. The tree itself has a root node with three children. The root may be expanded and collapsed. Any of the tree nodes may be selected.
Simple Example Code
simpleTree.jsp
<%@ page <netui:treeItem <netui:treeLabel>0</netui:treeLabel> <netui:treeItem> <netui:treeLabel>0.0</netui:treeLabel> </netui:treeItem> <netui:treeItem>0.1</netui:treeItem> <netui:treeItem>0.2</netui:treeItem> </netui:treeItem> </netui:tree> </netui:body> </netui:html>
The <netui:tree> tag is the JSP tag that adds a tree to the page. It is responsible for rendering the tree in the generated HTML page. In this example, the contents of the tree itself are also defined in the <netui:tree> tag by using the <netui:treeItem> tags and nesting them in a tree structure. In this simple case, the tree has a root (0) with three children (0.0, 0.1, and 0.2).
There are three required attributes on the <netui:tree> tag, dataSource, tagId and selectionAction. The dataSource is used to bind to a TreeElement based data structure representing the tree to be displayed. The selectionAction is the action that will be called when a node is selected in the tree. In some cases, it may also be called when a node in the tree is expanded or collapsed. In addition, the tagId attribute is also required. If runAtClient is true then you must also specify the name of the tree by setting the tagId.
Note: In the example above, the leaf nodes are defined in two manners. The first child (0.0) uses the <netui:treeLabel> to set the nodes label. The next two children (0.1 and 0.2) are defined with the label as the body of the <netui:treeItem>. The <netui:treeItem> supports setting the label value from the body of the <netui:treeItem> if it is a leaf in the tree. You are required to use the <netui:treeLabel> for all interior nodes or nodes with children. In other words, <netui:treeItem> does not support mixed content; meaning that interior nodes must use <netui:treeLabel> to set the label value and all text inside the body is ignored.
Controller.jpf
package simpleTree; import org.apache.beehive.netui.pageflow.PageFlowController; import org.apache.beehive.netui.pageflow.annotations.Jpf; import org.apache.beehive.netui.tags.tree.TreeElement; @Jpf.Controller( simpleActions={ @Jpf.SimpleAction(name="begin", path="simpleTree.jsp"), @Jpf.SimpleAction(name="postback", path="simpleTree.jsp") } ) public class Controller extends PageFlowController { private TreeElement _simpleTree; public TreeElement getSimpleTree() { return _simpleTree; } public void setSimpleTree(TreeElement _simpleTree) { this._simpleTree = _simpleTree; } }
This very simple Page Flow controller supports displaying a tree. There is a single property "simpleTree" which holds a reference to a TreeElement. This TreeElement represents the root of the underlying tree object structure which is rendered by the <netui:tree> tag. There are two actions defined, the standard begin action and the postback action. The postback action is called when a selection or expansion link is selected in the rendered tree.
Simple Sample Lifecycle
This section describes the basic tree lifecycle using the SimpleTree example above. The following figure represents the basic lifecycle of a tree being rendered by a <netui:tree> tag.
The dataSource attribute is a required attribute on all trees. It binds to an instance of a TreeElement (defined in org.apache.beehive.netui.tags.tree). All trees are represented as tree data structure with a single root. The dataSource attribute binds to this root.
When the <netui:tree> tag begins processing it checks to see if the variable bound to by the dataSource is equal to null. If it is, then the tree will process it's body content to create the tree data structure. If the dataSource is not null, then that tree's data structure is used to render content. If you want to programmatically (or dynamically) create a tree, you may create the tree structure before the bound variable is accessed. Typically this would be done in the onCreate method of a shared flow or page flow.
In the simpleTree sample, the first time the page is displayed the body of the tree tag is processed because the page flow's property simpleTree is null. This creates the initial tree data structure which is then rendered. When the page is requested again, for example when a tree element is selected, the tree data structure created on the first request continues to be used and the body of the <netui:tree> tag is ignored.
Note: A very common development task is to iteratively develop the <netui:tree>'s body content. In order for any changes to be reflected when the tree is rendered, the variable bound to by dataSource must be null. It is common to add an action to the page flow that will reset the value to null and call that from a link on a page. If variable is not null, changes to the JSP will not be reflected in the rendered tree.
Tag and Classes
This section describes the primary JSP tags and how they relate to the classes which define the underlying data structure representing the tree. All of the tree features are available both in the tree tags as well as the underlying tree classes (described below).
Tag to Class Mapping
There are a number of JSP tags that allow creation of tree through JSPs. These tags build the underlying data structures representing the tree. This section describes the mapping between the JSP tags and the actual classes that represent the tree.
Note: in many cases, this document describes setting attributes on the tree JSP tags to enable features. In reality, the attributes are passed through to the TreeElement class which usually has a corresponding property. Other tags map their values to properties of the TreeElement. If you are programmatically creating a tree by building the tree hierarchy using TreeElements, you directly set properties on the tree classes.
The following list describes the mapping of the tree JSP tags to underlying tree classes:
- Tree -- The <netui:tree> tag doesn't create a TreeElement. It binds to a TreeElement representing the root of the tree data structure. The <netui:tree> tag does create the initial TreeRenderState object representing how the tree is rendered.
- TreeItem -- The <netui:treeItem> tag will create a TreeElement. If the <netui:treeItem> is the root of a tree, then the TreeRootElement will be created.
- TreeLabel -- The <netui:treeLabel> tag sets the value of the label which is stored as a property of a TreeElement. Using this tag is required for non-leaf nodes. For leaf nodes the body content of the <netui:treeItem> will be used as the label value as long as that body does not contain other JSP tags (mixed content).
- TreeContent -- The <netui:treeContent> tag sets the value of the content for a TreeElement. The content is a property of the TreeElement.
- TreeProperyOverride -- The <netui:treePropertyOverride> tag is used to override various attributes on the tree such as the selection action and images. This tag will create an InheritableState object and set it on the TreeElement.
- TreeHtmlAttribute -- The <netui:treeHtmlAttribute> tag is used to set additional attributes on the HTML generated when rendering the node. This tag will create a TreeHtmlAttributeInfo class that is set on the TreeElement.
ITreeRootElement
In the SimpleTree example above, we described the tree data structure as being a hierarchy of TreeElement nodes. Many advanced features, including runAtClient, of the tree require the root of the tree to implement the interface ITreeRootElement. The class TreeRootElement extends TreeElement and implements ITreeRootElement, providing a default implementation. In the SimpleTree example, when the body of the <netui:tree> is processed, the root <netui:treeItem> is created as a TreeRootElement and all other <netui:treeItem>'s are created as TreeElements.
The following features require the root element in a tree to implement ITreeRootElement:
- runAtClient -- Allows the tree to be expanded and collapsed on the client without round trips to the server.
- Root Images -- Allows setting different expand and collapse images on the root node of the tree.
The following additional state is tracked by the root element:
- Selection -- Direct access to the currently selected tree element.
- Tree State -- Access to the InheritableState and TreeRenderState defined on the tree (explained below).
- Images -- Allows different expand and collapse images to be set on the root supporting the Root Images feature.
Tree Features
This section describes the basic features of the NetUI Tree. The SimpleTree example introduces the basic mechanics for creating a tree in a page flow. A tree is output into the HTML page as a hierarchy of TreeElements. The SimpleTree example renders the following:
The root of the tree supports expanding and collapsing. The children of a node appear at the same level. Trees appear commonly in applications such as file system explorers and are good at representing limited hierarchical data sets.
runAtClient
The <netui:tree> tag has an attribute runAtClient which when set to true will enabled expanding and collapsing the tree on the client without server round trips. When runAtClient is on, the tree will be completely rendered into the generated HTML. Client side JavaScript will then collapse and expand nodes when the user interacts with the tree. The following image describes the interactions between the server and client.
runAtClient uses XmlHttpRequest to update the underlying state on the server as the user interacts with the tree on the client. This mode requires JavaScript and XmlHttpRequest support in the client browser. This mode of operation is commonly referred to as AJAX (Asynchronous JavaScript and XML). It minimizes the amount of information sent between the client and server when the user is exploring the tree itself.
In the diagram above, when the tree is rendered, all of the nodes will be rendered into the HTML document generated. JavaScript on the client will then process the tree when the HTML document is loaded. The JavaScript will turn off display of tree nodes which are collapsed so that the tree appears in the expected state. As the user interacts with the tree by expanding and/or collapsing nodes, JavaScript will continue to turn on and off the display of tree nodes (and their children). In order to update the state of the tree stored on the server, the client also use XmlHttpRequest to send messages to the server indicating the nodes that are being expanded and collapsed. The next full server request will display the tree properly because the internal state has been updated as the user interacted with the tree.
expandOnServer
When a tree has the runAtClient attribute set, then individual elements can indicate that they need to be expanded on the server by setting the expandOnServer attribute on the <netui:treeItem> tag. When expandOnServer is enabled, if the node is in a collapsed state, the node itself will be rendered in the generated HTML, but all children nodes will not. When the user expands the node, an XmlHttpRequest is made to the server and the children (and possibly their children) will be rendered into HTML and sent back to the client. JavaScript will update the DOM and cause the children to be displayed. Once the children are received, all further expand and collapse operations happen on the client.
runAtClient and expandOnServer can be used together to optimize the amount of tree state rendered into the initial request and then to minimize the amount of state transferred when the user is exploring the tree. It is very common for people to drill into one or two areas of a tree after searching the top level nodes. To optimize for this type of browsing, render out the top few levels of a tree and then create a layer of children that set expandOnServer to true. The top few layers will be initially rendered and when a user goes deep into one, the server provides the branch asynchronously when requested.
TreeElement Rendered Contents
This section describes the markup written out to represent a tree node in the rendered HTML document. The basic Markup looks like this:
[Tree Markup] [Expand/Collapse Icon] [Anchor - [Icon][Label]] [Content]
- Tree Markup [
- lineJoin.gif,
- lastLineJoin.gif,
-verticalLine.gif, spacer.gif] -- There are four images that represent the "structure" of the tree. These are used to create the visual hiearchical representation of the tree.
- Expand/Collapse Icon [
- nodeCollapsed.gif,
- lastNodeCollapsed.gif
- rootCollapsed.gif,
- nodeExpanded.gif,
- lastNodeExpanded.gif
- rootExpanded.gif ] -- There are six images that represent the expand and collapse links on an interior node. The root images are only available if the root of the tree implements ITreeRootElement.
- Icon [
- folder.gif, ] -- This Icon and the Label represent the node in the tree. Either act as a selectable link that will call the selection action.
- Label -- The label is a text item representing the node. This is a property of the TreeElement. This is a selectable link that will call the selection action.
- Content -- This is an optional text item that may appear after the label. It is not selectable.
The tree supports setting a default location where the images are picked from within a WebApp. All of the images are found by default in the resources\beehive\version1\images directory. It is possible to change both the default location for finding the images in addition to the images themselves by explicitly setting the name of the image on the Tree.
Using a Custom TreeRenderer Implementation
The HTML markup for the tree is handled by the TreeRenderer class. By default, TreeRenderer handles tree rendering across the web application, unless another rendering class is specified.
You can override the rendering behavior of the default TreeRenderer class with a custom renderer class. A custom TreeRenderer class is especially useful for precise control of whitespace, line breaks, and image placement in the rendered tree.
To override the default TreeRenderer class:
- extend the TreeRenderer class and override any of the formatting methods that are appropriate to your purposes
- configure NetUI to use your extended class to render the tree
An example custom TreeRenderer class appears below. This class overrides the method renderConnectionImageSuffix() so that a new line is not added after the <img> element for the connetcting expand/collapse image and renderSelectionLinkPrefix() so that no white space indentation is placed before the anchor used to select a node. Also, the methods renderItemIconPrefix() and renderItemIconSuffix() are overridden to wrap a <span> around the <img> element for the node icon. A <span> might be used to incorporate CSS styles or a call to a JavaScript routine.
package mytree.renderer; import org.apache.beehive.netui.tags.rendering.AbstractRenderAppender; import org.apache.beehive.netui.tags.tree.TreeElement; import org.apache.beehive.netui.tags.tree.TreeRenderer; public class MyTreeRenderer extends TreeRenderer { protected void renderConnectionImageSuffix(AbstractRenderAppender writer, TreeElement node) { } protected void renderSelectionLinkPrefix(AbstractRenderAppender writer, TreeElement node) { } protected void renderItemIconPrefix(AbstractRenderAppender writer, TreeElement node) { writer.append("<span ID=\"myItemIcon\" style=\"cursor:pointer;\""); writer.append(" onClick=\"doSomething()\">"); } protected void renderItemIconSuffix(AbstractRenderAppender writer, TreeElement node) { writer.append("</span>"); } // more overridden methods... }
To configure NetUI to use your custom TreeRenderer, edit the <tree-renderer-class> element of the beehive-netui-config.xml file to refer to your custom class:
<tree-renderer-class>mytree.renderer.MyTreeRenderer</tree-renderer-class> | http://beehive.apache.org/docs/1.0.2/netui/tags/tree.html | CC-MAIN-2014-42 | refinedweb | 2,669 | 55.44 |
Hello, readers! In this article, we will be focusing on the functionality of Python pprint module in detail. So, let us begin! 🙂
Understanding Python pprint module
Be it any programming language, the presentation of data has always played a key role while representing the end product or application. Apart from the developer, a lot of other people from the functional team utilize the outcome of a specific module to move further with the operation or analysis. For the same, it is necessary for the output to be pretty and clear.
Especially with API calls, we often get a bulk of unformatted data from the calls as JSON files in key-value pair form. It seems too difficult for us to real and goes through the bulk of unformatted data.
Taking this into consideration, we have Python pprint module to solve the problem.
Python pprint module formats the entire output passed to it and represents the same in a structured format.
So, what’s the problem with Python print() function? Though print() function represents the output, it does NO formatting to it and therefore, is not suitable for heavy data values.
Have a look at the below example to understand the problem with print() function
Why not just use the print() function?
In the below example, we have fetched the data from API and have loaded it into JSON format. We try to print loads of data using the print() function.
import json response_API = requests.get('') #print(response_API.status_code) data = response_API.text parse_json = json.loads(data) print(parse_json)
Output:
As you can see, the bulky data gets represented in an unstructured format due to which it becomes difficult for anyone to analyze the JSON data.
Implementing pprint() module with data from API calls
On the other hand, we now try to represent the same data that we fetched from the API in the above example and try to represent it using the pprint() module.
Example:
import requests import json from pprint import pprint response_API = requests.get('') #print(response_API.status_code) data = response_API.text parse_json = json.loads(data) pprint(parse_json)
Output:
As clearly understood above, the entire bulky data is represented in a structured and pretty format using pprint() function, which makes it easier to read and analyze the data.
Conclusion
Try implementing pprint() function with other scenarios and do let us know your understanding about the same in the comment section. And feel free to drop a message in case you come across any question. For more such posts related to Python programming, stay tuned with us.
Till then, Happy Learning!! 🙂 | https://www.askpython.com/python-modules/pprint-module | CC-MAIN-2021-31 | refinedweb | 429 | 55.95 |
Are you writing a Python application and do you need to check for duplicates in a list? You are in the right place, let’s find out how to work with duplicates.
There are several approaches to check for duplicates in a Python list. Converting a list to a set allows to find out if the list contains duplicates by comparing the size of the list with the size of the set. This tells if the list contains duplicates and one way to know which items are duplicates you can use collections.Counter.
There are two aspects of duplicates you might want to know more about:
- How to know if there are any duplicates in a list.
- If duplicates are present in the list identify which elements are duplicates.
Let’s get started!
Check If a Python List Has Duplicates
I have the following list and first I want to know if this list contains any duplicates:
>>> planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars']
We can see if this list has any duplicates by using the properties of a Python set.
Here is what happens when I convert this list to a set:
>>> set(planets) {'earth', 'mars', 'jupiter', 'mercury'}
Ignore the fact that the order of the elements has changed (considering that a set is unordered).
The important thing to notice is that the duplicate string “mars” has disappeared because a set only contains unique values.
So, to check if a list contains any duplicates we can simply compare the size of the list with the size of the set. If they are different the list contains duplicates.
The size of the list and the set are:
>>> len(planets) 5 >>> len(set(planets)) 4
We can write a function that uses a conditional statement to verify if a list contains any duplicates and that returns True if it does.
>>> def has_duplicates(values): ... if len(values) != len(set(values)): ... return True ... else: ... return False ... >>> >>> has_duplicates(planets) True
Let’s redefine the list, remove the duplicate string and pass the list to our function again:
>>> planets = ['mercury', 'earth', 'mars', 'jupiter'] >>> has_duplicates(planets) False
Et voilà, this time it returns False as we expected.
Now that we know how to check IF a list contains duplicates it would be useful to get the value of duplicate elements.
We could come up with some convoluted code that uses for loops to figure out which element is in the list but not in the tuple, but that wouldn’t be the right approach.
A better approach could be to create a dictionary where every key is an item in the list and each value the number of times that item is present in the list.
We can achieve this result simply by using collections.Counter that is a dictionary subclass where elements of an iterable become dictionary keys and their counts are dictionary values.
>>> from collections import Counter >>> Counter(planets) Counter({'mars': 2, 'mercury': 1, 'earth': 1, 'jupiter': 1})
With a single line of code we can see that the string ‘mars’ appears two times in the list.
We can then create a list of duplicates using the following list comprehension:
>>> [key for key in Counter(planets).keys() if Counter(planets)[key]>1] ['mars']
This expression creates a list that contains keys for which the count value is greater than 1 (they appear more than one time in the original list).
Check For Duplicates in Two Python Lists
In some cases you might want to find elements that are the same in two different lists.
Let’s take the following lists:
>>> planets1 = ['mercury', 'earth', 'mars'] >>> planets2 = ['earth', 'jupiter', 'saturn']
We convert them into tuples and see the methods available to tuples in case there is anything that can help us.
>>> p1 = set(planets1) >>> p2 = set(planets2) >>> p1. p1.add( p1.intersection( p1.remove( p1.clear( p1.intersection_update( p1.symmetric_difference( p1.copy( p1.isdisjoint( p1.symmetric_difference_update( p1.difference( p1.issubset( p1.union( p1.difference_update( p1.issuperset( p1.update( p1.discard( p1.pop(
The intersection method could be the one, let’s confirm it using its help page:
>>> help(p1.intersection)
Yes, that’s the correct method…
>>> p1.intersection(p2) {'earth'}
The result is a tuple that contains the element in common.
We can obtain the same result by using the & operator:
>>> p1 & p2 {'earth'}
Check For Duplicates in a List of Tuples
What if we have a list of tuples and we want to verify if there are any duplicates and which ones are they?
Let’s say we have created a game and we use a list of tuples to store first name and score for each player.
But, for some reason we haven’t thought that there could be two players with the same first name and score.
When we identify the problem we decide to create a function that tells us if there is a duplicate in our list of tuples and which one is the duplicate.
>>> scores = [('Jane', 45), ('Anthony', 340), ('Jake', 34), ('Jane', 45)]
We can use the same approach explained before with collections.Counter to get back a dictionary that tells us which ones are the duplicate tuples and how many times are present.
>>> from collections import Counter >>> Counter(scores) Counter({('Jane', 45): 2, ('Anthony', 340): 1, ('Jake', 34): 1})
Pretty simple to do, that’s one of the reasons why I love Python. Things you might think require lots of code can be often written with just a couple of lines.
Let’s write a function that raises an exception at the first duplicate tuple found in the list.
from collections import Counter def has_duplicates(elements): counter = Counter(elements) for key, value in counter.items(): if value > 1: raise ValueError("Duplicate score found {}".format(key)) scores = [('Jane', 45), ('Anthony', 340), ('Jake', 34), ('Jane', 45)] has_duplicates(scores)
The output is:
# python3 duplicates_list.py Traceback (most recent call last): File "duplicates_list.py", line 12, in <module> has_duplicates(scores) File "duplicates_list.py", line 8, in has_duplicates raise ValueError("Duplicate score found {}".format(key)) ValueError: Duplicate score found ('Jane', 45)
This is just to give you an idea of the logic you can implement depending on what you need your Python program to do.
Find Duplicates in a List of Dictionaries
This time we want to find duplicate objects in a list of dictionaries.
>>> users = [{'name':'Jane', 'score': 45}, {'name':'Anthony', 'score': 234}, {'name':'John', 'score': 786}, {'name':'Jane', 'score': 45}]
A duplicate dictionary would be one that has the same values for both keys ‘name’ and ‘score’.
With a list comprehension we can generate a list of lists where each list contains both values for each dictionary:
>>> [list(user.values()) for user in users] [['Jane', 45], ['Anthony', 234], ['John', 786], ['Jane', 45]]
I wonder what happens if I use collections.Counter with this list of lists:
>>> from collections import Counter >>> Counter([['Jane', 45], ['Anthony', 234], ['John', 786], ['Jane', 45]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/claudiosabato/opt/anaconda3/lib/python3.8/collections/__init__.py", line 552, in __init__ self.update(iterable, **kwds) File "/Users/claudiosabato/opt/anaconda3/lib/python3.8/collections/__init__.py", line 637, in update _count_elements(self, iterable) TypeError: unhashable type: 'list'
Why are we getting the error unhashable type: ‘list’?
This error is caused by the fact that you cannot use lists as the keys of a dictionary because keys of a dictionary have to be immutable and lists are mutable.
So, let’s convert our list of lists into a list of tuples and then apply collections.Counter to it again.
To get a list of tuples we have to update the previous list comprehension and also add the tuple() function:
>>> [tuple(user.values()) for user in users] [('Jane', 45), ('Anthony', 234), ('John', 786), ('Jane', 45)]
And now let’s apply Counter to it:
>>> Counter([tuple(user.values()) for user in users]) Counter({('Jane', 45): 2, ('Anthony', 234): 1, ('John', 786): 1})
The only duplicate dictionary is the one whose values are ‘Jane’ and 45.
Find Duplicates in a List and Get Their Index
We have seen how to find duplicates in a list, but how can we get their index in the list?
Let’s first create a function that uses the list comprehension we have created at the beginning of this tutorial to get duplicates in a list:
from collections import Counter def get_duplicates(values): return [key for key in Counter(values).keys() if Counter(values)[key]>1] planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] duplicates = get_duplicates(planets) print(duplicates)
We get back a list that contains the duplicates:
# python3 duplicates_list.py ['earth', 'mars']
The next step is to get the indexes in the list for each element that has duplicates. For that we will use the enumerate function.
Here is how you can generate all the indexes in our list using enumerate:
>>> [index for index, value in enumerate(planets)] [0, 1, 2, 3, 4, 5]
Create a function that takes as inputs our list and an element of the list and returns a dictionary where the key is the element of the list and the value is a list that contains the indexes for that element in the list.
It’s easier to code than to explain 🙂
def get_indexes_for_element(values, element): element_indexes = [index for index, value in enumerate(values) if value == element] return { element : element_indexes }
Let’s call it to see if it returns what we expect:
planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] print(get_indexes_for_element(planets, 'earth')) [output] {'earth': [1, 5]}
Exactly what we want!
Time to put everything together…
…we will create a list of dictionaries where each dictionary has the format we have just seen with the string ‘earth’.
Let’s add a third function that goes through all the duplicates and generates the final list of dictionaries:
def get_indexes_for_duplicates(values, duplicates): indexes_for_duplicates = [] for duplicate in duplicates: indexes_for_duplicates.append(get_indexes_for_element(values, duplicate)) return indexes_for_duplicates
Here is the final code:
from collections import Counter def get_duplicates(values): return [key for key in Counter(values).keys() if Counter(values)[key]>1] def get_indexes_for_element(values, element): element_indexes = [index for index, value in enumerate(values) if value == element] return { element : element_indexes } def get_indexes_for_duplicates(values, duplicates): indexes_for_duplicates = [] for duplicate in duplicates: indexes_for_duplicates.append(get_indexes_for_element(values, duplicate)) return indexes_for_duplicates planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] duplicates = get_duplicates(planets) print(get_indexes_for_duplicates(planets, duplicates))
And the output is…
# python3 duplicates_list.py [{'earth': [1, 5]}, {'mars': [2, 4]}]
It works well 🙂
Find Duplicates in a Python List and Remove Them
One last thing that can be useful to do is to remove any duplicate elements from a list.
We could use the list remove() method to do that but it would only work well if a single duplicate for a give element is present in the list.
Let’s have a look at this example:
>>> planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] >>> planets.remove('earth') >>> planets ['mercury', 'mars', 'jupiter', 'mars', 'earth'] >>> planets.remove('mars') >>> planets ['mercury', 'jupiter', 'mars', 'earth']
The list remove() method deletes the first occurrence of a given element from a list.
For this approach to work, after removing a given element we need to confirm if the list still contains any duplicates.
We can use a while loop that is executed as long as the list of duplicates is not empty:
from collections import Counter def get_duplicates(values): return [key for key in Counter(values).keys() if Counter(values)[key]>1] planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] print("The initial list is {}".format(planets)) while len(get_duplicates(planets)) != 0: duplicates = get_duplicates(planets) print("Loop iteration: the duplicates in the list are {}".format(duplicates)) planets.remove(duplicates[0]) print("The list without duplicates is {}".format(planets))
If the list still contains duplicates we remove from the list the first element in the duplicates list. Eventually the duplicates list will be empty and the execution of the while loop will stop.
# python3 remove_duplicates.py The initial list is ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] Loop iteration: the duplicates in the list are ['earth', 'mars'] Loop iteration: the duplicates in the list are ['mars'] The list without duplicates is ['mercury', 'jupiter', 'mars', 'earth']
How To Remove Duplicate Numbers From a List
Let’s find out if the approach we just used to remove duplicate strings from a list also works with a list of numbers.
Firstly we will make our code more generic by using an additional function that receives a list and returns the same list without duplicates.
def get_list_without_duplicates(values): print("The initial list is {}".format(values)) while len(get_duplicates(values)) != 0: duplicates = get_duplicates(values) print("Loop iteration: the duplicates in the list are {}".format(duplicates)) values.remove(duplicates[0]) print("The list without duplicates is {}".format(values)) return values
The implementation of the get_duplicates() function doesn’t change compared to the previous code. And here is how we can call the new function:
planets = ['mercury', 'earth', 'mars', 'jupiter', 'mars', 'earth'] print(get_list_without_duplicates(planets))
Confirm that the result is correct before continuing.
Now, let’s try to pass a list of numbers instead.
numbers = [1, 2, 3, 3, 3, 4, 3, 5, 5, 7, 54, 45, 43, 43, 2, 1] print(get_list_without_duplicates(numbers))
Our program does the job:
# python3 remove_duplicate_numbers.py The initial list is [1, 2, 3, 3, 3, 4, 3, 5, 5, 7, 54, 45, 43, 43, 2, 1] Loop iteration: the duplicates in the list are [1, 2, 3, 5, 43] Loop iteration: the duplicates in the list are [2, 3, 5, 43] Loop iteration: the duplicates in the list are [3, 5, 43] Loop iteration: the duplicates in the list are [3, 5, 43] Loop iteration: the duplicates in the list are [3, 5, 43] Loop iteration: the duplicates in the list are [5, 43] Loop iteration: the duplicates in the list are [43] The list without duplicates is [4, 3, 5, 7, 54, 45, 43, 2, 1] [4, 3, 5, 7, 54, 45, 43, 2, 1]
If you want the list to be sorted you can do it using the list sort() method in the get_list_without_duplicates() function before the return statement.
def get_list_without_duplicates(values): ... ... values.sort() return values
Try to run the program and confirm that you receive a sorted list.
Conclusion
After going through this tutorial you shouldn’t have any doubts on how to check if a list has duplicates and also on how to get the value and index of the duplicates.
We have also seen how this works with list of lists, list of tuples and lists of dictionaries.
And now it’s your time to use the method you feel it’s best for you.
Happy coding!
I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer! | https://codefather.tech/blog/python-check-for-duplicates-in-list/ | CC-MAIN-2021-31 | refinedweb | 2,459 | 57.2 |
Hi guys.. Im stuck on my project and i urgently need ur help.
i want to randomly generate some moving rectangles (one after another moving in the same direction). this should occur infinitely. So far i have only managed to create one moving rectangle.
i hope u guys can help me out plz
thanks..
import <strong class="highlight">Tkinter</strong> as tk import time root = tk.Tk() canvas = tk.Canvas(root, width=400, height=400) canvas.pack() # canvas.create_rectangle(x0, y0, x1, y1, option, ... ) # x0, y0, x1, y1 are corner coordinates of ulc to lrc diagonal rc1 = canvas.create_rectangle(20, 260, 120, 360, outline='white', fill='blue') rc2 = canvas.create_rectangle(20, 10, 120, 110, outline='white', fill='red') for x in range(50): y = x = 5 time.sleep(0.025) canvas.move(rc1, x, -y) canvas.move(rc2, x, y) canvas.update() root.mainloop() | https://www.daniweb.com/programming/software-development/threads/158484/random-generator-in-tkinter | CC-MAIN-2018-17 | refinedweb | 144 | 63.15 |
Updated with links of .NET Best Practice No: 1, 2, 4, 5, and Video
Is this Article worth reading ahead?
Introduction: My application performance is the best like a rocket J
Thanks Javier and Michael
At the end of the day its count, calculate and display
Performance counters are not magicians
Types of measures in application
Example on which performance counter will be tested
Adding our first instantaneous performance counter in 4 steps
Creating more sensible counter
Average performance counters
Rate performance counters
Performance counters left
Adding counters by C# code
Let’s ease some pain using Performance counter helper
Do not use it in production
Conclusion
Source code
Other Practices
My FAQ articles
This article discusses how we can use performance counter to gather data from an application. So we will first understand the fundamentals and then we will see a simple example from which we will collect some performance data.
Let us start this article by a small chat between customer and developer.
Scenario 1
Customer: How’s your application performance?
Subjective developer: Well it’s speedy, it’s the best …huuh aaa ooh it’s a like rocket.
Scenario 2
Customer: How’s your application performance?
Quantitative developer: With 2 GB RAM , xyz processor and 20000 customer records the customer screen load in 20 secs.
I am sure the second developer looks more promising than the first developer. In this article we will explore how we can use performance counters to measure performance of an application. So let’s start counting 1,2,3,4….
Courtesy :
I really do not have the intellectual to write something on performance counters. But reading the below articles I was able to manage something. So first let me thank these guys and then we can move ahead in the article.
Thanks a bunch Javier Canillas for creating the performance counter helper , it really eases of lot of code
Thanks Michael Groeger for the wonderful article, I took the code of counter creation from your article
I also picked up lot of pieces from
Any performance evaluation works on count, calculate and display. For instance if you want to count how many pages in memory where processed per second we first need to count number of pages and also how many seconds where elapsed. Once we are finished with counting we then need to calculate i.e. divide the number of pages by seconds elapsed. Finally we need to display the data of our performance.
Now that we know it’s a 3 step process i.e. count, calculate and display. The counting part is done by the application. So the application needs to feed in the data during the counting phase. Please note the data is not automatically detected by the performance counters , some help needs to be provided by the application. The calculation and display is done by the performance counter and monitor.
If application does not provide counter data performance counters cannot measure by himself. Performance counter cannot measure applications which do not feed performance data. In other words the application needs to feed in counter data by creating performance counter objects.
Almost all application performance measurements fall in to one of the below six categories.
Instantaneous values: Many times we just want to measure the most recent value. For instance we just want to measure how many customer records where processed? How much RAM memory has been used, etc. These types of measures are termed as instantaneous or absolute values. Performance counter supports these measurement types by using instantaneous counters.
Average values: Sometimes instant / recent values do not really show the real picture. For instance just saying that application consumed 1 GB space is not enough. But if we can get some kind of average data consumption like 10 MB data was consumed per 1000 records probably you can get more insight of what is happening inside the application. Performance counter supports these kinds of measurement types by using average performanance counters like AverageBase, AverageTimer32, AverageCount64 etc.
Rate values: There are situations when you want to know the rate of events with respect to time. For example you would like to how many records where processed per second. Rate counters help us to calculate these kinds of performance metrics.
Percentage values: Many times we would like to see values as percentages for comparison purposes. For example you want to compare performance data between 2 computers. Comparing direct values will not be a fair comparison. So if we can have % values from both computers then the comparison can make more sense. If we want to compare values between different performance counters, percentage is much better option rather than using absolute values.
For example if you want to compare how much RAM is utilized as compared to hard disk space. Comparing 1 GB ram usage with 50 GB hard disk usage is like comparing apples with oranges. If you can express these values as percentages then comparison will be fair and justifiable. Percentage performance counters can help us to express absolute values as percentages.
Difference values: Many times we would like to get difference performance data , for instance how much time was elapsed from the time application started, how much hard disk consumption was done by the application from the time it started etc. In order to collect these kinds of performance data we need to record the original value and the recent value. To get final performance data we need to subtract the original value from the recent value. Performance counter provides difference counters to calculate such kind of performance data.
So summarizing there are 5 types of performance counters which can satisfy all the above counting needs. Below figure shows the same in a pictorial format.
In this complete article we will be considering a simple counter example as explained below. In this example we will have a timer which generates random number every 100 milliseconds. These random numbers are later checked to see if it’s less than 2. Incase its less than 2 then function ‘MyFunction’ is invoked.
MyFunction
Below is the code where the timer runs every 100 milliseconds and calculates random number. If the random number is smaller than 2 we invoke the function ‘MyFunction’.
private void timer1_Tick(object sender, EventArgs e)
{
// Generate random number between 1 to 5.
Random objRnd = new Random();
int y = objRnd.Next(1, 5);
// If random number is less than 2 call my Function
if (y > 2)
{
MyFunction();
}
}
Below is the code for ‘MyFunction’ which is invoked when the value of random number is less than 2. The method does not do anything as such.
private void MyFunction()
{
}
All our performance counters example in this article will use the above defined sample.
Before we go in to in depth of how to add performance counters, let’s first understand the structure of performance counters. When we create performance counters it needs to belong to some group. So we need to create a category and all performance counters will lie under that category.
We will like to just count how many times ‘MyFunction’ was called. So let’s create an instantaneous counter called as 'NumberOfTimeFunctionCalled'. Before we move ahead let’s see how many different types of instantaneous counters are provided by performance counters:
Below definitions are taken from.
NumberOfItems32: An instantaneous counter that shows the most recently observed value.
NumberOfItems64: An instantaneous counter that shows the most recently observed value. Used, for example, to maintain a simple count of a very large number of items or operations. It is the same as NumberOfItems32 except that it uses larger fields to accommodate larger values.
NumberOfItemsHEX32: An instantaneous counter that shows the most recently observed value in hexadecimal format. Used, for example, to maintain a simple count of items or operations.
NumberOfItemsHEX64: An instantaneous counter that shows the most recently observed value. Used, for example, to maintain a simple count of a very large number of items or operations. It is the same as NumberOfItemsHEX32 except that it uses larger fields to accommodate larger values.
Step 1 Create the counter: For our current scenario ‘NumberOfItems32’ will suffice. So let’s first create ‘NumberOfItems32’ instantaneous counter. There are two ways to create counters one is through the code and the other is using the server explorer of VS 2008. The code approach we will see later. For the time we will use server explorer to create our counter. So open your visual studio à click on view à server explorer and you should see the performance counters section as shown in the below figure. Right click on the performance counters section and select create new category.
NumberOfTimeFunctionCalled
When we create a new category you can specify the name of the category and add counters in to this category. For the current example we have given category name as ‘MyApplication’ and added a counter type of ‘NumberOfItem32’ with name ‘NumberOfTimeFunctionCalled’.
Step 2 Add the counter to your visual studio application: Once you have added the counter on the server explorer, you can drag and drop the counter on the ASPX page as shown below.
You need to mark ‘ReadOnly’ value as false so that you can modify the counter value from the code.
Step 3 Add the code to count the counter: Finally we need to increment the counter. We have first cleared any old values in the counter during the form load. Please note that counter values are stored globally so they do not do reset by themselves we need to do it explicitly. So in the form load we have cleared the raw value to zero.
private void Form1_Load(object sender, EventArgs e)
{
perfNumberOfTimeFunctionCalled.RawValue = 0;
}
Whenever the function is called we are incrementing the value by using ‘Increment’ method. Every call to the increment function increases the number by 1.
private void MyFunction()
{
perfNumberOfTimeFunctionCalled.Increment();
}
Step 4 View the counter data: Now that we have specified the counter in the application which increments every time ‘MyFunction’ function is called. It’s time to use performance monitor to display the performance counter. So go to start à run and type ‘perfmon’. You will see there are lots of by default performance counters. For clarity sake we will remove all the counters for now and add our performance counter i.e. ‘NumberofTimeFunctionCalled’.
NumberofTimeFunctionCalled
You can now view the graphical display as shown in the below figure. Ensure that your application is running because application emits data which is then interpreted by the performance monitor.
Above view is a graphical view of the same. To view the same in textual format you use the view report tab provided by performance monitor. You can see the report shows that ‘MyFunction’ was called 9696 times from the time application started.
In the previous section we have measured how many times ‘MyFunction’ was called. But this performance count does not really show any kind of measure. It would be great if we can also see the count of how many times the timer was called. Then later we can compare between the numbers of time timer was called and ‘MyFunction’ was called.
So create an instantaneous counter and increment this counter when the timer fires as shown in the below code.
private void timer1_Tick(object sender, EventArgs e)
{
perfNumberOfTimeTimerCalled.Increment();
Random objRnd = new Random();
int y = objRnd.Next(1, 5);
if (y > 2)
{
MyFunction();
}
}
You can see both the counters in t he below graph the blue line showing the number of times ‘MyFunction’ was called and the black one showing number of times timer called.
If we look in to the report view we can see for how many times the timer fired and how many times was ‘MyFunction’ called.
In the previous section we had counted two counters one which says how many times did the timer fire and the other says how many times ‘MyFunction’ was called. If we can have some kind of average data which says how many times was ‘MyFunctionCalled’ for the number of times timer called it will be make more sense.
In order to get these kinds of metrics Average performance counters can be used. So for our scenario we need to count the number of time function was called and number of time the timer fired. Then we need to divide them to find on a average how many times was the function for the timer fired.
MyFunctionCalled
We need to add two counters one for the numerator and the other for the denominator. For the numerator counter we need to add ‘AverageCount64’ type of counter while for the denominator we need to add ‘AverageBase’ type of counter.
You need to add the ‘AverageBase’ counter after the ‘AverageCount64’ type counter or else you will get an error as shown below.
For every timer tick we increment the number of time timer called counter.
private void timer1_Tick(object sender, EventArgs e)
{
perfAvgNumberofTimeTimerCalled.Increment();
Random objRnd = new Random();
int y = objRnd.Next(1, 5);
if (y > 2)
{
MyFunction();
}
}
For every function call we increment the number of time function called counter.
private void MyFunction()
{
perfNumberOfTimeFunctionCalled.Increment();
}
If you run the application in the view report mode you should see something as shown below. You can see on a average ‘MyFunction’ is called 0.5 times.
If you do the calculation you will get the same figure which is been calculated by the performance monitor.
From our sample we would now like to find out the rate of ‘MyFunction’ calls with respect to time. So we would like know how many calls are made every second. So browse to the server explorer and add ‘rateofCountsPerSecond32’ counter as shown in the below figure. Increase this counter every time ‘MyFunction’ is called.
rateofCountsPerSecond32
If you run the application you should be able to see the ‘RateofMyFunctionCalledPerSecond’ value. Below is a simple report which shows the rate of counter data which was ran for 15 seconds. The total call made in this 15 second was 72. So the average call is 5 ‘MyFunction’ calls per second.
We have left percentage counters and difference counters as they are pretty simple and straightforward. In order to maintain this article to the point and specific I have excused both these counter types.
Till now we have added the performance counter using server explorer. You can also add the counter by code. The first thing is we need to import System.Diagnostics namespace.
We then need to create object of ‘CounterCreationDataCollection’ object.
System.Diagnostics
CounterCreationDataCollection
CounterCreationDataCollection Mycounters = new CounterCreationDataCollection();
Create our actual counter and specify the counter type.
CounterCreationData totalOps = new CounterCreationData();
totalOps.CounterName = "Numberofoperations";
totalOps.CounterHelp = "Total number of operations executed";
totalOps.CounterType = PerformanceCounterType.NumberOfItems32;
Mycounters.Add(totalOps);
Finally create the counter inside a category. Below code snippet is creating the counter in ‘MyCategory’ category.
PerformanceCounterCategory.Create("MyCategory","Sample category for Codeproject", Mycounters);
Its quiet a pain to write the counter creation code. You can use performance counter helper to ease and make your code smaller. You can find the performance counter helper at ,
Oh yes, use it only when you are doing development. If you are using in production ensure that there is an enabling and disabling mechanism or else it will affect your application performance.
You can find the sample source code for the above performance counters discussed at you can download the source code from here
For best Practices Part 1, click here
For best Practices Part 2,. | http://www.codeproject.com/Articles/42001/NET-Best-Practice-No-3-Using-performance-counters?fid=1548691&df=90&mpp=10&sort=Position&spc=None&select=4196774&tid=3195173 | CC-MAIN-2016-22 | refinedweb | 2,575 | 55.64 |
/>
In this post I will write a Python implementation of Benford's Law which describes the distribution of the first digits of most sets of numeric data.
I recently posted an article on Zipf's Law and the application of the Zipfian Distribution to word frequencies in a piece of text. Benford's Law can be considered a special case of Zipfian Law.
Applying the Zipfian Distribution to bodies of text is fraught with difficulty due to the vagaries of natural language and I am sceptical of the practicalities and usefulness of doing so beyond demoing the Zipfian Distribution and its implementation.
However, the Benford Distribution is very different. If you have a set of numeric data you can try to fit it to the Benford Distribution without worrying about all the quirks and messiness of natural language. You don't even have to worry about the total number of possible distinct values - every number starts with 1 to 9. simple console graph to show the results.
The project consists of two files:
- benfordslaw.py
- benfordslaw_demo.py
These can be downloaded as a zip, or you can clone or download the Github repository. Let's look at benfordslaw.py.
Source Code Links
import collections BENFORD_PERCENTAGES = [0, 0.301, 0.176, 0.125, 0.097, 0.079, 0.067, 0.058, 0.051, 0.046] def calculate(data): """ Calculates a set of values from the numeric list input data showing how closely the first digits fit the Benford Distribution. Results are returned as a list of dictionaries. """ results = [] first_digits = list(map(lambda n: str(n)[0], data)) first_digit_frequencies = collections.Counter(first_digits) for n in range(1, 10): data_frequency = first_digit_frequencies[str(n)] data_frequency_percent = data_frequency / len(data) benford_frequency = len(data) * BENFORD_PERCENTAGES[n] benford_frequency_percent = BENFORD_PERCENTAGES[n] difference_frequency = data_frequency - benford_frequency difference_frequency_percent = data_frequency_percent - benford_frequency_percent results.append({"n": n, "data_frequency": data_frequency, "data_frequency_percent": data_frequency_percent, "benford_frequency": benford_frequency, "benford_frequency_percent": benford_frequency_percent, "difference_frequency": difference_frequency, "difference_frequency_percent": difference_frequency_percent}) return results
Firstly we import collections to use collections.Counter. Then comes a constant list of the relative frequencies of the digits 1 to 9 as decimal fractions. I have padded it out with a superfluous 0 so we can index the values using the digits they represent. It is up the top outside the function so it can be used by external code.
The calculate function takes a list and creates from it a list of the first digits (as strings) which is then used to construct a collections.Counter. This object now contains a set of key/value pairs for each distinct first digit. A useful feature of Counter is that if we try to access a key which does not exist it will return 0.
Next we need to iterate from 1 to 9, calculating a few values for each digit showing how it compares to the Benford Distribution. These are then used to create dictionaries which are added to a list which is then returned.
Now we can try the module out in benfordslaw_demo.py.
benfordslaw_demo.py
import random import benfordslaw def main(): print("-----------------") print("| codedrome.com |") print("| Benford's Law |") print("-----------------\n") data = get_random_data() #data = get_benford_data() print(len(data)) benford_table = benfordslaw.calculate(data) print_as_table(benford_table) print() print_as_graph(benford_table) def get_random_data(): """ Returns a list of 1000 numbers approximately following the uniform distribution NOT the Benford Distribution. """ random_data = [0] * 1000 random_data = list(map(lambda n: n + random.randint(1, 1000), random_data)) return random_data def get_benford_data(): """ Returns a list of about 1000 numbers approximately following the Benford Distribution. """ benford_data = [] for first_digit in range(1, 10): random_factor = random.uniform(0.8, 1.2) for num_count in range(1, int(1000 * benfordslaw.BENFORD_PERCENTAGES[first_digit] * random_factor)): start = first_digit * 1000 benford_data.append(random.randint(start, start + 1000)) return benford_data def print_as_table(benford_table): width = 59 print("-" * width) print("| | Data | Benford | Difference |") print("| n | Freq Pct | Freq Pct | Freq Pct |") print("-" * width) for item in benford_table: print("| {} | {:6.0f} | {:6.2f} | {:6.0f} | {:6.2f} | {:6.0f} | {:6.2f} |".format(item["n"], item["data_frequency"], item["data_frequency_percent"] * 100, item["benford_frequency"], item["benford_frequency_percent"] * 100, item["difference_frequency"], item["difference_frequency_percent"] * 100)) print("-" * width) def print_as_graph(benford_table): REDBG = "\x1B[41m" GREENBG = "\x1B[42m" RESET = "\x1B[0m" print(" 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%") print(" | | | | | | | | | | |\n") for item in benford_table: print(" {} {}\n {}\n ".format(str(item["n"]), GREENBG + (" " * int(round(item["benford_frequency_percent"] * 100))) + RESET, REDBG + (" " * int(round(item["data_frequency_percent"] * 100))) + RESET)) main()
main
After importing random and benfordslaw we enter the main function. This calls one of two functions to get some test data, and then throws it at benfordslaw.calculate. The results are then passed to print_as_table and print_as_graph.
get_random_data
This is a simple function which creates 1000 random values between 1 and 1000.
get_benford_data
This is more complex because it creates about 1000 values which roughly fit the Benford Distribution. For each digit 1-9 it iterates from 1 to the proportion of each digit in the Benford Distribution, retrieved from the benfordslaw module. So we don't get an exact fit each time this is adjusted by a random amount between 0.8 and 1.2. Within this loop we create a set of values with the relevant first digit.
print_as_table
A fiddly but straightforward function to print out the data structure returned by benfordslaw.calculate in a table.
print_as_graph
This also takes the data structure returned by benfordslaw.calculate and prints it as a graph in the console. Firstly we define some ANSI terminal colour constants and after some hard-coded headings we iterate the data, printing out the Benford and actual frequencies as bars in green and red respectively.
That's the coding finished so let's run the program.
Run
python3.7 benfordslaw_demo.py
This is the output with random data.
Program Output (random data)
----------------- | codedrome.com | | Benford's Law | ----------------- ----------------------------------------------------------- | | Data | Benford | Difference | | n | Freq Pct | Freq Pct | Freq Pct | ----------------------------------------------------------- | 1 | 117 | 11.70 | 301 | 30.10 | -184 | -18.40 | | 2 | 120 | 12.00 | 176 | 17.60 | -56 | -5.60 | | 3 | 96 | 9.60 | 125 | 12.50 | -29 | -2.90 | | 4 | 107 | 10.70 | 97 | 9.70 | 10 | 1.00 | | 5 | 89 | 8.90 | 79 | 7.90 | 10 | 1.00 | | 6 | 121 | 12.10 | 67 | 6.70 | 54 | 5.40 | | 7 | 103 | 10.30 | 58 | 5.80 | 45 | 4.50 | | 8 | 103 | 10.30 | 51 | 5.10 | 52 | 5.20 | | 9 | 144 | 14.40 | 46 | 4.60 | 98 | 9.80 | ----------------------------------------------------------- 0% 10% 20% 30% 40% 50% | | | | | | 1 2 3 4 5 6 7 8 9
The green Benford Distribution bars are always the same but the red bars show the actual distribution. In this case we can easily see that the actual distribution is roughly uniform and doesn't fit the Benford Distribution at all. Very suspicious!
In main comment out data = get_random_data(), uncomment data = get_benford_data() and run the program again.
Program Output (Benford Distribution data)
----------------- | codedrome.com | | Benford's Law | ----------------- ----------------------------------------------------------- | | Data | Benford | Difference | | n | Freq Pct | Freq Pct | Freq Pct | ----------------------------------------------------------- | 1 | 289 | 29.02 | 300 | 30.10 | -11 | -1.08 | | 2 | 177 | 17.77 | 175 | 17.60 | 2 | 0.17 | | 3 | 113 | 11.35 | 124 | 12.50 | -12 | -1.15 | | 4 | 102 | 10.24 | 97 | 9.70 | 5 | 0.54 | | 5 | 86 | 8.63 | 79 | 7.90 | 7 | 0.73 | | 6 | 80 | 8.03 | 67 | 6.70 | 13 | 1.33 | | 7 | 60 | 6.02 | 58 | 5.80 | 2 | 0.22 | | 8 | 49 | 4.92 | 51 | 5.10 | -2 | -0.18 | | 9 | 40 | 4.02 | 46 | 4.60 | -6 | -0.58 | ----------------------------------------------------------- 0% 10% 20% 30% 40% 50% | | | | | | 1 2 3 4 5 6 7 8 9
This set of data is a much better fit to Benford's Distribution. If we didn't know better we would think it was genuine. | https://www.codedrome.com/benfords-law-in-python/ | CC-MAIN-2021-25 | refinedweb | 1,276 | 61.53 |
This is your resource to discuss support topics with your peers, and learn from each other.
03-30-2012 10:46 AM
NDK is supposed to include ncurses. Would anyone be able to point me to a simple example of where ncurses is used in NDK?
If I even add ncurses.h to a new project template (Minimal Screen Application) I get the following error during build:
"ncurses.h:114: error: two or more data types in declaration specifiers"
Any suggestions on how to use ncurses in NDK would be much appreciated.
Roger
03-30-2012 03:08 PM
I have got rid of the error by not including the header:
#include <bps/navigator.h>
The printw("Hello World !!!");/* Print Hello World */ only prints to the console in QNX Momentics IDE. I still need to find out how to print on the tablet.
And, I guess I have to find out how to make getch() or a viable alternative work in ncurses as well.
Any sugestions?
Roger
03-30-2012 04:42 PM
04-02-2012 08:17 AM
Thank you but since ncurses library is loaded in PB I assumed it is usable for more than just listing in PB advertising. So far I have found it doesn't work with:
#include <bps/navigator.h>
and it only outputs within Momentics. I can't get it to display anything on the PB.
Does ncurses provide anything useful on the PB, if so, what and how is ncurses used?
Roger
04-02-2012 10:03 AM
I wrote a simple console display app that uses the freetype/opengl es code in bbutils to display text and also added a rudimentary ansi/vt100 parser. It was more work than i expected, but now i can use ncurses
. As a proof of concept I can run ninvaders in the console.
So indeed ncurses does work but you need to provide some sort of framework to actually parse and display the output. I assume you could use Qt to create the terminal window but at that point you don't really need ncurses.
ncurses would mostly be useful for porting existing ncurses based applications.
Norm
04-02-2012 11:09 AM
Exactly! ncurses does what is supposed to do and it is up to you whether to use it on PB or not? ncurses is *not* a Terminal Emulation -) | http://supportforums.blackberry.com/t5/Native-Development/ncurses/td-p/1645459 | CC-MAIN-2014-52 | refinedweb | 396 | 73.58 |
Button
Buttons are a common component used to control electronic devices. They are usually used as switches to connect or break circuits. Although buttons come in a variety of sizes and shapes, the one used here is a 6mm mini-button as shown in the following pictures.
Pin 1 is connected to pin 2 and pin 3 to pin 4. So you just need to connect either of pin 1 and pin 2 to pin 3 or pin 4.
The following is the internal structure of a button. Since the pin 1 is connected to pin 2, and pin 3 to pin 4, the symbol on the right below is usually used to represent a button.
Connect one side of the button to B18, and the other to GND. Press the button, and B18 will be Low level. In other words, we can know whether the button is pressed or not by reading the value of B18. Since we have already set pull-up for the button in the code, we don’t need to add a pull-up resistor in the circuit.
Let’s write a simple sketch to detect the input signal first.
Create a new code file named button.py.
For screen users, you can use the Python Shell. Click File -> New, or just press Ctrl + N, and ensure it’s saved under /home/pi/RPi_Beginner. Enter the name button.py and click OK to create.
For remote login, you can use the nano command, nano button.py.
Now, let’s write the code:
import RPi.GPIO as GPIO button_pin = 18 # Connect button at 18 GPIO.setmode(GPIO.BCM) GPIO.setup(button_pin, GPIO.IN, GPIO.PUD_UP) # Set button as input and pull up while True: button_status = GPIO.input(button_pin) # Read button input and give the value to status if button_status == 1: # Check status value print "Button Released!" else: print "Button Pressed!"
Keep the GPIO and LED wiring the same in the code, but set button_pin to 18. In GPIO.setup, set button_pin as input (GPIO.IN), and add GPIO.PUD_UP. We will check it later.
In the loop, we can also use the GPIO.input to read the button status, which returns two values: 0(Low) and 1(High). Use the if statement to determine the status by the value – whether the button is pressed or released. Pay attention to the operation symbol in the statement, which determines whether two parts are equal or not. Note that it’s two equal signs “==“, which is different from “=” which is used in assignment.
So, what exactly does the previous GPIO.PUD_UP do?
It means to pull up a pin. Since the voltage in the circuit will be unstable when the button is released and the pin 18 is disconnected in the circuit. Therefor to keep a stable high (UP) or low (DOWN) level, it’s necessary to attach a pull-up (GPIO.PUD_UP) or a pull-down (GPIO.PUD_DOWN). But why a pull-up instead of pull-down here? Because the other pin of the button is connected to GND, or, Low level. If we attach a pull-down, the button will be at Low level after it is released, which means it will always be Low no matter being pressed or released, thus we cannot tell the button status then. Therefore, it has to be a pull-up.
Now, save the code and run it.
When the button is not pressed, “Button Released!” will be sent on the screen continuously. When it is pressed, “Button Pressed!” will be displayed. As the code is always detecting, the corresponding information will be printed on the screen continuously. But this is too annoying if it just keeps prompting. How to solve this problem then? | https://learn.sunfounder.com/7-7-button/ | CC-MAIN-2021-39 | refinedweb | 623 | 76.32 |
dubins 0.9.1
Code to generate and manipulate dubins curves
Overview
This software finds the shortest paths between configurations for the Dubins’ car [Dubins51],
Sampling of a Dubin’s path at finite size sizes
import dubins q0 = (x0, y0, theta0) q1 = (x1, y1, theta1) turning_radius = 1.0 step_size = 0.5 qs, _ = dubins.path_sample(q0, q1, turning_radius, step_size)
Contributions
This work was completed as part of [Walker11].
References
- Downloads (All Versions):
- 13 downloads in the last day
- 52 downloads in the last week
- 251 downloads in the last month
- Author: Andrew Walker
- Categories
- Package Index Owner: Andrew.Walker
- DOAP record: dubins-0.9.1.xml | https://pypi.python.org/pypi/dubins/0.9.1 | CC-MAIN-2015-18 | refinedweb | 106 | 55.54 |
Flutter Tabbar
In this section, we are going to learn how to add a tab bar and its working in Flutter. Tabs are used for navigation. The styling is different for different devices based on the OS.
Tabs are common in Android and iOS apps which follow the Material Design guidelines. Flutter provides an easy way to add a tab layout. We use a TabBar and TabBarView with a TabController to add tabs. The controller is used to sync between both.
Lets see an example to explore tabs
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: Text('Flutter Tabs Demo'), bottom: TabBar( tabs: [ Tab(icon: Icon(Icons.contacts), text: "Tab 1"), Tab(icon: Icon(Icons.camera_alt), text: "Tab 2") ], ), ), body: TabBarView( children: [ Container( child: Center( child: Text('It is a contact tab, which is responsible for displaying the contacts stored in your mobile', style: TextStyle(fontSize: 32.0), ) ), ), Container( child: Center( child: Text('It is a second layout tab, which is responsible for taking pictures from your mobile.', style: TextStyle(fontSize: 35.0), ), ), ) , ], ), ), ), ); } }
Output
| https://salesforcedrillers.com/learn-flutter/flutter-tabbar/ | CC-MAIN-2022-40 | refinedweb | 195 | 57.67 |
18 September 2008 14:09 [Source: ICIS news]
By Joe Kamalick?xml:namespace>
WASHINGTON (?xml:namespace>
Kevin Swift, chief economist at the American Chemistry Council (ACC), holds that the
“The softness in the
Global chemical volume growth, which is tied closely with industrial production, is poised to slow to 3% in 2008 from 4.5% in 2007 and 5.2% in 2006, he noted.
“The supply chain is like a bull whip. The consumer has the handle and the chemical industry is at the end,” he said. “The slowdown in consumer spending will go up through the supply chain and hit chemicals.”
But other manufacturing analysts are not so certain of a general economic malaise that ultimately will eat away at producers just as it has consumed one-time giants in the financial sector.
Tom Duesterberg, president of the Manufacturers Alliance, argues that US and international producers of industrial and consumer goods are in better shape than their counterparts in the financial sector, especially because they are not beset by bad debt related to the underlying US real estate and housing crisis.
“First of all, the manufacturing companies that survived the last recession - the 2001-2003 recession that was much deeper than this one - have pretty good balance sheets and are good credit risks,” Duesterberg said.
“Coming out of the 2001-2003 recession, manufacturers have been much more conservative,” he said. “Apart from the hard-hit housing and auto sectors, which are on their heels right now, a lot of manufacturing is doing reasonably well.”
“The financial crisis has not affected the bulk of manufacturing so far. With their good balance sheets and credit standing, if they need working capital or capital for expansion, we haven’t seen any evidence that good companies can’t get it,” he said.
“That said, it is clear that lending standards are being tightened quite a bit, so terms for financing are getting a little bit tougher. And each new wave of this crisis weakens the overall financial system even more.”
“There is still plenty of credit out there, but each new blow makes it more problematic,” he said.
“One good thing is that there is plenty of international competition in financial markets,” Duesterberg said. “Where 30 years ago US companies had to rely on internal US institutions, now European and Asian banks play a large role, so there is more competition.”
“Of course it is a bad thing when someone like Lehman Brothers goes out, because that means there is that much less competition. But Swiss, German, British and Japanese banks are a little more active than they used to be.”
“To my mind, we are in one of the more serious economic disruptions this country has seen since World War II, but at this point it is mostly a financial sector phenomenon,” Duesterberg added.
However, the Manufacturers Alliance is made up largely of leading global manufacturing firms in electronics, aerospace, computers, medical technology, energy and chemicals, and the outlook for mid-size and smaller producers of industrial materials and consumer products is more uncertain.
Hank Cox, vice-president at the National Association of Manufacturers (NAM), is concerned about whether and how the financial crisis might affect producers.
“It is a bit early to see how all of this is going to play out, but we are concerned about the availability of investment capital,” Cox said.
“Manufacturing is highly capital-intensive,” he noted. “To be competitive in the global marketplace, we must have the most modern technologies and a steady stream of R&D [research and development] funds.” And that requires credit availability.
Even so, Cox is not certain that the financial troubles afflicting Wall Street will necessarily infect
“I don’t believe manufacturers are rethinking their capital improvement or expansion plans yet,” Cox said in answer to a question, “until they see how this plays out.”
“We are on unfamiliar ground here,” he said.
US Treasury Department undersecretary David McCormick conceded this week that “capital market stress continues to weigh on our economy”, but he told the Brookings Institute that “the housing correction is at the root of the challenges facing our financial institutions and our markets”.
“Housing poses the biggest downside risk to our economy and continues to be a drag on growth,” McCormick said.
“We are working to minimise the impact of the housing correction on the rest of the economy,” he noted, referring to federal stimulus programmes initiated earlier this year to, among other things, provide first-time home buyers a $7,500 tax credit.
“But we do not want to impede the progress of the housing correction, because the sooner we turn the corner on housing, the sooner we will see home values stabilise, the sooner we will see more people buying homes and the sooner housing will again contribute to economic growth,” he said.
Citing the recent rash of financial sector shocks and federal interventions, McCormick conceded that “it will take time to work through these stresses.
“Progress will not come in a straight line, and there will be bumps in the road as we make progress,” he said.
“The events of the last few weeks are evidence of this and are important and necessary steps to work through the uncertainty and turmoil in our markets and minimise their impact on the rest of the economy.”
McCormick said there are signs of progress in the crucial housing sector.
“Fewer new homes are being built, and this means the total number of new single-family homes on the market is down 27% from a July 2006 peak. And though it is early, new and existing home sales show tentative signs of stabilising.”
Those moderating declines came as
The National Association of Home Builders (NAHB) said its home builders housing market index (HMI) gained two points in September to 18, rising from its record low of 16 in the previous two months.
NAHB president Sandy Dunn said many home builders “are sensing that home sales are nearing a turning point” because of the federal stimulus programme for first-time home buyers, the Washington support for mortgage market majors Fannie Mae and Freddie Mac and declining loan interest rates.
“Meanwhile, consumer confidence has risen and more households are saying that now is a good time to buy a home,” Dunn said. “All of these factors, along with the recent downward movements in mortgage rates, suggest that new home sales will be stabilising in the final quarter of the year.”
ACC economist Swift perhaps shares some of that expectation.
“In 2009, we expect the North American capital goods market to soften, but the housing and light vehicle markets to stabilise,” he said. “By 2010, we see nearly all end markets starting to improve.”
Manufacturers
“We are on record at the
Still, no economic analysis can be complete without at least one “on the other hand” caveat.
As Duesterberg put it: “We can’t, the economic system can’t, absorb an unlimited number of blows with big financial institutions failing, because eventually there will be too much collateral damage to
To discuss issues facing the chemical industry go to
Bookmark Paul Hodges' Chemicals and the Economy blog and John Richardson’s | http://www.icis.com/Articles/2008/09/18/9156606/insight-is-the-sky-darkening-or-brighter.html | CC-MAIN-2014-41 | refinedweb | 1,199 | 55.58 |
This site is now read-only. You can find our new documentation site and support forum for posting questions here.
Be sure to read our welcome blog!
GATK UnifiedGenotyper freeze when run by Java application
Hello,
I have a simple run.sh bash script which runs gatk UnifiedGenotyper on 40 bam files. If I run the script manually, analysis finish without problem. If I start the analysis through Java script test.java, it freezes in the middle of the processing (approx. 20th sample), also depending on -nt and -nct values. If I kill the Java script after freezing, the analysis continue on the next sample without problems.
Do you have any suggestions where is the problem & how to fix it?
It's important for me to run the script through Java.
My version of gatk is 3.6; Java 1.8
samples have average coverage 35000
run.sh
!/bin/bash
for file in path/to/*.sorted.bam
do
FNAME=$(basename "$file");
java -jar GenomeAnalysisTK.jar -nt 4 -stand_emit_conf 10 -stand_call_conf 25 -nct 25 -maxAltAlleles 15 --output_mode EMIT_VARIANTS_ONLY --max_deletion_fraction 0.001 --min_indel_fraction_per_sample 0.001 -gt_mode DISCOVERY -T UnifiedGenotyper -R path/to/bundle_GATK/b37/b37/human_g1k_v37.fasta --disable_auto_index_creation_and_locking_when_reading_rods --genotype_likelihoods_model BOTH -ploidy 2 -L 17:1-9999999 -dcov 9999999 --logging_level INFO -I $file -o path/to/output/${FNAME}.genotyper.vcf --log_to_file path/to/output/${FNAME}.log
done
test.java
package test;
import java.io.File;
public class Test
{
public static void main(String[] args) { File currentDir = new File("."); try { Process process = Runtime.getRuntime().exec(currentDir.getAbsolutePath() + File.separator + "run.sh"); process.waitFor(); } catch (Exception e) { System.out.println(e.getMessage()); } }
}
Thanks a lot
nikosh
Answers
Hi @nikosh, I'm afraid this isn't something we're able to support. Maybe try monitoring memory and cpu usage to see if you're maxing out resources... Aside from that I have no idea how to troubleshoot this. | https://gatkforums.broadinstitute.org/gatk/discussion/8585/gatk-unifiedgenotyper-freeze-when-run-by-java-application | CC-MAIN-2020-29 | refinedweb | 312 | 54.18 |
05 March 2010 16:25 [Source: ICIS news]
PRAGUE (ICIS news)--PKN Orlen plans to start up its new 600,000 tonne/year purified terephthalic acid (PTA) plant at Wloclawek, Poland, during the second half of this year, the Polish oil, chemical and petrochemical group said on Friday.
Orlen said it was mainly building the plant, which will cost around €1.1bn ($1.5bn), because of a sharp increase in demand for polyethylene terephthalate (PET) bottles in ?xml:namespace>
The plant will be installed with an industrial metals recovery system designed by Envirogen Technologies, according to a statement from that company.
“The recovered metals will be recycled for use as a catalyst in the PTA manufacturing process,” said Envirogen.
Earnest Chemical, a joint venture between Chemtex International and Yu King Technology, would install the system, Envirogen said.
($1 = €0.74)
Please visit the complete ICIS plants and projects database | http://www.icis.com/Articles/2010/03/05/9340487/pkn-orlen-to-start-up-600000-tonneyear-pta-plant-this.html | CC-MAIN-2015-22 | refinedweb | 149 | 51.07 |
Introduction to digital signatures in .NET cryptography
November 14, 2013 7 Comments
Introduction
I’ve devoted the last few posts to cryptography in .NET: hashing, asymmetric and symmetric encryption. Digital signatures are yet another application of cryptography. They provide data integrity and non-repudiation. This latter means that a user cannot claim that he or she wasn’t the one how signed a particular – digital – document. As public keys can be distributed to other users for encryption purposes they are not good candidates for ensuring non-repudiation. So we need to use the sender’s private key with which the contents of a message can be signed. The contents will be hashed. “Signing” means encrypting with the sender’s private key.
Here’s a flow diagram of the process:
In this scenario we’d like to send some information to another person in a secure way. We want to encrypt it so that only that person can see it and we also want to sign that message so that the receiver will know that it came from us.
The message we want to send is shown on the left of the diagram as “plain text”. The next step is the same as what we saw in asymmetric encryption: we encrypt the message with the receiver’s public key. We get the cipher text as the result. We then hash that cipher text so that we know that it won’t be tampered with while it’s transmitted to the receiver. In addition it’s not necessary to sign the entire data content as it can potentially grow very large and asymmetric encryption is rather slow – we don’t want to waste a lot of time just signing large size data.
So instead of signing the actual cipher text we get the hash of it, we encrypt the hash using our own private key. The result is a digital signature and a cipher text. The cipher can only be encrypted by the receiver using their private key. On top of that the hash is signed with our private key. The receiver can decrypt the signature using our public key since – recall from the post on asymmetric encryption – the private and public keys are inverses of each other. The receiver will have access to our public key. If the decryption succeeds then the receiver will know that it must have come from someone who has the correct private key.
This all probably sounds a bit complex at first but I hope the demo will make it clear how it all works.
The creation of the cipher text is not actually required for digital signatures. The main purpose of digital signatures is tamper-proof messaging. In the demo we’ll go for the full encryption cycle – if you don’t require the encryption bit in your code then you can simply ignore it.
Demo
Create a new Console app in Visual Studio. Insert a class called Sender. Add two class level fields to Sender.cs:
private string _myRsaKeys = "..."; private string _receiversPublicKey = "...";
I’ve shown you some techniques in the previous post on how to generate valid RSA keys, I won’t repeat it here. The important thing here is that _myRsaKeys will be an XML string including both my private and public keys, so copy the entire XML contents there. Then generate another set of RSA keys and save the public key portion of it in _receiversPublicKey, but don’t throw away the rest, it will be needed later when we look at the Receiver. Again, refer to the previous post to see how to keep the private and public key portions of an RSA key pair in an XML string variable. This is a simulation of a case where I received the public key of a partner whome I wish to send encrypted messages.
We’ll need RSA ciphers for the sender and receiver so add the following methods to Sender.cs:
private RSACryptoServiceProvider GetSenderCipher() { RSACryptoServiceProvider sender = new RSACryptoServiceProvider(); sender.FromXmlString(_myRsaKeys); return sender; } private RSACryptoServiceProvider GetReceiverCipher() { RSACryptoServiceProvider sender = new RSACryptoServiceProvider(); sender.FromXmlString(_receiversPublicKey); return sender; }
This should look familiar from the previous post. We’ll use our own private key in the GetSenderCipher method for creating the signature – if you get lost you can always refer back to the diagram above. The receiver’s public key will be needed in order to encrypt the plain text and create the cipher text. They will use their private key to do the decryption.
We can compute the hash of the cipher text using the following method:
private byte[] ComputeHashForMessage(byte[] cipherBytes) { SHA1Managed alg = new SHA1Managed(); byte[] hash = alg.ComputeHash(cipherBytes); return hash; }
This should look familiar from the post on hashing techniques in .NET. We’ll sign this hash instead of the entire data transmitted.
There’s a built in signature provider in .NET represented by the RSAPKCS1SignatureFormatter object which will come handy in the following method:
private byte[] CalculateSignatureBytes(byte[] hashToSign) { RSAPKCS1SignatureFormatter signatureFormatter = new RSAPKCS1SignatureFormatter(GetSenderCipher()); signatureFormatter.SetHashAlgorithm("SHA1"); byte[] signature = signatureFormatter.CreateSignature(hashToSign); return signature; }
The RSAPKCS1SignatureFormatter object then accepts an RSA provider to sign with which in this case will be our private key. We specify SHA1 as the hash algorithm for the signature. This is the signature that the receiver will verify using our public key.
The methods can be connected in the following public method:
public DigitalSignatureResult BuildSignedMessage(string message) { byte[] messageBytes = Encoding.UTF8.GetBytes(message); byte[] cipherBytes = GetReceiverCipher().Encrypt(messageBytes, false); byte[] cipherHash = ComputeHashForMessage(cipherBytes); byte[] signatureHash = CalculateSignatureBytes(cipherHash); string cipher = Convert.ToBase64String(cipherBytes); string signature = Convert.ToBase64String(signatureHash); return new DigitalSignatureResult() { CipherText = cipher, SignatureText = signature }; }
…where DigitalSignatureResult is a simple DTO:
public class DigitalSignatureResult { public string CipherText { get; set; } public string SignatureText { get; set; } }
The steps in the BuildSignedMessage correspond to the flow diagram: we encrypt the message, compute a hash of it and finally sign it.
Let’s test from Program.cs if it looks OK up to this point:
static void Main(string[] args) { Sender sender = new Sender(); DigitalSignatureResult res = sender.BuildSignedMessage("Hello digital sig!"); Console.WriteLine(res.CipherText); Console.WriteLine(res.SignatureText); Console.ReadKey(); }
Run the programme and if everything went well then you should see two sets of character-jungles in the console window.
Now let’s see what the receiver looks like. Add a new class called Receiver. Insert the following class level private fields:
private string _myRsaKeys = "..."; private string _senderPublicKey = "...";
Here the values will be the inverses of the _myRsaKeys and _receiversPublicKey fields of Sender.cs. Receiver._myRsaKeys will be the full XML version of Sender._receiversPublicKey. Conversely Receiver._senderPublicKey will be the reduced public-key-only version of Sender._myRsaKeys. The sender’s public key will be used to verify their signature.
To make this clearer I have the following values in Receiver.cs:
private string</RSAKeyValue>";
…and in Sender.cs:
private string</RSAKeyValue>";
We’ll need to set up sender and receiver RSA providers in the Receiver class as well:
private RSACryptoServiceProvider GetSenderCipher() { RSACryptoServiceProvider sender = new RSACryptoServiceProvider(); sender.FromXmlString(_senderPublicKey); return sender; } private RSACryptoServiceProvider GetReceiverCipher() { RSACryptoServiceProvider sender = new RSACryptoServiceProvider(); sender.FromXmlString(_myRsaKeys); return sender; }
We’ll also need the same hash computation method that was employed on the Sender’s side.
private byte[] ComputeHashForMessage(byte[] cipherBytes) { SHA1Managed alg = new SHA1Managed(); byte[] hash = alg.ComputeHash(cipherBytes); return hash; }
I realise that this is a lot of duplication but imagine that the Sender and Receiver are different applications with no possibility to have a shared project. It’s important they they set up details such as “SHA1” in the ComputeHashForMessage methods for consistency. If one specifies SHA1 and the other one SHA256 then the process will fail of course so the two sides must agree on a common platform. Usually the person who needs to send a message to someone else will need to comply with what the receiver has set up on their side.
The RSAPKCS1SignatureDeformatter object has a VerifySignature method that is very useful in our case:
private void VerifySignature(byte[] computedHash, byte[] signatureBytes) { RSACryptoServiceProvider senderCipher = GetSenderCipher(); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(senderCipher); deformatter.SetHashAlgorithm("SHA1"); if (!deformatter.VerifySignature(computedHash, signatureBytes)) { throw new ApplicationException("Signature did not match from sender"); } }
We’ll need to pass in the computed hash of the cipher text received from the sender and the signature bytes so that we can verify the authenticity of the message. If this method returns true then the receiver will know that the message must have originated from someone with the correct private key. Otherwise there’s reason to suspect that the message has been tampered with. In fact we need to recompute that hash of the cipher the same way the sender computed the hash. You can see that in the following public method in Receiver.cs:); byte[] plainTextBytes = GetReceiverCipher().Decrypt(cipherTextBytes, false); return Encoding.UTF8.GetString(plainTextBytes); }
This is the inverse of the BuildSignedMessage of Sender.cs. We send in the DigitalSignatureResult object that resulted from the encryption process on the sender’s side. The cipher and signature are converted back to byte arrays. Then the hash is recomputed and the signature is verified. If we get this far then we know that the message is authentic and we can decrypt the message.
The ExtractMessage can be called in Program.cs as follows:
static void Main(string[] args) { Sender sender = new Sender(); DigitalSignatureResult res = sender.BuildSignedMessage("Hello digital sig!"); Console.WriteLine(res.CipherText); Console.WriteLine(res.SignatureText); String decryptedText = new Receiver().ExtractMessage(res); Console.WriteLine(decryptedText); Console.ReadKey(); }
Run the application and you should see that the signature is correct and the message is correctly decrypted by the receiver.
Digital certificates
We’ll wrap up this post on a short intro into digital certificates. Certificates are another, more advanced way to make sure that a message is coming from the person who claims to be the sender of the message. They are often used in conjunction with web traffic. If you see https:// in the URL then you know that some certificate is involved. In that case it’s not plain TCP that’s used for data transmission but SSL – Secure Sockets Layer – and TLS – Transport Layer Security.
A digital certificate is basically a public key assigned to a particular entity, like what a registration number is to a car. The number plate can be used to verify the owner of the car. The driver presents an ID card and if the data on the ID card matches what the police registry says about the owner of the car then the “certificate” is accepted. Otherwise the driver may have stolen the car or the number plate.
The format that a digital certificate follows is usually an X509 format. It contains an issuer, a validity period, the public key and the issuer’s signature. The digital signature helps us validate the public key of the sender. This process requires a certain level of trust in the issuer of the certificate. There are trusted issuers, so called Certificate Authorities (CAs), that the browsers have on their trusted issuers’ list.
It is the CA that signs the public key. They basically tell you like “we attest that the public key in this certificate comes from the owner of the public key”. The browser will have a list of those approved CAs and their public keys so they can validate signatures attached to these certificates.
So when the owner of the car presents an ID then it cannot just be any type of ID, it must have been issued by some authority. The authority attests through the ID that the person is really the one the ID claims them to be. This ties in well with claims-based security.
TLS and SSL are responsible to do the encryption between web browsers and web servers to make sure that the messages are not tampered with. You can use self-signed certificates for testing but if you use it in production then the web browser will warn you that the certificate didn’t come from one of the trusted CAs.
In other cases you may see that the browser warns that the certificate comes from a trusted CA, so the certificate is itself correct, but the domain name within the certificate is different from the domain name I’m visiting. It may be a sign that someone stole someone else’s certificate.
You can view the list of posts on Security and Cryptography here.
Thanks for this post and all the others, I read all your posts, great series on cryptography, do you ever provide working code examples, for example on gitHub?
cheers Damien
Thanks for your comment.
No, I haven’t thought of that too much yet, but now that you mention it I might load up the example codes in the future. I have only uploaded the DDD skeleton project up to this point.
My idea was that if people follow the instructions in the posts and write the example code themselves then they will learn more.
//Andras
Pingback: Lindermann's Blog | Criptografia Assimétrica
Hi Andras, I have tryed your code example and it give me an error “key doesn’t exist” in the following method:);
this line==>> byte[] plainTextBytes = GetReceiverCipher().Decrypt(cipherTextBytes, false);
return Encoding.UTF8.GetString(plainTextBytes);
}
please can you help me?.
Thanks
Pedro
Hi Pedro,
I’ve gone through the post step by step and it works without errors for me. Please check especially if you’ve set up the _myRsaKeys, _senderPublicKey and _receiversPublicKey private fields in both Sender and Receiver.cs.
You can download the entire sample from github:
//Andras
Hi Andres,
How to implement digital signature in asp.net webapi
Hi Ravinder, there’s a series dedicated to cryptography and digital signatures on this blog, check out the Security and Cryptography page. Look at the post entitled “Introduction to digital signatures in .NET cryptography” to get you started. //Andras | https://dotnetcodr.com/2013/11/14/introduction-to-digital-signatures-in-net-cryptography/ | CC-MAIN-2020-24 | refinedweb | 2,313 | 55.54 |
Months ago, I decided to study Angular. When I was doing some advance and create some app using it, I realize that Angular 2 is in Developer preview, so its matter of time that its going to be realeased. Because Angular 2 is not going to be compatible with Angular 1 ,and there are a lot of changes, the question is if its better to continue developing with Angular 1.x or start developing Angular 2.
Its a fact that not always we have to be with the last of versions, or the newest language of the market, but in this case, the app is still small so I could change with out problems.
I've played around with Angular 2 and watched/read some discussions so assuming you're comfortable with Angular 1 then here is a brief over view of things you'll notice that are different in Angular 2.
In a basic structure you will have a
app/ts folder where you'll be doing most your work and a
app/js where that gets told compiled by a
tsconfig.json file that will sit at the root of your project. You'll find in the
app/js folder files with a
.js.map extension. They "map" your ".ts" files to your browser for debugging as your browser cannot read native typescript.
If you're thinking I have to learn a whole new language?.... Yes, you do, but don't find this one too intimidating, this should make your development easier as seen in my #2, I felt like I had a good grasp on it after just a few hours playing with it.
This one you may have been implied as #1 states Angular 2 is in Typescript. Angular 2 is still a MV* but you'll be using 'components' as a way to bind code to your templates for instance take the following
import {component} from {angular2/core}; @component({ selector:'my-app', template: '<h1> Hello World! </h1>' }) export class AppComponent {}
Here think of the
import statement as your dependency injection in a v1 controller. You use
import to import your packages, where the
import {component} says you'll be making a
component you'd like to bind to your
HTML.
Notice the
@component decorator you have a
selector and
template. Here think of the
selector as your
$scope that you use like you use v1
directives where the name of the
selector is what you use to bind to your HTML like so
where
<my-app> is the name of your custom tag you'll use that will act as a place holder for whats declared in your template i.e.
<h1> Hello World! </h1>. Whereas this would like like the following in v1.
HTML
<h1>{{hello}}</h1>
js
$scope.hello = "Hello World!"
Also from my understanding if add something between these tags for instance
<my-app> Loading... </my-app>
then it display that "Loading..." in the view while the template is loading (the
<h1> Hello World! </h1> in our case)
note that what's declared in
template is the path or the raw HTML you'll be using in your
HTML in your
selector tag.
whereas a fuller implementation of Angular 1 would look more like
HTML
<h1 ng-{{hello}}</h1>
In v1 this would look something like
js
angular.module('controller', []) .controller('myCtrl', function( $scope) { $scope.hello = "Hello World!" })
This is what I really like about v2 as I found directive had the steeped learning curve for me in v1 and even when I had them figured out I often had the
css render. | https://codedump.io/share/JWOOmooHqpL8/1/angular-vs-angular-2 | CC-MAIN-2018-09 | refinedweb | 601 | 69.92 |
Tom's Journal Tom's Slashdot Journal en-us Copyright 1997-2008, SourceForge, Inc. All Rights Reserved. 2008-05-16T00:19:53+00:00 SourceForge, Inc. help@slashdot.org Technology hourly 1 1970-01-01T00:00+00:00 Tom's Journal Giving up on Wikipedia I'm giving up on Wikipedia today. Which means no more editing, and a lot less using it.The reason is one word: Deletionism.The details are three points:a) It goes so against the spirit of Wiki, because a deletion is a non-reversable, non-reviewable change. The history gets lost, all work of everyone gets lost, and nobody can see and check it later. Every other change in a Wiki is documented, and you can see exactly what was changed, by whom, and when. Not so with a deletion. If you are lucky, you can find out that there used to be a page named this, but nothing about its contents.b) It is destructive. You put hours of work into something, and it just gets deleted. Not updated, changed or even vandalised, but deleted. Poof, gone, as if it never existed. Have you ever lost your documents folder with no backup? Then you know the empty feeling. Don't do that to people, especially not those who might be new (and could have become worthy contributors, if they hadn't be hit in the face for their first attempt).c) Notability-Nazis. Some time ago, the main reasons for deletion where actually valid. Nowadays, the main reason for deletion is notability, or in simpler words "I've never heard about this". My position on notability is very simple: Add a "non-noteable" category, namespace or at least archive and move stuff there, but it should not even be on the list of reasons for deletion. To me, an encyclopedia is where I look up the stuff that I've never heard about, so it'd better be there.So far all these reasons, and a few minor ones, I've really switched sides over the past few weeks. I think I even begin to understand why large parts of the science community view Wikipedia with scepticism, and that much of the media's portrayl of their reasons is grossly simplified. Tom 2008-01-30T09:56:06+00:00 internet | http://slashdot.org/~Tom/journal/rss | crawl-001 | refinedweb | 387 | 74.39 |
Hey,
In the core of
concourse, volumes provide ways for the various executions to
have some form of state - be it in the form of root filesystems (acting as
the storage underneath container images) or as a place for, let's say, a
repository that was cloned via
git-resource - see
concourse/baggageclaim.
One of the implementations that we have of such abstraction users
overlayfs,
a filesystem in the upstream kernel that's been used quite a lot when it comes
to containers recently.
In a very
concourse-agnostic way, in this article I try to go very
pragmatically through some of the concepts that
overlayfs is based on, as well
as a bit deep into why when we tie
overlayfs with file ownership changes,
things can get slow.
raison d'etre (at least in the “containers world”)
The big deal about
overlayfs when it comes to containers (as I see, at least)
is the ability of presenting a directory tree that consists of multiple other
directory trees combined in a way that changes to it do not affect the
originating trees that were combined.
That is, providing a copy-on-write “layer” on top of the union of multiple other directory trees.
Let's dig into those two.
the union of multiple directory trees
An overlay-filesystem tries to present a filesystem which is the result over overlaying one filesystem on top of the other. […] an ‘upper’ filesystem and a ‘lower’ filesystem.
from kernel.org's overlayfs entry
What that means is that if we have, let's say, two distinct directory trees like the following:
dir1 dir2 / / a a b c
overlayfs is able to present a third directory (say,
dir3) that represents
putting, say,
dir1 on top of
dir2 (the order matters here):
dir3 / a b c
Naturally, this implies that
overlayfs needs to “break ties” when a conflict
occurs (like above, where we have
a in both
dir1 and
dir2).
When a name exists in both filesystems, the object in the ‘upper’ filesystem is visible while the object in the ‘lower’ filesystem is either hidden or, in the case of directories, merged with the ‘upper’ object.
Using that terminology, here's how we can see that playing out in in practice
(if you want to know more about
mount in general, make sure you check out
understanding mount namespaces)
# set up the directory hierarchy necessary for getting a final merged # view (`./merged`) based of two trees: `./upper` and `./lower`. # # ps.: `work` (passed as argument to `workdir`) is required for # overlayfs to be able to perform atomic actions. # mkdir ./{merged,work,upper,lower} touch ./upper/{a,b} touch ./lower/{a,c} sudo mount \ -t overlay \ overlay \ -o lowerdir=./lower,upperdir=./upper,workdir=./work \ ./merged . ├── lower │ ├── a │ └── c ├── upper │ ├── a │ └── b ├── merged < final view │ ├── a (from upper) │ ├── b (from upper) │ └── c (from lower) └── work < internal └── work
upper and lower
While both
upper and
lower contribute to the final merged view in pretty
much the same way from a “read” perspective, from a “write”, they're quite
different.
That's because lower layers are never written to - they only provide data -, while an upper layer can receive mutations (if not readonly).
For instance, considering the example above where
c comes solely from
lower,
and
b from upper, we can try writing to each in the
merged tree and see what
happens.
echo "will-persist" > ./merged/b echo "wont-persist" > ./merged/c
Both writes work:
cat ./merged/b will-persist cat ./merged/c wont-persist
But in the underlying directory trees:
cat ./upper/b will-persist cat ./lower/c (empty)
what about container tech?
What ends up happening in that case is that multiple lower directory trees are utilized (the container image layers), and an empty upper directory is put on top of those - this ends up creating a final view of a directory tree that contains the entire container image mounted, but whose writes do not ever mutate the original contents: they end up always going to the upper directory (the “ephemeral storage”).
For instance, let's say we have a container image that's made up of two layers:
layer1: layer2: /etc /bin myconf.ini my-binary
With that, a container runtime would then take those two layers are lower
directories, create an empty
upper dir, and mount that somewhere:
sudo mount \ -t overlay \ overlay \ -o lowerdir=/layer1:/layer2,upperdir=/upper,workdir=/work \ /merged
And then use that
/merged as the rootfs of the container.
copy-on-write
When in the previous section we did a write to a file in the
merged directory
that came from the readonly
lower directory tree, what happened there was
copy-on-write taking place.
Because we can't modify the files on that layer,
overlayfs takes care of
reading all of the data (and metadata) from that file, copying it up to the
upper directory, and only then, presenting to our application the file
descriptor that we can use for writes.
When a file in the lower filesystem is accessed in a way the requires write-access, such as opening for write access, changing some metadata etc., the file is first copied from the lower filesystem to the upper filesystem (
copy_up).
from kernel.org's overlayfs entry
To see this in practice, consider the following directory configuration that's a simplification of the previous case.
upper: lower: merged: / / / a a (from upper)
Given that the filesystem employes copy-on-write semantics, despite us having
the file visible under both
./lower and
./merged, even with two distinct
device numbers, in the end there's no such duplication, until we decide to
change it (“on write”).
More specifically, until we decide to open the file for writing:
open("./merged/a", O_RDWR) | | *--> copy up to `merged` --> available for writes w/out change to the file under `lower`.
For instance, we can have a 1GB file in a lower dir, then see how we end up paying the price of a copy up whenever we try to open it as read-write.
First, let's setup the directories (just how we did before):
# create the dirs # mkdir ./{merged,work,upper,lower} # write 1GB to `./lower/a` # dd if=/dev/zero of=./lower/a bs=$((1 << 12)) count=$((1 << 18)) # mount # sudo mount \ -t overlay \ overlay \ -o lowerdir=./lower,upperdir=./upper,workdir=./work \ ./merged
Then, create a program that first opens the file as readonly (
O_RDONLY), then
“changes its mind”, opening it again, now as read-write (
O_RDWR):
#include <fcntl.h> #include <stdio.h> #include <unistd.h> static const char* file = "./merged/1GB"; int main(int argc, char** argv) { int fd; fd = openat(AT_FDCWD, file, O_RDONLY); if (!~fd) { perror("openat O_RDONLY"); return 1; } if (!~close(fd)) { perror("close"); return 1; } fd = openat(AT_FDCWD, file, O_RDWR); if (!~fd) { perror("openat O_RDWR"); return 1; } return close(fd); }
With the use of
strace, we can see the difference in time between opening
the file as readonly and read-write:
strace -T -e openat ./a.out openat(AT_FDCWD, "./merged/a", O_RDONLY) = 3 <0.000110> openat(AT_FDCWD, "./merged/a", O_RDWR) = 3 <0.297918> | .-----------------------------. | .-----------. | arguments passed | time taken syscall return
“seeing” the price of specific copy ups
It turns out that it's quite easy to “accidentally” pay the price of a copy up without even knowing - open the file with the wrong flag, and you'll force a copy up.
For instance, it's been the case that
concourse needs to shift the ownership
of all files in a container image if it sees that it needs to translate that
image from
unprivileged to
privilged, forcing every file to be
copyed up.
While one can initially think that there's only the cost associated with
N
chown(2)s syscalls taking place (which is already something in its own), in the
case of
overlayfs, that also means adding the extra disk io for cloning each
of those files.12
Using a tool like
bpftrace we can see, e.g., how much time we've been
spending on that very specific case:
chown(2)ing.
Given that the copy up of data occurs at
ovl_copy_up_data
static int ovl_copy_up_data(struct path* old, struct path* new, loff_t len) { // ... }
we can trace that and discover the whole stack trace that leads to it:
k:ovl_copy_up_data { printf("%s", kstack); }
telling us then:
ovl_copy_up_data+1 ovl_do_copy_up+1578 ovl_copy_up_one+624 ovl_copy_up_flags+167 ovl_copy_up+16 ovl_setattr+78 notify_change+761 chown_common+461 do_fchownat+147 __x64_sys_chown+34 do_syscall_64+90 entry_SYSCALL_64_after_hwframe+68
Now, given that we want to capture those copy ups that originated only from
chown(2) syscalls, whose internal implementation delegates to
ovl_setattr:
static const struct inode_operations ovl_file_inode_operations = { .setattr = ovl_setattr, .permission = ovl_permission, .getattr = ovl_getattr, .listxattr = ovl_listxattr, .get_acl = ovl_get_acl, .update_time = ovl_update_time, .fiemap = ovl_fiemap, };
we can set up one extra hook that records the thread id that's going through
setattr so that we only capture the data being copied up through
chown(2)s.
#!/snap/bin/bpftrace BEGIN { printf("%-8s %-16s %-16s %-16s %-16s\n", "PID", "COMM", "NAME", "LEN(B)", "ELAPSED (ms)"); } kprobe:do_fchownat { // keep track of the filename // @fname[tid] = str(arg1); } kprobe:ovl_copy_up_data / @fname[tid] != "" / { // keep track of the size of the file being copied up // as well as its start timestamp (in nanosecs) // @len[tid] = arg2; @start[tid] = nsecs; } kretprobe:ovl_copy_up_data / @len[tid] != 0 / { // once the coping finished, display the values // printf("%-8d %-16s %-16s %-16d %d\n", pid, comm, @fname[tid], @len[tid], (nsecs - @start[tid]) / 1000000); // free those spaces // delete(@len[tid]); } kretprobe:do_fchownat { // free those spaces // delete(@fname[tid]); delete(@start[tid]); }
That running, we can see it collecting data in practice:
PID COMM NAME LEN(B) ELAPSED (ms) 12399 sample.out ./merged/a 1073741824 787
1: it's possible to avoid the copying of the underlying data when
chown(2)ing if using “metadata only copy up”, but we don't have that activated
at the moment. Unfortunately, that only landed in 4.19, which is still not all
that disseminated.
See “Overlayfs memory usage improvements” in 4.19.
2: we could in the future leverage
shiftfs and avoid the whole
chown(2)ing altogethere - Canonical has been shipping their kernels with it
(mainly for LXD as far as I can tell), which is a good indication that it could
come to upstream at some point soon - see “trying out
shiftfs | https://ops.tips/notes/practical-look-into-overlayfs/ | CC-MAIN-2020-05 | refinedweb | 1,717 | 56.08 |
This is the mail archive of the libstdc++@sources.redhat.com mailing list for the libstdc++ project.
_G_config.h is complaining about: 1) mbstate_t typedef not defined. This is defined in AIX wchar.h if _XOPEN_SOURCE=500, which is the default. Somehow the build is causing _XOPEN_SOURCE to be defined to something else. 2) __off_t and __off64_t typedefs not defined. I cannot see where these typedefs would be defined. This appears to be a glibc extension in bits/types.h. I would have expected __off_t and __off64_t to be defined in terms of off_t and off64_t, as with __mbstate_t. libio.h is complaining about: 1) _IO_lock_t undefined: /* Handle lock. */ #ifdef _IO_MTSAFE_IO # if defined __GLIBC__ && __GLIBC__ >= 2 # include <bits/stdio-lock.h> # else /*# include <comthread.h>*/ # endif #else typedef void _IO_lock_t; #endif _IO_MTSAFE_IO is defined by _G_config.h and the system is not using glibc, therefore _IO_lock_t never is defined. Those are the failures that I have tracked down so far. David | http://gcc.gnu.org/ml/libstdc++/2000-09/msg00113.html | crawl-001 | refinedweb | 161 | 70.6 |
C++, name mangling and function signatures
One of the guys in the office was having problems compiling POVray on solaris - the last link step kept failing with an unknown symbol. It turns out that the POVray source had declared the symbol in the .h file using the pattern:
int function(const char *, unsigned int);but defined the function in the .cpp file using the pattern:
int function(const char *, const unsigned int) {}When it came to the link step, the compiler complained that other object files referencing the function could not link, because the function as declared was not in any of the linked object files. We can easily ascertain this fact using the nm utility. To more easily see the differences, you need to use the -C option, which performs the neat-oh C++ name demangling.
The example code is here. Which demonstrates this issue precisely.
First we compile, but do not link the .cpp files. To perform this step do: CC -c *.cpp.
% nm -C *.o inter.o: [Index] Value Size Type Bind Other Shndx Name [2] | 0| 25|FUNC |GLOB |0 |2 |int function(const char*,const unsigned) [__1cIfunction6FpkckI_i_] [1] | 0| 0|FILE |LOCL |0 |ABS |inter.cpp link.o: [Index] Value Size Type Bind Other Shndx Name [4] | 0| 0|NOTY |GLOB |0 |ABS |__fsr_init_value [2] | 0| 0|FUNC |GLOB |0 |UNDEF |int function(const char*,unsigned) [__1cIfunction6FpkcI_i_] [1] | 0| 0|FILE |LOCL |0 |ABS |link.cpp [3] | 0| 41|FUNC |GLOB |0 |2 |mainwithout the demangling, you would see the function names in brackets, which are not easy to distinguish, but once you add in the demangling the difference is obvious. Of course even if you #included the .h file into the .cpp file to 'type enforce' the function signature, because to the compiler they are not the same function it simply presumes that the declaration in the .h file is for another function.
It is annoying, but you have to pay attention to these things when you're writing C++.
Contrast the patterns observed when we compile using the gnu compiler: g++ -c *.cpp
% nm -C *.o inter.o: [Index] Value Size Type Bind Other Shndx Name [2] | 0| 0|SECT |LOCL |0 |1 | [3] | 0| 0|SECT |LOCL |0 |2 | [5] | 0| 0|SECT |LOCL |0 |4 | [4] | 0| 0|SECT |LOCL |0 |3 | [6] | 0| 10|FUNC |GLOB |0 |1 |function(const char*, unsigned) [_Z8functionPKcj] [1] | 0| 0|FILE |LOCL |0 |ABS |inter.cpp link.o: [Index] Value Size Type Bind Other Shndx Name [5] | 0| 0|SECT |LOCL |0 |5 | [2] | 0| 0|SECT |LOCL |0 |1 | [3] | 0| 0|SECT |LOCL |0 |3 | [4] | 0| 0|SECT |LOCL |0 |4 | [6] | 0| 0|SECT |LOCL |0 |7 | [9] | 0| 0|NOTY |GLOB |0 |UNDEF |__gxx_personality_v0 [8] | 0| 0|NOTY |GLOB |0 |UNDEF |function(const char*, unsigned) [_Z8functionPKcj] [1] | 0| 0|FILE |LOCL |0 |ABS |link.cpp [7] | 0| 53|FUNC |GLOB |0 |1 |mainWho is correct at this step? I don't quite have the answer for that, as if you tried to define two functions that differed by that const, the compiler has no way to disambiguate them. If you're being really picky, you could say that dropping the const against standard pass-by-value variables is incorrect; after all it's a function taking a const, and it's declaration should respect that. February 08, 2005 01:09 PM GMT Permalink
The curse of make (svr)
Sounds like it should be a movie title. The curse of the black-hearted and arcane makefiles.
On one of our projects we're constantly adding subdirectories of tests that need to be picked up by the harness. Somebody started to place the names of the subdirectories in a variable in the Makefile, so it looked like:
SUBDIRS=acl mount umountThis is all very fine and well until we start having 50+ directories, and a policy which states that the subdirectories have to be kept in order and that you can't exceed 80 characters per line (queue lots and lots of backslashes and rearranging of lines every time you add a new subdirectory). This is sub-optimal, so I changed the SUBDIRS variable like so:
SUBDIRS :sh = /bin/ls */[Mm]akefile | sed -e '@/[Mm]akefile@@g'The :sh tells make that the SUBDIRS variable is set by the output from the ls command filtered through the sed command. Short and simple.
Welcome to the world of development. Sometimes we need to EXCLUDE certain subdirectories - the functionality isn't there (it happens), the command line options change (ui reviews cause this a lot).
Fixing this is a bit more difficult. The first try is normally:
This does not work!!!!
ALL_SUBDIRS :sh = /bin/ls */[Mm]akefile | sed -e '@/[Mm]akefile@@g' EXCLUDE_SUBDIRS = cli SUBDIRS :sh = \ for all in $(ALL_SUBDIRS); do \ for excl in $(EXCLUDE_SUBDIRS); do \ if [ "$excl" = "$all" ]; then \ all=""; \ fi; \ done; \ echo $all; \ doneThe reason why this does not work is that at the first pass, the variables ALL_SUBIRS and EXCLUDE_SUBDIRS are not set (it's a make thing), so what we need to do is add a level of indirection to the solution.
ALL_SUBDIRS :sh = /bin/ls */[Mm]akefile | sed -e '@/[Mm]akefile@@g' EXCLUDE_SUBDIRS = cli FOO = \ for all in $(ALL_SUBDIRS); do \ for excl in $(EXCLUDE_SUBDIRS); do \ if [ "$excl" = "$all" ]; then \ all=""; \ fi; \ done; \ echo $all; \ done SUBDIRS = $(FOO:sh)This works, but it contains a subtle bug! If you don't have any entries in EXCLUDE_SUBDIRS, then the expansion fails with a syntax error: sh: syntax error at line 1: `;' unexpected . This error is caused as the code: for var in <>; do requires a token, so we have to change it once more:
ALL_SUBDIRS :sh = /bin/ls */[Mm]akefile | sed -e '@/[Mm]akefile@@g' EXCLUDE_SUBDIRS = cli FOO = \ for all in $(ALL_SUBDIRS); do \ for excl in $(EXCLUDE_SUBDIRS) WILLNEVERMATCH; do \ if [ "$excl" = "$all" ]; then \ all=""; \ fi; \ done; \ echo $all; \ done SUBDIRS = $(FOO:sh)but this means that we need to go through the loop even if EXCLUDE_SUBDIRS is never set, so more changes:
ALL_SUBDIRS :sh = /bin/ls */[Mm]akefile | sed -e '@/[Mm]akefile@@g' EXCLUDE_SUBDIRS = cli FOO = \ if [ -n "$EXCLUDE_SUBDIRS" ]; then \ for all in $(ALL_SUBDIRS); do \ for excl in $(EXCLUDE_SUBDIRS) WILLNEVERMATCH; do \ if [ "$excl" = "$all" ]; then \ all=""; \ fi; \ done; \ echo $all; \ done; \ else\ echo $(ALL_SUBDIRS); \ fi SUBDIRS = $(FOO:sh)This has two lessons associated with it.
- Make is not easy
- remember to test all the variants of a solution
What file is playing under xmms
Here's a simple program that determines what file is playing under xmms. Short, sweet and to the point. You need the xmms headers and libintl, but apart form those it should compile just dandily (big ifs of course).
#include <sys/types.h> #include <xmmsctrl.h> #include <glib.h> #include <stdio.h> int main(int argc, char **argv) { gint session = 0; gchar *file; gint pos; if (xmms_remote_get_version(session) == 0) { return (0); } pos = xmms_remote_get_playlist_pos(session); file = xmms_remote_get_playlist_file(session, pos); if (file != NULL) { printf("%s\n", file); } }February 03, 2005 03:27 PM GMT Permalink
Symbolic annoyance, preprocessor hints and tips
One of the guys in the office was having a compilation problem (hey tim!). Neither gcc nor sun cc were being (too) helpful in their error messages.
The piece of code in particular was a function declaration like:
void foo(food_t *);When it was compiled both sun cc said:"foo.c", line 4: syntax error before or at: *, and gcc said: foo.c:4: error: syntax error before '*' token which is not a particularly useful error message. Even when the code is compiled with full warnings (-v for sun cc, -Wall for gcc) we get the same useless error message.
Experience tells us that this means that the data type food_t has not been declared, as a result the food_t * parses as a syntax error.
This was part of a (moderately) complicated piece of code, we knew the data type was being declared in one header file, but didn't know if that file was being included in this particular piece of code. In cases like this the preprocessor is a boon. We knew that a header file foo.h was needed so send in the preprocessor. Using the -E option to gcc (or sun cc), it only preprocesses the file, producing a stream of output.
Interpreting the output is a quite easy. In this case we were looking for a typedef unsigned int food_t;, which would tell us that the variable datatype had been defined. In this case it had not, meaning, in our case that the header file foo.h had not been included as part of the foo.c file. We #included the file, and lo and behold we made it to the next step.
I've grossly simplified the example to illustrate a point, but invariably when you encounter syntax errors in your c files, and are stumped for the reason why, it's only one of the many tools in your arsenal for finding out the reason why. After all what kind of ill effects are being induced in your code as a result of using complicated #define macros. February 02, 2005 06:13 PM GMT Permalink
playing around with mice and windows
Updated: 2005/02/03 - it didn't build so well on Linux.
This is a bit of code for Solaris which allows you to:
- Move your mouse around the screen
- Resize the window under the mouse
- Move the window under the mouse
The meaning of the -R/usr/openwin/lib for solaris is to set the run-time linker lookup to try the /usr/openwin/lib path for libraries, as part of the symbol resolution step. Otherwise it relies on either the LD_LIBRARY_PATH (It is evil), or the crle path (man crle - it is neat).
For Linux you normally have the /etc/ld.so.conf file, which typically has /usr/X11R6/lib in there (and if you've got qt, probably has /usr/lib/qt3/lib as well). If you want to find out more abou tthis then look at the info/man page for ldconfig.
I have this code for window managers that don't have mouse/window movement shaping hotkeys of their own (e.g. fvwm). It makes the gnome window
managers almost useful. It should be portable to other X based OS's.
It comes with the usual preamble - use it at your own risk, if it eats your cat then it's not mine (or Sun's) fault.
#include <alloca.h> #include <libgen.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #if defined(LINUX) #include <string.h> #include <stdint.h> #endif #include <sys/types.h> #include <unistd.h> #include <X11/X.h> #include <X11/Xlib.h> static char *appname; struct systeminfo { int rootx; int rooty; int width; int height; int winx; int winy; Display *display; Window rootwin; Window undermouse; XWindowAttributes childattr; }; static char *actionhelp(); static void usage(int exitcode) { (void) printf("usage: %s {<action> [+-]<valx>[%%] [+-]<valy>[%%] }+ \n", appname); (void) printf("\tif you use +- it is taken as a delta, otherwise it is" " absolute\n"); (void) printf("Where action is one of %s\n", actionhelp()); (void) printf("\tFor example %s mm 0 0 would move the mouse to the " "\n\ttop left of the screen\n", appname); exit(exitcode); } static int XError(Display *disp, XErrorEvent *code) { char buffer[2000]; XGetErrorText(disp, code->error_code, buffer, 1999); (void) printf("Error: %s\n", buffer); return (0); } static int isdelta(const char *value) { return ((*value == '-') || (*value == '+')); } static int isperc(const char *value) { return ((strrchr(value, '%') - value) == (strlen(value) - 1)); } static int transform(const char *val, int start, int maxMetric) { int av = atoi(val); /*(void) printf("%s %d %d %d\n", val, av, start, maxMetric);*/ if (isdelta(val) && isperc(val)) return (start + (int)(maxMetric * av / 100)); if (isdelta(val)) return (start + av); if (isperc(val)) return ((int)(maxMetric * av / 100)); return (av); } static void getxy(struct systeminfo *info, const char *xarg, const char *yarg, int *xval, int *yval, uintptr_t offx, uintptr_t offy) { /*LINTED*/ *xval = transform(xarg, *((int *)((char *)info + offx)), isperc(xarg) && isdelta(xarg) ? info->width : WidthOfScreen(DefaultScreenOfDisplay(info->display))); /*LINTED*/ *yval = transform(yarg, *((int *)((char *)info + offy)), isperc(yarg) && isdelta(yarg) ? info->height : HeightOfScreen(DefaultScreenOfDisplay(info->display))); /* (void) printf("%d %d\n", *xval, *yval); */ } static void MoveMouse(struct systeminfo *info, int xarg, int yarg) { XWarpPointer(info->display, None, info->rootwin, 0, 0, 0, 0, xarg, yarg); } static void ResizeWindow(struct systeminfo *info, int xarg, int yarg) { XResizeWindow(info->display, info->undermouse, xarg, yarg); } static void MoveWindow(struct systeminfo *info, int xarg, int yarg) { XMoveWindow(info->display, info->undermouse, xarg, yarg); } #define funtostring(FV) #FV, FV static struct activity { char *action; char *helpstring; void (*function)(struct systeminfo *, int, int); uintptr_t offsetx; uintptr_t offsety; } activitylist[] = { { "mm", funtostring(MoveMouse), offsetof(struct systeminfo, rootx), offsetof(struct systeminfo, rooty) }, { "rw", funtostring(ResizeWindow), offsetof(struct systeminfo, width), offsetof(struct systeminfo, height) }, { "mw", funtostring(MoveWindow), offsetof(struct systeminfo, winx), offsetof(struct systeminfo, winy) }, { NULL, NULL, NULL } }; static char *actionhelp(void) { static char *buffer = NULL; char *stribo; struct activity *ack = activitylist; stribo = alloca(1024); if (buffer != NULL) return (buffer); buffer = calloc(1, getpagesize()); while (ack->action != NULL) { (void) sprintf(stribo, "%s(%s) ", ack->action, ack->helpstring); (void) strcat(buffer, stribo); ack++; } return (buffer); } extern Window XmuClientWindow(Display *, Window); static void InitializeWinfoid(struct systeminfo *winfoid) { unsigned int mask; winfoid->rootwin = XDefaultRootWindow(winfoid->display); XQueryPointer(winfoid->display, winfoid->rootwin, &winfoid->rootwin, &winfoid->undermouse, &winfoid->rootx, &winfoid->rooty, &winfoid->winx, &winfoid->winy, &mask); XGetWindowAttributes(winfoid->display, winfoid->undermouse, &winfoid->childattr); winfoid->winx = winfoid->childattr.x; winfoid->winy = winfoid->childattr.y; winfoid->undermouse = XmuClientWindow(winfoid->display, winfoid->undermouse); XGetWindowAttributes(winfoid->display, winfoid->undermouse, &winfoid->childattr); winfoid->width = winfoid->childattr.width; winfoid->height = winfoid->childattr.height; } int main(int argc, char **argv) { struct systeminfo winfoid; int atarg; int thisx, thisy; char *disp; appname = basename(strdup(argv[0])); XSetErrorHandler(XError); if ((argc < 3) || ((argc - 1) % 3)) usage(1); disp = XDisplayName(NULL); if (disp == NULL) disp = ":0.0"; winfoid.display = XOpenDisplay(disp); if (winfoid.display == NULL) { (void) fprintf(stderr, "Can't open display %s\n", disp); exit(2); } InitializeWinfoid(&winfoid); /* handle arguments */ for (atarg = 1; atarg < argc; atarg += 3) { struct activity *atac = activitylist; while (atac->action != NULL) { if (strncmp(atac->action, argv[atarg], 2) == 0) break; atac++; } if (atac->action != NULL) { getxy(&winfoid, argv[atarg+1], argv[atarg+2], &thisx, &thisy, atac->offsetx, atac->offsety); atac->function(&winfoid, thisx, thisy); } } XCloseDisplay(winfoid.display); return (0); }January 27, 2005 05:03 PM GMT Permalink
fuser trickiness
I encountered this one a bit over a year ago while having a conversation with Ed in MPK (or is it a year and a half?). The fuser command is used to list the processes using a file system - fuser /home/bubba would list all the users of /home/bubba; and you can kill them too, using the -k option. So far so good.
What happens, though when you want to do something with the output?
haiiro[64i]~% fuser /home/bubba /home/bubba: 6780c 6760c 6758c 6756c 6502c 6422c 6404c 6368c 6332c 6331c 6330c 6322c 6308c 6301c 6206c 6081c 5951c 5879c 5756c 5251c 5247c 5201c 5092c 5004c 4992c 4987c 4985c 4982c 4980c 4968c 4952c 4920c 4672c 4080c 4079c 3990c 3989c 3987c 3985c 3983c 3981c 3979c 3975c 3973c 3969c 3963c 3943c 3939c 3937c 3935c 3898c 3896c 3893c 3891c 3882c 3880c 3836c 3834c 3831c 3769c 3726cit's a bit hard to parse? not so! What you can do is redirect stderr to /dev/null and magic happens
haiiro[64i]~% fuser /home/bubba 2>/dev/null 6781 6760 6758 6756 6502 6422 6404 6368 6332 6331 6330 6322 6308 6301 6206 6081 5951 5879 5756 5251 5247 5201 5092 5004 4992 4987 4985 4982 4980 4968 4952 4920 4672 4080 4079 3990 3989 3987 3985 3983 3981 3979 3975 3973 3969 3963 3943 3939 3937 3935 3898 3896 3893 3891 3882 3880 3836 3834 3831 3769No parse issues there. Then you can get full process information on each of the processes using a small bit of shell:
haiiro[64i]~% ps -o pid,args -p "$(fuser /home/bubba 2>/dev/null)" PID COMMAND 6206 /usr/openwin/bin/xterm -geom 80x25 -e /bin/zsh 3943 /usr/lib/evolution/1.4/evolution-alarm-notify --sm-config-prefix /evolution-ala 3939 nautilus --sm-config-prefix /nautilus-udaGgf/ --sm-client-id 11819cee2200010909 3935 metacity --sm-save-file 1106677632-2610-3195804027.ms 3880 /bin/ksh /usr/dt/config/Xsession2.jds 3834 /usr/dt/bin/sdt_shell -c unset DT; DISPLAY=:0; /usr/dt/bin/dt : : :Just what the doctor ordered for a sysadmin. January 27, 2005 10:38 AM GMT Permalink
Exit status from commands in a pipeline (ksh)
It's already answered in the comp.unix.shell FAQ, so stop asking me!
For the most part it's the slightly more compatible shells that require some work. As the ksh that ships in Solaris needs to be compatible with practically everything it's a bit tough to insist that people convert their scripts to languages that may not be present on all their machines.
The one I learned (moons ago) was to execute each of the elements in the background, and then wait on the exit status of each of the processes one by one.
mkfifo /tmp/fifo1 tar cf /tmp/fifo1 /blob& pid1=$! gzip -c /tmp/fifo1 >compressed.tar.gz& pid2=$! wait $pid1 tarstatus=$? if (( tarstatus != 0 )); then echo "tar command exited with: $tarstatus" fi wait $pid2 gzipstatus=$? if (( gzipstatus != 0 )); then echo "gzip command exited with: $gzipstatus" fiI'm never using this ever again! January 26, 2005 05:02 PM GMT Permalink
Solaris on laptops and summer/winter time
Well this one really caught me by surprise. I use Solaris on my laptop and since the the timezone changed I've noticed that the clock was out by an hour when I rebooted from Solaris to another operating system. It turns out that Solaris uses a configuration file - /etc/rtc_config to determine the number of seconds offset that your bios clock is offset relative to GMT. Solaris uses GMT on the inside, all dates and times presented to the user are manipulated via the TZ variable (so you can screw around with date displays using TZ=<foo> date).
There is a cron job for root, which runs at 2:01 every morning which executed /usr/sbin/rtc -c, which reconfigures the zone_lag entry in the /etc/rtc_config file. For some strange and unusual reason (call it sanity) my laptop is not powered on at this late time of night (think beer) so I was regularly an hour out of sync with the real world. xntp would kick in and the clock would be resynced with the real world until I rebooted into another OS where it would be incorrect. The fix is of course to execute the /usr/sbin/rtc -c program from the command line and when ntp next kicks off all is right with the world. It's a gotcha.
November 05, 2004 11:16 AM GMT Permalink
Copy on Write
Well I suppose it had to happen. Someone in the office asked me what was Copy on Write(aka COW) and what was the point of it.
To put it succinctly, Copy on Write is where you share a page until some destructive activity is performed on it, whereupon the writing process is given a new private copy (well duh!) of the page which is no longer set to copy-on-write, all the other processes that are sharing the page keep the shared, unchanged page themselves.
Implementations of copy on write typically mark a page as un-writeable, and when the page is written to it causes an access fault. Because the page is marked as a COW page the OS knows to deal with it differently than an ordinary access fault. It creates a new page that contains the content of the old page, removes the COW bit from this page and marks it read/writeable then returns control to the process at the same address that caused the access fault. This causes the code to execute this instruction again, writing the data to this new private copy. If it didn't do this then you would not have the correct data in this location in only the new copy.
Why do we do this? It's quite simple really - forking. Every time you fork it needs to duplicate the address space of the parent process in the child. If you made a complete copy of all the data pages every time you forked this would amount to a large amount of memory that has to be kept around just to deal with memory that may or may not be used in the sub-process. If you consider that a whole truck load of forks are simply just to perform an exec of a new process the creation and teardown of the data is an horrible waste of processor time and resources so we don't do this.
This leads to an interesting problem. If you have, say 50 processes, each with a 1M COW segment you need to ensure that you have 50M of available swap just in case. Ever wonder what the difference between the allocated and reserved swap was? These COW pages are just another part of this equation. October 27, 2004 09:48 PM IST Permalink
dtrace - ticks!
I have a lot of fun when I see Bryan making his dtrace demos. They're all cool, he says type this in: dtrace -i 'syscall:::entry { @[execname] = count() }', press enter, wait a few seconds and then hit control-c. You then get a result of the aggregation - the number of system calls per process over the time in question.
I'm a neat freak, A couple of seconds plus or minus a half a second is useless to me, I crave precision. That's why the tick provider is so cool.
Say I want a trace to run for 5 seconds, I add 'tick-5sec { exit(0) }' to the end of my script or command and after 5 seconds all the gathered data is output.
you can simply profile what a system is doing by 'tick-97hz { @[stack()] = count() }', which shows what happens in line with the clock.
That's not all, you can output data points every 'tick' intervals, so for example if you are gathering the system call information, and want to output the call count every 5 seconds you can do: 'syscall:::entry { @[probefunc] = count() } tick-5sec { printa(@); cleara(@); }', which gives you the system call count every 5 seconds - just like iostat would give you the io count every 5 seconds or mpstat would give you the processor information every 5 seconds.... Easily accomplished in a few lines.
Dtrace... it slices, it dices, it makes coffee in the morning (and it will need to for me as it's 2am). September 09, 2004 02:10 AM IST Permalink
Preparation is the key
I have a shiney laptop, and I was planning on showing off a 64bit operating system running on it for my last dtrace presentation, so making sure I had the latest and greatest AMD64 bits, I started to prepare a few scripts that would allow me to show off what dtrace can do. I fired up one of my most complicated examples and bang my laptop rebooted.
It's just as well this was in my pre-flight test mode and not in front of everyone, because heaven knows, you don't need to have it all go horribly wrong in front of everyone.
As a preparation freak, I of course have the latest clean build of Solaris on an alternate boot environment on the laptop, so I quickly swapped unstable for stable to ensure that the demo went without a hitch.
Live upgrade, yet another reason why Solaris rules! September 09, 2004 01:58 AM IST Permalink
AMD64 - compilation flag differences from cc to gcc
Well I've been asked more than once for this, so I decided that a publicly accessible version would help people.
The wonderful world of AMD64
I already have the laptop capable of doing that (an Acer Ferrari 3200), so part of my work consists of getting the latest and greatest development bits onto it, and running. I get a tingle from executing isainfo -b, and get a result of 64.
Some people may think that this is lame (yes, Fintan, I mean you), but it means that I can test and verify all kinds of things in my time travelling into and out of the office by train. For example, this morning I verified that the read-only code for ext2 works just fine on 64bits. Mind you for fine read it works for a find /mntpt -type f -exec od {} \| head 2 \;, which for me is about as much testing as I can afford to spend on it. It needed a couple of compile flag changes, to support 64bit mode (-m64 | -xarch=amd64) but the code was just fine - a testament to the open source folks.
Another verification was a sound driver - I checked out the tools.de via82xx driver, which seemed to be the most appropriate one for the laptop, made some minor changes to the Makefiles (it didn't try to make 64bit drivers) and again I was treated with the witty remarks of Eddie Izzard; but this time it was running over a 64bit kernel.
Now if only my work was this easy :) September 02, 2004 04:48 PM IST Permalink
automount gotchas
Solaris's automount is great, but it's a tad confusing.
for instance the default /etc/auto_master line has an entry reading:
+auto_masterwhich translates to 'look up the other choices here'.
If your /etc/nsswitch.conf entry for automount reads:
automount: files nisThis means that it will look up nis at this point before continuing. If this entry is at the start of the auto_master file this means that NIS entries win over files entries, so if we have a nis map which specifies different options to mounting, such as -nobrowse, then this option is used instead of the option in the file.
In SunOS 4.x days all the automount maps were dot-delimited, so we had entries like auto.home and auto.master, but when NIS+ was introduced this became a problem, as this was a map called auto in a nis branch called home, so the default maps were relabelled to use underscores instead of periods.
Of course we don't want to break backwards compatibility with SunOS 4.x nis servers, so when you request an underscore delimited map under NIS if it doesn't find the map, it will try to find a period delimited map of the same form.
For example /etc/auto_master reads:
+auto_master /net -hosts -nosuid,nobrowse /home auto_home -nobrowseThen lookups will search the ypmap auto_master (and if that map is missing then auto.master), so if you have a line in NIS stating: /home auto.home, it will override the entry in /etc/auto_master that says: /home auto_home, so if you have an /etc/auto_home file, it will not be considered when searching for entries in /home. August 03, 2004 08:01 PM IST Permalink
Korn shell arrays
Korn shell supports arrays. You can have about 4000 elements in a korn shell array, and the performance is not great, but they're quite handy for walking through sets of variables (like paths).
The syntax is:
set -A <array> [values...]This will set the array named to the values passed, clearing the variable before setting. This is fine, but what if we're simply appending to an array? Lots of folks want to do that. In this case what you use is:
set +A <array> [values...]All very fine and well, but how do we reference the values in the array? You use the variable[<index>] syntax.
array[<index>]=<value>What about getting all the values from the array? simply use either @ or * as the index.
Then there's dereferencing it. Dereferencing the entry involves using ${array[index]}, otherwise the $ would evaluate up to the left bracket, and not evaluate the content of the array, such is the grammar of ksh.
Putting this all together into something useful (like a gcc wrapper for gcc specific options)
set -A arguments -- "$@" typeset -i index=0 while [[ -n ${arguments[$index]} ]]; do case ${arguments[$index]} in -W|-Wall) arguments[$index]=-v;; -Werror) arguments[$index]=-errwarn=%all;; -O?) arguments[$index]=-xO${arguments[$index]##-O};; esac index=$((index + 1)) done cc -xCC "${arguments[@]}"July 21, 2004 03:00 PM IST Permalink | http://blogs.sun.com/petesh | crawl-001 | refinedweb | 4,778 | 58.01 |
nice()
Change the priority of a process
Synopsis:
#include <unistd.h> int nice( int incr );
Arguments:
- incr
- The amount that you want to add to the process's priority.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The nice() function allows a process to change its priority. The invoking process must be in a scheduling class that supports the operation.
This function has no effect in any of the scheduling policies that BlackBerry 10 OS supports. Use sched_setparam() , pthread_setschedparam() , or pthread_setschedprio() instead of this function.
The nice() function adds the value of incr to the nice value of the calling process. A process's nice value is a nonnegative number; a greater positive value results in a lower CPU priority.
A maximum nice value of 2 * NZERO - 1 and a minimum nice value of 0 are imposed by the system. NZERO is defined in <limits.h> with a default value of 20. If you request a value above or below these limits, the nice value is set to the corresponding limit. A nice value of 40 is treated as 39. Only a process with superuser privileges can lower the nice value.
Returns:
The new nice value minus NZERO. If an error occurred, -1 is returned, the process's nice value isn't changed, and errno is set.
Errors:
- EINVAL
- The nice() function was called by a process in a scheduling class other than time-sharing.
- EPERM
- The incr argument was negative or greater than 40, and the effective user ID of the calling process isn't the superuser.
Classification:
Caveats:
As -1 is a permissible return value in a successful situation, an application wishing to check for error situations should set errno to 0, then call nice(), and if it returns -1, check to see if errno is nonzero.
Last modified: 2013-12-23 | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/n/nice.html | CC-MAIN-2014-15 | refinedweb | 317 | 57.27 |
kOfxPropVersion
— Identifies a specific version of a host or plugin.
#include "/ofxCore.h" #define kOfxPropVersion "OfxPropVersion"
This is a property that belongs to the host descriptor (read only), plugin descriptor (read/write).
Identifies a specific version of a host or plugin.
This is a multi dimensional integer property that represents the version of a host (host descriptor), or plugin (plugin descriptor). These represent a version number of the form '1.2.3.4', with each dimension adding another 'dot' on the right.
A version is considered to be more recent than another if its ordered set of values is lexicographically greater than another, reading left to right. (ie: 1.2.4 is smaller than 1.2.6). Also, if the number of dimensions is different, then the values of the missing dimensions are considered to be zero (so 1.2.4 is greater than 1.2). | http://openeffects.org/documentation/reference/re245.html | CC-MAIN-2018-26 | refinedweb | 146 | 57.87 |
XPath Expression Evaluation
Evaluating XPath expressions in PhpStorm has two main purposes: Testing XPath expressions that are to be used in program
code or XSLT scripts, and making structured queries against XML documents.
The Evaluate XPath action can be invoked either from the editor context menu,
the main Search Menu or the main toolbar by clicking the action's icon
.
The Expression Evaluation has two different modes, a simple mode, that allows you to enter simple one-line expressions and doesn't allow you to configure and Context settings. For more convenient editing of long expressions in a multi-line style way, there's the advanced mode dialog that also has a button to edit some context settings, such as namespaces and their prefixes, and variables to use for the evaluation.
Both dialogs feature.
Some error checks and XPath inspections also provide Quick Fixes for detected problems, e.g. the possibility to map an unresolved namespace-prefix to a URI by intention.
Simple Mode
The simple mode comes with an input field that can be used to enter simple one-line expressions that don't require any customization of namespace prefixes or make use of predefined variables. The last recently used expressions can be selected from the drop-down list.
Advanced Mode
The advanced mode adds the possibility to edit expressions in a multiline editor and has another button to edit the XPath Context. The expression history can be browsed by the Up- and Down arrays on the right of the dialog or the keyboard shortcuts for the previous/next history element (usually Ctrl-Alt-Up, Ctrl-Alt-Down).
XPath Context
This dialog allows you to assign custom prefixes to the namespace URIs that are used in the context document. This can be useful to assign a shorter prefix, resolve prefix clashes or to actually define a prefix for the default namespace. This can be essential because XPath does not automatically match elements in the default namespace without specifying a prefix for the element to be matched.
The XPath Context also includes the possibility to define custom XPath variables that can be used in queries for repeating expressions. Each variable in the table can be assigned an expression that will be evaluated once when the query is executed. The resulting value is then available for multiple use at no additional computational cost.
Options
Highlight results
This highlights the matched nodes in the current editor. Matched nodes that don't belong to the current editor (may
happen by using the
document() function) are not highlighted. It's recommended to display such
cross-document results in the Find Usages toolwindow.
Show results in Usage View
Shows all matched nodes in the Find Usages toolwindow. Check Open in new tab to open the result in a new tab instead of reusing the last one. | https://www.jetbrains.com/help/phpstorm/2016.1/xpath-expression-evaluation.html | CC-MAIN-2018-30 | refinedweb | 471 | 50.57 |
than an attempt at solving problems that should be addressed by the platform itself (if at all!)
David Newton wrote:
I don't understand the objection made by Jelle
David Newton wrote:Sorry, but I believe getters and setters pretty much fall into the brain-numbingly trivial. Java chooses not to have real properties--why should I suffer from that choice?
Annotating a property with @Getter and @Setter is about as drop-dead simple as you can get, both source-wise, and implementation-wise.
And given the option between a bunch of annotations, and 10x+ as much code, I'll take annotations any day of the week.
..is a traditional Japanese term for an activity that is wasteful and doesn't add value or is unproductive..
nimo frey wrote:By the way, other (dynamic) languages (Ruby or Scala) omit getter/setters completely. It is noise.
Jelle Klap wrote:What about documentation? The JavaDoc tool doesn't (ok - shouldn't) generate API documentation for private members, so the public accessors are the only suitable way of adding a meaningful description of what a ""property" represents in the domain, what its legal values are, deprecation information, an instance' serialized representation, locking information etc.
I think labelling accessors as purely noise is somewhat of generalization.
But getters/setters are the most "trivial" of the "noisy" methods that this framework can generate for you - what about hashCode() equals() and toString()?
David Newton wrote: ... not rocket surgery...
Well, to be fair, that's not entirely accurate: other languages support real properties, where explicit getters and setters are optional. When an accessor needs its own functionality, it can be provided.
nimo frey wrote:
Well, to be fair, that's not entirely accurate: other languages support real properties, where explicit getters and setters are optional. When an accessor needs its own functionality, it can be provided.
I do not understand this:
Why does ruby or scala developers prefer using field based access, if it is a bad programming style (encapsulation or the like) ?
they are more like providing a class with implicit get() and set() methods.
nimo frey wrote:I was wondering about ruby or scala code which makes extensive use of fields (for example, objects which has only fields).
will it allow me to search the usages (keeping the namespace intact)
It's probably best to call them "properties", since that's the canonical term.
they just provide *real* property support, unlike Java.
David Newton wrote:You don't--how can you annotate a method that doesn't exist?
You *might* be able to do some byte-code manipulation, or figure out a way to make Hibernate apply its annotations to the methods after Lombok generates the accessors, but IMO the effort really wouldn't be worth it. | http://www.coderanch.com/t/510925/java/java/getter-setter-generation-annotations | CC-MAIN-2015-22 | refinedweb | 462 | 53.81 |
22 May 2009 21:20 [Source: ICIS news]
HOUSTON (ICIS news)--Passage of a ?xml:namespace>
HR 2454, the American Clean Energy and Security Act (ACES Act), would put more controls on production of hydroflourocarbons (HFC), the Halogenated Solvents Industry Alliance (HSIA) said.
Perc is used as an intermediary in the production of hydroflourocarbons (HFC).
“The proposed controls on HFC 125 and 134a production would obviously impact perchloroethylene demand,” the HSIA said. “How much, and how quickly, will depend on what are the next generation of refrigerants and how quickly we can transition to them.”
The House Committee on Energy and Commerce passed the bill on Thursday.
The bill would cap US industrial and transportation emissions of carbon dioxide (CO2) and other greenhouse gases (GHG) and mandate annual reductions to 83% below 2005 levels by 2050.
Some kinds of HFC have been found to contribute to GHG.
($1 = €0.72)
For more on per | http://www.icis.com/Articles/2009/05/22/9218965/us-climate-bill-may-lower-perc-demand.html | CC-MAIN-2013-48 | refinedweb | 154 | 62.98 |
17 July 2012 04:38 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
“We switched one line of our SBR plant to produce oil-extended grade SBR 1712 yesterday [Monday] afternoon,” the source said.
Fuxiang Chemical has one two-line SBR plant with a total capacity of 100,000tonnes/year, with both producing non-oil grade SBR 1502 before 16 July. However, the company changed one line to produce oil-extended grade SBR 1712 that goes into making of tyres.
“The line producing oil-extended grade SBR 1712 will operate at 80% and the other line producing non-oil grade SBR 1502 will operate at 100%,” the source added.
Non-oil grade SBR 1502 traded at yuan (CNY) 20,000-20,800/tonne ($3,135-3,260/tonne) in east
Oil-extended grade SBR 1712 traded at CNY18,700-18,800/tonne, down by CNY300-700/tonne from last week, according to Chemease, an ICIS service in
( | http://www.icis.com/Articles/2012/07/17/9578578/chinas-fuxiang-chemical-produces-oil-extended-grade-sbr-1712.html | CC-MAIN-2015-11 | refinedweb | 156 | 66.57 |
I was presented with a connectivity issue when trying to configure SharePoint 2013 using a CTP build of SQL 2014. They got the following error when they were it was trying to create the Configuration Database.
Exception: System.ArgumentException: myserver,50000 is an invalid or loopback address. Specify a valid server address.
at Microsoft.SharePoint.Administration.SPServer.ValidateAddress(String address)
at Microsoft.SharePoint.Administration.SPServer..ctor(String address, SPFarm farm, Guid id)
at Microsoft.SharePoint.Administration.SPConfigurationDatabase.RegisterDefaultDatabaseServices(SqlConnectionStringBuilder connectionString)
at Microsoft.SharePoint.Administration.SPConfigurationDatabase.Provision(SqlConnectionStringBuilder connectionString)()
They had indicated that they had hit this before, and they worked around it by creating a SQL Alias. However this time it was not working. It was presented to me as a possible issue with using SQL 2014 and I was asked to have a look to see if this would affect other customers using SQL 2014.
I found some references regarding the error, and the majority of comments indicated to have SQL Server use the default port of 1433. Also some that said create an Alias. Some of the SharePoint documentation even shows how to change the SQL Port, and they also show how to create an Alias, but none really explained why this was necessary, or what SharePoint what actually looking for.
For this issue, it has nothing to do with SQL 2014 specifically and could happen with any version of SQL. The issue is what SharePoint is looking for. Whatever you put in for the Server name needs to be a valid DNS name. For a non-default port (1433), you would need to create a SQL Alias. If you create a SQL Alias, the name should be resolvable and not a made up name that doesn’t exist in DNS. Otherwise, you will get the same error.
Techie Details
I started by looking at the error first. Of note, this is a SharePoint specific error and not a SQL error.
Exception: System.ArgumentException: myserver,50000 is an invalid or loopback address. Specify a valid server address.
at Microsoft.SharePoint.Administration.SPServer.ValidateAddress(String address)
This was an ArgumentException when SPServer.ValidateAddress was called. I’m going to assume that the string being passed in is whatever we entered for the database server. In my case it would be “myserver,50000”. I’ve seen this type of behavior before, here is one example. My first question was, what is ValidateAddress actually doing? I had an assumption based on the behavior that it was doing a name lookup on what was being passed in, but I don’t like assumptions, so I wanted to verify.
Enter JustDecompile! This is a create tool if you want to see what .NET Assemblies are really doing. The trick sometimes is to figure out what the actual assembly is. I know SharePoint 2013 using the .NET 4.0 Framework, so the assemblies that are GAC’d will be in C:\Windows\Microsoft.NET\assembly\GAC_MSIL. After that, I go off of the namespace as assemblies are typically aligned to the namespaces that are within it. I didn’t see an assembly for Microsoft.SharePoint.Administration, so I grabbed the Microsoft.SharePoint assembly within C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint\v4.0_15.0.0.0__71e9bce111e9429c. This prompted me to load a few others, but it told me which ones to go get.
Within the Microsoft.SharePoint assembly, we can see that we have the Administration namespace.
So, now we want the SPServer object and the ValidateAddress method.
internal static void ValidateAddress(string address)
{
Uri uri;
if (address == null)
{
throw new ArgumentNullException("address");
}
UriHostNameType uriHostNameType = Uri.CheckHostName(address); <– This is what gets us into trouble
if (uriHostNameType == UriHostNameType.Unknown)
{
object[] objArray = new object[] { address };
throw new ArgumentException(SPResource.GetString("InvalidServerAddress", objArray)); <– The exception will be thrown here
}
uri = (uriHostNameType != UriHostNameType.IPv6 ||
address.Length <= 0 ||
address[0] == ‘[‘ ||
address[address.Length – 1] == ‘]’ ?
new Uri(string.Concat("http://", address)) : new Uri(string.Concat("http://[", address, "]")));
if (uri.IsLoopback)
{
object[] objArray1 = new object[] { address };
throw new ArgumentException(SPResource.GetString("InvalidServerAddress", objArray1));
}
}
Uri.CheckHostName Method
Determines whether the specified host name is a valid DNS name.
So, if the string we pass in cannot be resolved via DNS, it will fail. We never get to the point where we actually hit SQL itself.
Adam W. Saxton | Microsoft Escalation Services
So this is the SharePoint bug, nothing less, nothing more. SQL aliases didn't have to be resolvable DNS names…
Is there a workaround for this? I am receiving this after upgrading to SSRS 2012 in SharePoint Integrated mode. We are hosting the databases on a non default port. Aliases aren't working. Machine,port isn't working.
Is there a host file entry we can make? In our case it would need to be machine specific so it can be applied to our three environments.
I am hoping there is a way to get around having to enable the SQL Browser service in order to specify the instance name.
An alias should be a valid workaround for this. That is really the only workaround available if you want to use a non-standard port for a default instance.
SharePoint will use the .NET SqlClient to connect and it should look for an alias if one is available. If the SharePoint process is x64, make sure the Alias is x64 as well (from a registry perspective).
We had this issue recently at client where we were deploying MS Project Server 2013 & SharePoint 2013 with SQL 2014 Availability Groups. SharePoint 2013 Configuration Wizard was failing at the 'Specify Configuration Database Settings' screen.
Our SQL Availability group SQLAvailabilityGroup was returing the ping requests, hence DNS resolving it.
We were using:
a. SQL 2014 Availability Group
b. Non-standard SQL Port
None of these worked:
SQLAvailabilityGroup
SQLAvailabilityGroup,Portname
What worked for us was using the default instance name:
SQLAvailabilityGroupSQLInstanceName,Portname
Thanks
Faisal Masood
PMP
MCSE, MOS: SharePoint 2013
MCITP, MCTS: SharePoint 2010
MCSA: Office 365
MS: MS Project 2013
MS: Azure
SharePoint, Office 365, Azure, ProjectServer EPM Consultant
Forgot to mention:
The default SQL instance name is
MSSQLServer
Hence the connection was:
SQLAvailabilityGroupMSSQLServer,Portname | https://blogs.msdn.microsoft.com/psssql/2013/10/04/invalid-or-loopback-address-when-configuring-sharepoint-against-a-sql-server/ | CC-MAIN-2017-13 | refinedweb | 1,022 | 50.43 |
Hello!
This has been driving me nuts. I am setting up unit tests for a static class which manages a collection of songs. This is how my unit test class looks:
//START CODE
package flexUnitTests {
import com.myapp.managers.MusicManager;
import flash.utils.Dictionary;
import flexunit.framework.Assert;
public class MyAppManagerTest {
[Before]
public function setUp():void {
var songData:Dictionary = new Dictionary();
songData["mn0012345"] = new Dictionary();
songData["mn0012345"]["title"] = "All the Pretty Little Horses";
songData["mn0012345"]["description"] = "by: American Traditional | Voice, Piano | 3 pages";
MusicManager.setSongData(songData);
}
[Test]
public function test_getAuthorsBySKU():void {
var expected:String = "American Traditional";
var given:String = MusicManager.getAuthorsBySKU("mn0012345");
Assert.assertEquals(expected, given);
}
}
}
//END OF CODE
You will notice two calls in red above. When I leave them in the code I see a variety of errors which look like this:
"Call to a possibly undefined method '' through a reference with a static type com.myapp..."
And
"Access of possible undefined property '' through a reference with static type com.myapp..."
Then, when I comment out the two lines in red above, these errors go away. Flash Builder seems really flakey to me. Often I notice that the error list varies, how can it just no longer be an error? Where did this new access error come from, in a no related part of the code, by adding or removing a function call to a static class which remains in the import statement.
Note that the MusicManager contains no references to any of the UI mxml that is throwing these errors. It just simply loads data into a few globals and allows you to grab info.
How is my usage of this function making foreign objects inaccessible?
Please help!!! I am really hoping there is an answer but I have a bad feeling the answer is just that Flash Builder is flakey.
I did some more work on the issue above. There are functions with in the MusicManager that call the UserManager to get a user's ID. When I comment out these calls then the access errors go away. Well the user manager has some calls back to mxml that tell the class that changes where made. My best guess is this is where it stems into the code that is randomly throwing errors. But, it compiles fine and runs fine on a device. Is there something with test cases which doesn't invoke the UI? | https://forums.adobe.com/thread/1151705 | CC-MAIN-2018-22 | refinedweb | 399 | 64.81 |
package codesnippets; import java.util.Scanner; import java.util.Stack; /* * This code snippet shows a how to reverse a string using a Stack. */ public class StringReverse { public static void main(String [] args){ Scanner scanner = new Scanner(System.in); String str = ""; Stack<String> stack = new Stack<String>(); System.out.println("Enter a string to be reversed: "); str = scanner.nextLine(); if (str == null || str.equals("")){ System.out.println("It seems you aren't ready as yet to enter the string, ok buhbye !!"); System.exit(0); } for (int i=0;i<str.length();i++){ // Here we push all the characters in the string one by one into the Stack stack.push(str.substring(i,i+1)); } String strrev = ""; while(!stack.isEmpty()){ // Here we pop all the elements from the Stack one by one which is essentially reversing. strrev += stack.pop(); } System.out.println("Reverse of the string \"" + str + "\" is: \"" + strrev + "\""); } }
Are you able to help answer this sponsored question?
Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies. | https://www.daniweb.com/programming/software-development/code/217299/string-reverse-using-stack | CC-MAIN-2017-13 | refinedweb | 179 | 61.22 |
Greetings! I'm getting my head around user auth in React by building a simple app with Auth0 features. So far so good. The problem starts when I try to hit the /userinfo endpoint. I'm using Superagent to make my API request.
import auth0 from 'auth0-js'; import request from 'superagent'; import { auth0Globals } from '../config.js'; import { getAccessToken } from './AuthService'; function userProfile(auth) { request .get( 'https://' + auth.CLIENT_DOMAIN + '/userinfo' ) .set( 'authorization', 'Bearer ' + getAccessToken() ) .end( function(err, res) { if ( err ) { console.log(err); } }); } const user = userProfile(auth0Globals);
The server responds with a 401 error, citing Invalid Credentials as the culprit. I'm getting this in the browser as well as in Postman with Auth0's pre-built GET request for /userinfo. This leads me to believe that my client is probably set up incorrectly, but I'm also finding that I can't access user info for the example client that comes with new Auth0 accounts.
Any ideas for what I might be doing wrong? I can confirm that auth.CLIENT_DOMAIN and the getAccessToken() function are returning data and that the data is correct.
Answer by pelaez89 · Sep 26, 2017 at 10:35 PM
I could replicate this problem while having a rule modifying the scope claim of the access token of the open id token. When I disabled the rule everything started working again. This was not happening yesterday and I don't see any other feasible explanation besides a change in Auth0 code since nothing changed on my rule code or lock config. Maybe you were doing something similar in a rule?
Answer by jmangelo · Aug 31, 2017 at 09:11 AM
I could not reproduce this situation, the
401, unless I provided an incorrect access token.
The access token you're using is an opaque access token, around 16 characters, or a JWT access token? If it's a JWT access token consider including the header and payload components in your question (you can redact the values of any claims you deem sensitive).
In addition, it may be useful to update the question with the exact contents of the
WWW-Authenticate response header you get along with the
401.
Answers Answers and Comments
2 suddenly results in 401, unauthorized (CRITICAL!) 13 Answers
user.login_count undefined 1 Answer | https://community.auth0.com/questions/7839/invalid-credentials-when-hitting-the-userinfo-endp | CC-MAIN-2018-09 | refinedweb | 380 | 58.08 |
Dear diary, on Thu, Jul 28, 2005 at 06:52:45PM CEST, I got a letter where Junio C Hamano <[EMAIL PROTECTED]> told me that... > Petr Baudis <[EMAIL PROTECTED]> writes: > > > AFAIK the plan is to centralize all the kernel repositories to a single > > one. For that, developers would generally push into branches with name > > different that "master". > > I did not know about that plan, but that is interesting and now > I understand why you think it is important to be able for more > than one person to push into a single repository.
Advertising
For that particular thing, this is only part of the motivation. The much bigger part of the motivation are projects which don't have a central maintainer but where group of people needs to be equal in access to a central repository. That's actually vast majority of larger projects, I think. > How will the namespace of N-hundred branches in that repository > be managed? To avoid collisions, wouldn't there be some > coordination, and there will be branch names there that > everybody agrees that they are owned by you? You could name your branches e.g. "davej/agpgart", "davej/cpufreq", etc. But those proposals of central repository were certainly quite preliminary, and perhaps I overstated saying "the plan is". > At that point, wouldn't it be easier for _you_ (as one kernel > developer who owns such globally unique branch names) to name > your branch you intend to push there the same way in your > working repository as well? And if you are cloning locally or whatever, you have to mention the branch name explicitly. One of the Cogito design bits is that branch name is something local to the repository. When you are adding a branch, the local name you assign it is your private thing repository-wise, and doesn't have to have any correlation to other repositories you might interact width. As I already argued, this helps when you are importing someone else's master as your branch called whatever (obviously not master), and if you have to deal with two remote branches with the same name (such a conflict is bound to happen and bound to be vulnerable to be a huge hassle). That also applies to pushing, you might be pushing to multiple repositories - say you are working on some cool kernel stuff for SuSE, so you might want to push to kernel.org _and_ into the deep bowels of some SuSE kernel infrastructure (whatever - I'm not familiar with those things yet if you are now drooling to get some insight about how this is working in SuSE]. -- | https://www.mail-archive.com/git@vger.kernel.org/msg02161.html | CC-MAIN-2017-04 | refinedweb | 437 | 57.4 |
lfind, lsearch - linear search of an array
#include <search.h> void *lfind(const void *key, const void *base, size_t *nmemb, size_t size, int(*compar)(const void *, const void *)); void *lsearch(const void *key, void *base, size_t *nmemb, size_t size, int(*compar)(const void *, const void *));
lfind()zero otherwise. If lsearch() does not find a matching element, then the key object is inserted at the end of the table, and *nmemb is incremented. In particular, one should know that a matching element exists, or that more room is available.
lfind() returns a pointer to a matching member of the array, or NULL if no match is found. lsearch() returns a pointer to a matching member of the array, or to the newly added member if no match is found.
SVr4, 4.3BSD, POSIX.1-2001. Present in libc since libc-4.6.27.
The naming is unfortunate.
bsearch(3), hsearch(3), tsearch(3)
This page is part of release 3.24 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://huge-man-linux.net/man3/lfind.html | CC-MAIN-2017-13 | refinedweb | 180 | 73.58 |
I recently had a difficult problem to solve: assigning 94 students into teams of four. The first reason it’s difficult is that you end up with 23.5 teams, and since we can’t chop students in half, we have to go with 22 teams of four, and two teams of three.
But we’re not done yet: the competition should be fair, in the sense that teams should be roughly equally matched: we don’t want to have one really good team that easily wins. So we get some estimations of students’ abilities— let’s say they get a score of 1 (worst), 2 or 3 (best). Then we can define a team’s strength as the sum of the students’ ability scores, and we want teams strengths to be roughly equal.
But we might even still have further requirements: maybe we want students to not be in teams with students they’ve already worked with (so they meet more people), or not put students who have done the competition together (as experience isn’t quite the same thing as ability).
Now this problem isn’t difficult because it’s hard to solve, but because it’s difficult to figure out exactly what the requirements are. The way I’d like to solve this problem is by specifying a small part of the problem, having something give me a possible solution, and then iterating to further define the problem (to avoid the bad cases I see).
I’ve had to solve a few problems of this nature, and after writing almost the same Python script each time, I refactored out the common code into Hufflepuff, an open-source project I released today. Like any good UNIX tool, it’s not especially interesting or complex itself, but lets you glue together other simple tools to produce something useful.
Let’s see how it works with a cut-down version of the example above. First, create a working directory, install a Python virtualenv and install Hufflepuff from pypi, and test it works:
$ mkdir -p ~/tmp/teams; cd ~/tmp/teams $ virtualenv . $ . bin/activate (teams)$ pip install hufflepuff (teams)$ hufflepuff -h usage: hufflepuff [-h] [-c CONFIG_FILE] [--initial-binary INITIAL_BINARY] [--initial-file INITIAL_FILE] [--mutate-binary MUTATE_BINARY] [--score-binary SCORE_BINARY] [--beam-width BEAM_WIDTH] [--expand-mantissa EXPAND_MANTISSA] [--expand-multiplier EXPAND_MULTIPLIER] [--target TARGET] [--num-iterations NUM_ITERATIONS] [--parallelism PARALLELISM] ...
We’ll also need some test data to play with, and for simplicity, we’ll just have a few students:
(teams)$ python >>> import json, random >>> with open('students.json', 'w') as f: ... json.dump([ ... { ... 'name': name, ... 'skill': random.randint(1, 3), ... 'experience': random.random() < 0.3, ... } ... for name in 'ABCDEFGHIJKLMN' ... ], f) ... >>> [Ctrl-D]
You should now have a students.json file with some students, each with a unique name, skill level, and experience indicating whether they’ve done the competition before or not.
Now we need to provide three things to Hufflepuff: an initial assignment of students to teams, a program to mutate those teams, and a program to score a team assignment.
For the initial assignment, we need to specify the team sizes, and provide a valid assignment: so let’s just put the students in order. Here’s initial.py, which goes into your working directory:
import json # For 14 students, two teams of four, and two of three. team_sizes = [4] * 2 + [3] * 2 with open('students.json') as f: students = json.load(f) assert sum(team_sizes) == len(students) print json.dumps([ [students.pop(0)['name'] for _ in range(team_size)] for team_size in team_sizes ]) assert len(students) == 0
Now when you run it, you should get the following output. It should be fairly obvious: the first team has four people (A, B, C, and D).
(teams)$ python initial.py [["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K"], ["L", "M", "N"]]
The next thing to provide to Hufflepuff is a way of mutating the state. In this example, the easiest thing to do is to swap a pair of students in different teams. We need to be carefuly to only produce valid states (every student should be in exactly one team), and ideally we shouldn’t duplicate states— so since teams are a set of students, let’s keep them in sorted order within the team.
Here’s mutate.py, also to be placed in the working directory:
import json import random import sys # Read lines from stdin (ending cleanly on EOF): for line in iter(sys.stdin.readline, ''): teams = json.loads(line) # Swap between 1-3 pairs. for _ in range(random.randint(1, 3)): # Select two teams to swap between. team_a, team_b = random.sample(teams, 2) # Choose a person from each team. person_a = random.choice(team_a) person_b = random.choice(team_b) # Swap them. team_a[:] = sorted( person_b if name == person_a else name for name in team_a ) team_b[:] = sorted( person_a if name == person_b else name for name in team_b ) print json.dumps(teams)
You should be able to run it as below. The first JSON list is input, the second is output, and it should continue accepting input until you send EOF (by pressing Ctrl-D).
(teams)$ python mutate.py [["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K"], ["L", "M", "N"]] [["B", "C", "J", "M"], ["E", "F", "G", "L"], ["D", "I", "K"], ["A", "H", "N"]]
You’ll have noticed that it swaps a few pairs of people around. The initial state will be pretty bad, so we want to make a lot of swaps, to quickly head towards the better state. Towards the end of the search, lots of swaps will usually be bad, and we want single swaps to settle on the local optimum. There are more sophisticated things you could do, but I’ve found this is easy and works well enough in practice.
The last thing we need to provide is some way of scoring the state— nicely congregating all your experimental decisions of what to optimise into a simple problem: giving a score for a team assignment.
In this case, it’s easiest to specify the score as a “cost”, and say how bad an assignment is. We’ll inflict penalties for teams with more than one experienced student, and for the difference between a team’s strength and the average team strength. Here’s score.py, also to be placed in the working directory:
import json import sys with open('students.json') as f: students_by_name = { student['name']: student for student in json.load(f) } def experience_penalty(teams, penalty=100): score = 0 for team in teams: n_experienced = sum(1 for student in team if student['experience']) if n_experienced > 1: score += penalty return score def skill_penalty(teams): strengths = [ sum(student['skill'] for student in team) for team in teams ] average_strength = sum(strengths) / float(len(strengths)) return sum( abs(average_strength - strength) for strength in strengths ) for line in iter(sys.stdin.readline, ''): teams = json.loads(line) # Replace students' names with their full info. teams = [ [students_by_name[name] for name in team] for team in teams ] score = experience_penalty(teams) + skill_penalty(teams) print score
If you run it, and provide it the initial team JSON, it should print out some score (which will vary based on your students.json file):
(teams)$ python score.py [["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K"], ["L", "M", "N"]] 104.0
A side note: it’s handy to put a “debug mode” into the scoring program, so you can give it a solution, and quickly see how well it does on each of the conditions. This can be useful for distinguishing between multiple equally-scoring solutions, and also for telling if the search found the optimum.
Finally, we’ll write a search.cfg file to specify what we want Hufflepuff to do (we could also just pass the parameters as command line args, but this is nicer):
initial-binary = python initial.py mutate-binary = python mutate.py score-binary = python score.py target = min
Then, all we need to do is to run Hufflepuff, which will take all those things, and run a beam search. As it runs, it prints out the scores of the items in it’s current search beam to stderr, and finally prints out [score, state] JSON-encoded lists to stdout of the best states it ever saw.
(teams)$ hufflepuff -c search.cfg ... [2.0, [["A", "C", "D", "K"], ["B", "G", "J", "L"], ["F", "H", "I"], ["E", "M", "N"]]] [2.0, [["A", "C", "D", "K"], ["B", "G", "J", "L"], ["F", "H", "N"], ["E", "I", "M"]]] [2.0, [["A", "C", "E", "G"], ["D", "H", "J", "M"], ["B", "I", "L"], ["F", "K", "N"]]] [2.0, [["A", "C", "G", "L"], ["I", "J", "K", "M"], ["D", "F", "N"], ["B", "E", "H"]]] [2.0, [["A", "C", "L", "N"], ["I", "J", "K", "M"], ["D", "F", "G"], ["B", "E", "H"]]]
As you can see, it found a bunch of possible solutions, all of which had score 2.0. I can then manually inspect those states, determine if there’s any major problems with them, and refine the scoring program if necessary.
A cute little trick is that you can take those states (without the score), put them into best.json, and then run hufflepuff -c search.cfg --initial-binary='cat $initial-file' --initial-file=best.json to start the search from those states (and you can make it less ugly by defining initial-binary in search.cfg since that’s the default).
Pull requests, bugs and feature requests are welcome, and I’m also happy to answer questions in the comments below. And if case you were wondering, here’s the inspiration for the name. | https://blog.flowblok.id.au/2015-10/finding-good-answers-quickly.html | CC-MAIN-2018-34 | refinedweb | 1,599 | 70.23 |
Hey guys i was wondering whether anyone could help me out ive got to create a program that creates three directory entries and place them in an array of length 10. Once the entries have been placed in the array a for loop should be used to retrieve each entry from the array and display it on the screen. im stuck lol this is what i have so far. im unsure as to how i can print off my array as a string?
Code :
import java.util.*; public class ArrayEntries { public static void main(String[] args) { Entry [] = new Entry[10]; // create three entries and store in array Entry [0] = ("Garry Julesl"); Entry [1] = ("143 Treseifion"); Entry [2] = ("01407760799"); Entry [3] = ("Liza Williams"); Entry [4] = ("2 Gil Street"); Entry [5] = ("01407723233"); Entry [6] = ("Louise Jones"); Entry [7] = ("2 Llainoch"); Entry [8] = ("01407760000"); // print only the three entries for(int i= 0; i< Entry.length; i++) { System.out.println(Entry[i]); } } } | http://www.javaprogrammingforums.com/%20collections-generics/1626-array-program-assistance-needed-printingthethread.html | CC-MAIN-2018-26 | refinedweb | 159 | 66.67 |
TableView sorting my clicking column Headerb.pradeep May 29, 2013 6:40 AM
my application needs sorting feature which is provided by sortorder(true) but I have data set of around 100,000 rows (10 columns each of strings of length 30),
Sorting works way better with swing Jtable
Any suggestion on how to improve sorting performance.
P.S. : I have one thing in my mind that to use some other sorting method and then load table again with sorted data but it is not a proper solution as then data is needed to be loaded again and again in tableview.
Thanks
1. Re: TableView sorting my clicking column Headerjsmith May 29, 2013 7:03 PM (in response to b.pradeep)This question is cross posted to:
2. Re: TableView sorting my clicking column Headerb.pradeep May 30, 2013 10:51 AM (in response to jsmith)I posted it there but didn't get solution
3. Re: TableView sorting my clicking column HeaderJames_D May 30, 2013 7:18 PM (in response to b.pradeep)I think you got about as good an answer as can be given right now. Sorting appears to be considerably slower than sorting the underlying lists: that's a bug and you should report it.
There's currently very little API allowing you to change the implementation of the sorting that is used. In JavaFX8, TableView introduces a sort() method. I haven't investigated this much, but if you're in a situation where you can use the early-access version of JDK8 you could consider subclassing TableView and overriding the sort() method.
Have a look through the existing bug reports, particularly [url]RT-19479 and related issues.
Update: I played with overriding TableView.sort and it seems to work as expected. See [url]cross-posted question.
Update (again): I figured out how to fix this in JavaFX 2.2. The issue lies with getting the correct data model.
Edited by: James_D on May 30, 2013 7:07 AM
Edited by: James_D on May 30, 2013 12:16 PM
4. Re: TableView sorting my clicking column HeaderJames_D May 30, 2013 5:37 PM (in response to James_D)Ah, figured it out. I updated my StackOverflow post accordingly.
5. Re: TableView sorting my clicking column Headerjsmith May 30, 2013 6:26 PM (in response to James_D)That's a really neat find James.
I don't think I would have figured out that supplying a property accessor on the cell's data value item would have a massive impact on sorting performance unless I spent a lot of time in a profiler . . .
6. Re: TableView sorting my clicking column HeaderJames_D May 30, 2013 7:13 PM (in response to jsmith)I was actually guessing the reflective calls that have to be present in the PropertyValueFactory were the culprit, so I went to implement a cell value factory directly. When I had to return an ObservableValue<String> and realized the Person class wasn't giving me access to one, the light bulb went on...
It turns out that the guess about reflection was not so wrong. The PropertyValueFactory does some caching of the value specifically because performance would be affected otherwise. Setting a cell factory saves a little additional time, but not much.
The JavaFX8 API is still helpful; you can subclass TableView and override sort(), or (and this is probably better) plug in a sorting strategy by calling setSortPolicy(...). This gives the opportunity to remove a little of the indirection of getting the cell value factory from the column and then getting the cell value from that. (I guess TableColumn.setComparator() can be used to similar effect.) Again that's a very minor performance increment compared to providing the property accessors, but it's nice to have the option. Using that also gave me the chance to time the sorting: I was getting around 0.16 seconds to sort on a single column, which is plenty fast enough. It's interesting to note that the first sort took 3-4 times longer, but you already knew that...
7. Re: TableView sorting my clicking column Headerb.pradeep Jun 14, 2013 6:01 AM (in response to James_D)
Thanks james for wonderful answer,
Now am in a situation.... Problem is I need to implement "active sort" with new row insertion every 15 - 20 milliseconds,
What am currently doing is to reapplysortorder every time a data point is inserted
private void reapplyTableSortOrder() {
ArrayList<TableColumn<Person, ?>> sortOrder = new ArrayList<TableColumn<Person, ?>>(table.getSortOrder());;
table.getSortOrder().clear();
table.getSortOrder().addAll(sortOrder);
}
but this is not good in performance (I have looked at swing example which is way faster).
Any help will be really appreciated....
8. Re: TableView sorting my clicking column HeaderJames_D Jun 14, 2013 2:11 PM (in response to b.pradeep)
I'd probably try to insert the new data in the correct location, rather than adding it (at the end?) and then sorting again after. It might take a bit of work to figure out what that location is, but the idea would be to build a Comparator from the sortOrder, and then to use Collections.binarySearch(List<T>, T, Comparator<T>) to get the correct location.
9. Re: TableView sorting my clicking column Headerb.pradeep Jun 15, 2013 5:54 AM (in response to James_D)
I have tried it but as am using observableList (as argument in tableview are required of this type) I have to first convert it to array an dthen do a binary search.
I have tried to implement my own binary searc (recursive version) but performance is bad as compared to first converting to array and then using Array.binarysearch.
Any suggestion on how to do good binary search o large data of observable list
Thanks
10. Re: TableView sorting my clicking column HeaderJames_D Jun 15, 2013 11:03 AM (in response to b.pradeep)
You can just use Collections.binarySearch(table.getItems(), ...).
11. Re: TableView sorting my clicking column Headerb.pradeep Jun 15, 2013 2:47 PM (in response to James_D)
James am quite new to java and javafx but I really need to implement these features and need your help...
What I want is to have active sorting and auto insertion every 20ms, But as user can select whihc column he want to sort on fly...
am not able to properly parse on how to get which column's key is sorted and then how to properly pass my comparator.....
and what if it is sorted by more than one column but this is a thing to pursue later right now I want something which can help me sort ascending and descending.
I need comparator for int float and string
Thanks
12. Re: TableView sorting my clicking column HeaderJames_D Jun 15, 2013 4:14 PM (in response to b.pradeep)1 person found this helpful
Something like
import java.util.Collections; import java.util.Comparator; import javafx.application.Application;.geometry.HPos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.SortType; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.BorderPane; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class TableInsertExample extends Application { @Override public void start(Stage primaryStage) { final BorderPane root = new BorderPane(); final TableView<Person> table = new TableView<Person>(); table.setItems(createData()); final TableColumn<Person, String> firstNameColumn = new TableColumn<>("First Name"); final TableColumn<Person, String> lastNameColumn = new TableColumn<>("Last Name"); firstNameColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName")); lastNameColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName")); table.getColumns().addAll(firstNameColumn, lastNameColumn); final GridPane addPersonPane = new GridPane(); final TextField firstNameTF = new TextField(); final TextField lastNameTF = new TextField(); final Button addButton = new Button("Add"); addPersonPane.addRow(0, new Label("First Name:"), firstNameTF); addPersonPane.addRow(1, new Label("Last Name:"), lastNameTF); addPersonPane.addRow(2, addButton); final ColumnConstraints leftColConstraints = new ColumnConstraints(); leftColConstraints.setHalignment(HPos.RIGHT); final ColumnConstraints rightColConstraints = new ColumnConstraints(); rightColConstraints.setHalignment(HPos.LEFT); addPersonPane.getColumnConstraints().addAll(leftColConstraints, rightColConstraints); addButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { final Person person = new Person(firstNameTF.getText(), lastNameTF.getText()); int index ; final ObservableList<TableColumn<Person, ?>> tableSortOrder = table.getSortOrder(); if (tableSortOrder.size()==0) { index = table.getItems().size(); } else { Comparator<Person> comp = new Comparator<Person>() { @Override public int compare(Person person1, Person person2) { for (TableColumn<Person, ?> col : tableSortOrder) { Comparator colComp = col.getComparator(); if (colComp == null) { colComp = TableColumn.DEFAULT_COMPARATOR; } final Object o1 = col.getCellData(person1); final Object o2 = col.getCellData(person2); int c = colComp.compare(o1, o2); if (col.getSortType() == SortType.DESCENDING) { c = -c ; } if (c != 0) { return c; } } return 0 ; } }; index = Collections.binarySearch(table.getItems(), person, comp); if (index < 0) { index = -index-1 ; } } table.getItems().add(index, person); } }); root.setCenter(table); root.setBottom(addPersonPane); primaryStage.setScene(new Scene(root, 400, 600)); primaryStage.show(); } public static void main(String[] args) { launch(args); } private ObservableList<Person> createData() { return FXCollections.observableArrayList( new Person("Hugo" ,"Lloris"), new Person("Benoit", "Assou-Ekotto"), new Person("Jan", "Vertonghen"), new Person("Michael", "Dawson"), new Person("Kyle", "Walker"), new Person("Scott", "Parker"), new Person("Mousa", "Dembele"), new Person("Gylfi","Sigurdsson"), new Person("Gareth", "Bale"), new Person("Aaron", "Lennon"), new Person("Jermaine", "Defoe") ); } public static class Person { private final StringProperty firstName ; private final StringProperty lastName ; Person(String firstName, String lastName) { this.firstName = new SimpleStringProperty(this, "firstName", firstName); this.lastName = new SimpleStringProperty(this, "lastName", lastName); } public String getFirstName() { return firstName.get(); } public void setFirstName(String firstName) { this.firstName.set(firstName);} public StringProperty firstNameProperty() { return firstName ; } public String getLastName() { return lastName.get(); } public void setLastName(String lastName) { this.lastName.set(lastName); } public StringProperty lastNameProperty() { return lastName ; } @Override public String toString() { return firstName.get() + " " + lastName.get() ; } } }
Message was edited by: James_D Added test for column sort type to handle descending sorts.
13. Re: TableView sorting my clicking column Headerb.pradeep Jun 16, 2013 6:19 AM (in response to James_D)
@James_D Can you please tell me why this last method in person class (toString is overridden, I mean what is use of it.)
Thanks
P.S. : I have mix of column five column <col1 : int, col2: float, col3 : int, col4 : float , col5 : String>
Thanks james it solve half of my problem
14. Re: TableView sorting my clicking column Headerb.pradeep Jun 17, 2013 7:48 AM (in response to James_D)
Also I need to ask this thing
now insertion performance is good but gui is not interactive
I am clicking on rows but it is not selectiion (or taking too much time)
also scrolling also become difficult
gui is freezing in terms of scrolling....
any suggestion for that
P.S. am adding one person object every 20 millisecond.
Thank
Main culprit for slow insertion is
table.getItems.add(index,person);
any idea on how to improve....
Message was edited by: b.pradeep Main culprit for slow insertion is table.getItems.add(index,person); | https://community.oracle.com/message/11069618 | CC-MAIN-2017-34 | refinedweb | 1,815 | 50.02 |
Mar 14, 2017 10:22 AM|flameater|LINK
Hi guys,
My project was targeted for Net Framework 4.6. Then I upgraded it to 4.6.1 and updated the various packages accordingly.
Now with the project targeting 4.6.1, and Microsoft.ASPNet.WebAPI version 5.2.3, I am getting the above error in the file Startup.Auth.cs.
Originally, errors lit up like a Christmas tree after the Net Framework version change. I have uninstalled, installed and upgraded various related packages several times, and now only two errors remain.
The type or namespace name 'ApplicationOAuthProvider' could not be found (are you missing a using directive or an assembly reference?
The type or namespace name 'Providers' does not exist in the namespace 'CorsApi' (are you missing an assembly reference?)
Does anyone know how to overcome these? As far as uninstallation and reinstallation of the packages are concerned that has been done several times. The Local Copy properties for all packages are also set to True.
Thank you.
Mar 14, 2017 01:17 PM|flameater|LINK
Solved it.
The file Startup.Auth.cs, which was auto-generated, was malformed.
Here's a way to solve it.
Create a new Web API project. Make sure that it is running. Then compare the same files against the malfunctioning project and make changes accordingly.
1 reply
Last post Mar 14, 2017 01:17 PM by flameater | https://forums.asp.net/t/2117423.aspx?The+type+or+namespace+name+Providers+does+not+exist+in+the+namespace+CorsApi+ | CC-MAIN-2019-43 | refinedweb | 234 | 70.19 |
Difference between revisions of "RAP/RWT Cluster"
Revision as of 07:58, 26 July 2011
|.
- A further consequence of the missing
Display#sleep()is of course that entry points must not contain the usual event loop (see below for an example). readAndDispatch loop must be removed from the entry point. Make your entry point look like the one below.
public class SimpleEntryPoint implements IEntryPoint { public int createUI() { Display display = new Display(); Shell shell = new Shell( display ); shell.setBounds( 10, 10, 850, 600 );.
Schedule
We plan to ship the first version with milestone 1 of RAP 1.5 which will be available end of August 2011. The exact date depends on the Juno/Simultaneous Release Plan. | http://wiki.eclipse.org/index.php?title=RAP/RWT_Cluster&diff=prev&oldid=262689&printable=yes | CC-MAIN-2020-50 | refinedweb | 115 | 67.76 |
Overview
XSLT supports the concept of passing parameters to a stylesheet when executing it. This has been possible for a while when using the XSLTProcessor in JavaScript. However when using an
<?xml-stylesheet?> processing instruction (PI) there used to be no way to provide parameters.
To solve this two new PIs are implemented in Firefox 2 (see Supported versions below for details),
<?xslt-param?> and
<?xslt-param-namespace?>. Both PIs can contain "pseudo attributes" the same way that the
xml-stylesheet PI does.
The following document passes the two parameters "color" and "size" to the stylesheet "style.xsl".
<?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?>
Note that these PIs have no effect when transformation is done using the
XSLTProcessor object in JavaScript.
Processing instructions
The attributes in the
xslt-param and
xslt-param-namespace PIs are parsed using the rules defined in xml-stylesheet. Any unrecognized attributes must be ignored. Parsing of any attribute must not fail due to the presence of an unrecognized attribute as long as that attribute follows the syntax in
xml-stylesheet.
Both the
xslt-param and the
xslt-param-namespace PIs must appear in the prolog of the document, i.e. before the first element tag. All PIs in the prolog must be honored, both ones occurring before and onces occurring after any
xml-stylesheet PIs.
If there are multiple
xml-stylesheet PIs the parameters apply to all stylesheets as a consequence of that all stylesheets are imported into a single stylesheet per the XSLT spec.reference? Note that multiple
xml-stylesheet XSLT PIs are not supported in Firefox currently.
xslt-param
The
xslt-param PI supports 4 attributes:
- name
- The local-name part of the parameter name. No syntax checking is done on the attribute, however if it is not a valid NCName it will never match any parameter in the stylesheet.
- namespace
- The namespace of the parameter name. No syntax checking is done on the attribute.
- value
- Contains the string value for the parameter. The value of the attribute is used as value for the parameter. The datatype will always be string.
- An XPath expression for the parameter. The value of the attribute is parsed as an XPath expression. The result of evaluating the expression is used as value for the parameter.
If the name attribute is missing or empty the PI is ignored.
If the namespace attribute is missing or empty the null namespace is used.
It is not an error to specify a parameter name that does not exist in the stylesheet (or that is a variable in the stylesheet). The PI is simply ignored.
If both value and select are present or if neither value nor select are present the PI is ignored.
Note that
value="..." is not strictly equal to
select="'...'" since the value can contain both apostrophe and quote characters.
Examples
Set the parameter 'color' to the string 'red':
<?xslt-param name="color" value="red"?>
Set the parameter 'columns' to the number 2:
<?xslt-param name="columns" select="2"?>
Set the parameter 'books' to a nodeset containing all
<book> elements in the null namespace:
<?xslt-param name="books" select="//book"?>
Set the parameter 'show-toc' to boolean
true:
<?xslt-param name="show-toc" select="true()"?>
The select attribute context
The following context is used to parse and evaluate the expression in the select attribute.
- The context node is the node used as initial current node used when executing the stylesheet.
- The context position is the position of the context node in the initial current node list used when executing the stylesheet.
- The context size is the size of the initial current node list used when executing the stylesheet.
- No variables are available.
- The function library is the standard XPath function library.
- The namespace declarations are determined by the
xslt-param-namespacePIs, see below.
If the select attribute fails to parse or execute, the PI is ignored (in particular, it does not fall back to the value attribute).
xslt-param-namespace
The
xslt-param-namespace uses two attributes:
- prefix
- The prefix that is mapped.
- namespace
- The namespace the prefix maps to.
An
xslt-param-namespace PI affects the expression in the select attribute for all
xslt-params following the PI. This applies even if there are other nodes such as comments or other PIs between the
xslt-param-namespace and
xslt-param PIs.
It is not an error for multiple PIs to use the same prefix, every new PI just changes what namespace the prefix maps to.
If prefix is missing, empty, or equals an invalid NCName, the PI is ignored.
If namespace is missing, the PI is ignored. If namespace is empty, the prefix mapping is removed.
Examples
Set the parameter 'books' to a nodeset containing all
<book> elements in the '' namespace:
<?xslt-param-namespace prefix="my" namespace=""?> <?xslt-param name="books" select="//my:book"?>
Supported versions
Supported as of Firefox 2.0.0.1. The value attribute is supported in Firefox 2, but the select attribute crashes for some expressions in the 2.0 release.
Possible future developments
Should we allow any XSLT functions in the expression?
document() seems useful, but it seems tricky to maintain the invariant that
generate-id() should produce the same string for the same document.
What about querying URL parameters in the XSLT stylesheet? E.g. Passing them to specified <xsl:param>'s. | https://developer.mozilla.org/en-US/docs/Web/XSLT/PI_Parameters | CC-MAIN-2016-30 | refinedweb | 904 | 59.4 |
#include <unistd.h>
int execl (path, arg0, arg1, ..., argn, (char *)0) const char *path, *arg0, *arg1, ..., *argn;
int execle (path, arg0, arg1, ..., argn, (char *)0, envp) const char *path, *arg0, *arg1, ..., *argn; char *const envp[ ];
int execlp (file, arg0, arg1, ..., argn, (char *)0) const char *file, *arg0, *arg1, ..., *argn;
int execv (path, argv) const char *path; char *const argv[];
int execve (path, argv, envp) const char *path; char *const argv[], envp[];
int execvp (file, argv) const char *file; char *const argv[];
extern char **environ;
The exec system call in all its forms transforms the calling process into a new process.
The new process may be constructed from an ordinary executable file. Executable files consist of a header (see a.out(FP)), a text segment, and a data segment. The data segment contains an initialized portion and an uninitialized portion (bss). There can be no return from a successful exec because the calling process is overlaid by the new process.
An executable file may also be a text file, either as a ``#! script'' or as a ``shell script.'' A #! script always has #! as its first two characters and must always specify the full path of an existing command interpreter on its #! line. The command interpreter specified on the #! line is loaded to execute the script and replaces the calling process in the memory. If the text file does not have #! as its first two characters, the exec*() system call sets errno to [ENOEXEC] and returns with a return value of -1. Some command interpreters, such as the Bourne and Korn shells (/bin/sh, /bin/ksh), will detect the [ENOEXEC] error value and try to pass the script as input or argument to an invocation of the command interpreter. This functionality differs in execlp(S) and execvp(S) which pass the file to the Bourne shell as an argument if [ENOEXEC] is detected.
Executables created by C programs always use the function main as their entry point. The prototype for main is (arguments are optional):
main(argc, argv, envp) int argc; char **argv, **envp;
where argc is the argument count, argv is an array of character pointers to the arguments themselves, and envp is an array of character pointers to the environment strings. As indicated, argc is conventionally at least one, and the first member of the array points to a string containing the name of the file.
The path argument points to a path name that identifies the new process file.
The file argument points to the new process file. The path prefix for this file is obtained by a search of the directories passed as the environment line "PATH="; see environ(M). The environment is supplied by the shell; see sh(C).
arg0, arg1, ..., argn are pointers to null-terminated character strings. These strings constitute the argument list available to the new process. By convention, at least arg0 must be present and point to a string that is the same as path (or its last component).
argv is an array of character pointers to null-terminated strings. These strings constitute the argument list available to the new process. By convention, argv must have at least one member, and it must point to a string that is the same as path (or its last component). argv is terminated by a null pointer.
envp is an array of character pointers to null-terminated strings. These strings constitute the environment for the new process. envp is terminated by a null pointer. For execl, execlp, execv and execvp, the C run-time start-off routine places a pointer to the environment of the calling process in the global cell:
extern char **environ;
and it is used to pass the environment of the calling process to the new process. The environ array should not be accessed directly by an application. Instead, the use of a library routine, such as getenv(S), is recommended.
File descriptors open in the calling process remain open in the new process, except for those whose close-on-exec flag is set; see fcntl(S). For those file descriptors that remain open, the file pointer is unchanged.
Signals set to terminate the calling process are set to terminate the new process. Signals set to be ignored by the calling process are set to be ignored by the new process. Signals set to be caught by the calling process are set to terminate the new process; see sigaction(S).
For signals set by sigset, exec ensures that the new process has the same system signal action for each signal type whose action is SIG_DFL, SIG_IGN, or SIG_HOLD as the calling process. However, if the action is to catch the signal, then the action is reset to SIG_DFL, and any pending signal for this type is held.
When any of these exec routines is called successfully and does not return, routines registered previously by atexit(S) will not be executed at the termination of the new process and must be registered again for the new process if they need to be executed at the termination of the new process.
If the set-user-ID mode bit of the new process file is set (see chmod(S)), exec sets the effective user ID of the new process to the owner ID of the new process file. Similarly, if the set-group-ID mode bit of the new process file is set, the effective group ID of the new process is set to the group ID of the new process file. The real user ID and real group ID of the new process remain the same as those of the calling process.
The shared memory segments attached to the calling process are not attached to the new process; see shmop(S).
At the startup of the new process, LC_ALL is set to a null string:
setlocale(LC_ALL, "");and consequently, all internationalization variables starting with LC_ and the variable LANG have the value for the system configured default locale. See locale(M) for how to set a system default locale. In the XPG4 environment (and in the XPG4 environment only), LC_ALL is set to "C" at startup:
setlocale(LC_ALL, "C");Consequently, for the XPG4 environment, variables starting with LC_ and the variable LANG have the value ``C''.
Profiling is disabled for the new process; see profil(S).
The new process also inherits the following attributes from the calling process:
The exec system call fails and returns to the calling process if one or more of the following is true:
X/Open CAE Specification, System Interfaces and Headers,
Issue 4, 1992
;
IEEE POSIX Std 1003.1-1990 System Application Program Interface (API) [C Language] (ISO/IEC 9945-1) ;
and NIST FIPS 151-1 . | http://osr507doc.xinuos.com/cgi-bin/man/man?exec+S | CC-MAIN-2021-43 | refinedweb | 1,116 | 70.13 |
handle is the connected endpoint that will be used for I/O.
buf is the buffer to write from or receive into.
len is the number of bytes to transfer.
The timeout parameter in the following methods indicates how long to blocking trying to transfer data. If timeout == 0, then the call behaves as a normal send/recv call, i.e., for blocking sockets, the call will block until action is possible; for non-blocking sockets, EWOULDBLOCK will be returned if no action is immediately possible.
EWOULDBLOCK
If timeout != 0, the call will wait until the relative time specified in *timeout elapses.:
errno
ETIME
EOF
On partial transfers, i.e., if any data is transferred before timeout / error / EOF, bytes_transferred> will contain the number of bytes transferred.
Methods with iovec parameter are I/O vector variants of the I/O operations.
Methods with the extra flags argument will always result in send getting called. Methods without the extra flags argument will result in send getting called on Win32 platforms, and write getting called on non-Win32 platforms.
send
write
strnew
ACE_Handle_Sets
The ACE namespace contains all types (classes, structures, typedefs, etc), and global functions and variables in the ACE framework.
ACE_DIRECTORY_SEPARATOR_CHAR
Returns the "basename" of a pathname separated by delim. For instance, the basename of "/tmp/foo.cpp" is "foo.cpp" when delim is '/'.
e.g., the "12" in ACE 5.1.12. Returns 0 for "stable" (non-beta) releases.
INADDR_ANY
AF_UNSPEC
Bind a new unused port to handle.
Clear flags associated with handle.
E.g., the "0" in SunPro C++ 4.32.0.
E.g., the "4" in SunPro C++ 4.32.0.
E.g., the "32" in SunPro C++ 4.32.0.
E.g., the "SunPro C++" in SunPro C++ 4.32.0.
Helper routine for get_ip_interfaces, differs by UNIX platform so put into own subroutine. perform some ioctls to retrieve ifconf list of ifreq structs.
0
Computes the ISO 8802-3 standard 32 bits CRC for the @ len iovec buffers.
Computes the ISO 8802-3 standard 32 bits CRC for the buffer.
Computes the ISO 8802-3 standard 32 bits CRC for the string.
Computes CRC-CCITT for the @ len iovec buffers.
Computes CRC-CCITT for the buffer.
Computes CRC-CCITT for the string.
ACE_LIB_TEXT("/")
ACE_DEFAULT_CLOSE_ALL_HANDLES
ACE_LIB_TEXT("<unknown>")
Become a daemon process using the algorithm in Richard Stevens "Advanced Programming in the UNIX Environment." If close_all_handles is non-zero then all open file handles are closed.
Returns the "dirname" of a pathname. For instance, the dirname of "/tmp/foo.cpp" is "/tmp" when delim is '/'. If pathname has no delim ".\0" is returned. This method does not modify pathname and is not reentrant.
Wait for timeout before proceeding to a recv operation. val keeps track of whether we're in non-blocking mode or not.
recv
Wait for timeout before proceeding to a send operation. val keeps track of whether we're in non-blocking mode or not.
On Windows, determines if a specified pathname ends with ".exe" (not case sensitive). If on Windows and there is no ".exe" suffix, a new ACE_TCHAR array is allocated and a copy of pathname with the ".exe" suffix is copied into it. In this case, the caller is responsible for calling delete [] on the returned pointer.
pathname
Shut down ACE library services. Can be called only once per program invocation.
if avoid_zombies == 0 call ACE_OS::fork directly, else create an orphan process that's inherited by the init process; init cleans up when the orphan process terminates so we don't create zombies.
ACE_OS::fork
Format buffer into printable format. This is useful for debugging.
Euclid's greatest common divisor algorithm.
ACE_INVALID_HANDLE
Get our broadcast address based on our host_addr. If hostname is non-0 we'll use it to determine our IP address. If handle is not ACE_INVALID_HANDLE then we'll use this to determine our broadcast address, otherwise we'll have to create a socket internally (and free it). Returns -1 on failure and 0 on success.
Return the current setting of flags associated with handle.
Routine to return a handle from which ioctl requests can be made. Caller must close the handle.
ioctl
Return count and array of all configured IP interfaces on this host, rc = 0 on success (count == number of interfaces else -1). Caller is responsible for calling delete [] on addr_array.
Returns the temporary directory including the trailing slash in buffer. Returns -1 for an error or if the buffer_len is not long enough.
Timed wait for handle to get exception ready.
Timed wait for handle to get read ready.
Timed wait for handle to get read, write, or exception ready.
Wait up to timeout amount of time to passively establish a connection. This method doesn't perform the accept, it just does the timed wait.
accept
Wait up to timeout amount of time to complete an actively established non-blocking connection. If is_tli is non-0 then we are being called by a TLI wrapper (which behaves slightly differently from a socket wrapper).
Wait up to timeout> amount of time to actively open a device. This method doesn't perform the connect, it just does the timed wait.
connect
Timed wait for handle to get write ready.
Computes the hash value of <str> using the "Hash PJW" routine.
Convert a hex character to its byte representation.
This class implements the functions for the initialization and shutting down ACE. These functions are called only once per ACE invokation.
Returns 1 if IPv6 is enabled on the current host; 0 if not. This is an execution-time check. If ACE has not been compiled with ACE_HAS_IPV6, it always returns 0. If ACE_HAS_IPV6 is enabled, this function tries to create a PF_INET6 socket, returning 1 if it succeeds, and 0 if it fails. Caches the result so it only gets checked once.
Function that can burn up noticeable CPU time: brute-force determination of whether number n is prime. Returns 0 if it is prime, or the smallest factor if it is not prime. min_factor and max_factor can be used to partition the work among threads. For just one thread, typical values are 2 and n/2.
Determins whether the given error code corresponds to to a WinSock error. If so returns true, false otherwise.
For internal use only.
Finds the file filename either using an absolute path or using a relative path in conjunction with ACE_LD_SEARCH_PATH (e.g., $LD_LIBRARY_PATH on UNIX or the directories scaned by Win32 API SearchPath on Win32). This function will add appropriate suffix (e.g., .dll on Win32 or .so on UNIX) according to the OS platform. In addition, this function will apply the appropriate prefix (e.g., "lib" on UNIX and "" on Win32) if the filename doesn't match directly.
Transforms entry_point into a form that can be located in a dynamic library using <dlsym>. For example, with Win32/Borland extern "C" functions which use the default calling convention have a '_' prepended. Always returns a buffer that has been dynamically allocated using <operator new="">.
Uses ldfind to locate and open the appropriate filename and returns a pointer to the file, else it returns a NULL pointer. type specifies how the file should be open.
ldfind
Computes the base 2 logarithm of <num>.
e.g., the "5" in ACE 5.1.12.
Map troublesome win32 errno values to values that standard C strerr function understands. Thank you Microsoft.
Returns the maximum number of open handles currently permitted in this process. This maximum may be extended using ACE::set_handle_limit.
ACE::set_handle_limit
Calculates the minimum enclosing frame size for the given values.
e.g., the "1" in ACE 5.1.12.
Hex conversion utility.
Opening the temp file. File is automagically unlinked when it is closed. This is useful for have temp files.
Check if error indicates the process being out of handles (file descriptors).
Checks if process with <pid> is still alive. Returns 1 if it is still alive, 0 if it isn't alive, and -1 if something weird happened.
This makes sure that handle is set into non-blocking mode. val keeps track of whether were in non-blocking mode or not.
Receive into a variable number of pieces.
Accepts a variable, caller-specified, number of pointer/length pairs. Arguments following n are char *, size_t pairs.
Cleanup after a timed operation, restore the appropriate non-blocking status of handle.
Rounds the request to a multiple of the allocation granularity.
Rounds the request to a multiple of the page size.
Wrapper facade for the most common use of select that uses ACE_Handle_Sets.
Wrapper facade for select that uses ACE_Handle_Sets.
Varargs variant.
Send all the message_blocks chained through their next and cont pointers. This call uses the underlying OS gather-write operation to reduce the domain-crossing penalty.
cont
Set flags associated with handle.
-1
Reset the limit on the number of open handles. If new_limit == -1 set the limit to the maximum allowable. Otherwise, set the limit value to new_limit. If increase_limit_only is non-0 then only allow increases to the limit.
Returns a string containing the error message corresponding to a WinSock error. This works around an omission in the Win32 API.
Delete the memory allocated by strnew.
Returns a pointer to the "end" of the string, i.e., the character past the ' '.
'
Return a dynamically allocated duplicate of str, substituting the environment variable if str[0] == '$'. Note that the pointer is allocated with ACE_OS::malloc and must be freed by ACE_OS::free.
str
==
'$'
ACE_OS::malloc
ACE_OS::free
Create a fresh new copy of str, up to n chars long. Uses ACE_OS::malloc to allocate the new string.
This method is just like strdup, except that it uses operator new rather than malloc. If s is NULL returns NULL rather than segfaulting.
strdup
operator
new
malloc
As strrepl, but for wide characters.
Replace all instances of search in s with replace. Returns the number of replacements made.
As strsplit_r, but for wide characters.
Splits string <s> into pieces separated by the string <token>. <next_start> is an opaque cookie handed back by the call to store its state for the next invocation, thus making it re-entrant. This operates very similar to Perl's <split> function except that it returns pieces one at a time instead of into an array.
Terminate the process abruptly with id <pid>. On Win32 platforms this uses <terminateprocess> and on POSIX platforms is uses <kill> with the -9 (SIGKILL) signal, which cannot be caught or ignored. Note that this call is potentially dangerous to use since the process being terminated may not have a chance to cleanup before it shuts down.
Returns the current timestamp in the form "hour:minute:second:microsecond." The month, day, and year are also stored in the beginning of the date_and_time array, which is a user-supplied array of size time_len> ACE_TCHARs. Returns 0 if unsuccessful, else returns pointer to beginning of the "time" portion of date_and_time. If return_pointer_to_first_digit is 0 then return a pointer to the space before the time, else return a pointer to the beginning of the time portion.
ACE_TCHARs
This method uses process id and object pointer to come up with a machine wide unique name. The process ID will provide uniqueness between processes on the same machine. The "this" pointer of the <object> will provide uniqueness between other "live" objects in the same process. The uniqueness of this name is therefore only valid for the life of <object>.
Write all the message_blocks chained through their next and cont pointers. This call uses the underlying OS gather-write operation to reduce the domain-crossing penalty.
Counter to match <init()>/<fini()> calls. <init()> must increment it; <fini()> must decrement it. <fini()> then does nothing until it reaches 0. | https://www.dre.vanderbilt.edu/Doxygen/5.4.4/html/ace/namespaceACE.html | CC-MAIN-2022-40 | refinedweb | 1,960 | 68.97 |
Generate QR code image with Python, Pillow, qrcode
You can easily generate QR code images using Python's QR code generation library "qrcode". It is also possible to embed a QR code in another image or embed an image in a QR code using Pillow.
Here, the following contents will be described.
- Python QR Code image generator: qrcode
- Generate QR code image from the command line
- Generate QR code image with Python code
- QR code version of the generated image:
version
- Error correction level:
error_correction
- Cell size:
box_size
- Margin width:
border
- Color:
fill_color,
back_color
- Embed the QR code into the image
- Embed the image into the QR code
Python QR Code image generator: qrcode
The QR code is a two-dimensional code composed of square black and white dots (cells) standardized by ISO (ISO / IEC 18004) and JIS (JIS-X-0510).
Python has a library "qrcode" for generating QR code images.
It can be installed with
pip (or
pip3).
$ pip install qrcode
Please also install Pillow (PIL).
$ pip install pillow
Generate QR code image from the command line
If you only want to create a simple QR code image, you can use the command line.
Once you have
qrcode installed, you can use the
qr command.
$ qr "text for qrcode" > qrcode.png
In this example, a QR code image file named
qrcode.png containing string data
text for qrcode is generated. The image size is adjusted automatically according to the length of the string.
QR code contains only a string. How to process a string depends on the application that read QR code.
For example, in many smartphone camera apps that support QR code reading, if QR code contains URL, a notification whether to open the URL is displayed, and if the user allows it, it opens in the browser.
Generate QR code image with Python code
qrcode.make() creates
PilImage object.
With
PilImage object, you can use the attributes and methods of the Pillow(PIL)
Image object, such as
size.
- Image Module PIL.Image.Image — Pillow (PIL Fork) 6.2.1 documentation
- Related: How to use Pillow (PIL: Python Imaging Library)
Use
save() to save as an image file.
import qrcode img = qrcode.make('test text') print(type(img)) print(img.size) # <class 'qrcode.image.pil.PilImage'> # (290, 290) img.save('data/dst/qrcode_test.png')
You can also use the
QRCode class to change the details.
The basic flow is as follows.
qr = qrcode.QRCode() qr.add_data('test text') qr.make() img = qr.make_image() img.save('data/dst/qrcode_test2.png')
You can make various settings.
qr = qrcode.QRCode( version=12, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=2, border=8 ) qr.add_data('test text') qr.make() img = qr.make_image(fill_color="red", back_color="#23dda0") img.save('data/dst/qrcode_test2_2.png')
Each parameter will be described below.
QR code version of the generated image: version
The version of the QR code of the generated image can be set to
version.
For the relationship between the information capacity and versions of QR code, refer to the official page of Denso Wave below.
As the value of
version increases, the number of cells (square black and white dots) included in the QR code increases, and the image size and the information capacity increase. The minimum value of
version is
1 and the maximum value is
40.
By specifying
version, you can generate a QR code image larger than the optimal version (minimum size), so it is useful when you want to create multiple QR codes with different data contents with the same size.
Note that even if you specify a smaller version, if the data does not fit, it will automatically be the minimum version that fits the data.
Error correction level: error_correction
You can set the error correction level with
error_correction.
There are the following four levels. The values in parentheses indicate error correction ability (error correction rate for all codewords).
qrcode.constants.ERROR_CORRECT_L(Approx 7%)
qrcode.constants.ERROR_CORRECT_M(Approx 15%, default)
qrcode.constants.ERROR_CORRECT_Q(Approx 25%)
qrcode.constants.ERROR_CORRECT_H(Approx 30%)
For more information about the QR code error correction feature, refer to the official page of Denso Wave below.
When generating a QR code image from string of the same length, increasing the error correction level increases the size of the generated QR code image.
Cell size: box_size
With
box_size you can set the size of the cell (square black and white dot) in pixels.
Even if
version is the same (the number of cells is the same), you can change the size of the generated image by changing
box_size.
The default value is
10.
Margin width: border
You can use
border to set the width (number of cells) of the outer margin.
The number of pixels in the margin width is
box_size * border.
The default value is
4, which is the minimum width in the specification.
Color: fill_color, back_color
You can set the color with the
fill_color and
back_color of the
make_image() method.
Specify
fill_color and
back_color using color names
black,
white,
red, etc. or the
#xxxxxx style.
Embed the QR code into the image
PilImage objects can be pasted directly to other images using the Pillow
Image object's
paste() method.
The sample code to paste the QR code in the lower right corner is as follows.
import qrcode from PIL import Image img_bg = Image.open('data/src/lena.jpg') qr = qrcode.QRCode(box_size=2) qr.add_data('I am Lena') qr.make() img_qr = qr.make_image() pos = (img_bg.size[0] - img_qr.size[0], img_bg.size[1] - img_qr.size[1]) img_bg.paste(img_qr, pos) img_bg.save('data/dst/qr_lena.png')
For more information about
paste(), see the following articles:
Embed the image into the QR code
It is easy to embed the image into the QR code.
Note that superimposing an image on a QR code is not officially recommended..
face = Image.open('data/src/lena.jpg').crop((175, 90, 235, 150)) qr_big = qrcode.QRCode( error_correction=qrcode.constants.ERROR_CORRECT_H ) qr_big.add_data('I am Lena') qr_big.make() img_qr_big = qr_big.make_image().convert('RGB') pos = ((img_qr_big.size[0] - face.size[0]) // 2, (img_qr_big.size[1] - face.size[1]) // 2) img_qr_big.paste(face, pos) img_qr_big.save('data/dst/qr_lena2.png')
Depending on the size of the image to be embedded, it is safe to set the error correction level (
error_correction) to a high level. Also, when embedding a color image in a black and white QR code, it is necessary to convert the QR code to the
RGB mode with
convert('RGB'). | https://note.nkmk.me/en/python-pillow-qrcode/ | CC-MAIN-2020-40 | refinedweb | 1,076 | 50.84 |
Join devRant
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple APILearn More
Search - "garbage"
-
- "If Java had true garbage collection, most programs would delete themselves upon execution." - Robert Sewell31
- Relatives: You're a computer guy, right, what are you working on these days?
Me: *should I bother explaining, should I not* Oh, just some stuff.
R: Oh come on, tell us, how difficult can it be?
M: *sigh* I'm working on a custom garbage collector for-
R: !!
They're now under the impression that I'm involved in collecting rubbish from bins. Sigh. My hair doesn't help here, either, lol (I have one of those tangled, unruly mops of hair)
This will take time to explain.21
-
-
-
- You know why i hate lenovo with a burning passion? Not because they make industrial waste and sell it. Not because they trick non tech people into buying their garbage. No, i hate them because their shitass laptops dont even fit in my rubbish bin.31
- Saw a rant a few days ago about hotel WiFi being shitty.
I'm just here to confirm that rant was accurate.2
-
-
- FULLSTACK DEVELOPER
- A buzzword that startup companies use when they can't hire a lot of people. Multitasking all the way sucker!7
- I tried to download a 441GB torrent with a gigabit down and I ended up crashing my garbage router
-
-
-
-
- Fuck in app browsers. They should be fucking banned, honestly.
Instagram, Gmail, Kik, any if you cunts that have browsers in your app... Go fuck yourself.9
- So I found an old laptop in the garbage, it had a better fan so I dremeled out my old fan and glued in the salvaged fan. It fits like a glove. All wired in and ready to go.1
-
- Me: *spends 3 days configuring my linux mint install to not look like garbage, installing stuff, making a lot of scripts*
Linux mint 19 "Tara": *releases*
Me: fuck2
- Let's take bets on the root cause of the S3 outage!
I'm guessing a bad deploy of a sever-side Java application with a garbage collection problem.6
-15
- When you think php is pure garbage but this third party tool that you really need is fully written on it and you have to use it.10
-
- Chuck Norris can write Java without wearing glasses. He can C#.
Chuck Norris can compile C++ with just a word editor and K&R.
Chuck Norris can read the comment you almost put in on line 63 (it would have been very helpful.)
Chuck Norris can optimize programs in binary.
Chuck Norris does garbage collection with his mind.6
- I just had to download Firefox to be able to download chrome because Edge kept crashing. Think about that for a second.
It kept crashing on a BING SEARCH...9
- This always makes me smile..
The full article with more funny comparisons is at this link
-
-
-
- If Java had true garbage collector, most programs would delete themselves upon execution. -Robert Sewel 😂😂4
-
- Fucking GARBAGE
Sitting in the hall, quietly listening to an Arduino tutorial and I bring up terminal cuz I didn’t have the IDE and unnamed teacher starts yelling at me for hacking?!? Fuck ignorant teachers.15
- A new low level language. Modern and clean, like swift or python. Simple syntax and semantics. Low level (non garbage collected, non vm, pointers). I want a new take on C.18
-
- There is no such thing as an 'idea' person.
Learn to art, learn to code, or learn to FUCK OFF!
Talented people can take bad ideas and make gold.
Without skill the best idea will turn out garbage.2
- Put this in your build script for compile-time garbage collection:
find / -name "*.java" -type f -delete5
-
- Wordpress :(
Here is another piece of garbage from a previous Wordpress "developer".
This is NOT the generated HTML, it's the actual source code within a custom category template.
The client has said their archives stopped working this year.
*** MASSIVE FACE PALM ***14
-
-
- PHP7
0 == ‘foobar’ // true
PHP8
0 == ‘foobar’ // false
Nuff said. Before you tell me that js also has quirks, just remember that js having quirks doesn’t make php less garbage.28
- Converting old Android projects to kotlin feels soo damn good!
All that Java garbage is going into the t r a s h, boy8
- Pointers in C. You love'em or you hate'em. A lot of room to shoot ourselves in the foot or hang ourselves. Or doing both because someone thought it would be genius to tie the guns to the rope.2
- If java had real garbage collection then most programs would delete themself immediately upon running.2
- <rant>
I swear to god if see another "Here's how I made my amazing new website with Wixs" advert on Youtube, I'm going to throw my laptop out the god damn window!
</rant>8
- Every time I think
"Who the fuck coded this peace of garbage"
And then git blame the file
Only to see that it was me... 3+ months ago2
- Fuck Swift is garbage. 😡
How did such a promising language turn into such a steaming 💩??
This may be controversial but I think open-sourcing it may have been a huge mistake.19
- Word of advice: never buy the UMIDICI C Note 2.
Bought it myself and it's an utter piece of garbage.
Just bought another phone which runs stock android 7 and Lineage OS might be installable.
Also it can be rooted, good enough for me
-
-
-
- You left me a tiny hole to look through, I can’t even PUT FUCKING AWAY that garbage and you expect me to trust you on design! Fuck you!3
-
-
- "Java uninstalling itself Windows 7"...
The garbage collector is working! :D3
-
- I told a guy to implement an algorithm in cpp. He wrote this weird 600+ lines of code which contains only global variables and void functions then I told him to make it object oriented and he just put all those garbage in the class and gave me back and on top of that class name is Template and file name is template.cpp. I don't have words to describe his code. May be this picture can help you understand my state. Oh, if you think this matchOn_r1, r2,r3 are different then you are mistaken they are just different with one argument (one global argument). This is just part of the code. He has this shit all over the place. Why the fuck this kind of people exists?19
- People that blast their video in a restaurant that isn't that loud are awful people.
Like fuck you I don't wanna hear your garbage video at full volume you cock sucking cunts.4
-
- When it finally works after hours or days of suffering.
Or, when you clean things up and get to delete some garbage code.
Makes it all worth it in the end5
- Customer wanted us to put XP on a netbook after having us look at her XP tower.
This is what we all want to say about her "new" PC
- FUCK TOMCAT
FUCK JAVA
FUCK SYSTEMJS
FUCK SYNCFUSION
FUCK THIS SHIT WHOEVER DESIGNED ANY OF THIS GARBAGE SHOULD BURN IN THE LOWEST CIRCLE OF HELL.9
- Follow-up.
After getting fired last week, I went to the company today to take my papers, then the security guard asked for my government ID and refused to let me go the 5th floor to HR office, apparently because they had a meeting, then they had me waiting 20 minutes in the ground floor at the reception and when I asked if I could go to the bathroom he came in to the elevator with me and waited for me to get out to escort me back, I was so fucking furious by this point I just had it and told him who gave you the orders to take my gov ID and escort me everywhere like I'm a fucking maniac or a thief? Are you afraid of me breaking chairs or destroying offices or you think I'm gonna kill someone?
He then told me sorry sir but it's the orders, then I went to HR office and complained and called for the manager and she just came out with a bunch of BS, uhh I'm so sorry sometimes security can be a bit rude and what not.
SO YOU FUCKING MORONS THIS IS THE LAST TIME I'LL EVER BE COMING TO THIS FUCKING COMPANY AND YOU CAN'T EVEN GIVE ONE GOOD IMPRESSION FOR 30 MINUTES? HOLY SHIT!!!
Never in my life have I seen such incompetence, I just kept getting shocked to the last minute.1
- What the actual fuck?!!! ifconfig: command not found even after installing net-tools, just wtf
Who the fuck thought replacing nicely formated output of ifconfig with that garbage that "ip a" shits out was a good idea?!!
I will hate whoever did that until they burn in hell11
-
-
-
-
-
- Oooh what I hate it..... Timezones... Who really came up with that shit? GMT, UTC, CET and garbage like that. And then also the DST crap.
Whats wrong with the same time in the whole world? Without DST or timezone garbage that just makes life harder for both developers and travellers which are going to meet someone or have something booked.18
-
- The worst (best) pun I've seen in a while.
I hope it was intentional. Probably not. But one can hope.
- Anybody ever have a client treat you like a garbage slave and then actually _cry_ over the phone because you quit and now they don't want you to stop working for them?3
-
-
- !dev
K pop is garbage and yet somehow their fans are a bigger cancer than that sad excuse of music.37
-
- I have no idea how this code that I wrote last year work and there's obviously no documentation but thankfully I gave my classes very useful names such as "YuDoDis", "Texter467", "TheHolyButton", "GARBAGE", etc. Fucking hate myself sometimes
- Practice "garbage collector": relax by keeping your eyes closed for exactly 10 minutes when you feel tired (you won't fall asleep).
I usually do it once (after lunch) or twice a day (and mid afternoon).
Benefits are huge: just try it.7
-
-."
-
- Oh... You're holding my repo up for ransom? Hah you're funny. I'm not paying money for the garbage I haven't touched since...
Also
git push -f3
- People like to shit on Java when it really wouldn't be so bad if Eclipse wasn't the 'default' Java IDE.
Seriously: Eclipse is garbage.10
- If you’re angry at testers for constantly finding bugs and returning your garbage tasks, don’t. Wipe the Cheetos dust off your fingers and keyboard just once and try to write something that will actually work properly.4
- devRant gross truth time: the garbage can at my desk is used exclusively to dispose of boogers and chewed off fingernails.4
-
-
- Have you heard about Apple's new vacuum cleaner?
It's supposed to be the only Apple product that DOESN'T suck5
-
- So in C++ there is no garbage collector to clean up the mess u leave behind?
And now i feel like a garbage collector.... always cleaning up after monkeys... :(13
-
-
-
- Oh you're a real programmer because you use pointers.... Big man you are. Meanwhile I'm at home because I use a garbage collector and don't have any memory bugs.9
- Just found out about the CoC changes on stackoverflow. I urge you people to also have more confidence in yourself and tell the stackoverflow commmunity how you want to be adressed.
CoC changes:
- Today is haut garbage, too much stupid, too much management. Feeling nihilistic. Time to do something crazy
*updates linux-firmware6
-
-
- My internet provider is a fucking joke. Joke as in my internet is so garbage that it'd be better if I didn't have any internet at all.2
- "We have a nice documentation you can use to get this up and running"
>half the bloody variables used in said documentation are never even mentioned how they are defined
Nice.
-
-
- React is garbage. I refuse to learn something that actually expects me to litter my JS with HTML.19
-
- Every time I come back to Java:
"Oh man OOP is fun"
A few days later...
"This stupidly verbose, hand-holding garbage."4
- Just lost 2 hours of work because XCode decided to crash for no fucking reason. What a hot piece of garbage. Fuck XCode. FUCK.7
-
- going over some old code in the project...
thinking what garbage is this?
oh oh it was junior me :(5
- .2
- Everyone shitting on SO answers being mean (which sometimes they are), meanwhile:...
Garbage like this is how you become a misanthrope.11
- !rant
If someone asked you to fill a partition with garbage data, what's the fastest way you'd use?
My fav is a piped 'yes' command. I've seen it max SSD's out.11
- Please and please, if you cannot take the time out to create new classes do not copy and paste another without editing it properly! I noticed you do a find and replace and then leave 50% of variable names un-edited because all errors are gone. I am begging you in the name of Zeus edit your shit!
Here is one dick head:1
- So to un install Premie Pro I first need to sign in to my Adobe account, to then fucking update Creative Cloud, and then, then I can remove the garbage. Or so I hope ffs...2
- Tired of older generation developers teaching people not to use the back button. Make your application not garbage and let the people use the browser as intended for shit sake.1
-
- Mobile (Android/iOS) gaming has such potential but publishers keep pushing out mindless garbage. What's the point of getting a gaming phone only to spend your time playing gatcha games?6
- At the moment I'm working on a project where every line of code is actually garbage. However, the client insists on continuing to use ZF1.
Zend_Locale is a mess. I've been sitting on it for five hours and nothing's working.8
- Fucking fuck Nvidia. Shit suckers and ass lickers can't make a fucking thing properly. Everytime I have to compile something involving cuDNN and cuda I wish I could kill myself first. It's a piece of garbage software that we're stuck with. Fuck you mother fuckin Nvidia.3
- This is hands-down the worst codebase I've ever touched. 50% laziness, 50% poorly-conceived alterations to business logic. One of those where if it isn't throwing an error, you DON'T TOUCH IT.8
- Ideal dev job would be teaching kids code. Probably a side-gig at a local school.
Main gig would be writing code to exploit the "push to prod" Internet of Things things. Security on that is garbage. 🚮
- Stupid fucking communities normally all pieces of garbage. And no, there is no built in garbage collection, but then I find this, I POST 1 THING AND I GET GREAT RESPONES AND REALLY NICE ENGAGEMENT LIKE WTF3
- Me: Can you write the exact code one more time but in C language this time, so we can see it?
Other: But why, what's the problem?
Me: I don't know, maybe is garbage collector which collected all your code because IT LOOKS LIKE TRASHHHHH :@:@:@:@2
- Trying to inspect something to see if it works in IE.
FUCK YOU IE! this piece of pure garbage should be fucking illegal
-
-
-
- My best co-workers are my food buddies. Our tables are always full of snacks and garbage. Oh how i miss those days.
- sAleSfoRce aPEx is a hot wet garbage fire. How can I make this actually make this work right when I need to compare case sensitive strings?10
- Create a bug-free compiler for a Lang like c# but a little less overcomplicated and a lot faster. I don't believe a strictly typed and garbage collected language needs to be much less than half as fast as c++.2
- FUCKING HELL.
It's already enough that this FUCKING API I have to work with is a mess of JSON and XML responses mixed together.
With mixed german and english keys and attributes all sprinkled over it.
And API access locked to Austria only for some reason.
And then they even manage to fuck up the little bit of JSON they use.
It's just a fucking array of strings (where one could easily use integers).
They can stick this fucking steaming pile of shit that they call API up their PHP infested assholes.
I hate web development sometimes.5
- After switching from win to linux, and observing chrome process background behaviour for a while now I can with great certainity say it resembles a malware..
- The garbage recruiters are trying to sell is insane.
Don’t scrape the bottom of the ocean trying to pass barnacles off as salmon!
Just because someone can make computer go “beep boop” -- and you can’t — says more about you then it does about them.
Do they have a single thing in their portfolio that is even a little better than the output of the average “Learn x in y mins” video on youtube? Let that stock simmer for a little longer before you serve it!
Nothing in their portfolio at all you say? They’ve never once written code unless they were forced to? Top talent! Hired!
They scored 80% on your screening test? Wow! My dog scored 90%.
Modern day snake oil peddlers the lot of them.8
-
- !dev
ISP: "We are going to give you this piece of garbage Puma6 modem that will cause your internet to randomly die because we want to save a few bucks instead of actually having it function properly"
Me: "Can I replace it with my own?"
ISP: "No?"
I love not having fibre.
So either I shoot myself in the foot by going to another ISP (meaning I'll get *at best* 1/5th of the speed, while my current speed already is a severe bottleneck) or I have to keep content with this fucking piece of garbage internet that decides to commit sudoku over nothing...7
-
- Is there an easy way to make your website not look like complete garbage, if you have no idea and no time for some web front-end?11
-
- When you're at the end of a sprint, implemented a cool new feature and only the garbage issues are left over -.-
-
- My gradnfather died, and basically i got all the garbage books about programming. I was 9 by the time. Now im 13, and i still dont know how to code...2
-...
-
-
-
-
-
- I've been a dedicated Golang programmer for a few years now.
But lately I learned rust, and now even the thought of garbage collection makes me davastated :(1
- me.ask(“advice”);
I’m going to fly tomorrow and was wondering if I can bring my raspberry pi in my hand luggage. As known sometimes people in security checks are definitely not that awake and I don’t want my rPi in a garbage bin thinking it’s a bomb or something.
Otherwise I’ll just copy everything I need on a VM and go with it , but I wanted my sensors live ahah13
-
-
- Prepared my first own Pathfinder Campaign over the last week. Three hours before it starts someone calls it off.
A week of work thrown in the garbage. Feels good.5
- Facebook refuses to load up due to a "long running script".
Would you please fuck off with your "hurr let's do *EVERYTHING* in JS" garbage please?6
- I hate CakePHP! it sucks. And most of the people who like this shit are cunts with long hair. They love shoving this garbage framework down your throat as they high five each other.7
- Automatically clean up code, removing redundant and duplicate bits, splitting large functions, and formatting it nicely. Especially useful when trying to understand some garbage code someone else wrote which you need to rewrite.2
-
-
- 24 hours while a "pool" in my school (pool is a two-weeks fast formation where you can work 24h/24 to understand how a programming language works)
It was a C++ pool with a garbage subject meant to reproduce the functioning of a factory with... Factories.
Unit tests were use to mark us, so you know the struggle6
- Babel and webpack kicked my ass today. fuck you babel, and fuck u too webpack. neither one of u fucks is making my life any better at the moment. things were moving along, now my app just looks like this. something in this transpile garbage. I'm not missing '>' . it's just not transpiling correctly I think.8
- How do you guys deal with reviewing garbage code?
Do you waste a ton of time, trying to understand the code, so you can write constructive feedback?
Today I wasted 4 hours reviewing something like that and I'm still not finished.10
-
- !rant
Nothing worse than recieving little to no documentation/requirements on a project, garbage in = garbage out..
- So I was searching how to speedup my page speed of site which is built on Codeigniter and despite minified css and js I read this:
" CI active records are garbage, use classic quries"
:'( I used active records all over my app
-
-
-
-
- Finally leaving the """innovation lab""" where I worked and was a fucking garbage.
I can now expect a correct project management and a real task list6
- Everyone here complaining about Windows updates...
Your not forced to use it at gun point.
Windows is garbage, end of story. So either stop fucking using such garbage or stop fucking complaining about it!
I get the feeling you all like complaining more than you like having a good computer though...6
- So another rant inspired me.
Tell me one fact or detail about your favorite programming language, other devs not using it, might not know about.
I go with: In Delphi you don't have garbage collection, unless you use interfaces the right way.7
- Friend asked him if I could test his program.
I help him test his program and found a memory leak.
He investigated the issue...
After a few hours, he found out that his garbage collector had a memory leak :^
-
- That moment when project managers all demand a share of your weekly hours, failing to accept that productivity diminishes exponentially with the number of projects you have to switch between.
- Having my first memory leak problem ever. This sucks. I've tried what seems like everything. Forcing garbage collection every time I press a key to try and debug the issue. Fuck. I have 'using' blocks everywhere, and I have no idea what I'm doing wrong.5
-.15
- Slowly increase the users of our system from 5 to 15. The dal is fucking garbage so it gets slower and slower...
-
-
- Today I felt like the grinch explaining to my team that you can have memory leaks in a garbage collected language if they keep leaving live references.
- Colleague wrote all his test cases after finishing his code and set expectedOutput to garbage. His tests failed, printing actualOutput. Then he just replaced the garbage expectedOutput with actualOutput. Bingo bango, all tests passed.
"How do you like me now TDD?"1
- In interviews, I tend to forget the basics while I can answer more advanced questions. For example, I can't for the life of me remember the four principles of OOP but I can talk about garbage collection in my main programming language.1
- So apparently windowses "mirror drive" functionality is garbage. It is supposed to work like raid 1 and write data to two partitions simultaneously, but instead it randomly selects a drive and then proceeds to copy over the whole more recent drive image onto the older one daily at 3 am, thus writing a terrabyte of data to one of my drives daily. Thanks Microsoft!1
- Indian developers were committing hundreds of garbage pull requests to get a free Hacktoberfest t-shirt.
Meanwhile repository admins:2
- !rant
This is what I do every time I feel like garbage.
class Main:
def feelsgood():
x = input("Type your name")
print(x + " is awesome!")
Main.feelsgood()
- Can you guys let me know how microsoft teams is? Is it good, or is it polluted with fluff and garbage?15
-
-.2
- Android fanboys are equivalent to Windows fanboys. Both use garbage software and tell others it’s the norm.17
- Shit! Fuck!
Today I broke the quarantine to buy an HDMI splitter.
Turns out the secondary monitor I have is old as fuck so I can not extend the display, only duplicate 🤦🏼♂️
50€ to the garbage.
At least I bought a big ethernet cable to plug it on my PC and now I have 120mbps instead of the 2/3 I had on WiFi14
- Yes Microsoft I clearly want a fucking Korean Windows iso after entering in my English product key from England on a page written in English. Absolute fucking garbage just microshaft continuing to force us onto winblows 104
- Window 10 Bluetooth is garbage. Mouse lags like hell.🤦♂️
Same mouse works totally smooth on MacOS though.13
- I hate when the client gives you their "beautiful" html templates designed in Microsoft Word and then later asks you to modify that heaping pile of garbage 😂1
-
- From now on I won't be supporting ie. Instead I will just show a page saying fuck you. Maybe then people will stop using that garbage.2
- Its nice to work for a client that does not call broken features "garbage".
I mean I get it, broken code is garbage but it makes the hours and minutes leading to meetings less anxious when I know I won't be hearing comments like that.4
-
- Non technical bosses managing technical people should never be allowed. It'd be like if the head chef at a restaurant only knew how to cook Lean Cuisine, but bossed around all the other chefs on how they should do their job.2
- Meditation. Or Awareness Meditation to be precise. It enables me to regain control over my mind, because I get distracted really fast. It really helps sorting things out, taking a step back and getting an overview where I actually am and if what I'm doing right now is actually relevant/has priority. I mostly find that it's not, so I have to return to the important stuff.
For those interested: meditation sounds weird, even obvious at first or you just don't get what's it all about. You actually have to practice meditation for a long time and study the concepts until you start to understand what all these phrases and talking means. Behind them lies great wisdom/huge amount of concepts which is easily underestimated. So don't be frustrated too much if you don't feel it working right away. Be assured I've been there too. Also don't start with meditations like 'just stop thinking or think nothing' because in my opinion this is highly complex shit and frustrating at first. Start with awareness or breathing meditations or even get an app to support your daily habit.1
-.13
-
-
- There should be a garbage collector for IRC channels. If there's no activity for a given period of time, then just cancel it from above...2
- Named my current project "dumpster fire" so I can say "This dumpster fire doesn't even get through compiler anymore!" will work on that level too enjoy Visual Studio, but the installer is GARBAGE.
My install of 2017 didn't come with a certain package, so I go to the installer to add it. Thing constantly fails with "could not find file" in the txt log. Decided I might as well update studio while I'm here. Turns out I had python packages for it too, since during this update python decided to have a fit in another project because modules and pylint suddenly disappeared.
Wtf?1
-
-
-.
- i just tried source tree to easily clone my repositories and wasn't able to login it appears they are using Internet explorer for the login part. and guess what ? ... yup it doesn't fucking work.
WHY WOULD ANYONE USE INTERNET EXPLORER FUCKING PIECE OF GARBAGE. ANYONE STILL USING THAT SHIT SHOULD BE BANNED FROM THE INTERNET FOREVER ESPECIALLY A PROGRAMMER
-
- this is dumb.. i been trying to learn more about google places' A.P.I so i could implement them in android studios... spend 4 hours and all i can see is garbage tutorial and no detail place. oh at least i got my A.P.I key! pshh my googling skills are failing me big time!. make this shit easier google!.4
- Xamarin.Forms sucks ass. Piece of garbage. If you wanna make a big project better not choose Xamarin.Form, trust me
- 1) IList doesn't have an AddRange.
2) WPF bindings must be ObservableCollections
3) Comboxes using Event Notification on PropertyChange are originally developed by some dope at Microsoft who still doesn't comprehend Big-O
4) LINQ can only do so much...
It's Christmas. My gift from Santa is trying to get through an end of year crunch on a project that is made entirely out of hot sweaty year old garbage, and the garbage collector is a halfwit who comes seemingly only when they want to, regardless of when I call Dispose().
It's 12:26pm here. That means it's time for bourbon and a good bit of "F*** this, I'm done for the day."7
- Dr Robotnik has to be a java dev... Bloated, lazy, never leaves his seat, occasionally garbage collecting his messy desk
- Is anybody aware of some tecnique to install Visual Studio without having it to dump like 20Gb of useless garbage in unforeseeable locations of your hard drive?11
- You can be very good at writing algorithms and good quality code, but if your architecture is garbage, you'll be doing hacky fixes and end up with a spaghetti code.3
- Does anybody know where to start when implementing your own language as a plugin in Visual studio.
Sure, I could modify a plugin for another language, but I'd like to learn it, and Google just spits out garbage.8
- Update: now we are all home office for a while, and i had to set up signal (the dev team normally uses telegram) to keep in touch with everyone and wow what a fucking garbage app.11
- I have a love hate relationship with the Java garbage collector I love it when it works but when I notice it gcing in performance tests I know bad days are ahead
- Anyone have keyboard recommendations below $50 USD? I can't stand the one my office provides anymore. Flipping thing is a $10 piece of garbage that comes with the computers. Note that noise is an issue.16
- Everyone is a liar and the world is now a joke
I’ve been sitting here watching a parade of garbage doing the same crap and why as in reason is beyond my grasp currently37
-#.
-
- I hate bitmaps in Android. Whoever created those disgusting functions without thinking of of a *simple* way to deal with the garbage they cause is an asshole and I hope they go to the worst corners of hell.
-
-
- I would love to reschedule my whole life to live during the cool night time throughout the summer, but I can't because I don't live alone...
Guess I have to feel like garbage for the next few weeks...2
-
-.1
- so idk im not able to get a job yet or anything but is linkedin bad?
i havent heard anything but i just went to and something tells me that someone doesnt like it…
- Rust's type system is amazing. I love it so much, but every time I get a compiler error I look at garbage collection with envy. It's such a love/hate relationship.7
- Fuck Citrix Podio/GlobiFlow garbage-ass automation tool. I’m ready to use something else or just outright build my own workflow app for my team.
-
- Got a XPS 15 (2016 design) and after 3 months I've had it, going back to mb pro. Sleek design and all, but they keyboard/track pad is garbage, and the rest is dust/oil/everything magnet!1
- This fucking IDE
You can't look at the Values you want by default. You have to add them manually. And when you add a too big number of Values at the same time that fucking garbage called Software crashes...
Holy shit
- We're doing refactoring and deciding on which class to go into which module. A colleague said, "garbage put in core, shit put in common".
Me:
- Java's garbage collector must be broken - it failed to get rid of this dumpster fire another dev called "source code". But, hey, at least the profiler works.
- So last week, I struggled to loop through an an array on HPSM JavaScript... I felt like garbage. I have a computer Science degree BTW.1
-"
}4
-
- Asp.net before MVC, I'm talking all the VB syntax and .aspx files garbage. Feels like I'm working in the year 2003. 😭1
- I just wrote pure garbage for the last two hours hoping that if I crank it out fast enough it will have been worth it.
You already know what happened next.2
- Why do you have to use pointers in C++? Why doesn't C++ have a good garbage collector? Surely it has to be more advanced than C it has two more +s.....2
- Garbage; learn with research and a good project or something.
..although so far, the bootcamps I've attended have been under a big corp and labelled as "training"..
- !dev
with 8MP@iPad Air 2 ╮( ̄▽ ̄"")╭
and Nokia Lumia 1020 even Huawei(unknown model but surely 48MP) can't do that
(1020 produced low quality images (more ambiguous than that) and Huawei got even just a white circle, garbage.)3
- Am I the only one around here who tinks Dart devtools are fucking garbage?
Who the hell would print a log inside a canvas?6
- Simple binary questionnaire;
The application is:
0 - Garbage
1 - Good enough6
-
- jQuery is a fucking garbage of the 21st century. Endless ugliest ever mapping of html element values to JSON and back. Every fucking time.3
- The cesspool project I've bitched about on here a number of times wrapped up about 8 weeks ago. The code was delivered to the client and they took care of their own hosting needs.
They finally got their new site up and running. It looks great and seems to be really performant. Too bad it is complete garbage under the hood.
-
- Changes with Java 14 are:
Records is available (preview), a new class java.lang.Record. The java.lang package is implicitly imported on demand, that is, import java.lang.*
The G1 garbage collector now supports NUMA-aware memory allocations.
The ZGC (Z Garbage Collector) is now available as an experimental feature on macOS and Windows.
Improvements to Parallel GC.
The following methods related to thread suspension in java.lang.Thread and java.lang.ThreadGroup have been terminally deprecated in this release.5
-
- IBM should take over making the game Jenga...since they only seem good at making teetering towers of barely functional garbage that require constant massaging and hand holding to stay up.
- "Graphic design is the design of highly disposable items… It all winds up in the garbage." - Karrie Jacobs
-
- browsing /r/assholedesign, and some of these things that talk about games or whatever that serve too many ads and I'm thinking, why are you downloading that garbage? it's just taking up space7
-
- so FUCKING GREAT when you work on a git project in eclipse...🙄
git bash shows only 1 file that I've edited, eclipse ... shows a whole bunch of files that are even commited and pushed a long time ago. WTF??🤪19
- when you get married after you start a gradle build, and then the build finishes 5 years into the marriage and you get divorced bc the software idea was garbage anyway ¯\_(ツ)_/¯
-.
-
- Can anyone suggest software development meme pages on Instagram that are not cringe or just absolute garbage?9
- On devrant I sometimes see a good amount of posts saying angular is garbage but nearly none about react. Why is angular so hated.3
- Garbage Lenovo Carbon X1 is garbage.
Plugged it in to charge this afternoon for multiple hours, then carry it to the train. Open it up for some in-transit dev time and...
...it's dead. Fuck sakes!1
Top Tags | https://devrant.com/search?term=garbage | CC-MAIN-2021-25 | refinedweb | 6,224 | 73.17 |
I created an interest rate calculator however I modified the class to specify required and range attributes. When I add them and change my variables to null I receive the error: "Adding Attribute Error
This is the FutureValueModel.cs class producing the errors:
public class FutureValueModel { [Required(ErrorMessage = "Please enter a monthly investment.")] [Range(1, 500, ErrorMessage = "Monthly investment amount must be between 1 and 500.")] public decimal? MonthlyInvestment { get; set; } [Required(ErrorMessage = "Please enter a yearly interest rate.")] [Range(0.1, 10.0, ErrorMessage = "Yearly interest rate must be between 0.1 and 10.0.")] public decimal? YearlyInterestRate { get; set; } [Required(ErrorMessage = "Please enter a number of years.")] [Range(1, 50, ErrorMessage = "Number of years must be between 1 and 50.")] public int? Years { get; set; }
Source: Visual Studio Questions | https://windowsquestions.com/2021/09/18/asp-core-adding-attribute-will-prevent-the-debug-session-from-continuing/ | CC-MAIN-2021-43 | refinedweb | 131 | 50.84 |
Subject: Re: [boost] [config] request for BOOST_NO_FWD_STD_DECLARATION
From: Stewart, Robert (Robert.Stewart_at_[hidden])
Date: 2011-02-22 08:20:14
Ivan Le Lann wrote:
> Le samedi 19 février 2011 à 19:37 +0100, Ion Gaztañaga a écrit :
> > having to include a lot of std headers to declare a function
> > with a std::string const reference as input parameter is a
> > bit too much
>
> For a function declaration, even when you pass/return by value,
> you only need to declare types.
That's true unless, as is the subject of this thread, the type you would like to forward declare is in namespace std. Then you get into the world of "as if." The implementer may declare std types with template parameters beyond those named in the standard, provided the extras are defaulted so the types work as if they didn't have the extra template parameters. If a type does have extra template parameters, however, forward declaring it without them means mismatching the declarations while including them means requires that they be defaulted correctly. Unfortunately, defaults can be specified only once.
Only std types that don't make use of defaulted template parameters could be forward declared and, even then, are nonportable, even among versions of the same standard library.
_____ | https://lists.boost.org/Archives/boost/2011/02/177468.php | CC-MAIN-2020-16 | refinedweb | 211 | 54.66 |
Annihilating My Friend Will with a Python Fluid Simulation, Like the Cur He Is
Will, SUNDER! link to vid if not working
A color version link to vid if not working
As part of my random walk through topics, I was playing with shaders. I switched over to python because I didn’t feel like hacking out a linear solver.
There are a number of different methods for simulating fluids. I had seen Dan Piponi’s talk on youtube where he describes Jos Stam’s stable fluids and thought it made it all seem pretty straightforward. Absolutely PHENOMENAL talk. Check it out! We need to
- apply forces. I applied a gravitational force proportional to the total white of the image at that point
- project velocity to be divergence free. This makes it an incompressible fluid. We also may want to project the velocity to be zero on boundaries. I’ve done a sketchy job of that. This requires solving a Laplace equation. A sketch:
- $ v_{orig} = v_{incomp} + \nabla w$
- $ \nabla \cdot v_{incomp}=0$
- $ \nabla ^2 w = \nabla \cdot v_{orig}$. Solve for w
- $ v_{incomp}=v_{orig} - \nabla w$
- Advect using interpolation. Advect backwards in time. Use \(v(x,t+dt) \approx v(x-v(x)*dt,t)\) rather than \(v(x,t+dt) \approx v(x,t)+dv(x,t)*dt\) . This is intuitively related to the fact that backward Euler is more stable than forward Euler. Numpy had a very convenient function for this step
Given those basic ideas, I was flying very much by the seat of my pants. I wasn’t really following any other codes. I made this to look cool. It is not a scientific calculation. I have no idea what the error is like. With a critical eye, I can definitely spot weird oscillatory artifacts. Maybe a small diffusion term would help?
When you solve for the corrections necessary to the velocity to make it incompressible $ \nabla \cdot v = 0$ , add the correction ONLY to the original field. As part of the incompressible solving step, you smooth out the original velocity field some. You probably don’t want that. By adding only the correction to the original field, you maintain the details in the original
When you discretize a domain, there are vertices, edges, and faces in your discretization. It is useful to think about upon which of these you should place your field values (velocity, pressure, electric field etc). I take it as a rule of thumb that if you do the discretization naturally, you are more likely to get a good numerical method. For example, I discretized my velocity field in two ways. A very natural way is on the edges of the graph. This is because velocity is really a stand in for material flux. The x component of the velocity belongs on the x oriented edges of the graph on the y component of velocity on the y oriented edges. If you count edges, this means that they actually in an arrays with different dimensions. There are one less edges than there are vertices.
This grid is 6x4 of vertices, but the vx edges are 6x3, and the vy edges are 5x4. The boxes are a grid 5x3.
For each box, we want to constrain that the sum of velocities coming out = 0. This is the discretization of the $ \nabla \cdot v = 0$ constraint. I’m basing this on my vague recollections of discrete differential geometry and some other things I’ve see. That fields sometimes live on the edges of the discretization is very important for gauge fields, if that means anything to you. I did not try it another way, so maybe it is an unnecessary complication.
Since I needed velocities at the vertices of the grid, I do have a simple interpolation step from the vertices to the edges. So I have velocities being computed at both places. The one that is maintained between iterations lives on the vertices.
At small resolutions the code runs at real time. For the videos I made, it is probably running ~10x slower than real time. I guarantee you can make it better. Good enough for me at the moment. An FFT based Laplace solver would be fast. Could also go into GPU land? Multigrid? Me dunno.
I tried using cvxpy for the incompressibility solve, which gives a pleasant interface and great power of adding constraints, but wasn’t getting good results. i may have had a bug
This is some code just to perform the velocity projection step and plot the field. I performed the projection to 0 on the boundaries using an alternating projection method (as discussed in Piponi’s talk), which is very simple and flexible but inefficient. It probably is a lot more appropriate when you have strange changing boundaries. I could have built the K matrix system to do that too.
The input velocity field is spiraling outwards (not divergence free, there is a fluid source in the center)
We project out the divergence free part of that velocity field, and project it such that the velocity does not point out at the boundary. Lookin good.
Presolving the laplacian matrix vastly sped up each iteration. Makes sense.
Why in gods name does sparse.kron_sum have the argument ordering it does? I had a LOT of trouble with x vs y ordering. np.meshgrid wasn’t working like I though it should. Images might have a weird convention? What a nightmare. I think it’s ok now? Looks good enough anyway.
And here is the code to make the video. I converted to image sequence to an mp4 using ffmpeg
ffmpeg -i ./%06d.jpg will.mp4
import numpy as np import cv2 from scipy import interpolate from scipy import ndimage from scipy import sparse import scipy.sparse.linalg as linalg # import spsolve #ffmpeg -i ./%06d.jpg will.mp4 ### Setup dt = 0.01 img = cv2.imread('will.jpg') # make image smaller to make run faster if you want #img = cv2.pyrDown(img) #img = cv2.pyrDown(img) Nx = img.shape[0] Ny = img.shape[1] v = np.zeros((Nx,Ny,2)) x = np.linspace(0,1,Nx, endpoint=False) y = np.linspace(0,1,Ny, endpoint=False) X, Y = np.meshgrid(x,y, indexing='ij') #v[:,:,0] = -Y + 0.5 #v[:,:,1] = X - 0.5 #### Build necessary derivative and interpolation matrices def build_grad(N): # builds N-1 x N finite difference matrix data = np.array([-np.ones(N), np.ones(N-1)]) return sparse.diags(data, np.array([0, 1]), shape= (N-1,N)) # gradient operators gradx = sparse.kron(build_grad(Nx), sparse.identity(Ny-1)) grady = sparse.kron(sparse.identity(Nx-1), build_grad(Ny)) def build_K(N): # builds N-1 x N - 1 K second defivative matrix data = np.array([-np.ones(N-2), 2*np.ones(N-1), -np.ones(N-2)]) diags =np.array([-1, 0, 1]) return sparse.diags(data, diags ) # Laplacian operator . Zero dirichlet boundary conditions # why the hell is this reversed? Sigh. K = sparse.kronsum(build_K(Ny),build_K(Nx)) Ksolve = linalg.factorized(K) def build_interp(N): data = np.array([np.ones(N)/2., np.ones(N-1)/2.]) diags = np.array([0, 1]) return sparse.diags(data, diags, shape= (N-1,N)) interpy = sparse.kron(sparse.identity(Nx), build_interp(Ny)) interpx = sparse.kron(build_interp(Nx), sparse.identity(Ny)) def projection_pass(vx,vy): # alternating projection? Not necessary. In fact stupid. but easy. ''' vx[0,:] = 0 vx[-1,:] = 0 vy[:,0] = 0 vy[:,-1] = 0 ''' vx[0,:] /= 2. vx[-1,:] /= 2. vy[:,0] /= 2. vy[:,-1] /= 2. div = gradx.dot(vx.flatten()) + grady.dot(vy.flatten()) #calculate divergence w = Ksolve(div.flatten())#spsolve(K, div.flatten()) #solve potential return gradx.T.dot(w).reshape(Nx,Ny-1), grady.T.dot(w).reshape(Nx-1,Ny) for i in range(300): #while True: # v[:,:,0] += np.linalg.norm(img,axis=2) * dt * 0.001 # gravity force # interpolate onto edges vx = interpy.dot(v[:,:,0].flatten()).reshape(Nx,Ny-1) vy = interpx.dot(v[:,:,1].flatten()).reshape(Nx-1,Ny) # project incomperessible dvx, dvy = projection_pass(vx,vy) #interpolate change back to original grid v[:,:,0] -= interpy.T.dot(dvx.flatten()).reshape(Nx,Ny) v[:,:,1] -= interpx.T.dot(dvy.flatten()).reshape(Nx,Ny) #advect everything coords = np.stack( [(X - v[:,:,0]*dt)*Nx, (Y - v[:,:,1]*dt)*Ny], axis=0) print(coords.shape) print(v.shape) for j in range(3): img[:,:,j] = ndimage.map_coordinates(img[:,:,j], coords, order=5, mode='wrap') v[:,:,0] = ndimage.map_coordinates(v[:,:,0], coords, order=5, mode='wrap') v[:,:,1] = ndimage.map_coordinates(v[:,:,1], coords, order=5, mode='wrap') cv2.imshow('image',img) cv2.imwrite(f'will_anim3/{i:06}.jpg',img) k = cv2.waitKey(30) & 0xFF if k == ord(' '): break cv2.destroyAllWindows()
Code to produce the velocity graphs above.
import cvxpy as cvx import numpy as np from scipy import sparse from scipy.sparse.linalg import spsolve import matplotlib.pyplot as plt Nx = 50 Ny = 30 # velcitites live on the edges vx = np.zeros((Nx,Ny-1)) vy = np.zeros((Nx-1,Ny)) x = np.linspace(0,1,Nx, endpoint=False) y = np.linspace(0,1,Ny, endpoint=False) X, Y = np.meshgrid(x,y, indexing='ij') print(X[0,:]) print(X.shape) vx[:,:] = Y[:,1:] - 1 + X[:,1:] vy[:,:] = -X[1:,:] + Y[1:,:] data = np.array([-np.ones(Nx), np.ones(Nx-1)]) diags = np.array([0, 1]) grad = sparse.diags(data, diags, shape= (Nx-1,Nx)) print(grad.toarray()) gradx = sparse.kron(grad, sparse.identity(Ny-1)) data = np.array([-np.ones(Ny), np.ones(Ny-1)]) diags = np.array([0, 1]) grad = sparse.diags(data, diags, shape= (Ny-1,Ny)) print(grad.toarray()) grady = sparse.kron(sparse.identity(Nx-1), grad) print(gradx.shape) data = np.array([-np.ones(Nx-2), 2*np.ones(Nx-1), -np.ones(Nx-2)]) diags =np.array([-1, 0, 1]) Kx = sparse.diags(data, diags ) data = np.array([-np.ones(Ny-2), 2*np.ones(Ny-1), -np.ones(Ny-2)]) diags =np.array([-1, 0, 1]) Ky = sparse.diags(data, diags ) K = sparse.kronsum(Ky,Kx) plt.quiver(X[1:,1:], Y[1:,1:], vx[1:,:] + vx[:-1,:], vy[:,1:] + vy[:,:-1]) for i in range(60): div = gradx.dot(vx.flatten()) + grady.dot(vy.flatten()) print("div size", np.linalg.norm(div)) div = div.reshape(Nx-1,Ny-1) w = spsolve(K, div.flatten()) vx -= gradx.T.dot(w).reshape(Nx,Ny-1) vy -= grady.T.dot(w).reshape(Nx-1,Ny) # alternating projection? Not necessary. In fact stupid. but easy. div = gradx.dot(vx.flatten()) + grady.dot(vy.flatten()) print("new div size", np.linalg.norm(div)) vx[0,:] = 0 vx[-1,:] = 0 vy[:,0] = 0 vy[:,-1] = 0 div = gradx.dot(vx.flatten()) + grady.dot(vy.flatten()) print("new div size", np.linalg.norm(div)) print(vx) plt.figure() plt.quiver(X[1:,1:], Y[1:,1:], vx[1:,:] + vx[:-1,:], vy[:,1:] + vy[:,:-1]) plt.show()
I should give a particle in cell code a try
Links
-
-
-
- - Jos Stam stable fluid slides
-
-
Edit:
GregTJ found this post useful and made an even better simulator! Nice
()[] | https://www.philipzucker.com/annihilating-my-friend-will-with-a-python-fluid-simulation-like-the-cur-he-is/ | CC-MAIN-2021-39 | refinedweb | 1,859 | 62.54 |
Notes and disclaimers:
- This blog post contains raw notes for some of the SNIA’s SDC 2015 presentations (SNIA’s Storage Developers Conference 2015)
- These notes were typed during the talks and they may include typos and my own misinterpretations.
- Text in the bullets under each talk are quotes from the speaker or text from the speaker slides, not my personal opinion.
- If you feel that I misquoted you or badly represented the content of a talk, please add a comment to the post.
- I spent limited time fixing typos or correcting the text after the event. There are only so many hours in a day...
- I have not attended all sessions (since there are many being delivered at a time, that would actually not be possible :-)…
- SNIA usually posts the actual PDF decks a few weeks after the event. Attendees have access immediately.
- You can find the event agenda at
Understanding the Intel/Micron 3D XPoint Memory
Jim Handy, General Director, Objective Analysis
- Memory analyst, SSD analyst, blogs:,
- Not much information available since the announcement in July:
- Agenda: What? Why? Who? Is the world ready for it? Should I care? When?
- What: Picture of the 3D XPoint concept (pronounced 3d-cross-point). Micron’s photograph of “the real thing”.
- Intel has researched PCM for 45 years. Mentioned in an Intel article at “Electronics” in Sep 28, 1970.
- The many elements that have been tried shown in the periodic table of elements.
- NAND laid the path to the increased hierarchy levels. Showed prices of DRAM/NAND from 2001 to 2015. Gap is now 20x.
- Comparing bandwidth to price per gigabytes for different storage technologies: Tape, HDD, SSD, 3D XPoint, DRAM, L3, L2, L1
- Intel diagram mentions PCM-based DIMMs (far memory) and DDR DIMMs (near memory).
- Chart with latency for HDD SAS/SATA, SSD SAS/SATA, SSD NVMe, 3D XPoint NVMe – how much of it is the media, how much is the software stack?
- 3D Xpoint’s place in the memory/storage hierarchy. IOPS x Access time. DRAM, 3D XPoint (Optane), NVMe SSD, SATA SSD
- Great gains at low queue depth. 800GB SSD read IOPS using 16GB die. IOPS x queue depth of NAND vs. 3D XPoint.
- Economic benefits: measuring $/write IOPS for SAS HDD, SATA SSD, PCIe SSD, 3D XPoint
- Timing is good because: DRAM is running out of speed, NVDIMMs are catching on, some sysadmins understand how to use flash to reduce DRAM needs
- Timing is bad because: Nobody can make it economically, no software supports SCM (storage class memory), new layers take time to establish Why should I care: better cost/perf ratio, lower power consumption (less DRAM, more perf/server, lower OpEx), in-memory DB starts to make sense
- When? Micron slide projects 3D XPoint at end of FY17 (two months ahead of CY). Same slide shows NAND production surpassing DRAM production in FY17.
- Comparing average price per GB compared to the number of GB shipped over time. It takes a lot of shipments to lower price.
- Looking at the impact in the DRAM industry if this actually happens. DRAM slows down dramatically starting in FY17, as 3D XPoint revenues increase (optimistic).
Next Generation Data Centers: Hyperconverged Architectures Impact On Storage
Mark OConnell, Distinguished Engineer, EMC
- History: Client/Server –> shared SANs –> Scale-Out systems
- >> Scale-Out systems: architecture, expansion, balancing
- >> Evolution of the application platform: physical servers à virtualization à Virtualized application farm
- >> Virtualized application farms and Storage: local storage à Shared Storage (SAN) à Scale-Out Storage à Hyper-converged
- >> Early hyper-converged systems: HDFS (Hadoop) à JVM/Tasks/HDFS in every node
- Effects of hyper-converged systems
- >> Elasticity (compute/storage density varies)
- >> App management, containers, app frameworks
- >> Storage provisioning: frameworks (openstack swift/cinder/manila), pure service architectures
- >> Hybrid cloud enablement. Apps as self-describing bundles. Storage as a dynamically bound service. Enables movement off-prem.
Implications of Emerging Storage Technologies on Massive Scale Simulation Based Visual Effects
Yahya H. Mirza, CEO/CTO, Aclectic Systems Inc
- Steve Jobs quote: "You‘ve got to start with the customer experience and work back toward the technology".
- Problem 1: Improve customer experience. Higher resolution, frame rate, throughput, etc.
- Problem 2: Production cost continues to rise.
- Problem 3: Time to render single frame remains constant.
- Problem 4: Render farm power and cooling increasing. Coherent shared memory model.
- How do you reduce customer CapEx/OpEx. Low efficiency: 30% CPU. Prooblem is memory access latency and I/O.
- Production workflow: modeling, animation/simulation/shading, lighting, rendering, compositing. More and more simulation.
- Concrete production experiment: 2005. Story boards. Attempt to create a short film. Putting himself in the customer’s shoes. Shot decomposition.
- Real 3-minute short costs $2 million. Animatic to pitch the project.
- Character modeling and development. Includes flesh and muscle simulation. A lot of it done procedurally.
- Looking at Disney’s “Big Hero 6”, DreamWorks’ “Puss in Boots” and Weta’s “The Hobbit”, including simulation costs, frame rate, resolution, size of files, etc.
- Physically based rendering: global illumination effects, reflection, shadows. Comes down to light transport simulation, physically based materials description.
- Exemplary VFX shot pipeline. VFX Tool (Houdini/Maya), Voxelized Geometry (OpenVDB), Scene description (Alembic), Simulation Engine (PhysBam), Simulation Farm (RenderFarm), Simulation Output (OpenVDB), Rendering Engine (Mantra), Render Farm (RenderFarm), Output format (OpenEXR), Compositor (Flame), Long-term storage.
- One example: smoke simulation – reference model smoke/fire VFX. Complicated physical model. Hotspot algorithms: monte-carlo integration, ray-intersection test, linear algebra solver (multigrid).
- Storage implications. Compute storage (scene data, simulation data), Long term storage.
- Is public cloud computing viable for high-end VFX?
- Disney’s data center. 55K cores across 4 geos.
- Vertically integrated systems are going to be more and more important. FPGAs, ARM-based servers.
- Aclectic Colossus smoke demo. Showing 256x256x256.
- We don’t want coherency; we don’t want sharing. Excited about Intel OmniPath.
-
How Did Human Cells Build a Storage Engine?
Sanjay Joshi, CTO Life Sciences, EMC
- Human cell, Nuclear DNA, Transcription and Translation, DNA Structure
- The data structure: [char(3*10^9) human_genome] strand
- 3 gigabases [(3*10^9)*2]/8 = ~750MB. With overlaps, ~1GB per cell. 15-70 trillion cells.
- Actual files used to store genome are bigger, between 10GB and 4TB (includes lots of redundancy).
- Genome sequencing will surpass all other data types by 2040
- Protein coding portion is just a small portion of it. There’s a lot we don’t understand.
- Nuclear DNA: Is it a file? Flat file system, distributed, asynchronous. Search header, interpret, compile, execute.
- Nuclear DNA properties: Large:~20K genes/cell, Dynamic: append/overwrite/truncate, Semantics: strict, Consistent: No, Metadata: fixed, View: one-to-many
- Mitochondrial DNA: Object? Distributed hash table, a ring with 32 partitions. Constant across generations.
- Mitochondrial DNA: Small: ~40 genes/cell, Static: constancy, energy functions, Semantics: single origin, Consistent: Yes, Metadata: system based, View: one-to-one
- File versus object. Comparing Nuclear DNA and Mitochondrial DNA characteristics.
- The human body: 7500 names parts, 206 regularly occurring bones (newborns close to 300), ~640 skeletal muscles (320 pairs), 60+ organs, 37 trillion cells. Distributed cluster.
- Mapping the ISO 7 layers to this system. Picture.
- Finite state machine: max 10^45 states at 4*10^53 state-changes/sec. 10^24 NOPS (nucleotide ops per second) across biosphere.
- Consensus in cell biology: Safety: under all conditions: apoptosis. Availability: billions of replicate copies. Not timing dependent: asynchronous. Command completion: 10 base errors in every 10,000 protein translation (10 AA/sec).
- Object vs. file. Object: Maternal, Static, Haploid. Small, Simple, Energy, Early. File: Maternal and paternal, Diploid. Scalable, Dynamic, Complex. All cells are female first.
Move Objects to LTFS Tape Using HTTP Web Service Interface
Matt Starr, Chief Technical Officer, Spectra Logic
Jeff Braunstein, Developer Evangelist, Spectra Logic
- Worldwide data growth: 2009 = 800 EB, 2015 = 6.5ZB, 2020 = 35ZB
- Genomics. 6 cows = 1TB of data. They keep it forever.
- Video data. SD to Full HD to 4K UHD (4.2TB per hours) to 8K UHD. Also kept forever.
- Intel slide on the Internet minute. 90% of the people of the world never took a picture with anything but a camera phone.
- IOT - Total digital info create or replicated.
- $1000 genome scan take 780MB fully compressed. 2011 HiSeq-2000 scanner generates 20TB per month. Typical camera generates 105GB/day.
- More and more examples.
- Tape storage is the lowest cost. But it’s also complex to deploy. Comparing to Public and Private cloud…
- Pitfalls of public cloud – chart of $/PB/day. OpEx per PB/day reaches very high for public cloud.
- Risk of public cloud: Amazon has 1 trillion objects. If they lose 1% it would 10 billion objects.
- Risk of public cloud: Nirvanix. VC pulled the plug in September 2013.
- Cloud: Good: toolkits, naturally WAN friendly, user expectation: put it away.
- What if: Combine S3/Object with tape. Spectra S3 – Front end is REST, backend is LTFS tape.
- Cost: $.09/GB. 7.2PB. Potentially a $0.20 two-copy archive.
- Automated: App or user-built. Semi-Automated: NFI or scripting.
- Information available at
- All the tools you need to get started. Including simulator of the front end (BlackPearl) in a VM.
- S3 commands, plus data to write sequentially in bulk fashion.
- Configure user for access, buckets.
- Deep storage browser (source code on GitHub) allows you to browse the simulated storage.
- SDK available in Java, C#, many others. Includes integration with Visual Studio (demonstrated).
- Showing sample application. 4 lines of code from the SDK to move a folder to tape storage.
- Q: Access times when not cached? Hours or minutes. Depends on if the tape is already in the drive. You can ask to pull those to cache, set priorities. By default GET has higher priority than PUT. 28TB or 56TB of cache.
- Q: Can we use CIFS/NFS? Yes, there is an NFI (Network File Interface) using CIFS/NFS, which talks to the cache machine. Manages time-outs.
- Q: Any protection against this being used as disk? System monitors health of the tape. Using an object-based interface helps.
- Q: Can you stage a file for some time, like 24h? There is a large cache. But there are no guarantees on the latency. Keeping it on cache is more like Glacier. What’s the trigger to bring the data?
- Q: Glacier? Considering support for it. Data policy to move to lower cost, move it back (takes time). Not a lot of product or customers demanding it. S3 has become the standard, not sure if Glacier will be that for archive.
- Q: Drives are a precious resource. How do you handle overload? By default, reads have precedence over writes. Writes usually can wait.
Taxonomy of Differential Compression
Liwei Ren, Scientific Adviser, Trend Micro
- Mathematical model for describing file differences
- Lossless data compression categories: data compression (one file), differential compression (two files), data deduplication (multiple files)
- Purposes: network data transfer acceleration and storage space reduction
- Areas for DC – mobile phones’ firmware over the air, incremental update of files for security software, file synchronization and transfer over WAN, executable files
- Math model – Diff procedure: Delta = T – R, Merge procedure: T = R + Delta. Model for reduced network bandwidth, reduced storage cost.
- Applications: backup, revision control system, patch management, firmware over the air, malware signature update, file sync and transfer, distributed file system, cloud data migration
- Diff model. Two operations: COPY (source address, size [, destination address] ), ADD (data block, size [, destination address] )
- How to create the delta? How to encode the delta into a file? How to create the right sequence of COPY/ADD operations?
- Top task is an effective algorithm to identify common blocks. Not covering it here, since it would take more than half an hour…
- Modeling a diff package. Example.
- How do you measure the efficiency of an algorithm? You need a cost model.
- Categorizing: Local DC - LDC (xdelta, zdelta, bsdiff), Remote DC - RDC (rsync, RDC protocol, tsync), Iterative – IDC (proposed)
- Categorizing: Not-in-place merging: general files (xdelta, zdelta, bsdiff), executable files (bsdiff, courgette)
- Categorizing: In place merging: firmware as general files (FOTA), firmware as executable files (FOTA)
- Topics in depth: LDC vs RDC vs IDC for general files
- Topics in depth: LDC for executable files
- Topics in depth: LDC for in-place merging
New Consistent Hashing Algorithms for Data Storage
Jason Resch, Software Architect, Cleversafe
- Introducing a new algorithm for hashing.
- Hashing is useful. Used commonly is distributed storage, distributed caching.
- Independent users can coordinate (readers know where writers would write without talking to them).
- Typically, resizing a Hash Table is inefficient. Showing example.
- That’s why we need “Stable Hashing”. Showing example. Only a small portion of the keys need to be re-mapped.
- Stable hashing becomes a necessity when system is stateful and/or transferring state is expensive,
- Used in Caching/Routing (CARP), DHT/Storage (Gluster, DynamoDB, Cassandra, ceph, openstack)
- Stable Hashing with Global Namespaces. If you have a file name, you know what node has the data.
- Eliminates points of contention, no metadata systems. Namespace is fixed, but the system is dynamic.
- Balances read/write load across nodes, as well as storage utilization across nodes.
- Perfectly Stable Hashing (Rendezvous Hashing, Consistent Hashing). Precisely weighted (CARP, RUSH, CRUSH).
- It would be nice to have something that would offer the characteristics of both.
- Consistent: buckets inserted in random positions. Keys maps to the next node greater than that key. With a new node, only neighbors as disrupted. But neighbor has to send data to new node, might not distribute keys evenly.
- Rendezvous: Score = Hash (Bucket ID || Key). Bucket with the highest score wins. When adding a new node, some of the keys will move to it. Every node is disrupted evenly.
- CARP is rendezvous hashing with a twist. It multiples the scores by a “Load Factor” for each node. Allows for some nodes being more capable than others. Not perfectly stable: if node’s weighting changes or node is added, then all load factor must be recomputed.
- RUSH/CRUSH: Hierarchical tree, with each node assigned a probability to go left/right. CRUSH makes the tree match the fault domains of the system. Efficient to add nodes, but not to remove or re-weight nodes.
- New algorithm: Weighted Rendezvous Hashing (WRH). Both perfectly stable and precisely weighted.
- WRH adjusts scores before weighting them. Unlike CARP, scores aren’t relatively scaled.
- No unnecessary transfer of keys when adding/removing nodes. If adding node or increasing weight on node, other nodes will move keys to it, but nothing else. Transfers are equalized and perfectly efficient.
- WRH is simple to implement. Whole python code showed in one slide.
- All the magic is in one line: “Score = 1.0 / -math.log(hash_f)” - Proof of correctness provided for the math inclined.
- How Cleversafe uses WRH. System is grown by set of devices. Devices have a lifecycle: added, possibly expanded, then retired.
- Detailed explanation of the lifecycle and how keys move as nodes are added, expanded, retired.
- Storage Resource Map. Includes weight, hash_seed. Hash seed enables a clever trick to retire device sets more efficiently.
- Q: How to find data when things are being moved? If clients talk to the old node while keys are being moved. Old node will proxy the request to the new node.
Storage Class Memory Support in the Windows Operating System
Neal Christiansen, Principal Development Lead, Microsoft
- Windows support for non-volatile storage medium with RAM-like performance is a big change.
- Storage Class Memory (SCM): NVDIMM, 3D XPoint, others
- Microsoft involved with the standardization efforts in this space.
- New driver model necessary: SCM Bus Driver, SCM Disk Driver.
- Windows Goals for SCM: Support zero-copy access, run most user-mode apps unmodified, option for 100% backward compatibility (new types of failure modes), sector granular failure modes for app compat.
- Applications make lots of assumptions on the underlying storage
- SCM Storage Drivers will support BTT – Block Translation Table. Provides sector-level atomicity for writes.
- SCM is disruptive. Fastest performance and application compatibility can be conflicting goals.
- SCM-aware File Systems for Windows. Volume modes: block mode or DAS mode (chosen at format time).
- Block Mode Volumes – maintain existing semantics, full application compatibility
- DAS Mode Volumes – introduce new concepts (memory mapped files, maximizes performance). Some existing functionality is lost. Supported by NTFS and ReFS.
- Memory Mapped IO in DAS mode. Application can create a memory mapped section. Allowed when volumes resides on SCM hardware and the volume has been formatted for DAS mode.
- Memory Mapped IO: True zero copy access. BTT is not used. No paging reads or paging writes.
- Cached IO in DAS Mode: Cache manager creates a DAS-enabled cache map. Cache manager will copy directly between user’s buffer and SCM. Coherent with memory-mapped IO. App will see new failure patterns on power loss or system crash. No paging reads or paging writes.
- Non-cached IO in DAS Mode. Will send IO down the storage stack to the SCM driver. Will use BTT. Maintains existing storage semantics.
- If you really want the performance, you will need to change your code.
- DAS mode eliminates traditional hook points used by the file system to implement features.
- Features not in DAS Mode: NTFS encryption, NTS compression, NTFS TxF, ReFS integrity streams, ReFS cluster band, ReFS block cloning, Bitlocker volume encryption, snapshot via VolSnap, mirrored or parity via storage spaces or dynamic disks
- Sparse files won’t be there initially but will come in the future.
- Updated at the time the file is memory mapped: file modification time, mark file as modified in the USN journal, directory change notification
- File System Filters in DAS mode: no notification that a DAS volume is mounted, filter will indicate via a flag if they understand DAS mode semantics.
- Application compatibility with filters in DAS mode: No opportunity for data transformation filters (encryption, compression). Anti-virus are minimally impacted, but will need to watch for creation of writeable mapped sections (no paging writes anymore).
- Intel NVLM library. Open source library implemented by Intel. Defines set of application APIs for directly manipulating files on SCM hardware.
- NVLM library available for Linux today via GitHub. Microsoft working with Intel on a Windows port.
- Q: XIP (Execute in place)? It’s important, but the plans have not solidified yet.
- Q: NUMA? Can be in NUMA nodes. Typically, the file system and cache are agnostic to NUMA.
- Q: Hyper-V? Not ready to talk about what we are doing in that area.
- Q: Roll-out plan? We have one, but not ready to talk about it yet.
- Q: Data forensics? We’ve yet to discuss this with that group. But we will.
- Q: How far are you to completion? It’s running and working today. But it is not complete.
- Q: Windows client? To begin, we’re targeting the server. Because it’s available there first.
- Q: Effect on performance? When we’re ready to announce the schedule, we will announce the performance. The data about SCM is out there. It’s fast!
- Q: Will you backport? Probably not. We generally move forward only. Not many systems with this kind of hardware will run a down level OS.
- Q: What languages for the Windows port of NVML? Andy will cover that in his talk tomorrow.
- Q: How fast will memory mapped be? Potentially as fast as DRAM, but depends on the underlying technology.
The Bw-Tree Key-Value Store and Its Applications to Server/Cloud Data Management in Production
Sudipta Sengupta, Principal Research Scientist, Microsoft Research
- The B-Tree: key-ordered access to records. Balanced tree via page split and merge mechanisms.
- Design tenets: Lock free operation (high concurrency), log-structure storage (exploit flash devices with fast random reads and inefficient random writes), delta updates to pages (reduce cache invalidation, garbage creation)
- Bw-Tree Architecture: 3 layers: B-Tree (expose API, B-tree search/update, in-memory pages), Cache (logical page abstraction, move between memory and flash), Flash (reads/writes from/to storage, storage management).
- Mapping table: Expose logical pages to access method layer. Isolates updates to single page. Structure for lock-free multi-threaded concurrency control.
- Highly concurrent page updates with Bw-Tree. Explaining the process using a diagram.
- Bw-Tree Page Split: No hard threshold for splitting unlike in classical B-Tree. B-link structure allows “half-split” without locking.
- Flash SSDs: Log-Structured storage. Use log structure to exploit the benefits of flash and work around its quirks: random reads are fast, random in-place writes are expensive.
- LLAMA Log-Structured Store: Amortize cost of writes over many page updates. Random reads to fetch a “logical page”.
- Depart from tradition: logical page formed by linking together records on multiple physical pages on flash. Adapted from SkimpyStash.
- Detailed diagram comparing traditional page writing with the writing optimized storage organization with Bw-Tree.
- LLAMA: Optimized Logical Page Reads. Multiple delta records are packed when flushed together. Pages consolidated periodically in memory also get consolidated on flash when flushed.
- LLAMA: Garbage collection on flash. Two types of record units in the log: Valid or Orphaned. Garbage collection starts from the oldest portion of the log. Earliest written record on a logical page is encountered first.
- LLAMA: cache layer. Responsible for moving pages back and forth from storage.
- Bw-Tree Checkpointing: Need to flush to buffer and to storage. LLAMA checkpoint for fast recovery.
- Bw-Tree Fast Recovery. Restore mapping table from latest checkpoint region. Warm-up using sequential I/O.
- Bw-Tree: Support for transactions. Part of the Deuteronomy Architecture.
- End-to-end crash recovery. Data component (DC) and transactional component (TC) recovery. DC happens before TC.
- Bw-Tree in production: Key-sequential index in SQL Server in-memory database
- Bw-Tree in production: Indexing engine in Azure DocumentDB. Resource governance is important (CPU, Memory, IOPS, Storage)
- Bw-Tree in production: Sorted key-value store in Bing ObjectStore.
- Summary: Classic B-Tree redesigned for modern hardware and cloud. Lock-free, delta updating of pages, log-structure, flexible resource governor, transactional. Shipping in production.
- Going forward: Layer transactional component (Deuteronomy Architecture, CIDR 2015), open-source the codebase
ReFS v2: Cloning, Projecting, and Moving Data
J.R. Tipton, Development Lead, Microsoft
- Agenda: ReFS v1 primer, ReFS v2 at a glance, motivations for ReFS v2, cloning, translation, transformation
- ReFS v1 primer: Windows allocate-on-write file system, Merkel trees verify metadata integrity, online data correction from alternate copies, online chkdsk
- ReFS v2: Available in Windows Server 2016 TP4. Efficient, reliable storage for VMs, efficient parity, write tiering, read caching, block cloning, optimizations
- Motivations for ReFS v2: cheap storage does not mean slow, VM density, VM provisioning, more hardware flavors (SLC, MLC, TLC flash, SMR)
- Write performance. Magic does not work in a few environments (super fast hardware, small random writes, durable writes/FUA/sync/write-through)
- ReFS Block Cloning: Clone any block of one file into any other block in another file. Full file clone, reorder some or all data, project data from one area into another without copy
- ReFS Block Cloning: Metadata only operation. Copy-on-write used when needed (ReFS knows when).
- Cloning examples: deleting a Hyper-V VM checkpoint, VM provisioning from image.
- Cloning observations: app directed, avoids data copies, metadata operations, Hyper-V is the first but not the only one using this
- Cloning is no free lunch: multiple valid copies will copy-on-write upon changes. metadata overhead to track state, slam dunk in most cases, but not all
- ReFS cluster bands. Volume internally divvied up into bands that contain regular FS clusters (4KB, 64KB). Mostly invisible outside file system. Bands and clusters track independently (per-band metadata). Bands can come and go.
- ReFS can move bands around (read/write/update band pointer). Efficient write caching and parity. Writes to bands in fast tier. Tracks heat per band. Moves bands between tiers. More efficient allocation. You can move from 100% triple mirroring to 95% parity.
- ReFS cluster bands: small writes accumulate where writing is cheap (mirror, flash, log-structured arena), bands are later shuffled to tier where random writes are expensive (band transfers are fully sequential).
- ReFS cluster bands: transformation. ReFS can do stuff to the data in a band (can happen in the background). Examples: band compaction (put cold bands together, squeeze out free space), band compression (decompress on read).
- ReFS v2 summary: data cloning, data movement, data transformation. Smart when smart makes sense, switches to dumb when dumb is better. Takes advantages of hardware combinations. And lots of other stuff…
Innovator, Disruptor or Laggard, Where Will Your Storage Applications Live? Next Generation Storage
Bev Crair, Vice President and General Manager, Storage Group, Intel
- The world is changing: information growth, complexity, cloud, technology.
- Growth: 44ZB of data in all systems. 15% of the data is stored, since perceived cost is low.
- Every minute of every day: 2013 : 8h of of video uploaded to YouTube, 47,000 apps downloaded, 200 million e-mails
- Every minute of every day: 2015 : 300h of of video uploaded to YouTube, 51,000 apps downloaded, 204 million e-mails
- Data never sleeps: the internet in real time. tiles showing activities all around the internet.
- Data use pattern changes: sense and generate, collect and communicate, analyze and optimize. Example: HADRON collider
- Data use pattern changes: from collection to analyzing data, valuable data now reside outside the organization, analyzing and optimizing unstructured data
- Cloud impact on storage solutions: business impact, technology impact. Everyone wants an easy button
- Intelligent storage: Deduplication, real-time compression, intelligent tiering, thin provisioning. All of this is a software problem.
- Scale-out storage: From single system with internal network to nodes working together with an external network
- Non-Volatile Memory (NVM) accelerates the enterprise: Examples in Virtualization, Private Cloud, Database, Big Data and HPC
- Pyramid: CPU, DRAM, Intel DIMM (3D XPoint), Intel SSD (3D XPoint), NAND SSD, HDD, …
- Storage Media latency going down dramatically. With NVM, the bottleneck is now mostly in the software stack.
- Future storage architecture: complex chart with workloads for 2020 and beyond. New protocols, new ways to attach.
- Intel Storage Technologies. Not only hardware, but a fair amount of software. SPDK, NVMe driver, Acceleration Library, Lustre, others.
- Why does faster storage matter? Genome testing for cancer takes weeks, and the cancer mutates. Genome is 10TB. If we can speed up the time it takes to test it to one day, it makes a huge difference and you can create a medicine that saves a person’s life. That’s why it matters.
The Long-Term Future of Solid State Storage
Jim Handy, General Director, Objective Analysis
- How we got here? Why are we in the trouble we’re at right now? How do we get ahead of it? Where is it going tomorrow?
- Establishing a schism: Memory is in bytes (DRAM, Cache, Flash?), Storage is in blocks (Disk Tape, DVD, SAN, NAS, Cloud, Flash)
- Is it really about block? Block, NAND page, DRAM pages, CPU cache lines. It’s all in pages anyway…
- Is there another differentiator? Volatile vs. Persistent. It’s confusing…
- What is an SSD? SSDs are nothing new. Going back to DEC Bulk Core.
- Disk interfaces create delays. SSD vs HDD latency chart. Time scale in milliseconds.
- Zooming in to tens of microseconds. Different components of the SSD delay. Read time, Transfer time, Link transfer, platform and adapter, software
- Now looking at delays for MLC NAND ONFi2, ONFi3, PCIe x4 Gen3, future NVM on PCIe x4 Gen3
- Changing the scale to tens of microseconds on future NVM. Link Transfer, Platform & adapter and Software now accounts for most of the latency.
- How to move ahead? Get rid of the disk interfaces (PCIe, NVMe, new technologies). Work on the software: SNIA.
- Why now? DRAM Transfer rates. Chart transfer rates for SDRAM, DDR, DDR2, DDR3, DDR4. Designing the bus takes most of the time.
- DRAM running out of speed? We probably won’t see a DDR5. HMC or HBM a likely next step. Everything points to fixed memory sizes.
- NVM to the rescue. DRAM is not the only upgrade path. It became cheaper to use NAND flash than DRAM to upgrade a PC.
- NVM to be a new memory layer between DRAM & NAND: Intel/Micron 3D XPoint – “Optane”
- One won’t kill the other. Future systems will have DRAM, NVM, NAND, HDD. None of them will go away…
- New memories are faster than NAND. Chart with read bandwidth vs write bandwidth. Emerging NVRAM: FeRAM, eMRAM, RRAM, PRAM.
- Complex chart with emerging research memories. Clock frequency vs. Cell Area (cost).
- The computer of tomorrow. Memory or storage? In the beginning (core memory), there was no distinction between the two.
- We’re moving to an era where you can turn off the computer, turn it back on and there’s something in memory. Do you trust it?
- SCM – Storage Class Memory: high performance with archival properties. There are many other terms for it: Persistent Memory, Non-Volatile Memory.
- New NVM has disruptively low latency: Log chart with latency budgets for HDD, SATA SSD, NVMe, Persistent. When you go below 10 microseconds (as Persistent does), context switching does not make sense.
- Non-blocking I/O. NUMA latencies up to 200ns have been tolerated. Latencies below these cause disruption.
- Memory mapped files eliminate file system latency.
- The computer of tomorrow. Fixed DRAM size, upgradeable NVM (tomorrow’s DIMM), both flash and disk (flash on PCIe or own bus), much work needed on SCM software
- Q: Will all these layers survive? I believe so. There are potential improvements in all of them (cited a few on NAND, HDD).
- Q: Shouldn’t we drop one of the layers? Usually, adding layers (not removing them) is more interesting from a cost perspective.
- Q: Do we need a new protocol for SCM? NAND did well without much of that. Alternative memories could be put on a memory bus.
Concepts on Moving From SAS connected JBOD to an Ethernet Connected JBOD
Jim Pinkerton, Partner Architect Lead, Microsoft
- What if we took a JBOD, a simple device, and just put it on Ethernet?
- Re-Thinking the Software-defined Storage conceptual model definition: compute nodes, storage nodes, flakey storage devices
- Front-end fabric (Ethernet, IB or FC), Back-end fabric (directly attached or shared storage)
- Yesterday’s Storage Architecture: Still highly profitable. Compute nodes, traditional SAN/NAS box (shipped as an appliance)
- Today: Software Defined Storage (SDS) – “Converged”. Separate the storage service from the JBOD.
- Today: Software Defined Storage (SDS) – “Hyper-Converged” (H-C). Everything ships in a single box. Scale-out architecture.
- H-C appliances are a dream for the customer to install/use, but the $/GB storage is high.
- Microsoft Cloud Platform System (CPS). Shipped as a packaged deal. Microsoft tested and guaranteed.
- SDS with DAS – Storage layer divided into storage front-end (FE) and storage back-end (BE). The two communicate over Ethernet.
- SDS Topologies. Going from Converged and Hyper-Converged to a future EBOD topology. From file/block access to device access.
- Expose the raw device over Ethernet. The raw device is flaky, but we love it. The storage FE will abstract that, add reliability.
- I would like to have an EBOD box that could provide the storage BE.
- EBOD works for a variety of access protocols and topologies. Examples: SMB3 “block”, Lustre object store, Ceph object store, NVMe fabric, T10 objects.
- Shared SAS Interop. Nightmare experience (disk multi-path interop, expander multi-path interop, HBA distributed failure). This is why customers prefers appliances.
- To share or not to share. We want to share, but we do not want shared SAS. Customer deployment is more straightforward, but you have more traffic on Ethernet.
- Hyper-Scale cloud tension – fault domain rebuild time. Depends on number of disks behind a node and how much network you have.
- Fault domain for storage is too big. Required network speed offsets cost benefits of greater density. Many large disks behind a single node becomes a problem.
- Private cloud tension – not enough disks. Entry points at 4 nodes, small number of disks. Again, fault domain is too large.
- Goals in refactoring SDS – Storage back-end is a “data mover” (EBOD). Storage front-end is “general purpose CPU”.
- EBOD goals – Can you hit a cost point that’s interesting? Reduce storage costs, reduce size of fault domain, build a more robust ecosystem of DAS. Keep topology simple, so customer can build it themselves.
- EBOD: High end box, volume box, capacity box.
- EBOD volume box should be close to what a JBOD costs. Basically like exposing raw disks.
- Comparing current Hyper-Scale to EBOD. EBOD has an NIC and an SOC, in addition to the traditional expander in a JBOD.
- EBOD volume box – Small CPU and memory, dual 10GbE, SOC with RDMA NIC/SATA/SAS/PCIe, up to 20 devices, SFF-8639 connector, management (IPMI, DMTF Redfish?)
- Volume EBOD Proof Point – Intel Avaton, PCIe Gen 2, Chelsio 10GbE, SAS HBA, SAS SSD. Looking at random read IOPS (local, RDMA remote and non-RDMA remote). Max 159K IOPS w/RDMA, 122K IOPS w/o RDMA. Latency chart showing just a few msec.
- EBOD Performance Concept – Big CPU, Dual attach 40GbE, Possibly all NVME attach or SCM. Will show some of the results this afternoon.
- EBOD is an interesting approach that’s different from what we’re doing. But it’s nicely aligned with software-defined storage.
- Price point of EBOD must be carefully managed, but the low price point enables a smaller fault domain.
Planning for the Next Decade of NVM Programming
Andy Rudoff, SNIA NVM Programming TWG, Intel
- Looking at what’s coming up in the next decade, but will start with some history.
- Comparison of data storage technologies. Emerging NV technologies with read times in the same order of magnitude as DRAM.
- Moving the focus to software latency when using future NVM.
- Is it memory or storage? It’s persistent (like storage) and byte-addressable (like memory).
- Storage vs persistent memory. Block IO vs. byte addressable, sync/async (DMA master) vs. sync (DMA slave). High capacity vs. growing capacity.
- pmem: The new Tier. Byte addressable, but persistent. Not NAND. Can do small I/O. Can DMA to it.
- SNIA TWG (lots of companies). Defining the NVM programming model: NVM.PM.FILE mode and NVM.PM.VOLUME mode.
- All the OSes created in the last 30 years have a memory mapped file.
- Is this stuff real? Why are we spending so much time on this? Yes – Intel 3D XPoint technology, the Intel DIMM. Showed a wafer on stage. 1000x faster than NAND. 1000X endurance of NAND, 10X denser than conventional memory. As much as 6TB of this stuff…
- Timeline: Big gap between NAND flash memory (1989) and 3D XPoint (2015).
- Diagram of of the model with Management, Block, File and Memory access. Link at the end to the diagram.
- Detecting pmem: Defined in the ACPI 6.0. Linux support upstream (generic DIMM driver, DAX, ext4+DAX, KVM). Neal talked about Windows support yesterday.
- Heavy OSV involvement in TWG, we wrote the spec together.
- We don’t want every application to have to re-architecture itself. That’s why we have block and file there as well.
- The next decade
- Transparency levels: increasing barrier to adoption. increasing leverage. Could do it in layers. For instance, could be file system only, without app modification. For instance, could modify just the JVM to get significant advantages without changing the apps.
- Comparing to multiple cores in hardware and multi-threaded programming. Took a decade or longer, but it’s commonplace now.
- One transparent example: pmem Paging. Paging from the OS page cache (diagrams).
- Attributes of paging : major page faults, memory looks much larger, page in must pick a victim, many enterprise apps opt-out, interesting example: Java GC.
- What would it look like if you paged to pmem instead of paging to storage. I don’t even care that it’s persistent, just that there’s a lot of it.
- I could kick a page out synchronously, probably faster than a context switch. But the app could access the data in pmem without swapping it in (that‘s new!). Could have policies for which app lives in which memory. The OS could manage that, with application transparency.
- Would this really work? It will when pmem costs less, performance is close, capacity is significant and it is reliable. “We’re going to need a bigger byte” to hold error information.
- Not just for pmem. Other memories technologies are emerging. High bandwidth memory, NUMA localities, different NVM technologies.
- Extending into user space: NVM Library – pmem.io (64-bit Linux Alpha release). Windows is working on it as well.
- That is a non-transparent example. It’s hard (like multi-threading). Things can fail in interesting new ways.
- The library makes it easier and some of it is transactional.
- No kernel interception point, for things like replication. No chance to hook above or below the file system. You could do it in the library.
- Non-transparent use cases: volatile caching, in-memory database, storage appliance write cache, large byte-addressable data structures (hash table, dedup), HPC (checkpointing)
- Sweet spots: middleware, libraries, in-kernel usages.
- Big challenge: middleware, libraries. Is it worth the complexity.
- Building a software ecosystem for pmem, cost vs. benefit challenge.
- Prepare yourself: lean NVM programming model, map use cases to pmem, contribute to the libraries, software ecosystem
FS Design Around SMR: Seagate’s Journey and Reference System with EXT4
Adrian Palmer, Drive Development Engineering, Seagate Technologies
- SNIA Tutorial. I’m talking about the standard, as opposed as the design of our drive.
- SMR is being embraced by everyone, since this is a major change, a game changes.
- From random writes to resemble the write profile of sequential-access tape.
- 1 new condition: forward-write preferred. ZAC/ZBD spec: T10/13. Zones, SCSI ZBC standards, ATA ZAC standards.
- What is a file system? Essential software on a system, structured and unstructured data, stores metadata and data.
- Basic FS requirements: Write-in-place (superblock, known location on disk), Sequential write (journal), Unrestricted write type (random or sequential)
- Drive parameters: Sector (atomic unit of read/write access). Typically 512B size. Independently accessed. Read/write, no state.
- Drive parameters: Zone (atomic performant rewrite unit). Typically 256 MiB in size. Indirectly addressed via sector. Modified with ZAC/ZBD commands. Each zone has state (WritePointer, Condition, Size, Type).
- Write Profiles. Conventional (random access), Tape (sequential access), Flash (sequential access, erase blocks), SMR HA/HM (sequential access, zones). SMR write profile is similar to Tape and Flash.
- Allocation containers. Drive capacities are increasing, location mapping is expensive. 1.56% with 512B blocks or 0.2% with 4KB blocks.
- Remap the block device as a… block device. Partitions (w*sector size), Block size (x*sector size), Group size (y*Block size), FS (z*group size, expressed as blocks).
- Zones are a good fit to be matched with Groups. Absorb and mirror the metadata, don’t keep querying drive for metadata.
- Solving the sequential write problem. Separate the problem spaces with zones.
- Dedicate zones to each problem space: user data, file records, indexes, superblock, trees, journal, allocation containers.
- GPT/Superblocks: First and last zone (convention, not guaranteed). Update infrequently, and at dismount. Looks at known location and WritePointer. Copy-on-update. Organized wipe and update algorithm.
- Journal/soft updates. Update very frequently, 2 or more zones, set up as a circular buffer. Checkpoint at each zone. Wipe and overwrite oldest zone. Can be used as NV cache for metadata. Requires lots of storage space for efficient use and NV.
- Group descriptors: Infrequently changed. Changes on zone condition change, resize, free block counts. Write cached, butwritten at WritePointer. Organized as a B+Tree, not an indexed array. The B+Tree needs to be stored on-disk.
- File Records: POSIX information (ctime, mtime, atime, msize, fs specific attributes), updated very frequently. Allows records to be modified in memory, written to journal cache, gather from journal, write to new blocks at WritePointer.
- Mapping (file records to blocks). File ideally written as a single chunk (single pointer), but could become fragmented (multiple pointers). Can outgrow file record space, needs its own B+Tree. List can be in memory, in the journal, written out to disk at WritePointer.
- Data: Copy-on-write. Allocator chooses blocks at WritePointer. Writes are broken at zone boundary, creating new command and new mapping fragment.
- Cleanup: Cannot clean up as you go, need a separate step. Each zone will have holes. Garbage collection: Journal GC, Zones GC, Zone Compaction, Defragmentation.
- Advanced features: indexes, queries, extended attributes, snapshots, checksums/parity, RAID/JBOD.
Azure File Service: ‘Net Use’ the Cloud
David Goebel, Software Engineer, Microsoft
- Agenda: features and API (what), scenarios enabled (why), design of an SMB server not backed by a conventional FS (how)
- It’s not the Windows SMB server (srv2.sys). Uses Azure Tables and Azure Blobs for the actual files.
- Easier because we already have a highly available and distributed architecture.
- SMB 2.1 in preview since last summer. SMB 3.0 (encryption, persistent handles) in progress.
- Azure containers mapped as shares. Clients work unmodified out-of-the-box. We implemented the spec.
- Share namespace is coherently accessible
- MS-SMB2, not SMB1. Anticipates (but does not require) a traditional file system on the other side.
- In some ways it’s harder, since what’s there is not a file system. We have multiple tables (for leases, locks, etc). Nice and clean.
- SMB is a stateful protocol, while REST is all stateless. Some state is immutable (like FileId), some state is transient (like open counts), some is maintained by the client (like CreateGuid), some state is ephemeral (connection).
- Diagram with the big picture. Includes DNS, load balancer, session setup & traffic, front-end node, azure tables and blobs.
- Front-end has ephemeral and immutable state. Back-end has solid and fluid durable state.
- Diagram with two clients accessing the same file and share, using locks, etc. All the state handled by the back-end.
- Losing a front-end node considered a regular event (happens during updates), the client simple reconnects, transparently.
- Current state, SMB 2.1 (SMB 3.0 in the works). 5TB per share and 1TB per file. 1,000 8KB IOPS per share, 60MB/sec per share. Some NTFS features not supported, some limitations on characters and path length (due to HTTP/REST restrictions).
- Demo: I’m actually running my talk using a PPTX file on Azure File. Robocopy to file share. Delete, watch via explorer (notifications working fine). Watching also via wireshark.
- Currently Linux Support. Lists specific versions Ubuntu Server, Ubuntu Core, CentOS, Open SUSE, SUSE Linux Enterprise Server.
- Why: They want to move to cloud, but they can’t change their apps. Existing file I/O applications. Most of what was written over the last 30 years “just works”. Minor caveats that will become more minor over time.
- Discussed specific details about how permissions are currently implemented. ACL support is coming.
- Example: Encryption enabled scenario over the internet.
- What about REST? SMB and REST access the same data in the same namespace, so a gradual application transition without disruption is possible. REST for container, directory and file operations.
- The durability game. Modified state that normally exists only in server memory, which must be durably committed.
- Examples of state tiering: ephemeral state, immutable state, solid durable state, fluid durable state.
- Example: Durable Handle Reconnect. Intended for network hiccups, but stretched to also handles front-end reconnects. Limited our ability because of SMB 2.1 protocol compliance.
- Example: Persistent Handles. Unlike durable handles, SMB 3 is actually intended to support transparent failover when a front-end dies. Seamless transparent failover.
- Resource Links: Getting started blog () , NTFS features currently not supported (), naming restrictions for REST compatibility ().
Software Defined Storage - What Does it Look Like in 3 Years?
Richard McDougall, Big Data and Storage Chief Scientist, VMware
- How do you come up with a common, generic storage platform that serves the needs of application?
- Bringing a definition of SDS. Major trends in hardware, what the apps are doing, cloud platforms
- Storage workloads map. Many apps on 4 quadrants on 2 axis: capacity (10’s of Terabytes to 10’s of Petabytes) and IOPS (1K to 1M)
- What are cloud-native applications? Developer access via API, continuous integration and deployment, built for scale, availability architected in the app, microservices instead of monolithic stacks, decoupled from infrastructure
- What do Linux containers need from storage? Copy/clone root images, isolated namespace, QoS controls
- Options to deliver storage to containers: copy whole root tree (primitive), fast clone using shared read-only images, clone via “Another Union File System” (aufs), leverage native copy-on-write file system.
- Shared data: Containers can share file system within host or across hots (new interest in distributed file systems)
- Docker storage abstractions for containers: non-persistent boot environment, persistent data (backed by block volumes)
- Container storage use cases: unshared volumes, shared volumes, persist to external storage (API to cloud storage)
- Eliminate the silos: converged big data platform. Diagram shows Hadoop, HBase, Impala, Pivotal HawQ, Cassandra, Mongo, many others. HDFS, MAPR, GPFS, POSIX, block storage. Storage system common across all these, with the right access mechanism.
- Back to the quadrants based on capacity and IOPS. Now with hardware solutions instead of software. Many flash appliances in the upper left (low capacity, high IOPS). Isilon in the lower right (high capacity, low IOPS).
- Storage media technologies in 2016. Pyramid with latency, capacity per device, capacity per host for each layer: DRAM (1TB/device, 4TB/host, ~100ns latency), NVM (1TB, 4TB, ~500ns), NVMe SSD (4TB, 48TB, ~10us), capacity SSD (16TB, 192TB, ~1ms), magnetic storage (32TB, 384TB, ~10ms), object storage (?, ?, ~1s).
- Back to the quadrants based on capacity and IOPS. Now with storage media technologies.
- Details on the types of NVDIMM (NVIMM-N - Type 1, NVDIMM-F – Type 2, Type 4). Standards coming up for all of these. Needs work to virtualize those, so they show up properly inside VMs.
- Intel 3D XPoint Technology.
- What are the SDS solutions than can sit on top of all this? Back to quadrants with SDS solutions. Nexenta, Mentions ScaleiO, VSAN, ceph, Scality, MAPR, HDFS. Can you make one solution that works well for everything?
- What’s really behind a storage array? The value from the customer is that it’s all from one vendor and it all works. Nothing magic, but the vendor spent a ton of time on testing.
- Types of SDS: Fail-over software on commodity servers (lists many vendors), complexity in hardware, interconnects. Issues with hardware compatibility.
- Types of SDS: Software replication using servers + local disks. Simpler, but not very scalable.
- Types of SDS: Caching hot core/cold edge. NVMe flash devices up front, something slower behind it (even cloud). Several solutions, mostly startups.
- Types of SDS: Scale-out SDS. Scalable, fault-tolerant, rolling updates. More management, separate compute and storage silos. Model used by ceph, ScaleiO. Issues with hardware compatibility. You really need to test the hardware.
- Types of SDS: Hyper-converged SDS. Easy management, scalable, fault-tolerant, rolling upgrades. Fixed compute to storage ration. Model used by VSAN, Nutanix. Amount of variance in hardware still a problem. Need to invest in HCL verification.
- Storage interconnects. Lots of discussion on what’s the right direction. Protocols (iSCSI, FC, FCoE, NVMe, NVMe over Fabrics), Hardware transports (FC, Ethernet, IB, SAS), Device connectivity (SATA, SAS, NVMe)
- Network. iSCSI, iSER, FCoE, RDMA over Ethernet, NVMe Fabrics. Can storage use the network? RDMA debate for years. We’re at a tipping point.
- Device interconnects: HCA with SATA/SAS. NVMe SSD, NVM over PCIe. Comparing iSCSI, FCoE and NVMe over Ethernet.
- PCIe rack-level Fabric. Devices become addressable. PCIe rack-scale compute and storage, with host-to-host RDMA.
- NVMe – The new kid on the block. Support from various vendors. Quickly becoming the all-purpose stack for storage, becoming the universal standard for talking block.
- Beyond block: SDS Service Platforms. Back to the 4 quadrants, now with service platforms.
- Too many silos: block, object, database, key-value, big data. Each one is its own silo with its own machines, management stack, HCLs. No sharing of infrastructure.
- Option 1: Multi-purpose stack. Has everything we talked about, but it’s a compromise.
- Option 2: Common platform + ecosystem of services. Richest, best-of-breed services, on a single platform, manageable, shared resources.
Why the Storage You Have is Not the Storage Your Data Needs
Laz Vekiarides, CTO and Co-founder, ClearSky Data
- ClearSky Data is a tech company, consumes what we discussed in this conference.
- The problem we’re trying to solve is the management of the storage silos
- Enterprise storage today. Chart: Capacity vs. $/TB. Flash, Mid-Range, Scale-Out. Complex, costly silos
- Describe the lifecycle of the data, the many copies you make over time, the rebuilding and re-buying of infrastructure
- What enterprises want: buy just enough of the infrastructure, with enough performance, availability, security.
- Cloud economics – pay only for the stuff that you use, you don’t have to see all the gear behind the storage, someone does the physical management
- Tiering is a bad answer – Nothing remains static. How fast does hot data cool? How fast does it re-warm? What is the overhead to manage it? It’s a huge overhead. It’s not just a bandwidth problem.
- It’s the latency, stupid. Data travels at the speed of light. Fast, but finite. Boston to San Francisco: 29.4 milliseconds of round-trip time (best case). Reality (with switches, routers, protocols, virtualization) is more like 70 ms.
- So, where exactly is the cloud? Amazon East is near Ashburn, VA. Best case is 10ms RTT. Worst case is ~150ms (does not include time to actually access the storage).
- ClearSky solution: a global storage network. The infrastructure becomes invisible to you, what you see is a service level agreement.
- Solution: Geo-distributed data caching. Customer SAN, Edge, Metro POP, Cloud. Cache on the edge (all flash), cache on the metro POP.
- Edge to Metro POP are private lines (sub millisecond latency). Addressable market is the set of customers within a certain distance to the Metro POP.
- Latency math: Less than 1ms to the Metro POP, cache miss path is between 25ms and 50ms.
- Space Management: Edge (hot, 10%, 1 copy), POP (warm, <30%, 1-2 copies), Cloud (100%, n copies). All data is deduplicated and encrypted.
- Modeling cache performance: Miss ratio curve (MRC). Performance as f(size), working set knees, inform allocation policy.
- Reuse distance (unique intervening blocks between use and reuse). LRU is most of what’s out there. Look at stacking algorithms. Chart on cache size vs. miss ratio. There’s a talk on this tomorrow by CloudPhysics.
- Worked with customers to create a heat map data collector. Sizing tool for VM environments. Collected 3-9 days of workload.
- ~1,400 virtual disks, ~800 VMs, 18.9TB (68% full), avg read IOPS 5.2K, write IOPS 5.9K. Read IO 36KB, write IO 110KB. Read Latency 9.7ms, write latency 4.5ms.
- This is average latency, maximum is interesting, some are off the chart. Some were hundred of ms, even 2 second.
- Computing the cache miss ratio. How much cache would we need to get about 90% hit ratio? Could do it with less than 12% of the total.
- What is cache hit for writes? What fits in the write-back cache. You don’t want to be synchronous with the cloud. You’ll go bankrupt that way.
- Importance of the warm tier. Hot data (Edge, on prem, SSD) = 12%, warm data (Metro PoP, SSD and HDD) = 6%, cold data (Cloud) = 82%. Shown as a “donut”.
- Yes, this works! We’re having a very successful outcome with the customers currently engaged.
- Data access is very tiered. Small amounts of flash can yield disproportionate performance benefits. Single tier cache in front of high latency storage can’t work. Network latency is as important as bounding media latency.
- Make sure your caching is simple. Sometimes you are overthinking it.
- Identifying application patterns is hard. Try to identify the sets of LBA that are accessed. Identify hot spots, which change over time. The shape of the miss ratio remains similar.
Emerging Trends in Software Development
Donnie Berkholz, Research Director, 451 Research
- How people are building applications. How storage developers are creating and shipping software.
- Technology adoption is increasingly bottom-up. Open source, cloud. Used to be like building a cathedral, now it’s more like a bazaar.
- App-dev workloads are quickly moving to the cloud. Chart from all-on-prem at the top to all-cloud at the bottom.
- All on-prem going from 59% now to 37% in a few years. Moving to different types of clouds (private cloud, Public cloud (IaaS), Public cloud (SaaS).
- Showing charts for total data at organization, how much in off-premises cloud (TB and %). 64% of people have less than 20% on the cloud.
- The new stack. There’s a lot of fragmentation. 10 languages in the top 80%. Used to be only 3 languages. Same thing for databases. It’s more composable, right tool for the right job.
- No single stack. An infinite set of possibilities.
- Growth in Web APIs charted since 2005 (from ProgrammableWeb). Huge growth.
- What do enterprises think of storage vendors. Top vendors. People not particularly happy with their storage vendors. Promise index vs. fulfillment index.
- Development trends that will transform storage.
- Containers. Docker, docker, docker. Whale logos everywhere. When does it really make sense to use VMs or containers? You need lots of random I/O for these to work well. 10,000 containers in a cluster? Where do the databases go?
- Developers love Docker. Chart on configuration management GitHub totals (CFEngine, Puppet, Chef, Ansible, Salt, Docker). Shows developer adoption. Docker is off the charts.
- It’s not just a toy. Survey of 1,000 people on containers. Docker is only 2.5 years old now. 20% no plans, 56% evaluating. Total doing pilot or more add up to 21%. That’s really fast adoption
- Docker to microservices.
- Amazon: “Every single data transfer between teams has to happen through an API or you’re fired”. Avoid sending spreadsheets around.
- Microservices thinking is more business-oriented, as opposed to technology-oriented.
- Loosely couple teams. Team organization has a great influence in your development.
- The foundation of microservices. Terraform, MANTL, Apache Mesos, Capgemini Appollo, Amazon EC2 Container Service.
- It’s a lot about scheduling. Number of schedulers that use available resources. Makes storage even more random.
- Disruption in data processing. Spark. It’s a competitor to Hadoop, really good at caching in memory, also very fast on disk. 10x faster than map-reduce. People don’t have to be big data experts. Chart: Spark came out of nowhere (mining data from several public forums).
- The market is coming. Hadoop market as a whole growing 46% (CAGR).
- Storage-class memory. Picture of 3D XPoint. Do app developer care? Not sure. Not many optimize for cache lines in memory. Thinking about Redis in-memory database for caching. Developers probably will use SCM that way. Caching in the order of TB instead of GB.
- Network will be incredibly important. Moving bottlenecks around.
- Concurrency for developers. Chart of years vs. Percentage of Ohlon. Getting near to 1%. That’s a lot single the most popular is around 10%.
- Development trends
- DevOps. Taking agile development all the way to production. Agile, truly tip to tail. You want to iterate while involving your customers. Already happening with startups, but how do you scale?
- DevOps: Culture, Automation (Pets vs. Cattle), Measurement
- Automation: infrastructure as code. Continuous delivery.
- Measurement: Nagios, graphite, Graylog2, splunk, Kibana, Sensu, etsy/statsd
- DevOps is reaching DBAs. #1 stakeholder in recent survey.
- One of the most popular team structure change. Dispersing the storage team.
- The changing role of standards
- The changing role of benchmarks. Torturing databases for fun and profit.
- I would love for you to join our panel. If you fill our surveys, you get a lot of data for free.
Learnings from Nearly a Decade of Building Low-cost Cloud Storage
Gleb Budman, CEO, Backblaze
- What we learned, specifically the cost equation
- 150+ PB of customer data. 10B files.
- In 2007 we wanted to build something that would backup your PC/Mac data to the cloud. $5/month.
- Originally we wanted to put it all on S3, but we would lose money on every single customer.
- Next we wanted to buy SANs to put the data on, but that did not make sense either.
- We tried a whole bunch of things. NAS, USB-connected drives, etc.
- Cloud storage has a new player, with a shockingly low price: B2. One fourth of the cost of S3.
- Lower than Glacier, Nearline, S3-Infrequent Access, anything out there. Savings here add up.
- Datacenter: convert kilowatts-to-kilobits
- Datacenter Consideration: local cost to power, real state, taxes, climate, building/system efficiency, proximity to good people, connectivity.
- Hardware: Connect hard drives to the internet, with as little as possible in between.
- Blackblaze storage box, costs about $3K. As simple as possible, don’t make the hardware itself redundant. Use commodity parts (example: desktop power supply), use consumer hard drives, insource & use math for drive purchases.
- They told us we could not use consumer hard drives. But reality is that the failure rate was actually lower. They last 6 years on average. Even if the enterprise HDD never fail, they still don’t make sense.
- Insource & use math for drive purchases. Drives are the bulk of the cost. Chart with time vs. price per gigabyte. Talking about the Thailand Hard Drive Crisis.
- Software: Put all intelligence here.
- Blackblaze vault: 20 hard drives create 1 tome that share parts of a file, spread across racks.
- Avoid choke point. Every single storage pods is a first class citizen. We can parallelize.
- Algorithmically monitor SMART stats. Know which SMART codes correlate to annual failure rate. All the data is available on the site (all the codes for all the drives).
- Plan for silent corruption. Bad drive looks exactly like a good drive.
- Put replication above the file system.
- Run out of resources simultaneous. Hardware and software together. Avoid having CPU pegged and your memory unused. Have your resources in balance, tweak over time.
- Model and monitor storage burn. It’s important not to have too much or too little storage. Leading indicator is not storage, it’s bandwidth.
- Business processes. Design for failure, but fix failures quickly. Drives will die, it’s what happens at scale.
- Create repeatable repairs. Avoid the need for specialized people to do repair. Simple procedures: either swap a drive or swap a pod. Requires 5 minutes of training.
- Standardize on the pod chassis. Simplifies so many things…
- Use ROI to drive automation. Sometimes doing things twice is cheaper than automation. Know when it makes sense.
- Workflow for storage buffer. Treat buffer in days, not TB. Model how many days of space available you need. Break into three different buffer types: live and running vs. in stock but not live vs. parts.
- Culture: question “conventional wisdom”. No hardware worshippers. We love our red storage boxes, but we are a software team.
- Agile extends to hardware. Storage Pod Scrum, with product backlog, sprints, etc.
- Relentless focus on cost: Is it required? Is there a comparable lower cost option? Can business processes work around it? Can software work around it?
f4: Facebook’s Warm BLOB Storage System
Satadru Pan, Software Engineer, Facebook
- White paper “f4: Facebook’s Warm BLOB Storage System” at
- Looking at how data cools over time. 100x drop in reads in 60 days.
- Handling failure. Replication: 1.2 * 3 = 3.6. To lose data we need to lose 9 disks or 3 hosts. Hosts in different racks and datacenters.
- Handling load. Load spread across 3 hosts.
- Background: Data serving. CDN protects storage, router abstracts storage, web tier adds business logic.
- Background: Haystack [OSDI2010]. Volume is a series of blobs. In-memory index.
- Introducing f4: Haystack on cells. Cells = disks spread over a set of racks. Some compute resource in each cell. Tolerant to disk, host, rack or cell failures.
- Data splitting: Split data into smaller blocks. Reed Solomon encoding, Create stripes with 5 data blocks and 2 parity blocks.
- Blobs laid out sequentially in a block. Blobs do not cross block boundary. Can also rebuild blob, might not need to read all of the block.
- Each stripe in a different rack. Each block/blob split into racks. Mirror to another cell. 14 racks involved.
- Read. Router does Index read, Gets physical location (host, filename, offset). Router does data read. If data read fails, router sends request to compute (decoders).
- Read under datacenter failure. Replica cell in a different data center. Router proxies read to a mirror cell.
- Cross datacenter XOR. Third cell has a byte-by-byte XOR of the first two. Now mix this across 3 cells (triplet). Each has 67% data and 33% replica. 1.5 * 1.4 = 2.1X.
- Looking at reads with datacenter XOR. Router sends two read requests to two local routers. Builds the data from the reads from the two cells.
- Replication factors: Haystack with 3 copies (3.6X), f4 2.8 (2.8X), f4 2.1 (2.1X). Reduced replication factor, increased fault tolerance, increase load split.
- Evaluation. What and how much data is “warm”?
- CDN data: 1 day, 0.5 sampling. BLOB storage data: 2 week, 0.1%, Random distribution of blobs assumed, the worst case rates reported.
- Hot data vs. Warm data. 1 week – 350 reads/sec/disk, 1 month – 150r/d/s, 3 months – 70r/d/s, 1 year 20r/d/s. Wants to keep above 80 reads/sec/disk. So chose 3 months as divider between hot and warm.
- It is warm, not cold. Chart of blob age vs access. Even old data is read.
- F4 performance: most loaded disk in cluster: 35 reads/second. Well below the 80r/s threshold.
- F4 performance: latency. Chart of latency vs. read response. F4 is close to Haystack.
- Conclusions. Facebook blob storage is big and growing. Blobs cool down with age very rapidly. 100x drop in reads in 60 days. Haystack 3.6 replication over provisioning for old, warm data. F4 encodes data to lower replication to 2.1X, without compromising performance significantly.
Pelican: A Building Block for Exascale Cold Data Storage
Austin Donnelly, Principal Research Software Development Engineer, Microsoft
- White paper “Pelican: A building block for exascale cold data storage” at
- This is research, not a product. No product announcement here. This is a science project that we offer to the product teams.
- Background: Cold data in the cloud. Latency (ms. To hours) vs. frequency of access. SSD, 15K rpm HDD, 7.2K rpm HDD, Tape.
- Defining hot, warm, archival tiers. There is a gap between warm and archival. That’s were Pelican (Cold) lives.
- Pelican: Rack-scale co-design. Hardware and software (power, cooling, mechanical, HDD, software). Trade latency for lower cost. Massive density, low per-drive overhead.
- Pelican rack: 52U, 1152 3.5” HDD. 2 servers, PCIe bus stretched rack wide. 4 x 10Gb links. Only 8% of disks can spin.
- Looking at pictures of the rack. Very little there. Not many cables.
- Interconnect details. Port multiplier, SATA controller, Backplane switch (PCIe), server switches, server, datacenter network. Showing bandwidth between each.
- Research challenges: Not enough cooling, power, bandwidth.
- Resource use: Traditional systems can have all disks running at once. In Pelican, a disk is part of a domain: power (2 of 16), cooling (1 of 12), vibration (1 of 2), bandwidth (tree).
- Data placement: blob erasure-encoded on a set of concurrently active disks. Sets can conflict in resource requirement.
- Data placement: random is pretty bad for Pelican. Intuition: concentrate conflicts over a few set of disks. 48 groups of 24 disk. 4 classes of 12 fully-conflicting groups. Blob storage over 18 disks (15+3 erasure coding).
- IO scheduling: “spin up is the new seek”. All our IO is sequential, so we only need to optimize for spin up. Four schedulers, with 12 groups per scheduler, only one active at a time.
- Naïve scheduler: FIFO. Pelican scheduler: request batching – trade between throughput and fairness.
- Q: Would this much spin up and down reduce endurance of the disk. We’re studying it, not conclusive yet, but looking promising so far.
- Q: What kind of drive? Archive drives, not enterprise drives.
- Demo. Showing system with 36 HBAs in device manager. Showing Pelican visualization tool. Shows trays, drives, requests. Color-coded for status.
- Demo. Writing one file: drives spin up, request completes, drives spin down. Reading one file: drives spin up, read completes, drives spin down.
- Performance. Compare Pelican to a mythical beast. Results based on simulation.
- Simulator cross-validation. Burst workload.
- Rack throughput. Fully provisioned vs. Pelican vs. Random placement. Pelican works like fully provisioned up to 4 requests/second.
- Time to first byte. Pelican adds spin-up time (14.2 seconds).
- Power consumption. Comparing all disks on standby (1.8kW) vs. all disks active (10.8kW) vs. Pelican (3.7kW).
- Trace replay: European Center for Medium-range Weather Forecast. Every request for 2.4 years. Run through the simulator. Tiering model. Tiered system with Primary storage, cache and pelican.
- Trace replay: Plotting highest response time for a 2h period. Response time was not bad, simulator close to the rack.
- Trace replay: Plotting deepest queues for a 2h period. Again, simulator close to the rack.
- War stories. Booting a system with 1152 disks (BIOS changes needed). Port multiplier – port 0 (firmware change needed). Data model for system (serial numbers for everything). Things to track: slots, volumes, media.
Torturing Databases for Fun and Profit
Mai Zheng, Assistant Professor Computer Science Department - College of Arts and Sciences, New Mexico State University
- White paper “Torturing Databases for Fun and Profit” at
- Databases are used to store important data. Should provide ACID properties: atomicity, consistency, isolation, durability – even under failures.
- List of databases that passed the tests: <none>. Everything is broken under simulated power faults.
- Power outages are not that uncommon. Several high profile examples shown.
- Fault model: clean termination of I/O stream. Model does not introduce corruption/dropping/reorder.
- How to test: Connect database to iSCSI target, then decouple the database from the iSCSI target.
- Workload example. Key/value table. 2 threads, 2 transactions per thread.
- Known initial state, each transaction updates N random work rows and 1 meta row. Fully exercise concurrency control.
- Simulates power fault during our workload. Is there any ACID violation after recovery? Found atomicity violation.
- Capture I/O trace without kernel modification. Construct a post-fault disk image. Check the post-fault DB.
- This makes testing different fault points easy. But enhanced it with more context, to figure out what makes some fault points special.
- With that, five patterns found. Unintended update to the mmap’ed blocks. Pattern-based ranking of where fault injections will lead to pattern.
- Evaluated 8 databases (open source and commercial). Not a single database could survive.
- The most common violation was durability. Some violations are difficult to trigger, but the framework helped.
- Case study: A TokyoCabinet Bug. Looking at the fault and why the database recovery did not work.
- Pattern-based fault injection greatly reduced test points while achieving similar coverage.
- Wake up call: Traditional testing methodology may not be enough for today’s complex storage systems.
- Thorough testing requires purpose-built workloads and intelligent fault injection techniques.
- Different layers in the OS can help in different ways. For instance, iSCSI is an ideal place for fault injection.
- We should bridge the gaps in understanding and assumptions. For instance, durability might not be provided by the default DB configuration.
Personal Cloud Self-Protecting Self-Encrypting Storage Devices
Robert Thibadeau, Ph.D., Scientist and Entrepreneur, CMU, Bright Plaza
- This talk is about personal devices, not enterprise storage.
- The age of uncontrolled data leaks. Long list of major hacks recently. All phishing initiated.
- Security ~= Access Control. Security should SERVE UP privacy.
- Computer security ~= IPAAAA, Integrity, Private, Authentication, Authorization, Audit, Availability. The first 3 are encryption, the other aren’t.
- A storage device is a computing device. Primary host interface, firmware, special hardware functions, diagnostic parts, probe points.
- For years, there was a scripting language inside the drives.
- TCG Core Spec. Core (Data Structures, Basic Operations) + Scripting (Amazing use cases).
- Security Provider: Admin, Locking, Clock, Forensic Logging, Crypto services, internal controls, others.
- What is an SED (Self-Encrypting Device)? Drive Trust Alliance definition: Device uses built-in hardware encryption circuits to read/write data in/out of NV storage.
- At least one Media Encryption Key (MEK) is protected by at least one Key Encryption Key (KEK, usually a “password”).
- Self-Encrypting Storage. Personal Storage Landscape. People don’t realize how successful it is.
- All self-encrypting today: 100% of all SSDs, 100% of all enterprise storage (HDD, SSD, etc), all iOS devices, 100% of WD USB HDDs,
- Much smaller number of personal HDDs are Opal or SED. But Microsoft Bitlocker supports “eDrive” = Opal 2.0 drives of all kinds.
- You lose 40% of performance of a phone if you’re doing software encryption. You must do it in hardware.
- Working on NVM right now.
- Drive Trust Alliance: sole purpose to facilitate adoption of Personal SED.
- SP-SED Rule 1 – When we talk about cloud things, every personal device is actually in the cloud so… Look in the clouds for what should be in personal storage devices.
- TCG SED Range. Essentially partitions in the storage devices that have their own key. Bitlocker eDrive – 4 ranges. US Government uses DTA open source for creating resilient PCs using ranges. BYOD and Ransomware protection containers.
- Personal Data Storage (PDS). All data you want to protect can be permitted to be queried under your control.
- Example: You can ask if you are over 21, but not what your birthday is or how old you are, although data is in your PDS.
- MIT Media Lab, OpenPDS open source offered by Kerberos Consortium at MIT.
- Homomorphic Encryption. How can you do computing operations on encrypted data without ever decrypting the data. PDS: Ask questions without any possibility of getting at the data.
- It’s so simple, but really hard to get your mind wrapped around it. The requests come encrypted, results are encrypted and you can never see the plaintext over the line.
- General solution was discovered but it is not computationally infeasible (like Bitcoin). Only in the last few years (2011) it improved.
- HE Cloud Model and SP-DED Model. Uses OAuth. You can create personal data and you can get access to questions to your personal data. No plain text.
- Solution for Homomorphic Encryption. Examples – several copies of the data. Multiple encryption schemes. Each operation (Search, Addition, Multiplication) uses a different scheme.
- There’s a lot of technical work on this now. Your database will grow a lot to accommodate these kinds of operations.
- SP-SED Rule 2 – Like the internet cloud: if anybody can make money off an SP-SED, then people get really smart really fast… SP-SED should charge $$ for access to the private data they protect.
- The TCG Core Spec was written with this in mind. PDS and Homomorphic Encryption provide a conceptual path.
- Challenges to you: The TCG Core was designed to provide service identical to the Apple App Store, but in Self-Protecting Storage devices. Every personal storage device should let the owner of the device make money off his private data on it.
Hitachi Data Systems - Security Directions and Trends
Eric Hibbard, Chair SNIA Security Technical Working Group, CTO Security and Privacy HDS
- Protecting critical infrastructure. No agreement on what is critical.
- What are the sections of critical infrastructure (CI)? Some commonality, but no agreement. US=16 sectors, CA=10, EU=12, UK=9, JP=10.
- US Critical Infrastructure. Less than 20% controlled by the government. Significant vulnerabilities. Good news is that cybersecurity is a focus now. Bad news: a lot of interdependencies (lots of things depend on electric power).
- Threat landscape for CI. Extreme weather, pandemics, terrorism, accidents/technical failures, cyber threats.
- CI Protection – Catapulted to the forefront. Several incidents, widespread concern, edge of cyber-warfare, state-sponsored actions.
- President Obama declared a National Emergency on 04/01/2015 due to rising number of cyberattacks.
- CI protection initiatives. CI Decision-making organizations, CIP decisions. CIP decision-support system. The goal is to learn from attacks, go back and analyze what we could have done better.
- Where is the US public sector going? Rethinking strategy, know what to protect, understand value of information, beyond perimeter security, cooperation.
- Disruptive technologies: Mobile computing, cloud computing, machine-to-machine, big data analytics, industrial internet, Internet of things, Industry 4.0, software defined “anything”. There are security and privacy issues for each. Complexity compounded if used together.
- M2M maturity. Machine-to-machine communication between devices that are extremely intelligent, maybe AI.
- M2M analytics building block. Big Data + M2M. This is the heart and soul of smart cities. This must be secured.
- IoT. 50 billion connected objects expected by 2020. These will stay around for a long time. What if they are vulnerable and inside a wall?
- IoT will drive big data adoption. Real time and accurate data sensing. They will know where you are at any point in time.
- CI and emerging technology. IoT helps reduce cost, but it increases risks.
- Social Infrastructure (Hitachi View). Looking at all kinds of technologies and their interplay. It requires collaborative system.
- Securing smart sustainable cities. Complex systems, lots of IoT and cloud and big data, highly vulnerable. How to secure them?
Enterprise Key Management & KMIP: The Real Story - Q&A with EKM Vendors
Moderator: Tony Cox, Chair SNIA Storage Security Industry Forum, Chair OASIS KMIP Technical Committee
Panelists: Tim Hudson, CTO, Cryptsoft
Nathan Turajski, Senior Product Manager, HP
Bob Lockhart, Chief Solutions Architect, Thales e-Security, Inc
Liz Townsend, Director of Business Development, Townsend Security
Imam Sheikh, Director of Product Management, Vormetric Inc
- Goal: Q&A to explore perspective in EKM, KMIP.
- What are the most critical concerns and barriers to adoption?
- Some of developers that built the solution are no longer there. Key repository is an Excel spreadsheet. Need to explain that there are better key management solutions.
- Different teams see this differently (security, storage). Need a set of requirements across teams.
- Concern with using multiple vendors, interoperability.
- Getting the right folks educated about basic key management, standards, how to evaluate solutions.
- Understanding the existing solutions already implemented.
- Would you say that the OASIS key management has progressed to a point where it can be implemented with multiple venders?
- Yes, we have demonstrated this many times.
- Trend to use KMIP to pull keys down from repository.
- Different vendors excel in different areas and complex system do use multiple vendors.
- We have seen migrations from one vendor to another. The interoperability is real.
- KMIP has become a cost of entry. Vendors that do not implement it are being displaced.
- It’s not just storage. Mobile and Cloud as well.
- What’s driving customer purchasing? Is it proactive or reactive? With interoperability, where is the differentiation?
- It’s a mix of proactive and reactive. Each vendor has different background and different strengths (performance, clustering models). There are also existing vendor relationships.
- Organizations still buy for specific applications.
- It’s mixed, but some customers are planning two years down the line. One vendor might not be able to solve all the problems.
- Compliance is driving a lot of the proactive work, although meeting compliance is a low bar.
- Storage drives a lot of it, storage encryption drives a lot of it.
- What benefits are customers looking for when moving to KMIP? Bad guy getting to the key, good guy losing the key, reliably forget the key to erase data?
- There’s quote a mix of priorities. The operational requirements not to disrupt operations. Assurances that a key has been destroyed and are not kept anywhere.
- Those were all possible before. KMIP is about making those things easier to use and integrate.
- Motivation is to follow the standard, auditing key transitions across different vendors.
- When I look at the EU regulation, cloud computing federating key management. Is KMIP going to scale to billions of keys in the future?
- We have vendors that work today with tens of billions of key and moving beyond that. The underlying technology to handle federation is there, the products will mature over time.
- It might actually be trillions of keys, when you count all the applications like the smart cities, infrastructure.
- When LDAP is fully secure and everything is encrypted. How does secure and unsecure merge?
- Having conversations about different levels of protections for different attributes and objects.
- What is the different from a local key management to a remote or centralized approaches?
- There are lots of best practices in the high scale solutions (like separation of duties), and not all of them are there for the local solution.
- I don’t like to use simple and enterprise to classify. It’s better to call them weak and strong.
- There are scenarios where the key needs to local for some reason, but need to secure the key, maybe have a hybrid solution with a cloud component.
- Some enterprises think in terms of individual projects, local key management. If they step back, they will see the many applications and move to centralized.
- With the number of keys grows will we need a lot more repositories with more interop?
- Yes. It is more and more a requirement, like in cloud and mobile.
- Use KMIP layer to communicate between them.
- We’re familiar with use cases? What about abuse cases? How to protect that infrastructure?
- It goes back to not doing security by obscurity.
- You use a standard and audit the accesses. The system will be able to audit, analyze and alert you when it sees these abuses.
- The repository has to be secure, with two-factor authentication, real time monitoring, allow lists for who can access the system. Multiple people to control your key sets.
- Key management is part of the security strategy, which needs to be multi-layered.
- Simple systems and a common language is a vector for attack, but we need to do it.
- Key management and encryption is not the end all and be all. There must be multiple layers. Firewall, access control, audit, logging, etc. It needs to be comprehensive.
Lessons Learned from the 2015 Verizon Data Breach Investigations Report
Suzanne Widup, Senior Analyst, Verizon
- Fact based research, gleaned from case reports. Second year that we used data visualization. Report at
- 2015 DBIR: 70 contributed organizations, 79,790 security incidents, 2,122 confirmed data breaches, 61 countries
- The VERIS framework (actor – who did it, action - how they did it, asset – what was affected, attribute – how it was affected). Given away for free.
- We can’t share all the data. But some if it publicly disclosed and it’s in a GitHub repository as JSON files..
- You can be a part of it. Vcdb.org needs volunteers – be a security hero.
- Looking at incidents vs. breaches. Divided by industry. Some industries have higher vulnerabilities, but a part of it is due to visibility.
- Which industries exhibit similar threat profiles? There might be other industries that look similar to yours…
- Zooming into healthcare and other industries with similar threat profiles.
- Threat actors. Mostly external. Less than 20% internal.
- Threat actions. Credentials (down), RAM scrapers (up), spyware/keyloggers (down), phishing (up).
- The detection deficit. Overall trend is still pretty depressing. The bad guys are innovating faster than we are.
- Discovery time line (from 2015). Mostly discovered in days or less.
- The impact of breaches. We’re were not equipped to measure impact before. This year we partnered with insurance partners. We only have 50% of what is going on here.
- Plotting the impact of breaches. If you look at the number of incidents, it was going down. If you look at the records lost, it is growing.
- Charting number of records (1 to 100M) vs. expected loss (US$). There is a band from optimist to pessimist.
- The nefarious nine: misc errors, crimeware, privilege misuse, lost/stolen assets, web applications, denial of service, cyber-espionage, point of sale, payment card skimmers.
- Looks different if you use just breaches instead of all incidents. Point of sale is higher, for instance.
- All incidents, charted over time (graphics are fun!)
- More charts. Actors and the nine patterns. Breaches by industry.
- Detailed look at point of sale (highest in accommodation, entertainment and retail), crimeware, cyber-espionage (lots of phishing), insider and privilege misuse (financial motivation), lost/stolen devices, denial of service.
- Threat intelligence. Share early so it’s actionable.
- Phishing for hire companies (23% of recipients open phishing messages, 11% click on attachments)
- 10 CVEs account for 97% of exploits. Pay attention to the old vulnerabilities.
- Mobile malware. Android “wins” over iOS.
- Two-factor authentication and patching web servers mitigates 24% of vulnerabilities each.
Any written documentation/overviews on ReFS v2, for those unable to attend?
Awesome, "Storage Class Memory Support in the Windows Operating System".
SCM looks very exciting! Although "Features not in DAS Mode: …Bitlocker volume encryption, snapshot via VolSnap, mirrored or parity via storage spaces or dynamic disks" hopefully will be just a temporary limitation. Would love to see RDMA SOFS nodes
serving up SCM-level performance!
Also anxious to see ReFS v2 in 2016 TP4! "…Small writes accumulate where writing is cheap (mirror, flash, log-structured arena), bands are later shuffled to tier where random writes are expensive (band transfers are fully sequential)." If I understand
correctly, it sounds like it may solve the Storage Spaces tradeoff of mirroring (fast, low capacity) vs. parity (slow writes, high capacity)–writes could go to a mirrored band and then later are moved to a parity band?
The EBOD concept is also slick; it sounds similar in some ways to what Coraid did, exposing the raw disks over Ethernet. One note about their approach was that they used AoE (ATA over Ethernet) rather than TCP/IP, which isn’t well-suited to storage traffic,
particularly from a latency perspective.
EBOD on the one hand seems like simply redrawing the lines again between the various components of compute nodes and storage nodes. But EBOD could offer significant relief from the SAS requirement for JBODs with SOFS/Storage Spaces (finding SAS SSDs can feel
like hunting for truffles… without the dog; and they’re just as expensive!). And while Storage Spaces Direct also looks like a very appealing way to work around the complexity of JBODs/SAS/expanders/etc. and boost performance with NVMe options, with different
EBOD performance tiers, the SOFS node + EBOD model should allow more flexibility to put your storage dollar where you need it most–just buy inexpensive pizza box servers with HBAs hooked up to beefy, purpose-built EBODs, rather than buy very beefy, general-purpose
servers with high profit margins.
Hi there, yes this piece of writing is genuinely nice and I have learned
lot of things from it concerning blogging.
thanks.
Aw, this was a really good post. Taking the time and actual effort
to create a really good article… but what
can I say… I put things off a whole lot and never manage to get nearly anything done. | https://blogs.technet.microsoft.com/josebda/2015/09/21/raw-notes-from-the-storage-developer-conference-2015-snia-sdc-2015/ | CC-MAIN-2019-47 | refinedweb | 13,847 | 61.63 |
Movable Python: The Portable Python Distribution
Contents
Movable Python has lots of command line options. Most of these can be
configured through the GUI. Several of the command line
options are the same as (or mimic) the Python command line options.
This page documents the different options, and ends with a discussion of some
of the Python command line options that aren't supported by Movable Python.
If you type movpy -h at the command line, you get the following help
usage: movpy [option] ... [-c cmd | file | -] [arg] ...
Options and arguments :
-c cmd : program passed in as string (terminates option list)
-f : Change working directory to the script directory
-h : print this help message and exit
-i : inspect interactively after running script,
uses InteractiveConsole or IPython - probably needs a real stdin
-m mod : run library module as a script (terminates option list)
-u : unbuffered stdout and stderr
-V : print the movpy version and Python version number and exit
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-IPOFF : Don't use IPython, even if it is available, default to InteractiveConsole
-p : Attempt pysco.full() (incompatible with IPython interactive shell)
-b : Pause for <enter> after terminating script
-o : override saved options, only use comand line options
-koff : A command line option for the GUI, force no console
-k : A command line option for the GUI, force a console
-la file : Log output to file, open append in write mode
-lw file : Log output to file, open logfile in write mode
file : program read from script file
- : drop straight into InteractiveConsole or IPython
-pylab : Launch IPython in pylab mode
--config dir : Directory for config files (~ will be expanded)
arg ...: arguments passed to program in sys.argv[1:]
Run movpy without a file argument to bring up a lightweight GUI to choose a script
('-c', '-', '-V' or '-h' options override this behaviour)
Python environment variables are ignored.
As you can see, this rather terse text documents all the command line options.
If you need more of an explanation, read the rest of this page...
Some of the command line options are the same as the normal Python command line
options. (Type python -h at the command line to see what I mean.) This
means that programs which call sys.executable, followed by come command
line options will still usually work. IDLE does this for example.
The following options are intended to have the same effect (more-or-less) as
when used with normal Python.
For a discussion of Python command line options that are unsupported see
Unsupported Python Command Line Options.
This section lists all of the Movable Python command line options and
explains what they do. They are basically all accesible through the
GUI, but you will still need to know what they do.
If you use these options at the command line, the letters must be prefixed with
a -. For example :
movpy -p -f -i filename
This runs the Python programme filename, in its directory, with psyco on,
and switches to interactive mode after running.
This option allows you to pass a small program as a string. It is executed and
then Movable Python terminates. IDLE uses this option to launch its
subprocess.
Run the program in its directory. A lot of scripts expect the current
directory to be the directory in which they are located.
Prints the help message.
Enter the interactive interpreter mode after running the program. This allows
you to inspect the objects used by the program.
If IPOFF and p are both off, then the interpreter used will be
IPython.
The b option is ignored if i is set.
A console box is always used if you specify i.
Run a module as a script. The module must be somewhere on sys.path.
Run with unbuffered stdout and stderr. This is simulated on the Python
level, and so doesn't apply to the underlying C stdout and stderr.
Print the version of Movable Python and the version of Python.
Skip the first line of the script.
If IPOFF is set then IPython isn't used as the interactive
interpreter.
Switch psyco the specializing compiler on. (Do a psyco.full()). This
accelerates most Python programs.
It is not compatible with IPython, so using p with i will switch
IPython off.
Pause for <enter> after running the script. This is useful if the script is a
command line script that terminates immediately after running. Selecting b
allows you to see the results before the console window vanishes.
Override config.txt. You can save default options in the Special File
config.txt. (Also through the GUI.) o allows you to run a program
without using the default options.
If the GUI is launched with the die option, it will exit immediately it
runs a program.
If koff is selected, then movpy.exe will not launch programs with a
console box.
If k is selected, then movpyw.exe will launch programs with a console
box.
- forces Movable Python straight into interactive interpreter mode.
Whether IPython is used depends on the IPOFF option.
All Movpy command line options other than IPOFF (and o) are ignored when
going straight into interactive interpreter mode. (And a console box is forced
even if you didn't specify one !)
Additional command line options after the - are passed to IPython.
Note
The option pylab is special cased, see below.
Additionally, the option libdir is set by Movable Python, other
than that you can customize the behaviour of IPython by passing in command
line arguments.
Movable Python has built in support for matplotlib.
If you have the matplotlib files
in your lib/ directory you can run the following at the command line :
movpy.exe - -pylab
This should drop you straight into a IPython session, with pylab enabled.
Because of a limitation in IPython, the pylab session will run in its own
namespace. This means that although customize.py will run, you won't have
access to the namespace it ran in. You can still import movpy of course.
Log the output of the file, in append mode.
Log the output of the file, in write mode.
The config option allows you to specify a directory for config files. ~ will be expanded to the users home directory :
movpy --config ~/movpy
Movable Python supports most of the Python Command Line Options. There
are still a few it doesn't support. Some of the currently unsupported ones it
would be possible to implement, and others it would be very hard.
If Movable Python is launched with an unsupported command line option, then
a warning is printed to sys.stderr, and the option is ignored.
Currently unsupported ones are :
-d : debug output from parser
-E : ignore environment variables
Because we don't have access to the Python environment variables, we are
effectively running in E mode already.
Because we don't have access to the Python environment variables, we are
effectively running in E mode already.
-O and -OO : optimize generated bytecode
Movable Python is created using py2exe. You
specify the level of optimisation at the point that you create the
application.
To support these command line options would probably involve a lot of work
hacking py2exe.
Movable Python is created using py2exe. You
specify the level of optimisation at the point that you create the
application.
To support these command line options would probably involve a lot of work
hacking py2exe.
-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-S : don't imply 'import site' on initialization
We don't import site - but we do run customize.py. We could allow this
to be disabled.
We don't import site - but we do run customize.py. We could allow this
to be disabled.
-t and -tt : issue warnings about inconsistent tab usage (-tt:
issue errors)
-v : verbose (trace import statements)
-W arg : warning control (arg is action:message:category:module:lineno)
If you have a particular need for any of these options to be implemented, then
make a case for it on the Mailing List.
It may be possible.
Python allows its behaviour to be affected by several environment variables.
In order to isolate Movable Python [1] from the current Python install
(which may be a different version of Python), these environment variables
aren't accessible. It would be possible to create an alternative set of
environment variables specific to Movable Python. As Movable Python is
designed to be a portable distribution, it doesn't seem worthwhile. (In other
words, no-one would use them.)
The environment variables supported by a normal Python installation are :
Has the same effect as the -v command line option.
Has the same effect as the -i command line option.
Has the same effect as the -d command line option.
PYTHONUNBUFFERED
Has the same effect as the -u command line option.
PYTHONOPTIMIZE
Has the same effect as the -O and -OO command line options.
PYTHONSTARTUP
File executed on interactive startup (no default)
PYTHONPATH [2]
';'-separated list of directories prefixed to the default module search
path. The result is sys.path.
Alternate <prefix> directory (or <prefix>;<exec_prefix>). The default
module search path uses <prefix>lib.
Ignore case in 'import' statements (Windows).
It would be possible to implement options or environment variables to support
some of these, if there was a particular need. Again, make your case on the
Mailing List.
Return to Top
Part of the Movable Python Docs
Page last modified Wed Jul 16 02:31:30 2008.
Download Movable Python | http://www.voidspace.org.uk/python/movpy/reference/command_line.html | CC-MAIN-2014-52 | refinedweb | 1,581 | 66.03 |
Varnish joomla vcl jobs
Butuh orang yang paham dalam mengimplementasikan varnish di server nginx serta bisa mengkonfigurasikan menggunakan ESI
I need someone to setup Mangento 2 with redis, varnish and nginx as SSL termination on DigitalOcean or Linode.
.. or other invalid requests from a client or data returned
The application consist of about 100 Forms
Trying to narrow down the reason why. Previous programmer has suggested it may be -varnish configuration -need to combine/ minify js / css from various plugins -need to recode plugins to optimize site.
... ## Including (or calling) javascript files included
.. Fail2ban/ ModSecurity according to the Open source OWASP ModSecurity Core
The application consist of 123 Forms
I need someone to rip off the carpet in my living room and sand/varnish the wooden floor
...optimized VPS for
Hello, PLEASE DO NOT BID IF YOU ARE NOT AWS EXPERT. PLEASE DO NOT BID BEFORE YOU READ. ...minification - AWS Load Balancing* (Only if needed) - AWS Elastic File System* (Only if needed) - NGINX Integration - Redis Integration - Resource Monitoring Notification - Varnish Integration - Server Activity Monitoring - Support Period Thank you
.. two after startng the purchase, then nothing for 50-55
Recreate the attached please with the following lay.. la création
hola necesito hacer un varnish server stream conversemos por chat si te interesa ...saludos
Hi, I am looking a experienced developer that can install and configure varnish in our server and configure with our wordpress site, this task has to be performance by Team Viewer. We need this done today.
...experiencing performance issues. Details below. We need to get these performance issues fixed, is this something you can do for this budget? - The hosting solution is Cloudways with Varnish caching enabled. - No other Wordpress caches are installed. Cloudflare CDN is not enabled - The main performance issue lies in the "Projects" and "Campaigns" pages (links
..
Store with 30k products All magento default optimization has been done We don't wan't to use Varnish and Redis - to many problems Goal should be to open the page <1 sec URL: [login to view URL]
.. Webserver Configuration very well. - Know the Magento
..):
Hello, i installed Aws stack of "Magento Stack with Redis and Varnish Cache" you can check video's : [login to view URL] everythings ok. just need; 1- domain setup + Aws SSL (i want to see my page everytime secured link "https://") 2- like show on video Cdn settings ( create on aws with true way and
Help to set up and customize Varnish settings
..
deployed ec2 with centos distribution & cwp. server type apache, varnish cache and nginx reverse proxy. maria db, php 5.6. having ssl & cdn from cloudflare. server needs to be fixed/tweaked/configured for presta. facing ssl problems, ajax/server errors. need someone who knows best presta and configure stack to optimize prestashop and resolve conflicts: [login to view URL] Especially pages like this need to be done
We have varnish cache installed and actively running on Plesk server/ Magento2.2, but no cache hit
We have varnish cache installed and actively running on Plesk server/ Magento2.2, but no cache hit
Prestashop Version 1.6.1.18 installation website: [login to view
...in (H) PORTRAIT Extent: 192 pages (96 leaves) + 8 pp endsheets + case cover Quantity: 700copies Stock & Printing: Texts: Prints 5c x 5c (process + spot gloss varnish) on 135 gsm EURO Gloss artpaper Endsheets: Prints 5c x 5c on 135 gsm EURO Gloss artpaper Cover: Gloss laminate over 3 mm board Binding: Section sewn, separate ends, square
..
Hi, We have bought a Varnish cache option on our server. We want to integrate it to our Woocommerce webshop. Because it's a difficult process we're looking for a professional who can help us.
...all Windows 8/10 platforms (Business, Home, etc.) c) Demo-project (with conversion .pas files) must be easy compilable in Borland Delphi XE8 compiler without any additional VCL-components. **Additional References:** Microsoft Magnification API described here: <[login to view URL]> ## Deliverables 1)
..
Hi, we have a...hostserver ( VPS ) and we want it to has the most optimal settings for wordpress hosting. not very commercial but for our own websites ( like 35 websites) What we want is Varnish Cache, and recommended techniques for fast WP websites Make us some offers and recomendations. We dont have a clue, but think it is a simple project.
NEed to migrate Magento from one server to another. Ghosted other machine, but need to configure NGINX properly.
I need a varnish server to cache from backend server and serve static content. The server serves content initially from 2 website and may need to serve 5 websites. After successful installation and work around, you need to show me around, how to add remove a website to cache. Current settings: Digital Ocean 8GB RAM / 4vCPUs - 2 servers (one for
I am looking for the specialist who can make a good configuration of the ubuntu server that installed with MySQL,php-fpm and varnish cache server. Currently my server always display error 503 with varnish cache can not fetch with back
We are having issues with woocommerce adding products to the cart. I found this information..."^/(cart|my-account|checkout|addons)") { return (pass); } if ( [login to view URL] ~ "?add-to-cart=" ) { return (pass); } We can give you the vcl file to add the information. We will load the file. We will need assistance with varnish restarting and testing.
Standard VCL, interface don't have to be so nice but code very
...error: Error: Package: cachewall-0.38-1.el7.x86_64 (cachewall-release) Requires: hitch < 2.0 Error: Package: varnish-5.1.3-1.el7.x86_64 (varnishcache_varnish51) Requires: jemalloc Error: Package: varnish-5.1.3-1.el7.x86_64 (varnishcache_varnish51) Requires: libjemalloc.so.1()(64bit) Error: Package: cachewall-0.38-1 | https://www.freelancer.com/job-search/varnish-joomla-vcl/ | CC-MAIN-2018-22 | refinedweb | 954 | 56.96 |
Visual Studio 2005 has support for creating XML schemas. Launch Visual Studio 2005. Choose File from the New menu. The dialog shown in Figure 21-4 appears. Pick XML Schema from this dialog, and then click the Open button.
Figure 21-4. Creating a new XML schema file.
Visual Studio shows a design view for creating XML schema, as shown in Figure 21-5. The toolbox has XML schema objects that can be dragged onto the design surface for the new XML schema.
Figure 21-5. Creating a new XML schema file.
The schema object we will use most frequently in this example is element. An XML schema element defines an element in an XML file. For example, the simple XML file shown in Listing 21-1 has an element called Order in the namespace ns1. It also has an element called CustomerName in the namespace ns1. The CustomerName element is parented by the Order element.
Listing 21-1. XML File Representing a Simple Order
Eric Carter
The XML schema for this simple order XML file is created by following these steps:
Figure 21-6 shows the resulting designer view.
Figure 21-6. Design view of a simple Order schema.
When you save this schema, use the Save As command from the File menu to save it as order.xsd. You will have to pick XML Schema Files (*.xsd) from the Save as type drop-down in the Save As dialog. The order.xsd file will look like the one shown in Listing 21-2. You can see that an XML schema is just another XML file that defines what constitutes a valid Order XML file. It defines two elementsOrder and CustomerName. Because the Order element contains other elements, it is defined as a complexType. It contains a sequence of CustomerName elements that are of type string. Sequence in this case is misleadingthe way the XSD file is defined it will be a sequence of one and only one CustomerName elements. It is possible to define a sequence that has a varying number of elements in it using the maxOccurs and minOccurs settings, which we consider later in this chapter. For example, by setting minOccurs to 1 and maxOccurs to unbounded, you could allow one or more CustomerName elements to be associated with an order.
Listing 21-2. XSD Schema File for a Simple Order Schema
Note that this schema is defined entirely with elements. An alternative way of representing this same data is by using an Order element and a CustomerName attribute. If CustomerName is defined as an attribute, the resultant XML is as shown in Listing 21-3.
Listing 21-3. XML File for a Simple Order That Uses an Attribute
The XML schema for an Order XML file that uses an attribute is created in Visual Studio by following these steps:
Figure 21-7 shows the resultant designer view.
Figure 21-7. Design view of a simple Order schema that uses an attribute.
Listing 21-4 shows the schema for an order using an attribute. Because the Order element contains other attributes, it is defined as a complexType. It contains an empty sequencethis sequence can actually be removed without affecting the schema. It then defines CustomerName as an attribute of type string.
Listing 21-4. XSD Schema File for a Simple Order Schema That Uses an Attribute
Excel works equally well with schemas that use attributes or elements. Word, however, does not work very well when you use attributes in a schema. If you are creating a schema that you need to use in Excel and Word, you should try to use elements instead of attributes. For more information, see Chapter 22, "Working with XML in Word." | https://flylib.com/books/en/2.53.1/introduction_to_xml_schema_creation_in_visual_studio.html | CC-MAIN-2021-10 | refinedweb | 620 | 64.71 |
in Programming
I've said several times that XML Namespaces are simple, but I don't have a good proof document. So here it is.
XML Namespaces are an optional standand that you apply as a sort of "plug-in" to XML. All example XML documents in this text are namespaced documents.
- Namespaced document redefine tag names and attribute names to be a tuple. The name of all tags and attributes is now a pair of (namespace, name).
The "namespace" is an opaque string. It is conventionally a URL, like, the namespace for XHTML, but that's optional.
In an XHTML document, there is no tag em. There is only (, em). All tags that have the same tuple are the same. All tags that have a different tuple are not the same tag even if the name component is the same.
- To retain human-editability, we need a shortcut for writing these tuples. This is done with the xmlns attribute on tags.
This is a tag named em in the default "empty string" namespace:
<em>content</em>
This is the XHTML tag em for emphasis:
<em xmlns="">content</em>
The xmlns attribute affects everything beneath it.
<span> <span xmlns=""> <em>content</em> </span> </span>
That is an XHTML em tag, inside of an XHTML span tag, inside of a tag named ("", span) that is not XHTML.
Many namespaced XML documents will have an xmlns set on the root tag, and that may be the only sign you're in a namespaced document.
The xmlns tag can also set a namespace prefix, as so:
<xhtml:span xmlns:
That is also an XHTML span tag, exactly the same as:
<span xmlns="">
- Namespaces override each other in the obvious way.
<outer xmlns="outer.namespace"> <inner xmlns="inner.namespace"> <content/> </inner> <outercontent/> </outer>
The default namespace is set on the outer tag. The default namespace is overridden on the inner tag. The true identity of the content tag is (inner.namespace, content). The true identity of the outercontent tag is (outer.namespace, outercontent). xmlns:prefix-type tags work the same way.
The prefix is not part of the name. It is an error in namespace-based code to "do" anything with the prefix, except perhaps for serialization. It is an error to require the prefix to be set to a certain value.
(If I deserialize and reserialize something, I generally take the time in my code to try to preserve the prefixes. If no pre-existing prefix is available, I also generally have a dictionary of "friendly" default prefixes. These are both kindnesses to humans, not requirements.)
- No matter what the default xmlns namespace, all attributes are in the empty-string namespace unless set explicitly with a prefix. This means that in
<span xmlns="" class="sample">
the true identity of the attribute is ("", class). The XHTML standard is specified such that the ("", class) is the class attribute you know from XHTML. It is possible to namespace attributes with prefix:attribute="...", but you must declare a prefix to do so. This seems to be rarely done
That's about it.
However, you'll find that most things that use XML Namespaces use them incorrectly. Of course you'll usually not be in a position to fix it, so you have to adapt to the local dialect. Even XMPP, probably the second-best namespace-using standard behind XHTML and friends, will put two different namespaces on the opening stream element for things like clients vs. components and not directly specify that the stream tag should be treated with the same semantics in both cases, implicitly treating the stream tag as not namespaced while using the namespace declaration as just another attribute, but just for that one tag. | http://www.jerf.org/iri/post/2950 | CC-MAIN-2019-09 | refinedweb | 621 | 73.37 |
Source
dwmstatus / README.md
dwmstatus
This project is a fork of the suckless project by the same name.
About
I started using dwm not too long ago, and noticed that there was really no kind of nice, clean status implementation. All of them were in Python or some shell language. Then I looked at the dwm site and there was suddenly this new dwmstatus project up there. By default it just showed systemd load and time, and coming from i3 I was expecting a bit more. So I started editing this with two motives: learning C and making a good status bar. Now it does a bit more than show 3 differently formatted timezones and a 5-10-15 minute system load. I added some patches from the site to make it show network speed, temperature and a heavily edited battery meter (with time remaining and status) that I threw together. I also took some stuff from i3status and put it in here, notably the ip address check.
If this thing is of use to you, then I guess I'm doing something right.
Instalation and Use
This compiles fine with both clang and gcc for me. Note, it does have most of the same makedepends as dwm.
Running
make will compile dwmstatus and you can run it as you would any C
program,
./dwmstatus. There is documentation on how to run it in the man page.
Just as dwm is configured with a
config.h file, so is this status bar. There
are a few things you can do just editing this config file, like setting
location, where your battery is located, etc. To edit the order that things are
displayed, you will have to edit dwmstatus.c's
status() function.
You can also add functions by placing them in the includes folder and adding a
#include "includes/yourfile.c" in the
dwmstatus.c file.
If you're on Arch, then there are packages on the aur,
dwmstatus-ks and
dwmstatus-ks-git, that you can use to build the status bar.
Bugs
Please add bugs to the bitbucket project or email me at 1007380[at]gmail[Ðot]com.
See LICENSE. | https://bitbucket.org/KaiSforza/dwmstatus/src/677a14aad73b22a8bcf6b1df49bc0a9274bc6cf0/README.md?at=v0.5.0 | CC-MAIN-2016-07 | refinedweb | 362 | 73.88 |
24 September 2010 17:43 [Source: ICIS news]
By Nigel Davis
?xml:namespace>
LONDON
DSM has reached most of its 2010 strategic targets, the company said on Thursday, despite the economic downturn. Now it is looking to growth and wants to drive harder into the emerging economies.
Importantly, it sees sustainability as a key business driver and differentiator and not simply a responsibility, so intends to boost the proportion of eco-friendly products in the portfolio.
The former coal and petrochemicals producer (DSM was a coal miner a long time ago; it sold its petrochemicals business to SABIC in 2002) is going to continue with its transformation but is playing down that aspect of the strategy.
It has focused in recent five year periods on clear strategic, portfolio and financial goals and largely they have been achieved. The process seems to work.
The company, however, has probably chosen to focus on the right trends and well understood its own ability to change.
The life sciences businesses have been expanded and while there are clear challenges - to match change in the pharmaceutical industry, for instance, and in vitamins - DSM seems to know what it wants to do.
It is looking for partnerships and to
There are global/
In nutrition, there is likely to be some strengthening of the core - through cost control and what the company calls “improving the quality of earnings” but also some expansion.
In performance materials - DSM makes the high strength fibre Dyneema, engineering polymers and resins for coatings and composites - it will focus on eco-friendly products and solutions - for lighter materials and more environmentally friendly coatings, for example.
Again, there is talk of partnerships and also here of possible acquisitions. In high growth economies, strong sales growth is foreseen, the company says.
Indeed,
The company is much more focused on innovation and new products than it once was and expects sales from innovation to rise from nearly 12% of the total in 2010 to 20% by 2015.
And DSM is likely to shift more corporate functions to
“We are looking for acquisitions which will offer us additional technologies in life and material sciences,” board member Nico Gerardu said this week, talking of
“We are very proud of what we have achieved with our Vision 2010 strategy over the past five years,” DSM CEO Feike Sijbesma said.
“We have met most of our targets but even more importantly, we have demonstrated that we made the right decisions for the long-term future of the company,” he added.
“We have set ambitious sales and profitability targets. To realise these, we will take all four growth drivers, which are high growth economies; innovation; sustainability and acquisitions & partnerships, to the next level,” Sijbesma said in a statement.
“By strengthening our regional presence, we will further adjust our organisation to become truly global.”
The move from regional to global comes next for DSM as does a step up in growth driven largely by new business in
It wants to be generating a group EBITDA of between €1.4bn ($1.9bn) and €1.6bn in 2013 and a return on capital employed of 15%.
Based on current business it expects a “strong year” in 2010.
($1 = €0.75) | http://www.icis.com/Articles/2010/09/24/9396243/insight-dsm-talks-of-making-the-next-leap.html | CC-MAIN-2014-41 | refinedweb | 536 | 56.69 |
Welcome to the Open XML Format SDK 1.0
This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.. Microsoft provides a library for accessing these files as part of the WinFX technologies in the System.IO.Packaging namespace..
In This Section
About the Open XML Format SDK 1.0
Getting Started with the Open XML Format SDK 1.0
What's New in the Open XML Format SDK 1.0
Reference
Open XML API Class Diagram | https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb448854%28v%3Doffice.12%29 | CC-MAIN-2019-22 | refinedweb | 113 | 76.42 |
flutter_avatar
Various ready to use Avatars in your Flutter apps
Installing
In the
pubspec.yaml of your flutter project, add the following dependency:
dependencies: flutter_avatar: ^0.1.0
How To Use
In your file add the following import:
import 'package:flutter_avatar/flutter_avatar.dart';
Create a
FlutterAvatar widget:
FlutterAvatar( backgroundColor: Colors.blue, radius: 50, shape: BoxShape.circle, avatarShadow: BoxShadow( color: Colors.blue.withOpacity(0.6), blurRadius: 15, spreadRadius: 5, offset: Offset(0, -1), ), child: Text( 'TJ', style: TextStyle( fontSize: 35, color: Colors.white, fontWeight: FontWeight.bold, ), ), );
Customizations
Contributions
Feel free to contribute to this project.
If you find a bug or want a feature, but don't know how to fix/implement it, please fill an issue.
If you fixed a bug or implemented a feature, please send a pull request. | https://pub.dev/documentation/flutter_avatar/latest/ | CC-MAIN-2021-25 | refinedweb | 130 | 52.56 |
I.
Tom Bampton, who runs the monthly Game-In-A-Day 'competition' ( ), said "You're on!" He then added an extra contingency – I had to do it without the benefit of one of the (free) game engines out there. I could only use a basic library / API. 'starting ()
- ()
- Audacity () plus my microphone or free sound samples 'test, graohics.
Hour 17 – Smooth Move, Until You Hit the Wall
- More time is spent cleaning up graphics and fixing bugs.
- Add collision detection and smooth-scrolling to player movement.
- Player can now move multiple steps (turns) on a single mouse-clock.
- The player now goes through portals into other rooms.
- This exposes a cosmetic bug with overlapping walls and floors between adjoining rooms that is really jarring.
- More bug-fixing on rotated portals not allowing / prohibiting movement. totalFilling).
- I get the display routines working for monsters
- I make the monster block the player's movement.
- The perspective on the monster is totally different from the player, but I don't care. But the player graphic looks more terrible by comparison, so I re-do the player graphics.
-.
- Finish negotiation logic
- Add monster hunt / chase routines
- Monster chooses between spellcasting attacks (stubbed out) or melee combat
Hour 33 – Wandering Artwork
- Monsters now wander around if they aren't actively attacking the player.
- Artwork for some items and potions
- I add potions as items – they don't work yet, but they appear
- Potions get added to the player's potion inventory
- Potions have the appropriate effect on the player's stats. Healing Potions restore hit points, Essence potions restore mana points.
- I add pure treasure (which gets converted immediately into silver) as an item.
- I start working on equipment items..
If I read your question right, you are asking if you can create a commercial quality MMO or FPS in 3 months using Python.
Those two types of games are insanely difficult to make and very time consuming. It also sounds like you are new to gamedev, which means that the going will be even slower.
Most people will tell you to start small making games like Pong and Tetris before you jump into large scale and ambitious games. However, I'm a big fan of shooting for the stars.
If you decide to start off making one of those two types of games, just realize that it will take you years to complete, which will drastically reduce the chance of you ever finishing.
But, if you have the chops and the patience, I say go for it.
As for the programming language, you "could" do it in Python, but it's almost unheard of. Eve Online is one of the very few large scale commercial games that are written in Python.
Good Luck!
//
#include "stdafx.h"
#include "Game1.h"
//);
// calculate the size of the client area
RECT wr = {0, 0, 500, 400}; // set the size, but not the position
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size
//
wr.right - wr.left, // width of the window
wr.bottom - wr.top, // = {0};
// Enter the infinite;
}
else
{
// Run game code here
// ...
// ...
}
}
//);
}
And it opens a window with the message but I am not sure where to go from there...
Find a free game engine and start with that. I am working with Glest which is a free and complete game engine which has everything you need to use as a base framework.
Study it and see how it works. You will find it is quite simple to understand even if you don't understand the intricit details.
I'm from Mexico, and I am starting in the game development, but this article is great for me, because is an inspiration for me and it give me an idea about how to work with my time correctly.
Thanks a lot
(I am going to make a game in 40 hours with pygame too, thanks)
It's a long article man
that hard for me now to understand all information but i try . Visit us here
gooo brother thanks for your iformation tt4 | https://www.gamedev.net/resources/_/creative/game-design/how-to-build-a-game-in-a-week-from-scratch-with-no-budget-r2259 | CC-MAIN-2017-04 | refinedweb | 673 | 71.55 |
Java Program to find Maximum profit by buying and selling a share atmost twice
Maximum Profit by Buying And Selling a Share Atmost twice in Java
Here, in this page we will discuss the program to find maximum profit by buying and selling a share atmost twice in Java .
In daily share trading, a buyer buys shares in the morning and sells them on the same day. If the trader is allowed to make at most 2 transactions in a day, whereas the second transaction can only start after the first one is complete Buy->Sell->Buy->Sell. We are given with stock prices throughout the day, We need to find out the maximum profit that a share trader could have made.
Method 1
- Create an array say profit of size n and initialize all its value to 0.
- Iterate price[] from right(n-1) to left(0) and update profit[i] such that profit[i] stores maximum profit achievable from one transaction in sub-array price[i..n-1].
- Iterate price[] from left to right and update profit[i] such that profit[i] stores maximum profit such that profit[i] contains maximum achievable profit from two transactions in sub-array price[0..i].
- After completing the iteration print value of profit[n-1].
Time-Space Complexities Time - complexity : O(n) Space - complexity : O(n)
Code to find Maximum profit by buying and selling a share atmost twice in Java
Run
public class Main { static int maxProfit(int price[], int n) { // Create profit array // and initialize it as 0 int profit[] = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; profit[i] = Math.max(profit[i + 1], max_price - price[i]); } int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum // price in price[0..i] if (price[i] < min_price) min_price = price[i]; profit[i] = Math.max(profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; return result; } // Driver Code public static void main(String args[]) { int price[] = {2, 30, 15, 10, 8, 25, 80}; int n = price.length; System.out.println("Maximum Profit = " + maxProfit(price, n)); } }
Maximum Profit = 100
Method 2
- Initialize four variables for taking care of the first buy, first sell, second buy, second sell.
- Set first buy and second buy as INT_MIN and first and second sell as 0.
- This is to ensure to get profit from transactions.
- Iterate through the array and return the second buy as it will store maximum profit.
Time-Space Complexities Time - complexity : O(n) Space - complexity : O(1)
Run
public class Main { static int maxtwobuysell(int arr[], int size) { int first_buy = Integer.MIN_VALUE; int first_sell = 0; int second_buy = Integer.MIN_VALUE; int second_sell = 0; for (int i = 0; i < size; i++) { first_buy = Math.max(first_buy, -arr[i]); first_sell = Math.max(first_sell, first_buy + arr[i]); second_buy = Math.max(second_buy, first_sell - arr[i]); second_sell = Math.max(second_sell, second_buy + arr[i]); } return second_sell; } public static void main(String[] args) { int arr[] = {2, 30, 15, 10, 8, 25, 80}; int size = arr.length; System.out.print("Maximum Profit= "+maxtwobuysell(arr, size)); } }
Output
Maximum Profit = 100
Login/Signup to comment | https://prepinsta.com/java-program/to-find-maximum-profit-by-buying-and-selling-a-share-atmost-twice/ | CC-MAIN-2022-21 | refinedweb | 553 | 52.29 |
.
There are several reasons to learn Python. Some of them are as follows -
Spyder. It is like RStudio for Python. It gives an environment wherein writing python code is user-friendly. If you are a SAS User, you can think of it as SAS Enterprise Guide / SAS Studio. It comes with a syntax editor where you can write programs. It has a console to check each and every line of code. Under the 'Variable explorer', you can access your created data files and function. I highly recommend Spyder!
Jupyter (Ipython) Notebook.
IntroductionPython very fast.With popularity of big data and data science, Python has become first programming language of data scientists.
There are several reasons to learn Python. Some of them are as follows -
- Python runs well in automating various steps of a predictive model.
- Python has awesome robust libraries for machine learning, natural language processing, deep learning, big data and artificial Intelligence.
- Python wins over R when it comes to deploying machine learning models in production.
- It can be easily integrated with big data frameworks such as Spark and Hadoop.
- Python has a great online community support.
Do you know these sites are developed in Python?
- YouTube
- Dropbox
- Disqus
Table of Contentshe following is a list of some useful spyder shortcut keys which makes you more productive.
- Press F5 to run the entire script
- Press F9 to run selection or line
- Press Ctrl+ 1 to comment / uncomment
- Go to front of function and then press Ctrl + I to see documentation of the function
- Run %reset -f to clean workspace
- Ctrl + Left click on object to see source code
- Ctrl+Enter executes the current cell.
- Shift+Enter executes the current cell and advances the cursor to the next cell
List of arithmetic operators with examples
Basic programs
Assignment Operators
It is used to assign a value to the declared variable. For e.g. x += 25 means x = x+25.
x = 100 y = 10 x += y print(x)
print(x) 110In this case, x+=y implies x=x+y which is x = 100+ 10.
Similarly, you can use x-=y, x*=y and x /=y
Python Data StructuresIn every programming language, it is important to understand the data structures. Following are some data structures used in Python.
1. ListIt is a sequence of multiple values. It allows us to store different types of data such as integer, float, string etc. See the examples of list below. First one is an integer list containing only integer. Second one is string list containing only string values. Third one is mixed list containing integer, string and float values.
- x = [1, 2, 3, 4, 5]
- y = [‘A’, ‘O’, ‘G’, ‘M’]
- z = [‘A’, 4, 5.1, ‘M’]
Get List ItemWe can extract list item using Indexes. Index starts from 0 and end with (number of elements-1).
x = [1, 2, 3, 4, 5] x[0] x[1] x[4] x[-1] x[-2]
x[0] Out[68]: 1 x[1] Out[69]: 2 x[4] Out[70]: 5 x[-1] Out[71]: 5 x[-2] Out[72]: 4
x[0] picks first element from list. Negative sign tells Python to search list item from right to left. x[-1] selects the last element from list.
You can select multiple elements from a list using the following method
x[:3] returns[1, 2, 3]
2. Tuple print(), you can create your own custom function. It is also called user-defined functions. It helps you in automating the repetitive task and calling reusable code in easier way.
Rules to define a function
- Function starts with def keyword followed by function name and ( )
- Function body starts with a colon (:) and is indented
- The keyword return ends a function andgive value of previous expression.
def sum_fun(a, b): result = a + b return result
z = sum_fun(10, 15)Result : z = 25
Suppose you want python to assume 0 as default value if no value is specified for parameter b.
def sum_fun(a, b=0): result = a + b return result z = sum_fun(10)In the above function, b is set to be 0 if no value is provided for parameter b. It does not mean no other value than 0 can be set here. It can also be used as)Some of the leading packages in Python along with equivalent libraries in R are as follows-
- pandas. For data manipulation and data wrangling. A collections of functions to understand and explore data. It is counterpart of dplyr and reshape2 packages in R.
- NumPy. For numerical computing. It's a package for efficient array computations. It allows us to do some operations on an entire column or table in one line. It is roughly approximate to Rcpp package in R which eliminates the limitation of slow speedm, knn, randomForest, rpart, e1071 packages.
- Matplotlib.For data visualization. It's a leading package for graphics in Python. It is equivalent to ggplot2 package in R.
- Statsmodels.For statistical and predictive modeling. It includes various functions to explore data and generate descriptive and predictive analytics. It allows users to run descriptive statistics, methods to impute missing values, statistical tests and take table output to HTML format.
- pandasql. It allows SQL users to write SQL queries in Python. It is very helpful for people who loves writing SQL queries to manipulate data. It is equivalent to sqldf package in R..
1. import pandas as pd It imports the package pandas under the alias pd. A function DataFrame in package pandas is then submitted with pd.DataFrame.
2. import pandas
It imports the package without using alias but here the function DataFrame is submitted with full package name pandas.DataFrame1[:3]
0 -2.412015 1 -0.451752 2 1.174207
2. DataFrame
It is equivalent to data.frame in R. It is a 2-dimensional data structure that can store data of different data types such as characters, integers, floating point values, factors. Those who are well-conversant with MS Excel, they can think of data frame as Excel Spreadsheet.
Comparison of Data Type in Python and Pand can use read_csv() function from pandas package to get data into python from CSV file.
mydata= pd.read_csv("C:\\Users\\Deepanshu\\Documents\\file1.csv")Make sure you use double backslash when specifying path of CSV file. Alternatively, you can use forward slash to mention file path inside read_csv() function.
Detailed Tutorial : Import Data in Python
3. To see number of rows and columnsYou can run the command below to find out number of rows and columns.
df.shapeResult :(6, 3). It means 6 rows and 3 columns.
4. To view first 3 rowsThe df.head(N) function can be used to check out first some N rows.
df.head(3)
cost productcode sales 0 1020.0 AA 1010.0 1 1625.2 AA 1025.2 2 1204.0 AA 1404.2
5. Select or Drop Variables
To keep a single variable, you can write in any of the following three methods -
df.productcodeTo select variable by column position, you can use df.iloc function. In the example below, we are selecting second column. Column Index starts from 0. Hence, 1 refers to second column.
df["productcode"]
df.loc[: , "productcode"]
df.iloc[: , 1]We can keep multiple variables by specifying desired variables inside [ ]. Also, we can make use of df.loc() function.
df[["productcode", "cost"]]
df.loc[ : , ["productcode", "cost"]]
Drop Variable
We can remove variables by using df.drop() function. See the example below -
df2 = df.drop(['sales'], axis = 1)
6. To summarize data frame
To summarize or explore data, you can submit the command below.
df.describe()
cost sales count 6.000000 6.00000 mean 1166.150000 1242.65000 std 237.926793 230.46669 min 1003.700000 1010.00000 25% 1020.000000 1058.90000 50% 1072.000000 1205.85000 75% 1184.000000 1366.07500 max 1625.200000 1604.80000
To summarise all the character variables, you can use the following script.
df.describe(include=['O'])Similarly, you can use df.describe(include=['float64']) to view summary of all the numeric variables with decimals.
To select only a particular variable, you can write the following code -
df.productcode.describe()
OR
df["productcode"].describe()
count 6 unique 2 top BB freq 3 Name: productcode, dtype: object
7. To calculate summary statisticsWe can manually find out summary statistics such as count, mean, median by using commands below
df.sales.mean() df.sales.median() df.sales.count() df.sales.min() df.sales.max()
8. Filter DataSuppose you are asked to apply condition - productcode is equal to "AA" and sales greater than or equal to 1250.
df1 = df[(df.productcode == "AA") & (df.sales >= 1250)]It can also be written like :
df1 = df.query('(productcode == "AA") & (sales >= 1250)')In the second query, we do not need to specify DataFrame along with variable name.
9. Sort DataIn the code below, we are arrange data in ascending order by sales.
df.sort_values(['sales'])
10. Group By : Summary by Grouping VariableLike SQL GROUP BY, you want to summarize continuous variable by classification variable. In this case, we are calculating average sale and cost by product code.
df.groupby(df.productcode).mean()
cost sales productcode AA 1283.066667 1146.466667 BB 1049.233333 1338.833333Instead of summarising for multiple variable, you can run it for a single variable i.e. sales. Submit the following script.
df["sales"].groupby(df.productcode).mean()
11. Define Categorical VariableLet's create a classification variable - id which contains only 3 unique values - 1/2/3.
df0 = pd.DataFrame({'id': [1, 1, 2, 3, 1, 2, 2]})Let's define as a categorical variable.
We can use astype() function to make id as a categorical variable.
df0.id = df0["id"].astype('category')Summarize this classification variable to check descriptive statistics.
df0.describe()
id count 7 unique 3 top 2 freq 3
Frequency DistributionYou can calculate frequency distribution of a categorical variable. It is one of the method to explore a categorical variable.
df['productcode'].value_counts()
BB 3 AA 3
12. Generate HistogramHistogram is one of the method to check distribution of a continuous variable. In the figure shown below, there are two values for variable 'sales' in range 1000-1100. In the remaining intervals, there is only a single value. In this case, there are only 5 values. If you have a large dataset, you can plot histogram to identify outliers in a continuous variable.
df['sales'].hist()
13. BoxPlotBoxplot is a method to visualize continuous or numeric variable. It shows minimum, Q1, Q2, Q3, IQR, maximum value in a single graph.
df.boxplot(column='sales')
Detailed Tutorial :Data Analysis with Pandas Tutorial
Data Science using Python - ExamplesIn this section, we cover how to perform data mining and machine learning algorithms with Python. sklearn is the most frequently used library for running data mining and machine learning algorithms. We will also cover statsmodels library for regression techniques. statsmodels library generates formattable output which can be used further in project report and presentation.
1. Install the required librariesImport the following libraries before reading or exploring data
#Import required libraries
import pandas as pd
import statsmodels.api as sm
import numpy as np
2. Download and import data into PythonWith the use of python library, we can easily get data from web into python.
# Read data from web
df = pd.read_csv("")
Variables Type Description gre Continuous Graduate Record Exam score gpa Continuous Grade Point Average rank Categorical Prestige of the undergraduate institution admit Binary Admission in graduate school
The binary variable admit is a target variable.
3. Explore DataLet's explore data. We'll answer the following questions -
- How many rows and columns in the data file?
- What are the distribution of variables?
- Check if any outlier(s)
- If outlier(s), treat them
- Check if any missing value(s)
- Impute Missing values (if any)
# See no. of rows and columnsResult : 400 rows and 4 columns
df.shape
In the code below, we rename the variable rank to 'position' as rank is already a function in python.
# rename rank columnSummarize and plot all the columns.
df = df.rename(columns={'rank': 'position'})
# looking at cross tabulation report, we can check whether we have enough number of events against each unique values of categorical variable.
pd.crosstab(df['admit'], df['position'])
position 1 2 3 4 admit 0 28 97 93 55 1 33 54 28 12
Number of Missing Valuesistic Regression is a special type of regression where target variable is categorical in nature and independent variables be discrete or continuous. In this post, we will demonstrate only binary logistic regression which takes only binary values in target variable. Unlike linear regression, logistic regression model returns probability of target variable.It assumes binomial distribution of dependent variable. In other words, it belongs to binomial family..
#Reference CategoryIt returns two datasets - X and y. The dataset 'y' contains variable admit which is a target variable. The other dataset 'X' contains Intercept (constant value), dummy variables for Treatment, gre and gpa. Since 4 is set as a reference category, it will be 0 against all the three dummy variables. See sample below -% of data goes to training dataset which is used for building model and 20% goes to test dataset which would be used for validating the model.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
Build Logistic Regression ModelBy.summary() result.params
Logit Regression Results ============================================================================== Dep. Variable: admit No. Observations: 320 Model: Logit Df Residuals: 315 Method: MLE Df Model: 4 Date: Sat, 20 May 2017 Pseudo R-squ.: 0.03399 Time: 19:57:24 Log-Likelihood: -193.49 converged: True LL-Null: -200.30 LLR p-value: 0.008627 ======================================================================================= coef std err z P|z| [95.0% Conf. Int.] --------------------------------------------------------------------------------------- C(position)[T.1] 1.4933 0.440 3.392 0.001 0.630 2.356 C(position)[T.2] 0.6771 0.373 1.813 0.070 -0.055 1.409 C(position)[T.3] 0.1071 0.410 0.261 0.794 -0.696 0.910 gre 0.0005 0.001 0.442 0.659 -0.002 0.003 gpa 0.4613 0.214 -2.152 0.031 -0.881 -0.041 ======================================================================================
Confusion Matrix and Odd trees can have a target variable continuous or categorical. When it is continuous, it is called regression tree. And when it is categorical, it is called classification tree. It selects a variable at each step that best splits the set of values. There are several algorithms to find best split. Some of them are Gini, Entropy, C4.5, Chi-Square. There are several advantages of decision tree. It is simple to use and easy to understand. It requires a very few data preparation steps. It can handle mixed data - both categorical and continuous variables. In terms of speed, it is a very fast algorithm.
#Drop Intercept from predictors for tree algorithms X_train = X_train.drop(['Intercept'], axis = 1) X_test = X_test.drop(['Intercept'], axis = 1) #Decision Tree from sklearn.tree import DecisionTreeClassifier model_tree = DecisionTreeClassifier(max_depth=7) #Fit the model: model_tree.fit(X_train,y_train) #Make predictions on test set predictions_tree = model_tree.predict_proba(X_test) #AUC false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, predictions_tree[:,1]) auc(false_positive_rate, true_positive_rate)Result : AUC = 0.664
Important Note
Feature engineering plays an important role in building predictive models. In the above case, we have not performed variable selection. We can also select best parameters by using grid search fine tuning technique.
Random ForestDecision Tree has limitation of overfitting which implies it does not generalize pattern. It is very sensitive to a small change in training data. To overcome this problem, random forest comes into picture. It grows a large number of trees on randomised data. It selects random number of variables to grow each tree. It is more robust algorithm than decision tree. It is one of the most popular machine learning algorithm. It is commonly used in data science competitions. It is always ranked in top 5 algorithms. It has become a part of every data science toolkit.
#Random Forest from sklearn.ensemble import RandomForestClassifier model_rf = RandomForestClassifier(n_estimators=100, max_depth=7) #Fit the model: target = y_train['admit'] model_rf.fit(X_train,target) #Make predictions on test set predictions_rf = model_rf.predict_proba(X_test) #AUC false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, predictions_rf[:,1]) auc(false_positive_rate, true_positive_rate) #Variable Importance importances = pd.Series(model_rf.feature_importances_, index=X_train.columns).sort_values(ascending=False) print(importances) importances.plot.bar()
Result : AUC = 0.6974
Grid Search - Hyper Parameter TuningThe sklearn library makes hyper-parameters tuning very easy. It is a strategy to select the best parameters for an algorithm. In scikit-learn they are passed as arguments to the constructor of the estimator classes. For example, max_features in randomforest. alpha for lasso.
from sklearn.model_selection import GridSearchCV rf = RandomForestClassifier() target = y_train['admit'] param_grid = { 'n_estimators': [100, 200, 300], 'max_features': ['sqrt', 3, 4] } CV_rfc = GridSearchCV(estimator=rf , param_grid=param_grid, cv= 5, scoring='roc_auc') CV_rfc.fit(X_train,target) #Parameters with Scores CV_rfc.grid_scores_ #Best Parameters CV_rfc.best_params_ CV_rfc.best_estimator_ #Make predictions on test set predictions_rf = CV_rfc.predict_proba(X_test) #AUC false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, predictions_rf[:,1]) auc(false_positive_rate, true_positive_rate)
Cross Validation
# Cross Validation from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_predict,cross_val_score target = y['admit'] prediction_logit = cross_val_predict(LogisticRegression(), X, target, cv=10, method='predict_proba') #AUC cross_val_score(LogisticRegression(fit_intercept = False), X, target, cv=10, scoring='roc_auc').
from sklearn.preprocessing import LabelEncoder
def ConverttoNumeric(df):
cols = list(df.select_dtypes(include=['category','object']))
le = LabelEncoder()
for i in cols:
try:
df[i] = le.fit_transform(df[i])
except:
print('Error in Variable :'+i)
return df
ConverttoNumeric(df)
2. Create Dummy VariablesSuppose you want to convert categorical variables into dummy variables. It is different to the previous example as it creates dummy variables instead of convert it in numeric form.
productcode_dummy = pd.get_dummies(df["productcode"]) df2 = pd.concat([df, productcode_dummy], axis=1)
The output looks like below -
AA BB 0 1 0 1 1 0 2 1 0 3 0 1 4 0 1 5 0 1
Create k-1 Categories
To avoid multi-collinearity, you can set one of the category as reference category and leave it while creating dummy variables. In the script below, we are leaving first category.
productcode_dummy = pd.get_dummies(df["productcode"], prefix='pcode', drop_first=True) df2 = pd.concat([df, productcode_dummy], axis=1)
3. Impute Missing ValuesImputing missing values is an important step of predictive modeling. In many algorithms, if missing values are not filled, it removes complete row. If data contains a lot of missing values, it can lead to huge data loss. There are multiple ways to impute missing values. Some of the common techniques - to replace missing value with mean/median/zero. It makes sense to replace missing value with 0 when 0 signifies meaningful. For example, whether customer holds a credit card product.
Fill missing values of a particular variable
# fill missing values with 0 df['var1'] = df['var1'].fillna(0) # fill missing values with mean df['var1'] = df['var1'].fillna(df['var1'].mean())
Apply imputation to the whole dataset
from sklearn.preprocessing import Imputer # Set an imputer object mean_imputer = Imputer(missing_values='NaN', strategy='mean', axis=0) # Train the imputor mean_imputer = mean_imputer.fit(df) # Apply imputation df_new = mean_imputer.transform(df.values)
4. Outlier TreatmentThere are many ways to handle or treat outliers (or extreme values). Some of the methods are as follows -
- Cap extreme values at 95th / 99th percentile depending on distribution
- Apply log transformation of variables. See below the implementation of log transformation in Python.
import numpy as np
df['var1'] = np.log(df['var1'])
5. StandardizationIn some algorithms, it is required to standardize variables before running the actual algorithm. Standardization refers to the process of making mean of variable zero and unit variance (standard deviation).
#load dataset dataset = load_boston() predictors = dataset.data target = dataset.target df = pd.DataFrame(predictors, columns = dataset.feature_names) #Apply Standardization from sklearn.preprocessing import StandardScaler k = StandardScaler() df2 = k.fit_transform(df)
End NotesNext Step - Practice, practice and practice. Download free public data sets from Kaggle / UCLA websites and try to play around with data and generate insights from it with pandas package and build statistical models using sklearn package. I hope you would find this tutorial helpful. I tried to cover all the important topics which beginner must know about Python. Once completion of this tutorial, you can flaunt you know how to program it in Python and you can implement machine learning algorithms using sklearn package.
Hi, excelent tutorial!!! I'm mostly a user of R but want to learn python. The thing is i work a lot with spatial data: spatial relationships (spdep), interpolation (kriging with gstat or multilevel B-Splines with MBA) etc.; and then machine learning methods with the data that comes from spatial features.
I understand that the ML cappabilities are already in Pythoon but i'm worried about the spatial workflow, can you give me some insights on this?
Thanks,
Great blog!
Thanks for developing this. For first time after few attempts, I can start working with Python!
Glad you found it helpful. Cheers!
Hi Deepanshu. Can i have your contact number please. I want to talk regarding the courses.
Thanks. Some things come late in the tutorial (like the np loading) but it is a good overview.
Excelent! I appreciate the comparison between R and Python commands! Very useful!
Very well written article!
Hi.
I am using Pythin 3.6.
y, X = dmatrices("admit ~ gre + gpa + C(position, Treatment(reference=4))", df, return_type = 'dataframe')
This code generate this error
C, including its class ClassRegistry, has been deprecated since SymPy
1.0. It will be last supported in SymPy version 1.0. Use direct
imports from the defining module instead. See for more info.
.
.
.
TypeError: 'bool' object is not callable
How can I handle this ?
Thank you
Very useful tutorial, lucidly presented
⏳⛳🏳🚩🏁⛖🔛✖➕➖➗⁉⚌⚲.
Nice'm.
This is an excellent course which not only helped me understand key definitions but has also excited to me to learn more in this field. Thank You to all the Instructors who made it easier for many like me...
cyber security training in bangalore
You appear to know a lot about this. It’s like you read my thoughts!, Thanks for writing this.
Data Science Course in Vadodara
It is late to find this act. At least one should be familiar with the fact that such events exist. I agree with your blog and will come back to inspect it further in the future, so keep your performance going.
Data Science Course in Jaipur
Your style is really unique in comparison to other people I have read stuff from. I appreciate you for posting when you have the opportunity, Guess I will just bookmark this site.
Data Science Course in Nagpur
I don’t even know the way I stopped up here, but I believed this submit used to be good. I do not recognize who you are but definitely you’re going to a famous blogger in the event you are not already.
Data Science Course in Lucknow
nice article and very informative.
This comment has been removed by the author.
Excellent post,Keep sharing such type of wonderful post..
Very informative and well written post.
Thanks for sharing this informative content.,
Leanpitch provides online training in Scrum Master Certification during this lockdown period everyone can use it wisely.
Join Leanpitch 2 Days CSM Certification Workshop in different cities.
Scrum master certification online
CSM certification online
I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra. data science course in vadodara
This is really very nice post you shared, i like the post, thanks for sharing..
Best Data Science courses in Hyderabad
I have bookmarked your site since this site contains significant data in it. You rock for keeping incredible stuff. I am a lot of appreciative of this site.
data scientist training in hyderabad | https://www.listendata.com/2020/10/learn-python-for-data-science.html | CC-MAIN-2021-31 | refinedweb | 3,980 | 51.44 |
Next: XML Structure, Previous: XML Output, Up: XML Support
MIT/GNU Scheme implements XML names in a slightly complex way. Unfortunately, this complexity is a direct consequence of the definition of XML names rather than a mis-feature of this implementation.
The reason that XML names are complex is that XML namespace support, which was added after XML was standardized, is not very well integrated with the core XML definition. The most obvious problem is that names can't have associated namespaces when they appear in the DTD of a document, even if the body of the document uses them. Consequently, it must be possible to compare non-associated names with associated names.
An XML name consists of two parts: the qname, which is a symbol, possibly including a namespace prefix; and the Uniform Resource Identifier (URI), which identifies an optional namespace.
Creates and returns an XML name. Qname must be a symbol whose name satisfies
string-is-xml-name?. Uri must satisfy either
absolute-uri?or
null-xml-namespace-uri?. The returned value is an XML name that satisfies
xml-name?.
If uri is the null namespace (satisfies
null-xml-namespace-uri?), the returned value is a symbol equivalent to qname. This means that an ordinary symbol can be used as an XML name when there is no namespace associated with the name.
For convenience, qname may be a string, in which case it is converted to a symbol using
make-xml-qname.
For convenience, uri may be any object that
->uriis able to convert to a URI record, provided the resulting URI meets the above restrictions.
Returns the URI of xml-name. The result always satisfies
absolute-uri?or
null-xml-namespace-uri?.
Returns the qname of xml-name as a string. Equivalent to(symbol-name (xml-name->symbol xml-name))
The next two procedures get the prefix and local part of an XML name, respectively. The prefix of an XML name is the part of the qname to the left of the colon, while the local part is the part of the qname to the right of the colon. If there is no colon in the qname, the local part is the entire qname, and the prefix is the null symbol (i.e. `||').
The next procedure compares two XML names for equality. The rules for equality are slightly complex, in order to permit comparing names in the DTD with names in the document body. So, if both of the names have non-null namespace URIs, then the names are equal if and only if their local parts are equal and their URIs are equal. (The prefixes of the names are not considered in this case.) Otherwise, the names are equal if and only if their qnames are equal.
Returns
#tif xml-name-1 and xml-name-2 are the same name, and
#fotherwise.
These next procedures define the data abstraction for qnames. While
qnames are represented as symbols, only symbols whose names satisfy
string-is-xml-name? are qnames.
String must satisfy
string-is-xml-name?. Returns the qname corresponding to string (the symbol whose name is string).
The prefix of a qname or XML name may be absent if there is no colon in the name. The absent, or null, prefix is abstracted by the next two procedures. Note that the null prefix is a symbol, just like non-null prefixes.
Returns
#tif object is the null prefix, otherwise returns
#f.
The namespace URI of an XML name may be null, meaning that there is no namespace associated with the name. This namespace is represented by a relative URI record whose string representation is the null string.
Returns
#tif object is the null namespace URI record, otherwise returns
#f.
The following values are two distinguished URI records.
xml-uriis the URI reserved for use by the XML recommendation. This URI must be used with the `xml' prefix.
xmlns-uriis the URI reserved for use by the XML namespace recommendation. This URI must be used with the `xmlns' prefix. | http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/XML-Names.html | CC-MAIN-2016-07 | refinedweb | 672 | 65.12 |
bound provides a powerful but simple toolbox for dealing with capture-avoiding substitution in your code. It lets you use classes you already know:
Monad,
Foldable and
Traversable to manipulate your syntax tree, and it factors out issues of name capture into a reusable monad transformer named
Scope.
What I want to do today is help motivate the design of the
bound library by talking a bit about alternatives. This may serve, with a few digressions, as a bit of a crash course on capture-avoiding substitution, for those who don't deal with this issue on a day-to-day basis. This presentation is based on a talk I gave on
bound, but it has been upgraded to work with the School of Haskell tools for easier online consumption. In particular, I've tried to make the code fragments executable, and greatly expand on the content to cover things in greater depth. The original slides are also available, but were designed with me speaking over them in mind.
What is in a Name?
We use names in lots of contexts, but any program that deals with names has to deal with a number of issues such as capture avoidance and deciding alpha equivalance... and others that will come up as we go.
If you go to write a syntax tree, the dumbest thing that can possibly work would be something like:
type Name = String data Exp = Var Name | App Exp Exp | Lam Name Exp deriving (Eq,Show,Read) main = do print $ Var "x" print $ Lam "x" (Var "x") print $ Lam "x" (Lam "y" (Var "x"))
Two problems we want to address in almost any syntax tree are:
1.) Capture Avoidance
Blindly substituting
Lam "x" (Var "y")
into
Lam "y" (Var "z")
for
z would yield
Lam "y" (Lam "x" (Var "y"))
which now causes the formerly free variable
y to now reference the
y bound by the outer lambda.
2.) Alpha Equivalence
Lam "x" (Var "x")
and
Lam "y" (Var "y")
both mean the same thing and it'd be nice to be able to check this easily, make them hash the same for common sub-expression elimination, etc.
There is a cottage industry of solutions to the naming problem:
e.g.
- Naïve substitution
- The Barendregt convention
- HOAS
- Weak HOAS/PHOAS
- "I am not a Number: I am a Free Variable!"
- The Locally Nameless Representation
- Unbound, which mixes Barendregt with Locally Nameless
- Locally Nameless Syntax with De Bruijn Indices
I'm not looking to address all of these here, just a few, to showcase issues with the different points in the design space, and then to try to offer up a nice point in the design space (
bound) that combines many of the advantages with few of the disadvantages.
Naïve Substitution
Pros:
1.) The syntax trees are pretty and easy to read.
2.) Easy to use to get started
Cons:
1.) It is easy even for experts to make mistakes.
2.) Alpha equivalence checking is tedious
3.) It is comically slow.
import Data.List (union, span, (\\)) type Name = String data Exp = Var Name | App Exp Exp | Lam Name Exp deriving (Eq,Show,Read) -- show freeVars :: Exp -> [Name] freeVars (Var x) = [x] freeVars (App a b) = freeVars a `union` freeVars b freeVars (Lam n x) = freeVars x \\ [n] allVars :: Exp -> [Name] allVars (Var x) = [x] allVars (App a b) = allVars a `union` allVars b allVars (Lam n x) = allVars x subst :: Name -> Exp -> Exp -> Exp subst x s b = sub vs0 b where sub _ e@(Var v) | v == x = s | otherwise = e sub vs e@(Lam v e') | v == x = e | v `elem` fvs = Lam v' (sub (v':vs) e'') | otherwise = Lam v (sub vs e') where v' = newId vs e'' = subst v (Var v') e' sub vs (App f a) = sub vs f `App` sub vs a fvs = freeVars s vs0 = fvs `union` allVars b newId :: [Name] -> Name newId vs = head (names \\ vs) names :: [Name] names = [ [i] | i <- ['a'..'z']] ++ [i : show j | j <- [1..], i <- ['a'..'z'] ] -- /show -- show and we can see that this deals with capture avoidance main = print $ subst "z" (Lam "x" (Var "y")) (Lam "y" (Var "z")) -- /show
This code is adapted from Lennart Augustsson's excellent λ-calculus cooked four ways, which provides a nice crash course on name binding for evaluation.
[Edited August 27 2013: The code fragment above was updated based on a conversation with Marc André Ziegert to deal with an issue where in the
v case under
elem fvs
sub it wasn't properly updating the set of
allVars b when it introduced
v' into scope. I told you naïve substitution was tricky!]
The Barendregt Convention
This one is a serious contender. It is what GHC uses.
Pros:
1.) The Secrets of the Glasgow Haskell Compiler inliner paper by Simon and Simon describes a technique they call "the Rapier," which can make this really fast.
Cons:
1.) Easy even for experts to screw up.
2.) Alpha equivalence is still tedious.
3.) Need a globally unique variable supply. e.g. concurrent-supply
4.) The obvious implementation technique chews through a scarily large number of variable IDs! Without the Rapier there is a lot of "administrative" renaming going on.
Higher-Order Abstract Syntax (HOAS)
HOAS cheats and borrows substitution from the host language.
-- show data Exp a = Var a | Lam (Exp a -> Exp a) | App (Exp a) (Exp a) -- /show main = putStrLn "It typechecks, but a Show instance here is hard!"
Pros:
1.) It provides ridiculously fast substitution by comparison to other techniques.
2.) Meijer and Hutton's "Bananas in Space", Fegaras and Sheard's "Revisiting Catamorphisms over Datatypes with Embedded Functions (or, Programs from Outer Space) and Weirich and Washburn's "Boxes Go Bananas: Encoding Higher-order Abstract Syntax with Parametric Polymorphism" each describe forms of catamorphism that can be used on these to work under binders.
Cons:
1.) It doesn't work in theorem provers like Coq or Agda, because
Exp occurs in both positive and negative position, causing it to fail the positivity check.
2.) It is quite hard to work under binders. You often have to invert your control flow for passes and think "inside out."
3.) You have to deal with exotic terms that do bad things like inspect the expression they are given, so it is in some sense "too big."
4.) Alpha equivalence is still tedious.
5.) In "Rotten Bananas" on comonad.com I go through the issues with general recursion in this approach.
Variants such as Weak HOAS/PHOAS/Weirich and Washburn exist to address some of these issues (e.g. working in Coq/Agda, restoring positivity, ruling out exotic terms) at the expense of other problems (e.g. losing the notion of catamorphism or general recursion).
De Bruijn Indices
-Conor McBride, "I am not a number, I am a classy hack"
We can split variables into bound and free:
-- show {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Data.Foldable import Data.Traversable data Exp a = Free a | Bound !Int | App (Exp a) (Exp a) | Lam (Exp a) deriving (Eq,Show,Read,Functor,Foldable,Traversable) -- /show main = putStrLn "It typechecks, but it is boring."
We could define combinators to bind names and instantiate them
abstract :: Eq a => a -> Exp a -> Exp a instantiate :: Exp a -> Exp a -> Exp a
but let's adopt Conor McBride's less error prone convention instead:
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Data.Foldable import Data.Traversable -- show newtype Scope f a = Scope (f a) deriving (Eq,Show,Read,Functor,Foldable,Traversable) data Exp a = Free a | Bound !Int | App (Exp a) (Exp a) | Lam (Scope Exp a) -- /show deriving (Eq,Show,Read,Functor,Foldable,Traversable) main = putStrLn "It typechecks, and is even slightly interesting."
With Conor's convention,
abstract and
instantiate actually have useful types that prevent you from doing bad things. Renaming
Bound to
B and
Free to
F, then adapting the approach he takes in his excellent functional pearl with James McKinna "I am not a Number -- I am a Free Variable" to our running example to try to keep Conor's somewhat absurd sense of humor intact we get:
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Data.Foldable import Data.Traversable newtype Scope f a = Scope (f a) deriving (Eq,Show,Read,Functor,Foldable,Traversable) data Exp a = F a | B !Int | App (Exp a) (Exp a) | Lam (Scope Exp a) deriving (Eq,Show,Read,Functor,Foldable,Traversable) -- show abstract :: Eq a => a -> Exp a -> Scope Exp a abstract me expr = Scope (letmeB 0 expr) where letmeB this (F you) | you == me = B this | otherwise = F you letmeB this (B that) = B that letmeB this (App fun arg) = letmeB this fun `App` letmeB this arg letmeB this (Lam (Scope body)) = Lam $ Scope $ letmeB (succ this) body instantiate :: Exp a -> Scope Exp a -> Exp a instantiate what (Scope body) = what'sB 0 body where what'sB this (B that) | this == that = what | otherwise = B that what'sB this (F you) = F you what'sB this (App fun arg) = what'sB this fun `App` what'sB this arg what'sB this (Lam (Scope body)) = Lam $ Scope $ what'sB (succ this) body -- /show main = putStrLn "It typechecks, and is even slightly interesting."
We could even make a monad that does capture avoiding substitution for
Exp, but it is an awkward one-off experience.
Pros:
1.)
Scope,
abstract, and
instantiate made it harder to screw up walking under binders.
2.) Alpha equivalence is just
(==) due to the power of De Bruijn indices.
3.) We can make a
Monad for
Exp that does capture avoiding substitution.
4.) We can use
Traversable and
Foldable to find free variables and close terms.
Using these we can define combinators like
import Data.Foldable as Foldable import Data.Traversable -- show closed :: Traversable f => f a -> Maybe (f b) closed = traverse (const Nothing) isClosed :: Foldable f => f a -> Bool isClosed = Foldable.all (const False) -- /show main = putStrLn "The types check out."
to check for closed terms, and we can use `Exp Void` directly as a closed term.
Cons:
1.) We
succ a lot in
letmeB and
what'sB.
2.) Illegal terms such as
Lam (Scope (B 2)) still exist.
3.) We have to define one-off versions of
abstract and
instantiate for each expression type we come up with. This means this is a design pattern, not a library.
4.) The
Monad for
Exp is similarly a one-off deal.
Bird and Paterson, Part 1
We can turn to Bird and Paterson's encoding of De Bruijn indices in terms of polymorphic recursion from the first half of De Bruijn notation as a nested datatype.
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Data.Foldable import Data.Traversable -- show data Exp a = Var a | App (Exp a) (Exp a) | Lam (Exp (Maybe a)) deriving (Functor, Foldable, Traversable) instance Monad Exp where return = Var Var a >>= f = f a App l r >>= f = App (l >>= f) (r >>= f) Lam xs >>= f = undefined -- go for it! -- /show main = print "Did you finish (>>=)?"
Pros:
1.) This eliminates the illegal terms from Con #2 above once and for all, and we can write a one-off
Monad for it.
2.) We have the
Maybe to mark our extra variables, so we can't forget to deal with our bound term at any point in our recursion.
Cons:
1.) We still
succ a lot, except now we call
succ
Just.
2.) We still need to write one-off
abstract and
instantiate combinators.
3.) The
Monad for
Exp is a one-off deal.
4.) They lean somewhat unnecessarily on
RankNTypes to manipulate these expressions in terms of their folds, when the
Monad and other classes can all be defined within the confines of Haskell 98.
Attempt #1
We can modify Bird and Paterson's approach in a few ways, to steal some of the desirable properties from McBride's "I am not a Number; I'm a Free Variable" by noticing that Scope forms a Monad transformer!
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Control.Monad import Control.Monad.Trans import Data.Foldable import Data.Functor import Data.Traversable -- show newtype Scope f a = Scope { runScope :: f (Maybe a) } deriving (Functor, Foldable, Traversable) instance Monad f => Monad (Scope f) where return = Scope . return . Just Scope m >>= f = undefined -- go for it! instance MonadTrans Scope where lift = Scope . liftM Just -- /show main = print "Scope scopes out, but did you finish (>>=)?"
The astute observer will recognize that this form of
Scope is just
MaybeT from
transformers.
We can finally even define
abstract and
instantiate from Conor's approach once and for all, completely independently of our expression type. Sadly, they find themselves now devoid of humor.
This is starting to feel like a library, rather than design pattern.
Moreover, with that in hand, we can revisit the definition of
Exp and define our
Monad by borrowing from
Scope's expression-type-agnostic definition.
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Control.Monad import Control.Monad.Trans import Data.Foldable import Data.Functor import Data.Traversable newtype Scope f a = Scope { runScope :: f (Maybe a) } deriving (Functor, Foldable, Traversable) instance Monad f => Monad (Scope f) where return = Scope . return . Just Scope m >>= f = Scope $ m >>= maybe (return Nothing) (runScope . f) instance MonadTrans Scope where lift = Scope . liftM Just -- show data Exp a = Var a | App (Exp a) (Exp a) | Lam (Scope Exp a) deriving (Functor, Foldable, Traversable) instance Monad Exp where return = Var Var a >>= f = f a App l r >>= f = App (l >>= f) (r >>= f) Lam body >>= f = Lam (body >>= lift . f) -- /show main = putStrLn "Now we're getting somewhere!"
Pros:
1.) We were able to factor out
Scope,
abstract and
instantiate into code we can write once and package up.
2.) We've gained the benefits of McBride's conventions, as
abstract and
instantiate are really nice to reason about.
Cons:
1.) This is still going to
succ just as much as our earlier De Bruijn solutions. Using
lift to embed into
Scope has to traverse all of the leaves to mangle them with a
Just.
2.)
Eq
Ord,
Show, and
Read are now non-trivial to write due to polymorphic recursion.
Bird and Paterson, Part 2
Bird and Paterson did write the other half of their paper for a reason, though. In the other half they showed we can encode a generalized De Bruijn index notion using a different polymorphic recursion pattern.
data Exp a = Var a | App (Exp a) (Exp a) | Lam (Exp (Maybe (Exp a)))
The astute observer will now note that this is looking a bit less like
MaybeT. So what happened?
Normally when you work with De Bruijn indices you
succ only the variables down at the leaves.
What Bird and Paterson's generalized De Bruijn form allows you to do is
Just née
succ whole trees at a time!
If we adopt my
MonadTrans variant of McBride's
Scope as before, and generalize Bird and Paterson's approach, sticking to Haskell 98. We get very close to the final solution actually encoded in
bound.
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Control.Monad import Control.Monad.Trans import Data.Foldable import Data.Functor import Data.Maybe import Data.Traversable -- show newtype Scope f a = Scope { runScope :: f (Maybe (f a)) } deriving (Functor, Foldable, Traversable) instance Monad f => Monad (Scope f) where return = Scope . return . Just . return Scope e >>= f = Scope $ e >>= \v -> case v of Nothing -> return Nothing Just ea -> ea >>= runScope . f instance MonadTrans Scope where lift = Scope . return . Just abstract :: (Monad f, Eq a) => a -> f a -> Scope f a abstract a e = Scope (liftM k e) where k b = return b <$ guard (a /= b) instantiate :: Monad f => f a -> Scope f a -> f a instantiate k (Scope e) = e >>= fromMaybe k -- /show main = putStrLn "Almost there!"
The key difference realized by Bird and Paterson's design is that now, lifting an expression that does not have our bound term in it into our new
Scope, no longer requires touching every leaf in the expression. In fact it is
O(1)!
Scope is still a
Monad transformer, but it is a new one!
This is a salvageable representation, but I want to take one more step before we turn it into a library, before we talk about Pros and Cons.
Bound: Generalized Generalized De Bruijn
Often we need to deal with simultaneous substitution of several variables. e.g. all of the variables bound by a pattern, all of the variables bound by a lambda, many variables bound by recursive let
De Bruijn even as generalized above still only lets me
abstract or
instantiate a single variable at a time.
What I want relates to
EitherT as the above monad relates to
MaybeT.
Finally, I'm going to alpha rename
Either, because really when we do finally get to show you these syntax trees, they are going to be bad enough without meaningless
Left and
Right names cluttering up my tree. Let's use
B for bound (pronounced
zero) and
F for free (pronounced
succ) in homage to Conor's conventions above.
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Control.Monad import Control.Monad.Trans import Data.Foldable import Data.Functor import Data.Maybe import Data.Traversable -- show Var data Var b a = B b | F a deriving (Eq,Ord,Show,Read,Functor,Foldable,Traversable) instance Monad (Var b) where return = F F a >>= f = f a B b >>= _ = B b -- /show -- show Scope newtype Scope b f a = Scope { runScope :: f (Var b (f a)) } deriving (Functor,Foldable,Traversable) instance Monad f => Monad (Scope b f) where return = Scope . return . F . return Scope e >>= f = Scope $ e >>= \v -> case v of B b -> return (B b) F ea -> ea >>= runScope . f instance MonadTrans (Scope b) where lift = Scope . return . F -- /show -- show Abstraction and Instantiation abstract :: Monad f => (a -> Maybe b) -> f a -> Scope b f a abstract f e = Scope (liftM k e) where k y = case f y of Just z -> B z Nothing -> F (return y) instantiate :: Monad f => (b -> f a) -> Scope b f a -> f a instantiate k e = runScope e >>= \v -> case v of B b -> k b F a -> a -- /show main = putStrLn "It typechecks, therefore it must be correct!"
From here on out we can actually use the real
bound library.
Pros:
1.) Because we can now
succ/
F a whole tree, we don't have to pay the usual De Bruijn performance tax.
We get
O(1) lifting, and when we
instantiate we can skip past the whole
F'd tree.
2.) We use
Foldable and
Traversable to extract information about free variables and do
variable -> variable substitution.
3.) We can use the
MonadTrans instance for
Scope b to facilitate the construction of
Exp.
We do this so often that we turn the
>>= lift . f idiom into a combinator (
>>>=)
that we'll talk about further when we talk about patterns.
This is a complete example syntax tree example that supports the use of `Foldable`/`Traversable`/`Monad` to extract information about the free variables, and do capture-avoiding substitution!
-- /show {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Data.Foldable import Data.Traversable import Bound data Exp a = Var a | App (Exp a) (Exp a) | Lam (Scope () Exp a) | Let [Scope Int Exp a] (Scope Int Exp a) deriving (Functor,Foldable,Traversable) instance Monad Exp where return = Var Var a >>= f = f a App l r >>= f = App (l >>= f) (r >>= f) Lam s >>= f = Lam (s >>>= f) Let xs b >>= f = Let (map (>>>= f) xs) (b >>>= f) -- /show main = putStrLn "That's it!"
4.) We can now deal with simultaneous substitution. To make things interesting in the example above we've extended the example with a simultaneous binding for all of the variables in a recursive let!
Cons:
1.) I still haven't shown you how to get
Eq,
Ord,
Read,
Show such that
Eq and
Ord respect alpha-equivalence.
Loose Ends
To work around the polymorphic recursion in
Scope, we turn to my fairly boring and generically named
prelude-extras package. This package provides higher-rank versions of typeclasses from the
Prelude.
For example
class Eq1 t where (==#) :: Eq a => t a -> t a -> Bool (/=#) :: Eq a => t a -> t a -> Bool
along with
Eq2,
Ord1,
Ord2,
Show1,
Show2,
Read1 and
Read2.
I told you it was boring.
There has also been some discussion on the libraries mailing list of randomly renaming these things and putting (a subset?) of these in
transformers to permit Haskell 98
Show instances things like
IdentityT and
WriterT.
Now, what we can do is use the fact that these classes have default definitions and the instances for
Scope are defined in terms of
Eq1,
Ord1,
Show1, and
Read1 for the base data type, to obtain the final solution!
-- show {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} import Bound import Control.Applicative import Control.Monad import Data.Foldable import Data.Traversable import Prelude.Extras data Exp a = Var a | App (Exp a) (Exp a) | Lam (Scope () Exp a) deriving (Eq,Ord,Show,Read,Functor,Foldable,Traversable) instance Eq1 Exp instance Ord1 Exp instance Show1 Exp instance Read1 Exp instance Applicative Exp where pure = Var (<*>) = ap instance Monad Exp where return = Var Var a >>= f = f a App x y >>= f = App (x >>= f) (y >>= f) Lam e >>= f = Lam (e >>>= f) -- /show whnf :: Exp a -> Exp a whnf (App f a) = case whnf f of Lam b -> whnf (instantiate1 a b) f' -> App f' a whnf e = e lam :: Eq a => a -> Exp a -> Exp a lam v b = Lam (abstract1 v b) nf :: Exp a -> Exp a nf e@Var{} = e nf (Lam b) = Lam $ toScope $ nf $ fromScope b nf (App f a) = case whnf f of Lam b -> nf (instantiate1 a b) f' -> nf f' `App` nf a main = putStrLn "It compiles"
and we can finally show syntax tree terms again.
The instances of
Eq and
Ord for
Scope in particular are careful to compare only up to alpha-equivalence by quotienting out the placement of any internal
F levels in the tree as if they'd all been pushed out to the leaves.
We can use
abstract1 and
instantiate1, which are analogous to the
abstract and
instantiate we were using before we generalized our generalized De Bruijn index representation to define things like smart constructors
lam :: Eq a => a -> Exp a -> Exp a lam v b = Lam (abstract1 v b)
and evaluation strategies such as computing weak head normal form:
whnf :: Exp a -> Exp a whnf (App f a) = case whnf f of Lam b -> whnf (instantiate1 a b) f' -> App f' a whnf e = e
One thing the
f (Maybe a) representation was good for was for walking under binders.
bound offers the round trip through this representation as
fromScope and
toScope. Now, if we need to walk under a lambda, we can!
nf :: Exp a -> Exp a nf e@V{} = e nf (Lam b) = Lam $ toScope $ nf $ fromScope b nf (App f a) = case whnf f of Lam b -> nf (instantiate1 a b) f' -> nf f' `App` nf a
Bound.Class
Finally, it is worth commenting on the generality of
(>>>=) as it points to the class for which this package is named.
In addition to
Scope and
Var, the
bound package provides the
Bound class:
class Bound t where (>>>=) :: Monad f => t f a -> (a -> f b) -> t f b default (>>>=) :: (MonadTrans t, Monad f) => t f a -> (a -> f b) -> t f b m >>>= f = m >>= lift . f
An instance of
Bound is required to form a left module over all monads. That is to say it should satisfy the following two laws that were identified by Andrea Vezzosi:
1.) The first such law is analogous to the first monad law:
m >>>= return ≡ m
2.) The second such law is an associativity law:
m >>>= (λ x → k x >>= h) ≡ (m >>>= k) >>>= h
Trivially, any valid
MonadTrans instance satisfies these laws, hence the default definition.
This extra flexibility is used in the
bound
examples/ folder to deal with complex pattern matching or other binding/telescoping structures.
What's Next?
You've just taken a crash course on name capture and been shown how
bound deals with common isses and makes it easy to work with De Bruijn indices without ever thinking about De Bruijn indices.
Hopefully, you want to learn more. Perhaps after a slight break to let this settle. If so, I can offer you three further avenues for exploration off the top of my head.
First, I'd like to note that there are a few middlingly-complex examples in the
bound
examples/ folder to explore and use as a template. Notably:
1.)
Simple.hs continues in the vein
we've taken here but fleshes out recursive let and sticks to Haskell 98 religiously.
2.)
Deriving.hs takes over from
where we're leaving off with here and uses
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
to reduce boilerplate, and importantly adds pattern matching. This showcases the need for the
Bound
class for dealing with patterns, case alternatives, and similar module structures.
3.)
Overkill.hs offers a trip down the rabbit hole of type safety. It shows how strong the type guarantees can get, by using custom kinds to index into its patterns and improves the safety of pattern matching and let binding over and above the
Deriving.hs approach, but at the expense of a great deal more code!
Second, it is also possible to derive a higher order version of
bound that can deal with strongly typed EDSLs as well. I've included a worked example version of it here under a spoiler tag simply for completeness, including an example of what could be turned into a network serializable EDSL replete with local variable bindings and lambdas, but it isn't for the faint of heart. It is also probably buggy and is completely untested. If you fix any issues with it, please feel free to email me!
{-# LANGUAGE GADTs, Rank2Types, KindSignatures, ScopedTypeVariables, TypeOperators, DataKinds, PolyKinds, MultiParamTypeClasses, FlexibleInstances, TypeFamilies, DoRec, ExtendedDefaultRules #-} import Control.Applicative import Control.Category import Control.Comonad import Control.Monad.Fix import Control.Monad (ap) import Data.Functor.Identity import Data.Typeable import Data.Monoid import Data.Unique import System.IO.Unsafe import Unsafe.Coerce import Prelude hiding ((.),id) infixl 1 >>>-, >>- type Nat f g = forall x. f x -> g x class HFunctor t where hmap :: Nat f g -> Nat (t f) (t g) class HFunctor t => HTraversable t where htraverse :: Applicative m => (forall x. f x -> m (g x)) -> t f a -> m (t g a) class HFunctor t => HMonad t where hreturn :: Nat f (t f) (>>-) :: t f a -> Nat f (t g) -> t g a infixr 1 -<< (-<<) :: HMonad t => Nat f (t g) -> Nat (t f) (t g) f -<< m = m >>- f class HBound s where (>>>-) :: HMonad t => s t f a -> Nat f (t g) -> s t g a class HMonadTrans s where hlift :: HMonad t => Nat (t f) (s t f) data Var b f a where B :: b a -> Var b f a F :: f a -> Var b f a instance HFunctor (Var b) where hmap _ (B b) = B b hmap f (F a) = F (f a) instance HTraversable (Var b) where htraverse _ (B b) = pure (B b) htraverse f (F a) = F <$> f a instance HMonad (Var b) where hreturn = F B b >>- _ = B b F a >>- f = f a newtype Scope b t f a = Scope { unscope :: t (Var b (t f)) a } instance HFunctor t => HFunctor (Scope b t) where hmap f (Scope b) = Scope (hmap (hmap (hmap f)) b) instance HTraversable t => HTraversable (Scope b t) where htraverse f (Scope b) = Scope <$> htraverse (htraverse (htraverse f)) b instance HMonad t => HMonad (Scope b t) where hreturn = Scope . hreturn . F . hreturn Scope e >>- f = Scope $ e >>- \v -> case v of B b -> hreturn (B b) F ea -> ea >>- unscope . f instance HMonadTrans (Scope b) where hlift = Scope . hreturn . F instance HBound (Scope b) where Scope m >>>- f = Scope (hmap (hmap (>>- f)) m) data Equal a b where Refl :: Equal a a instance Category Equal where id = Refl Refl . Refl = Refl abstract :: HMonad t => (forall x. f x -> Maybe (b x)) -> Nat (t f) (Scope b t f) abstract f = Scope . hmap (\y -> case f y of Just b -> B b Nothing -> F (hreturn y)) instantiate :: HMonad t => Nat b (t f) -> Nat (Scope b t f) (t f) instantiate k (Scope e) = e >>- \v -> case v of B b -> k b F a -> a data Ix :: [*] -> * -> * where Z :: Ix (a ': as) a S :: Ix as b -> Ix (a ': as) b data Vec :: (* -> *) -> [*] -> * where HNil :: Vec f '[] (:::) :: f b -> Vec f bs -> Vec f (b ': bs) infixr 5 :++, ::: type family (:++) (as :: [*]) (bs :: [*]) :: [*] type instance '[] :++ bs = bs type instance (a ': as) :++ bs = a ': (as :++ bs) happend :: Vec f as -> Vec f bs -> Vec f (as :++ bs) happend HNil bs = bs happend (a ::: as) bs = a ::: happend as bs hsingleton :: f a -> Vec f '[a] hsingleton x = x ::: HNil instance HFunctor Vec where hmap _ HNil = HNil hmap f (x ::: xs) = f x ::: hmap f xs instance HTraversable Vec where htraverse _ HNil = pure HNil htraverse f (x ::: xs) = (:::) <$> f x <*> htraverse f xs class EqF f where (==?) :: f a -> f b -> Maybe (Equal a b) data Lit t where Integer :: Integer -> Lit Integer Double :: Double -> Lit Double String :: String -> Lit String instance EqF Lit where Integer a ==? Integer b = Just Refl ... value :: Lit a -> a value (Integer i) = i value (Double d) = d value (String s) = s class Literal a where literal :: a -> Lit a instance Literal Integer where literal = Integer instance Literal String where literal = String data Remote :: (* -> *) -> * -> * where Var :: f a -> Remote f a Lit :: Lit a -> Remote f a Lam :: Scope (Equal b) Remote f a -> Remote f (b -> a) Let :: Vec (Scope (Ix bs) Remote f) bs -> Scope (Ix bs) Remote f a -> Remote f a Ap :: Remote f (a -> b) -> Remote f a -> Remote f b lam_ :: EqF f => f a -> Remote f b -> Remote f (a -> b) lam_ v f = Lam (abstract (v ==?) f) lit :: Literal a => a -> Remote f a lit = Lit . literal instance HFunctor Remote where hmap f (Var a) = Var (f a) hmap _ (Lit t) = Lit t hmap f (Lam b) = Lam (hmap f b) hmap f (Let bs b) = Let (hmap (hmap f) bs) (hmap f b) hmap f (Ap x y) = Ap (hmap f x) (hmap f y) instance HTraversable Remote where htraverse f (Var a) = Var <$> f a htraverse _ (Lit t) = pure $ Lit t htraverse f (Lam b) = Lam <$> htraverse f b htraverse f (Let bs b) = Let <$> htraverse (htraverse f) bs <*> htraverse f b htraverse f (Ap x y) = Ap <$> htraverse f x <*> htraverse f y data MyF a where Mean :: MyF (Double -> Double) instance HMonad Remote where hreturn = Var Var a >>- f = f a Lit t >>- _ = Lit t Lam b >>- f = Lam (b >>>- f) Let bs b >>- f = Let (hmap (>>>- f) bs) (b >>>- f) Ap x y >>- f = Ap (x >>- f) (y >>- f) (!) :: Vec f v -> Ix v a -> f a (b ::: _) ! Z = b (_ ::: bs) ! S n = bs ! n eval :: Remote Identity a -> a eval (Var w) = extract w eval (Lit i) = value i eval (Lam b) = \a -> eval (instantiate (\Refl -> Var (Identity a)) b) eval (Let bs b) = eval (instantiate (vs !) b) where vs = hmap (instantiate (vs !)) bs eval (Ap x y) = eval x (eval y) closed :: HTraversable t => t f a -> Maybe (t g a) closed = htraverse (const Nothing) newtype V (a :: *) = V Unique instance EqF V where V a ==? V b | a == b = Just (unsafeCoerce Refl) | otherwise = Nothing lam :: (Remote V a -> Remote V b) -> Remote V (a -> b) lam f = unsafePerformIO $ do x <- fmap V newUnique return $ Lam $ abstract (x ==?) $ f $ Var x data Binding a = V a := Remote V a rhs :: Binding a -> Remote V a rhs (_ := a) = a data Bindings = forall bs. Bindings (Vec Binding bs) elemIndex :: Vec Binding bs -> V a -> Maybe (Ix bs a) elemIndex HNil _ = Nothing elemIndex ((x := r) ::: xs) y = case x ==? y of Just Refl -> Just Z Nothing -> S <$> elemIndex xs y instance Monoid Bindings where mempty = Bindings HNil Bindings xs `mappend` Bindings ys = Bindings (happend xs ys) -- Allow the use of DoRec to define let statements newtype Def a = Def { runDef :: IO (a, Bindings) } instance Functor Def where fmap f (Def m) = Def $ do (a,w) <- m return (f a, w) instance Applicative Def where pure = return (<*>) = ap instance Monad Def where return a = Def $ return (a, mempty) Def m >>= f = Def $ do (a, xs) <- m (b, ys) <- runDef (f a) return (b, xs <> ys) instance MonadFix Def where mfix m = Def $ mfix $ \ ~(a, _) -> runDef (m a) def :: Remote V a -> Def (Remote V a) def v@Var{} = Def $ return (v, mempty) -- this thing already has a name def r = Def $ do v <- fmap V newUnique return (Var v, Bindings (hsingleton (v := r))) let_ :: Def (Remote V a) -> Remote V a let_ (Def m) = unsafePerformIO $ do (r, Bindings bs) <- m return $ Let (hmap (abstract (elemIndex bs) . rhs) bs) (abstract (elemIndex bs) r)
Third, for a much larger "industrial scale" example you can explore our work-in-progress compiler for Ermine that uses
bound (and
lens) extensively for manipulating its
Term language,
Type system,
Kind system and the
Core language it spits out as a witness during type checking.
Happy Hacking!
August 19 2013
P.S. Apparently the proper Dutch convention with names is to use Nicolaas Govert de Bruijn when writing out a full name, but to capitalize De Bruijn when using the surname in isolation. | https://www.schoolofhaskell.com/user/edwardk/bound | CC-MAIN-2016-50 | refinedweb | 5,601 | 66.37 |
Dynamic data in templates
We have different pieces in place: the
Post model is defined in
models.py, we have
post_list in
views.py and the template added. But how will we actually make our posts appear in our HTML template? Because that is what we want to do – take some content (models saved in the database) and display it nicely in our template, right?
This is exactly what views are supposed to do: connect models and templates. In our
post_list view we will need to take the models we want to display and pass them to the template. In a view we decide what (model) will be displayed in a template.
OK, so how will we achieve this?
We need to open our
blog/views.py. So far
post_list view looks like this:
blog/views.py
from django.shortcuts import render def post_list(request): return render(request, 'blog/post_list.html', {})
Remember when we talked about including code written in different files? Now is the moment when we have to include the model we have written in
models.py. We will add the line
from .models import Post like this:
blog/views.py
from django.shortcuts import render from .models import Post
The dot before
models means current directory or current application. Both
views.py and
models.py are in the same directory. This means we can use
. and the name of the file (without
.py). Then we import the name of the model (
But what's next? To take actual blog posts from the
Post model we need something called
QuerySet.
QuerySet
You should already be familiar with how QuerySets work. We talked about them in Django ORM (QuerySets) chapter.
So now we want published blog posts sorted by
published_date, right? We already did that in QuerySets chapter!
blog/views.py
Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
Now we put this piece of code inside the
blog/views.py file by adding it to the function
def post_list(request), but don't forget to first add
from django.utils import timezone:
blog/views.py
from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {})
The last missing part is passing the
posts QuerySet to the template context. Don't worry – we will cover how to display it in a later chapter.
Please note that we create a variable for our QuerySet:
posts. Treat this as the name of our QuerySet. From now on we can refer to it by this name.
In the
render function we have one parameter
request (everything we receive from the user via the Internet) and another giving the template file (
'blog/post_list.html'). The last parameter,
{}, is a place in which we can add some things for the template to use. We need to give them names (we will stick to
'posts' right now). :) It should look like this:
{'posts': posts}. Please note that the part before
: is a string; you need to wrap it with quotes:
''.
So finally our
blog/views.py file should look like this:
blog/views.py
from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts})
That's it! Time to go back to our template and display this QuerySet!
Want to read a little bit more about QuerySets in Django? You should look here: | https://tutorial.djangogirls.org/en/dynamic_data_in_templates/ | CC-MAIN-2017-34 | refinedweb | 594 | 79.36 |
Kotlin vs Java: Which programming language to choose for your Android application
In the Android development community, usage for Kotlin continues to grow, especially since its introduction as a preferred language by Google in 2017. So, which language should you choose for developing your app for Android? This article goes over some of the benefits that developing in Kotlin has over Java.
As we write, the Kotlin mobile app development community is continuing to grow. It was in the year 2017 when Google recognized Kotlin as the second official language of Android app development. Since then, we have seen a monumental rise in the demand for the programming language amongst developers and enterprise communities. Google has already announced Kotlin as one of the most preferred languages for Android app developers. This goes to show that this programming language will prove to be pragmatic, state-of-the-art, and intuitive.
In the forthcoming sections of this write-up, we have provided a comprehensive differentiation between Java and Kotlin programming languages that can be employed for Android app development. We promise after reading this piece of content; you will be in a far better position to apply Android app development services more effectively.
The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.
Let’s start by understanding Kotlin.
Kotlin is a statistically typed programming language that is primarily employed for JavaScript and Java Virtual Machine (JVM). Some even describe it as a general-purpose language. It introduces functional features that assist in supporting Java interoperability. The principal purpose behind the project’s development was heightened productivity. Its ultimate objective is to enhance the coding experience to make it look practical and useful.
One of the significant focuses is to enable mixed-language projects. It tries to introduce enhanced syntax along with precise expressions and abstractions. By employing Kotlin with Java, it is possible to reduce excessive boilerplate code. This way, it provides a win-win situation for Android developers.
Where does Kotlin stand as a programming language in the year 2019?
Since Google introduced Kotlin in the year 2017, the programming language has seen a vast amount of growth in Android development. You will be surprised to know that the KotlinConf has been held only twice; however, it has become an institution in the developer community.
It tries to ensure its accessibility across all platforms. However, multi-platform programming has given prominence to a much more innovative outlook, i.e., sharing codes between all platforms. As Kotlin 1.3 has been released, enhancements in Kotlin/Native take the concept of multi-platform convenience to another level.
SEE ALSO: Jakarta EE 8 is sprinting towards an exciting future for enterprise Java
As a result, today, Android developers can employ a single integrated development environment (IDE) to develop Kotlin on all platforms. The latest release provides more mobile app scalability. This has been possible with the help of code reuse, which ensures saving of time and effort that can be put in to deal with more challenging tasks.
Kotlin/Native employs the compiler technology LLMV to integrate Kotlin sources into stand-alone binaries for multiple operating systems and CPU architectures, including Windows, iOS, Linux, Webassembly, and Mac.
In the current year, we are seeing more and more enterprises migrating to Kotlin. Alternatively, some are planning to do that. We are also witnessing mobile products like Netflix, Airbnb, Evernote, Pinterest, Twitter, and Trello switching to Kotlin for Android applications. Although the emergence of cross-platform Kotlin development has not been explosive, major industry players are observing the benefits offered.
So, does that mean it is the end of Java? Let’s find out.
Is the end of Java near?
Developers have a mixed opinion on this topic.
Java is a popular programming language that consists of a wide array of open-source tools and libraries that aid developers. However, no language is without loopholes, and Java has its own set of complications that can make the job of a developer intricate. With the introduction of Kotlin, developers will have solutions to regular programming headaches. It will enhance the Java ecosystem as a whole.
In the last few years, Kotlin has become a more stable and harmonious development alternative for Android studio. Certain developers have the opinion that it will end Java’s association for Android development in the years to come while others think that both can coexist without outweighing the other.
The very first thing is the fact that Kotlin’s strengths are much more than its setbacks. Java has to deal with certain limitations that impede Android API design. On the other hand, Kotlin is lightweight, clean, and far less tedious. This is especially true in terms of writing callbacks, data classes, and getters/setters. In more simple terms, Kotlin has been designed to enhance prevailing Java models by providing solutions to API design deficiencies.
These are some of Java’s weaknesses addressed by Kotlin.
Conciseness
There are a wide array of developers who praise Kotlin for its conciseness. This is one thing missing in Java. However, it has got to be said that reliability is much more critical than conciseness. It simplifies the job of developers by mitigating the risk for error. However, it does not practice concision solely for the sake of concision. The problem is the boilerplate code that makes it difficult to read and results in more bugs and wasted time to find them.
We have mentioned a simple calculator function written in Java.
public class ClearBridge { public static double calculate (double a, String op, double b) throws Exception { switch (op) { case "add": return a + b; case "subtract": return a - b; case "multiply": return a * b; case "divide": return a / b; default: throw new Exception(); } }
The same can be put in with the help of Kotlin.
fun calculate (a: Double, op: String, b: Double): Double { when (op) { "add" -> return a + b "subtract" -> return a - b "multiply" -> return a * b "divide" - > return a / b else -> throw Exception() } }
Although you might say that there is not much difference between the codes, the Kotlin version has been written in half the lines of code that it took for the program to run Java. Conciseness is exceptionally critical when it comes to productivity. If you wish to write large projects, it becomes effortless for the developer when he/she has more power for every line of code. A key point of differentiation is the fact that the Kotlin syntax is readable, concise and still substantial.
SEE ALSO: Top programming languages in 2019: Python sweeps the board
Interoperability
The core purpose of Kotlin is interoperability. From the start, the project intends to employ the collective knowledge and expertise to every library accessible to programmers. The developers can write modules in Kotlin that can run without any problem in the existing Java code.
Final words
In the end, it has got to be said that Kotlin has established itself as a preferred programming language for mobile app development. It provides ample opportunities to experiment with modern programming. All in all, it has set a new benchmark for what a programming language should be able to accomplish.
9 Comments on "Kotlin vs Java: Which programming language to choose for your Android application"
The explanation you have given about kotlin language is superb. As per the article the kotlin is really helpful, it is simple and concise.
Being a long time Android developer using Android Studio I must say that all the fuzz about writing less is silly. The IDE does a really good job at code completion so it’s really not that big of a deal. Also lamda and libs such as butter knife keep the code slimmed down.
I don’t have any problem with the Kotlin, but this text sucks especially that last example :). Write the program in any language you feel comfortable. I hate when I waste 10 good minutes of my life on text like these. When programming, you do 3 things, thinking, writing and debugging. The least time you spend is in writing. Bad programmer makes bugs and not the langauge he is using for writing.
The code for Java is not double compared to kotlin.
The example given here is ridiculous. If the aim is achieving same number of lines, you can write each case of switch statement in single line.
Been using kotlin since 2017 on a big webapp project. I love it. I’m doing 2 projects at the same time using java and kotlin. They can co-exist. Kotlin uses the same java libraries.
This is such a terrible comparison… The example showed kotlin with half the lines of code when in reality both were the same lines of code. The Kotlin example just removed line breaks. Overall bad comparison
If you don’t go to a new line for the return of each case in the Java version, then you have the same number of lines…
Kotlin, your blog is very helpful. | https://jaxenter.com/kotlin-java-android-162038.html | CC-MAIN-2019-47 | refinedweb | 1,516 | 55.44 |
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
st: RE: SV: RE: scalar and calculations
Your program can't see your tempname. Your tempname must be specified in the same program (namespace) and before it is used, as I was trying to indicate, or imply.
Another issue is that there is a Stata command -test-, which may well be getting in the way here.
Nick
n.j.cox@durham.ac.uk
Tomas Lind
Thanks Nick,
This code works (with tempname v2), but it does not work if I specify `v2'
in the -return- and -simulate- statements. That makes me a bit confused when
you say " Alternatively, and better,
tempname v
scalar `v' =
capture program drop test
program test , rclass
version 10
syntax [, n(integer 1) ]
drop _all
set obs `n'
gen zz=10
sum zz
scalar x = r(mean)
tempname v2
return scalar v2 = x^2 * `n'
end
tempname z
simulate z = r(v2) , reps(10) : test , n(100)
sum z // OK fungerar
/Tomas
-----Ursprungligt meddelande-----
Från: owner-statalist@hsphsun2.harvard.edu
[mailto:owner-statalist@hsphsun2.harvard.edu] För Nick Cox
Skickat: den 16 april 2010 16:17
Till: statalist@hsphsun2.harvard.edu
Ämne::
*
*
*
*
* For searches and help try:
*
*
* | http://www.stata.com/statalist/archive/2010-04/msg00900.html | CC-MAIN-2014-10 | refinedweb | 203 | 54.97 |
Online Schema Changes¶
Make schema changes execute online (ie while services are running) when safely and semantically possible. This will allow operators to reduce the amount of downtime currently required during deploys.
Problem description¶
All database migrations are currently required to be run offline.
Database migrations have historically been a source of lengthy downtime during deployments.
Schema changes are required to be repeated in two places: database model defined in Nova and writing a migration script.
Use Cases¶
Any deployer that would like to reduce the amount of downtime during deploys.
Developers that would like to spend less time writing migration scripts.
Deployers that would like to maintain a set of local schema changes.
Proposed change¶
A new alternative workflow for applying schema changes will be added that expands the schema, then contracts the schema (expand/contract workflow).
The new expand/contract workflow will not utilize any migration scripts, instead it will dynamically compare the running schema against the database model defined in Nova. DDL statements will be generated, and optionally executed, to make the running schema match the model.
The existing schema management workflow is the ‘db sync’ command to nova-manage. This is managed by sqlalchemy-migrate and uses individual migration scripts. This workflow will remain for now, but is expected to be removed at some future time, leaving the expand/contract workflow as the way to manage the database schema.
Until the sqlalchemy-migrate workflow is removed, all schema changes will still need sqlalchemy-migrate migration scripts to be written.
Three new nova-manage commands will be added:
expand. This would apply changes that are compatible with old running code.
migrate. This would apply changes that are necessary to be run offline.
contract. This would apply changes that are compatible with new running code.
Those schema changes that can be safely and semantically applied while running online will be applied during the expand and contract phases. Also, only those schema changes that will not acquire long running locks in the database will be considered for the online phases (expand, contract). All other schema changes will be applied during the migrate phase.
The three new commands would be built by dynamically executing alembic’s autogenerate and DDL generating features. A list of differences would be generated by alembic and then DDL statements would be generated using a separate feature of alembic.
The set of DDL statements that can be run in each phase would be dictated by the database software used (eg MySQL, PostgreSQL, etc), the version of the database software (eg MySQL 5.5, 5.6, etc) and the storage engine used (eg InnoDB, TokuDB, etc).
As an example, index additions can be executed online in MySQL 5.5, but not 5.1. An index addition would be run during the expand phase for MySQL 5.5 or higher, but during the migrate phase for MySQL 5.1.
It is intended that the initial set that will run online will be conservative at first and a subset of what is possible to run safely. This can be safely expanded at any time in the future.
Schema changes that will be potentially performed during expand: - Table creates - Column additions - Non-Unique Index additions
Schema changes that will be potentially performed during migrate: - Unique Index additions/drops - Foreign Key additions/drops
Schema changes that will be potentially performed during contract: - Table drops - Column drops - Non-Unique Index drops
Some schema changes that aren’t currently used or are difficult to automate will not be allowed initially. For instance, column type changes will not be allowed initially. This is because not all column type changes can be automated because of complexity and database restrictions. A subset of column type changes may be implemented in the future if they can be automated on all databases.
The migrate and contract phases would verify that the previous phases (expand in the case of migrate, expand and migrate in the case of contract) no longer need to be executed before continuing.
This would be performed by generating the list of needed changes for the previous phases and verifying the list is empty. This indicates the previous phases were either run or unnecessary.
A new ‘–dryrun’ argument would print, instead of execute, each generated DDL statement. This could be used by database administrators to see what would be executed for a particular phase. These can be optionally executed manually if desired. The schema synchronizer will not generate that DDL statement since the running schema does not have that difference anymore.
When ‘db contract’ is finally run and the running schema has been verified to match the models, the version in the migrate_version table would be updated to the latest shipped sqlalchemy-migrate migration version. This would maintain compatibility with the existing sqlalchemy-migrate workflow.
The fundamental difference between the two workflows is the expand/contract workflow is declarative (by using the model) and the sqlalchemy-migrate workflow is imperative (by using migration scripts).
By being declarative, it limits changes to one place (database model) and allows for more intelligent decisions (by factoring in the database software, engine, version, etc)
Alternatives¶
Splitting the existing single stream of migrations into three separate streams of migrations. This would allow some schema changes to be executed online.
This limits the schema changes that can be safely executed online to that of the lowest common denominator of databases supported by Nova.
This would also require changes to sqlalchemy-migrate to be able to manage seperate streams of migrations.
Another option would be remove the use of sqlalchemy-migrate for schema changes altogether. The ‘db sync’ command to nova-manage would be implemented by effectively calling ‘db expand’, ‘db migrate’ and ‘db contract’.
Performance Impact¶
Running online DDL changes can affect the performance of a running system. This is optional and is only done when the deployer explicitly requests it.
This can mitigated by the deployer by scheduling the expand and contract phases to be run during periods of low activity. The expand phase can be run an arbitrary amount of time before the migrate phase. Likewise, the contract phase does not need to be run immediately after the migrate phase is run.
Other deployer impact¶
Using the new expand/contract workflow is optional. If the deployer does not want to perform database schema changes online, then they can continue using the ‘db sync’ command with nova-manage.
Those deployers that want to take advantage of the online schema changes will need to run the ‘db expand’, ‘db migrate’ and ‘db contract’ commands at the appropriate steps in their deployment process.
Switching from the sqlalchemy-migrate workflow to the expand/contract workflow can happen at any time. The reverse can only happen after a final ‘db contract’ is run (to ensure all schema changes are applied and the migrate_version table is updated).
If the expand/contract workflow is used, then ‘db contract’ is required to be execute once for each formal release of Nova. This is to ensure that SQL namespaces (table, column, etc) can be reused in the future.
Deployers that have made local schema changes (extra indexes, columns, tables, etc) will need to update the model to ensure those additions aren’t dropped during the contract phase.
If using the expand/contract workflow, then deployers can run ‘db expand’ before stopping or restarting any services. ‘db migrate’ might acquire locks in the database and may affect running services. ‘db contract’ can be run after all Nova services are running the new code.
Developer impact¶
Eventually no more sqlalchemy-migrate migrations would need to be written leading to less work for developers.
No more migration compaction. The initial creation of tables for a database is handled completely by the schema synchronizer.
Some schema changes will no longer be allowed. This is generally restricted to schema changes that cannot be reasonably automated but those schema changes are generally the ones with the most downtime anyway.
Namespaces (table, column, index, etc) are not reusable in a formal release cycle. The contract phase is only required to be executed once per formal release, pinning old names until the next formal release.
Implementation¶
Dependencies¶
This builds on top of the validate-migrations-and-model spec. The existing use of alembic.autogenerate will now also be used to generate the list of needed changes to make the schema match the model.
This also depends on dropping the use of sqlalchemy-migrate for data migrations.
Testing¶
No tempest tests will be added since tempest does not do any upgrade testing.
A Nova unit test will be added to test starting from an empty database.
Grenade currently tests upgrades from older versions of Nova. A new test to use the new ‘db expand’, ‘db migrate’ and ‘db contract’ commands are necessary. This will be compared with the result of ‘db sync’ to ensure that upgrades from past commits end up semantically identical.
turbo-hipster tests upgrades using production database snapshots. It currently uses the ‘db sync’ command to nova-manage. The new expand/contract workflow will be tested as well to ensure that both workflows function correctly.
Documentation Impact¶
Documentation will need to be updated to include the new ‘expand’, ‘migrate’ and ‘contract’ commands to ‘nova-manage db’.
Release Notes will need to be updated to warn that the model will need to be updated with local schema changes.
Instance Types would need to be manually created as the 216 migration would not necessarily run anymore. | http://specs.openstack.org/openstack/nova-specs/specs/kilo/approved/online-schema-changes.html | CC-MAIN-2019-35 | refinedweb | 1,579 | 54.12 |
The QgsLayerTreeModel class is model implementation for Qt item views framework. More...
#include <qgslayertreemodel.h>
The QgsLayerTreeModel class is model implementation for Qt item views framework.
The model can be used in any QTreeView, it is however recommended to use it with QgsLayerTreeView which brings additional functionality specific to layer tree handling.
The model listens to the changes in the layer tree and signals the changes as appropriate, so that any view that uses the model is updated accordingly.
Behavior of the model can be customized with flags. For example, whether to show legend or whether to allow changes to the layer tree.
Construct a new tree model with given layer tree (root node must not be null pointer).
The root node is not transferred by the model.
Return at what number of legend nodes the layer node should be collapsed. -1 means no auto-collapse (default).
Get index of the item marked as current. Item marked as current is underlined.
Filter nodes from QgsMapLayerLegend according to the current filtering rules.
Return OR-ed combination of model flags.
Return legend node for given index.
Returns null for invalid index
Return layer tree node for given index.
Returns root node for invalid index. Returns null pointer if index does not refer to a layer tree node (e.g. it is a legend node)
Convert a list of indexes to a list of layer tree nodes.
Indices that do not represent layer tree nodes are skipped.
Return true if index represents a legend node (instead of layer node)
Return list of legend nodes attached to a particular layer node.
Return layer node to which a legend node belongs to.
Returns null pointer if index is not a legend node.
Get font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode::NodeType enumeration.
Get hints about map view - to be used in legend nodes.
Arguments that are not null will receive values. If there are no valid map view data (from previous call to setLegendMapViewData()), returned values are zeros.
Return index for a given legend node.
If the legend node does not belong to the layer tree, the result is undefined. If the legend node is belongs to the tree but it is filtered out, invalid model index is returned.
Return index for a given node. If the node does not belong to the layer tree, the result is undefined.
emit dataChanged() for layer tree node items
Force a refresh of legend nodes of a layer node.
Not necessary to call when layer's renderer is changed as the model listens to these events.
Return pointer to the root node of the layer tree. Always a non-null pointer.
Set at what number of legend nodes the layer node should be collapsed. Setting -1 disables the auto-collapse (default).
Set index of the current item. May be used by view. Item marked as current is underlined.
Enable or disable a model flag.
Set OR-ed combination of model flags.
Set font for a particular type of layer tree node. nodeType should come from QgsLayerTreeNode::NodeType enumeration.
Force only display of legend nodes which are valid for given map settings.
Setting null pointer or invalid map settings will disable the functionality. Ownership of map settings pointer does not change.
Force only display of legend nodes which are valid for given scale denominator.
Setting value <= 0 will disable the functionality
Give the layer tree model hints about the currently associated map view so that legend nodes that use map units can be scaled currectly.
Reset the model and use a new root group node.
Check whether a flag is enabled.
Minimal number of nodes when legend should be automatically collapsed. -1 = disabled.
Current index - will be underlined.
Set of flags for the model.
scale denominator for filtering of legend nodes (<= 0 means no filtering)
Active legend nodes for each layer node.
May have been filtered. Owner of legend nodes is still mOriginalLegendNodes !
Data structure for storage of legend nodes for each layer.
These are nodes as received from QgsMapLayerLegend
Pointer to the root node of the layer tree. Not owned by the model. | https://api.qgis.org/api/2.6/classQgsLayerTreeModel.html | CC-MAIN-2022-21 | refinedweb | 692 | 68.77 |
lock Statement (C# Reference)Sen Thomas
The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form:
Object thisLock = new Object();
lock (thisLock)
{
// Critical code section.
}("myLock") is a problem because any other code in the process using the same string, will share the same lock.
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.
using System.Threading; class ThreadTest { public void RunMe() { Console.WriteLine("RunMe called"); } static void Main() { ThreadTest b = new ThreadTest(); Thread t = new Thread(b.RunMe); t.Start(); } } // Output: RunMe called
The following sample uses threads and lock. As long as the lock statement is present, the statement block is a critical section and balance will never become a negative(); } } }
Virtual MethodsSen Thomas
Declaring a class member as *virtual* allows inheriting classes to override the base class behavior.
This is one of the pillars of OOP known as polymorphism.
Declaring a method as *sealed* breaks this inheritance chain., preventing inheriting classes from overriding base class methods.
class BaseClass
{
public virtual void Method_01()
{
Console.WriteLine("BaseClass.Method_01");
}
public virtual void Method_02()
{
Console.WriteLine("BaseClass.Method_02");
}
}
class DerivedClass : BaseClass
{
public override void Method_01()
{
Console.WriteLine("DerivedClass.Method_01");
}
public override sealed void Method_02()
{
Console.WriteLine("DerivedClass.Method_02");
}
}
class Consumer : DerivedClass
{
public override void Method_01()
{
Console.WriteLine("Consumer.Method_01");
}
public new void Method_02()
{
Console.WriteLine("Consumer.Method_02");
}
}
static void Main(string[] args)
{
BaseClass bc;
bc = new DerivedClass();
bc.Method_01();
bc.Method_02();
Console.ReadLine();
bc = new Consumer();
bc.Method_01();
bc.Method_02();
Console.ReadLine();
}
Customize default folder of Windows ExplorerSen Thomas
If you have noticed when you click on the Windows Explorer icon default folder in task bar in Win 7, it would go to libraries folder. You can customize this behavior. Let’s say we need to set the default behavior to open My Computer.
Here are steps to change it from libraries to my computer:
1. Close all the windows explorer windows.
2. Press Shift key and right click on the explorer icon
3. Click Properties menu item and Click Properties menu item and Go to Shortcut tab.
4. Change the Target to : %SystemRoot%\explorer.exe /E,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
5. Click Apply and Ok button.
So next time you open the windows explorer it would open my computer folder.
Windows 7 TipsSen Thomas
Minimize Everything except the current window
Many times we have a lot of applications open on the screen and if we have to minimize or hide other windows that are open in the background.
Then this tip can be handy.
Press the Windows Key + Home Key.
This would minimize all the background windows. | http://aspdotnet-authority.blogspot.com/ | CC-MAIN-2013-48 | refinedweb | 468 | 58.69 |
Qt Modules
The
Qt.* modules contain properties and rules for Qt.
Creating Dependencies to Qt Modules
The Qt modules are special in that they are submodules within the
Qt "namespace", which has ramifications on the syntax when expressing dependencies. Assume your product depends on the
core and
network modules. Then you could write:
Depends { name: "Qt.core" } Depends { name: "Qt.network" }
Or, alternatively:
Depends { name: "Qt"; submodules: ["core", "network" } }
List of Submodules
Module Properties
The following sections describe the properties of Qt modules that can be interesting to users.
core Properties
Some of the following properties only need to be defined if the respective installation of Qt was built in some unusual way, for instance by setting non-default
configure flags.
dbus Properties
declarative Properties
gui Properties
quick Properties
scxml Properties
Relevant File Tags
The following sections describe the file tags that are relevant for the Qt modules.
core File Tags
dbus File Tags
gui File Tags
scxml File Tags. | http://doc.qt.io/qbs/qt-modules.html | CC-MAIN-2017-17 | refinedweb | 160 | 55.54 |
dbm.
A tuple containing the exceptions that can be raised by each of the supported modules, with a unique exception also named dbm.error as the first item — the latter is used when dbm.error is raised.
This function attempts to guess which of the several simple database modules available — dbm.gnu, dbm.ndbm or dbm.dumb —.ndbm' or 'dbm.gnu'.().
Changed in version 3.2: get() and setdefault() are now available in all database modules.
Key and values are always stored as bytes. This means that when strings are used they are implicitly converted to the default encoding before being stored.
The following example records some hostnames and a corresponding title, and then prints out the contents of the database:
import dbm # Open database, creating it if necessary. db = dbm.open('cache', 'c') # # Close when done. db.close()
The individual submodules are described in the following sections.
Platforms: Unix.
Raised on dbm.gno objects.
Platforms: Unix.
Raised on dbm.ndbm).
The optional flag argument must be one of these values:
The optional mode argument is the Unix mode of the file, used only when the database has to be created. It defaults to octal 0o666 (and will be modified by the prevailing umask).
Note.
The module defines the following:
Raised on dbm.dumb-specific errors, such as I/O errors. KeyError is raised for general mapping errors like specifying an incorrect key.o666 (and will be modified by the prevailing umask).
In addition to the methods provided by the collections.MutableMapping class, dumbdbm objects provide the following method:
Synchronize the on-disk directory and data files. This method is called by the Shelve.sync() method. | https://wingware.com/psupport/python-manual/3.2/library/dbm.html | CC-MAIN-2016-22 | refinedweb | 276 | 60.61 |
A couple of suggestions...
1) don't use multiple indexes. create one index, with one document per
"thing" you want to return (in this case it sounds like books) and index
all of the relevent data about each thing in that doc. If multiple people
worked on a book, add all of their names to the same field. addd all of
the dates to the book doc -- if you need to distibguish the differnet
types of dates, make a seaprete field for each type.
If you *must* cross refrence...
2) make sure you aren't useing the Hits API to iterate over all the
results when gathering IDs -- use a lower level api (like a HitCollector)
3) use the FieldCache to get the IDs instead of he stored Document fields.
4) don't extract full ID lists from all of then indexes and then search
on one of the indexes again with the ID list ... use the ID lists
generated from the supporting indexes (people and dates) to build a Filter
that you can use when searching the main index.
: Date: Mon, 12 Jun 2006 12:22:30 +0300
: From: Mile Rosu <mile.rosu@level7.ro>
: Reply-To: java-user@lucene.apache.org
: To: java-user@lucene.apache.org
: Subject: Using more than one index
:
: Hello,
:
: We have an application dealing with historical books. The books have
: metadata consisting of event dates, and person names among others.
: The FullText, Person and Date indexes were split until we realized that
: for a larger number of documents (400K) the combination of the
: sequential search hits took a way too long time to complete (15 min).
: The date index was built using the suggestion found at:
: (big
: thanks for the hint)
:
: Is there a recommended approach to combining results from different
: indexes (with different fields)?
:
: The indexes structure:
: MainIndex:
: Fields:
: @ID@ - keyword (document id)
: @FULLTEXT@ - tokenized (used for full text6 search)
: Ptitle - tokenized (used for full text publication title
: search)
: Dtitle - tokenized (used for full text document title
: search)
: Type - keyword - (used for document type)
:
: PersonIndex:
: @ID@ - keyword (document id == mainIndex.@ID@)
: Person - tokenized (full text person name search)
: DateIndex:
: @ID@ - keyword (document id == mainIdex.@ID@)
: Date - date as YYYYMMDD - keyword
: Type - type of date (document date, birth day, etc...)
: @YYYY@ - year of date
: @YYYYMM@ - year and month of date
: @DDD@ - decade
: @CC@ - century of date
:
:
: Eg:
: If I want to search for documents that contain: person "John", full text
: "book" and date: before 06/12/2005
: Step 1: search in personIndex for John - retrieve all @ID@ from the hit
: list
: Step 2: search in DateIndex for documents that have dates before
: 06/12/2005 - retrieve id from the hit list
: Step 3: search in mainIndex for "book" - retrieve all @ID@
: Step 4: combine all the lists
: Step 5: search mainIndex for documents with the @ID@ from the combined
: id list
:
: Each search takes less then 1 second, but retrieving @ID@ from the index
: takes a lot more - the time increases by the number of hits. This is
: because when retrieving a field value from a document hit, the Lucene
: engine loads all the fields from the index (the entire document). So if
: in one search I get 300.000 hits cont, I have to iterate through all and
: retrieve the @ID@ field value - this takes a lot of time.
:
: Regards,
: Mile Rosu
:
: ---------------------------------------------------------------------
: | http://mail-archives.apache.org/mod_mbox/lucene-java-user/200606.mbox/%3CPine.LNX.4.58.0606122348410.13650@hal.rescomp.berkeley.edu%3E | CC-MAIN-2017-22 | refinedweb | 560 | 65.76 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
Hello PluginCafe!
I need to implement some sort of custom viewport or a custom material preview window in my object modifier or object generator plugin.
something like this:
Is it possible using python?
As I know, there is a BitmapButtonCustomGui class and maybe it can be used in order to accomplish this task, but I never used it and don't know how it works.
any tips or better ideas?
Hello,
there is no thing like a custom viewport.
You can render a given scene (BaseDocument) with RenderDocument() using the hardware (OpenGL) renderer. Then you can display the resulting BaseBitmap in the GUI somehow. That is what the material preview is doing.
BaseDocument
RenderDocument()
BaseBitmap
One way would be to use a GeDialog. In this case you could use a BitmapButtonCustomGui to display a BaseBitmap. This is something you could implement in Python.
GeDialog
BitmapButtonCustomGui
Another way could be to add a bitmap button to the description of your object (CUSTOMDATATYPE_BITMAPBUTTON). Such a bitmap button would display a registered icon (BITMAPBUTTON_ICONID1). So you would have to register your bitmap as an icon using RegisterIcon(). But I haven't tried that and I don't know how well that would work.
CUSTOMDATATYPE_BITMAPBUTTON
BITMAPBUTTON_ICONID1
A third solution would be to use the C++ SDK. Then you could define a custom data type which you could add to your object's parameter description. You could create a custom GUI for that data type that includes a GeUserArea that draws the bitmap the way you want.
GeUserArea
You find more information on parameter descriptions in these manuals:
And more information on GeDialogs and GeUserAreas in these manuals:
You find examples on how to create custom data types or custom GUI elements in C++ here:
best wishes,
Sebastian
Seems like I figured it out but I'll keep investigating.
I tried this way and it kinda works. but let's assume that I want to scale the sphere object from my object generator plugin. It works only if I'm updating the render settings or reloading python plugins. Is it possible to update it according to the DIRTY FLAGS of the object generator plugin?
let me know if I'm doing something wrong.
you could set DIRTYFLAGS_DESCRIPTION after an interaction with the TEST_SLIDER parameter (e.g. in SetDParameter or after MSG_DESCRIPTION_POSTSETPARAMETER). That should update the description.
TEST_SLIDER
SetDParameter
MSG_DESCRIPTION_POSTSETPARAMETER
@s_bach
SetDParameter seems to be easier but seems like I'm doing something wrong. Can you provide a code snippet, how to do this properly?
I'm probably doing something wrong.
def SetDParameter(self, node, id, t_data, flags) :
if id[0].id == c4d.TEST_SLIDER:
node.SetDirty(c4d.DIRTYFLAGS_DESCRIPTION)
it seems to work better if you change the dirty status of the bitmap. Something like this:
def GetDParameter(self, node, id, flags):
if id[0].id == c4d.THE_BITMAP_BUTTON:
data = c4d.BitmapButtonStruct(node, id, self.bmp.GetDirty())
return (True, data, flags | c4d.DESCFLAGS_GET_PARAM_GET)
return True
def SetDParameter(self, node, id, t_data, flags):
if id[0].id == c4d.THE_OTHER_PARAMETER:
self.bmp.SetDirty()
node.SetDirty(c4d.DIRTYFLAGS_DATA)
return False
btw, is it possible to prevent the description from constant updates during manipulating the slider and set the DIRTYFLAGS when the slider is already set to the desired value?
Seems like C4D's material preview is capable of detecting time intervals between manipulations and if the interval is not high enough, no update takes place. Should I import pythons datetime or maybe it is possible to accomplish this task directly from c4d's module?
This goes off topic so I'll make a new post.
The main issue is already solved, thanks to Sebastian! | https://plugincafe.maxon.net/topic/11308/bitmap-button | CC-MAIN-2021-39 | refinedweb | 646 | 57.87 |
The Java Specialists' Newsletter
Issue 0232001-06-21
Category:
Performance
Java version:
GitHub
Subscribe Free
RSS Feed
Welcome to the 23rd issue of The Java(tm) Specialists' Newsletter, where I try and get back to my roots of distributed
performance evaluation. My PhD thesis was entitled "Analytical
Performance Evaluation of Concurrent Communicating Systems using
SDL and Stochastic Petri Nets", or something like that. The main
idea was to automatically map protocols designed in the
Specification and Description Language (SDL) to a modelling
language called Stochastic Petri Nets for the simple reason that
there are a lot of well known analytical techniques available for
evaluating a Stochastic Petri Net's performance. But, all that
was of another era when it did not matter that it would take a
very long time to analyse a protocol of any real size. In fact,
that was last millenium, i.e. long long ago, i.e. don't bother
asking me any questions about it ;-)
When we measure performance we have to consider mainly two
criteria: memory and cpu cycles. I was able to significantly
reduce the amount of memory needed for the server by the idea
presented here, but I did not manage to increase the speed at
which clients are serviced, although it converged. If you think
of anything that would improve the speed of the SocketWheel,
please let me know, and you will earn instant fame in over 40
countries by being immortalized in my next newsletter.
Please forward this newsletter to as many people as you know who
are interested in programming in Java at more-than-entry-level.
NEW:
Please see our new "Extreme Java" course, combining
concurrency, a little bit of performance and Java 8.
Extreme Java - Concurrency & Performance for Java 8.
The typical way of implementing a server that needs to "talk
back" to the client is to construct a thread for each client that
is connected, normally through a thread pool. For example,
consider the Server.java file:
// Server.java
import java.net.*;
import java.io.*;
public class Server {
public static final int PORT = 4444;
public Server(int port) throws IOException {
ServerSocket ss = new ServerSocket(port);
while(true) {
new ServerThread(ss.accept());
}
}
private class ServerThread extends Thread {
private final Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
start();
}
public void run() {
try {
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
while(true) {
in.readObject();
out.writeObject(new String("test"));
out.flush();
out.reset();
}
} catch(Throwable t) {
System.out.println("Caught " + t + " - closing thread");
}
}
}
public static void main(String[] args) throws IOException {
new Server(PORT);
}
}
What this does is simply read an object and write an object for
the duration of the client being connected to the thread. When
the client disconnects, the thread will stop. The code is not
very "clean", I should handle closing of Sockets better than it
is, but I don't want to cloud over the issue at stake here.
A client would typically look like this (send an object, read an
object, wait some time, etc.):
// Client.java
import java.net.*;
import java.io.*;
public class Client {
public Client(int port) throws Exception {
Socket socket = new Socket("localhost", port);
ObjectOutputStream out = new ObjectOutputStream(
socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
for (int i=0; i<10; i++) {
out.writeObject(new Integer(i));
out.flush();
out.reset();
System.out.println(in.readObject());
Thread.sleep(1000);
}
}
public static void main(String[] args) throws Exception {
new Client(Server.PORT);
}
}
In order to test what happens when a lot of clients connect I
wrote a MultiClient class, which constructs 3500 sockets and
an equivalent number of object output and input streams to use
for sending messages. It then cycles through the sockets and
writes to them one object, then cycles through them again and
reads one object. The reason I took 3500 sockets is that on my
little notebook I could not open more than 3500 sockets, don't
ask why, I don't know. That number is *probably* system
dependent, so if you get an exception when trying to create a
socket, try what happens when you have less sockets.
// MultiClient.java
public class MultiClient {
public MultiClient(int port) throws Exception {
long time = -System.currentTimeMillis();
Socket[] sockets = new Socket[3500];
ObjectOutputStream[] outs =
new ObjectOutputStream[sockets.length];
ObjectInputStream[] ins =
new ObjectInputStream[sockets.length];
for (int i=0; i<sockets.length; i++) {
sockets[i] = new Socket("localhost", port);
outs[i] = new ObjectOutputStream(
sockets[i].getOutputStream());
ins[i] = new ObjectInputStream(
sockets[i].getInputStream());
}
System.out.println("Constructed all sockets");
for (int j=0; j<32; j++) {
long iterationTime = -System.currentTimeMillis();
for (int i=0; i<sockets.length; i++) {
outs[i].writeObject(new Integer(i));
outs[i].flush();
outs[i].reset();
}
System.out.println(j + ": Written to all sockets");
for (int i=0; i<sockets.length; i++) {
ins[i].readObject();
}
System.out.println(j + ": Read from all sockets");
iterationTime += System.currentTimeMillis();
System.out.println(j + ": Iteration took " +
iterationTime + "ms");
}
time += System.currentTimeMillis();
System.out.println("Writing to " + sockets.length +
" sockets 32 times took " + time + "ms");
}
public static void main(String[] args) throws Exception {
new MultiClient(Server.PORT);
}
}
This all works quite nicely, except that each thread in the
JDK1.3 implementation of the VM takes up 20KB for its stack. When
you add up all the other memory taken up for streams and sockets,
it comes to 97MB used up on the server, just to handle a paltry
3500 clients! So, if we had 35000 clients connecting, with the
presumption that our machine can handle that many sockets, we
not only create 35000 threads (which each don't do that much, but
it still takes a long time to construct them all, even if you use
a thread pool) but we also gobble up almost 1GB of memory!!!
I was pondering this problem a few days ago and came up with an
idea to use polling (yes, I know, polling sucks) to avoid
making a thread for each client. Instead of having a server
which uses a thread for each client that gets connected, we have
a list of sockets that are connected to the server. Writing to a
socket will block if the TCP buffer is full, which is about 64000
bytes, so we could have the problem of the server being hung up
completely if the client decides to not service the stream. I
will conveniently ignore that problem in this newsletter.
We want to have an ObjectOutputStream and an ObjectInputStream
associated with each Socket, so we make an inner class to contain
those values, which we call a SocketBucket. To make connecting
fast, we keep two lists of SocketBuckets, one for the new sockets
and one for the already connected sockets. We then run through
all the sockets and try to read from each of them with a timeout
of 1 millisecond. If there is nothing to read we get an
InterruptedIOException and go to the next socket.
If we found at least one socket that had some data, we
immediately go looking again, otherwise we go dream for a while
and then go looking for more data. There are many different ways
in which we could tune this approach, for example, you could keep
a set of the last sockets which had data and push their priority
up or down, depending on stochastic prediction techniques (not
that I remember what that means - just sounded cool!). One of
the disadvantages with this approach is also that the server has
to wait for an entire millisecond before looking at the next
socket. It would be much better to wait less, otherwise if you
have 1000 sockets connected, it will take 1 second just to check
if any of the sockets have data waiting. Unfortunately, 1 ms is
the shortest that we can wait with Java sockets.
Here is the code for the SocketWheel:
// SocketWheel.java
import java.net.*;
import java.io.*;
import java.util.*;
public class SocketWheel {
// the list contains SocketBuckets
private final List sockets = new LinkedList();
// we don't want to block a new connection while we are busy
// serving the existing ones
private final List newSockets = new LinkedList();
public SocketWheel() {
new ServerThread();
}
public void addSocket(Socket socket) throws IOException {
synchronized(newSockets) {
newSockets.add(new SocketBucket(socket));
newSockets.notify();
}
}
private class SocketBucket {
public final Socket socket;
public final ObjectOutputStream out;
public final ObjectInputStream in;
public SocketBucket(Socket socket) throws IOException {
this.socket = socket;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
socket.setSoTimeout(1); // VERY short timeout
}
}
private class ServerThread extends Thread {
public ServerThread() {
super("ServerThread");
start();
}
public void run() {
long dreamTime = 10;
boolean foundSomething;
while(true) {
try {
synchronized(newSockets) {
sockets.addAll(newSockets);
newSockets.clear();
}
foundSomething = false;
Iterator it = sockets.iterator();
while(it.hasNext()) {
SocketBucket bucket = (SocketBucket)it.next();
try {
bucket.in.readObject();
foundSomething = true;
bucket.out.writeObject(new String("test"));
bucket.out.flush();
bucket.out.reset();
} catch(InterruptedIOException ex) {
// just skip this socket
} catch(IOException ex) {
it.remove();
}
}
if (foundSomething) {
dreamTime = 6;
} else {
if (dreamTime < 1000)
dreamTime *= 1.5;
else dreamTime = 1000;
synchronized(newSockets) {
// only sleep if we didn't find anything
newSockets.wait(dreamTime);
}
}
} catch(Throwable t) {
System.out.println("Caught " + t + " - remove socket");
}
}
}
}
public static void main(String[] args) throws IOException {
SocketWheel wheel = new SocketWheel();
ServerSocket ss = new ServerSocket(Server.PORT);
while(true) {
Socket socket = ss.accept();
wheel.addSocket(socket);
}
}
}
When I connect to the SocketWheel server with the MultiClient,
the server uses up only 32MB of RAM, basically one third of the
other server, but it is a little bit slower to use this approach
as opposed to threading, and it is a lot more complicated. In
addition, the whole example sometimes gets stuck, I don't know
why. If the MultiClient stops proceeding and the CPU goes to 0%,
you'll have to restart the MultiClient. (If you spot the problem,
please let me know, I suspect it's an underlying C implementation
problem which is why I'm not pursuing it.)
With the SocketWheel, the test took 2:36 minutes to complete, the
normal threaded Server took only 2:23 minutes to complete, CPU
was at 100% both times, disk usage was 0%. The difference in
speed is not that great, whereas the memory usage is only 34MB in
the SocketWheel server, i.e. roughly 1/3 of the threaded server.
When we change the MultiClient to only use 350 sockets, the
SocketWheel takes 14 seconds, the threaded server only 11 seconds,
the SocketWheel uses 9.4MB, the threaded server 14MB, a smaller
difference, probably because that includes the total memory used
by java.exe measured with the task manager, i.e. it includes the
memory used by the JVM.
It was quite fun writing this SocketWheel, and was actually a lot
easier than I thought possible. Please tell me if you've done
something similar or if you think of ways to improve the speed
of the SocketWheel server. I tried having a couple of threads in
the SocketWheel, but the whole system just got stuck more often
and did not improve speed. Please don't use the SocketWheel "as
is" unless you're willing to discover and fix the bug that makes
it get stuck and cater for clients not reading their sockets.
I always appreciate any feedback, both positive and negative, so
please keep sending your ideas and suggestions. Please also
remember to take the time to send this newsletter to others who
are interested in Java.
Heinz
Performance Articles
Related Java Course | http://www.javaspecialists.eu/archive/Issue023.html | CC-MAIN-2016-30 | refinedweb | 1,914 | 55.13 |
I agree, the if clause should not be there, and have removed it from
cvs. If the state information is required it should be passed as an
argument to FigureCanvasBase.motion_notify_event() , like x and y are.
Regards
Steve
Send instant messages to your online friends
···
On Wed, 2005-07-20 at 20:27 -0700, matplotlib-users-request@lists.sourceforge.net wrote:
Hello everyone,
I just upgraded my matplotlib from 0.80 to to 0.83.1 and discovered a bug in the GTK backend. To be specific, the following code, beginning by line 171 in backend_gtk.py, is the problem:
def motion_notify_event(self, widget, event):
if event.is_hint:
x, y, state = event.window.get_pointer()
else:
x = event.x
y = event.y
state = event.state
# flipy so y=0 is bottom of canvas
y = self.figure.bbox.height() - y
if state:
FigureCanvasBase.motion_notify_event(self, x, y)
return True
Due to the 'if state' clause, the Canvas will only receive the 'motion_notify_event' if at the same time the mouse button is pressed. This has not been the case in previous version of matplotlib. There is e.g. no such distinction in backend_qt.py.
Regards,
Niklas Volbers. | https://discourse.matplotlib.org/t/bug-report-motion-notify-event-in-backend-gtk-py/3125 | CC-MAIN-2021-43 | refinedweb | 194 | 71.51 |
The Microsystems, Inc., maintains a registry of the names bound in the first level of the service namespace. To register a name, send an email request to fns-register@sun.com, or write to:
FNS Registration Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303
Please include a brief description of the intended use of the name and a description of the format of the reference that can be bound to that name.
The printer namespace provides a namespace for naming printers. The printer namespace is associated with (subordinate to) the service namespace. In other words, printer service and the printer namespace is one of the services in the service namespace. Printer names are identified by the prefixes service/printer or _service/printer. For example, service/printer/laser1 identifies the printer named laser1. | https://docs.oracle.com/cd/E19455-01/806-1387/af1pol-31471/index.html | CC-MAIN-2018-05 | refinedweb | 135 | 58.48 |
>>): # */ /*, used for windowing */ struct { int32_t tv_sec; /* Seconds */ int32_t tv_usec; /* Microseconds */ } ut_tv; /* Time entry was made */ #else long int ut_session; /* Session ID, used for windowing */ struct timeval ut_tv; /* Time entry was made */ #endif int32_t ut_addr_v6[4]; /* IP address of remote host */)). Neither of these programs creates the file, so if it is removed, record-keeping is turned off.; "new time" in the line field. UT_UNKNOWN seems to be a Linux invention. System V.
NOTES utmp struct.)
BUGS
This man page is based on the libc5 one, things may work differently now.
SEE ALSO
ac(1), date(1), last(1), login(1), who(1), getutent(3), updwtmp(3), init(8)
COLOPHON
This page is part of release 3.01 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.ubuntu.com/manpages/intrepid/man5/wtmp.5.html | CC-MAIN-2014-10 | refinedweb | 137 | 74.29 |
Blog Map
Next, we can write a set of queries to extract useful information from the document.
This blog is inactive.New blog: EricWhite.com/blogBlog TOCThere are a few points to note about this code:
· This code will correctly assemble the text for each paragraph, even if Track Changes has been turned on, and the paragraph contains inserted (or deleted) text.
· To see a large number of examples of these types of queries, see Querying XML Trees. In particular, it may be helpful to work through the Pure Functional Transformations of XML.
· This code uses casting to retrieve the element and attribute values. For more information, see How to: Retrieve the Value of an Element.
· This code uses the approach of projecting into an anonymous type. See How to: Project an Anonymous Type for more information.
· Because the style node for the paragraph is optional and might not exist, this code uses the technique detailed in How to: Filter on an Optional Element.
· To concatenate the text of all of the w:t nodes, this code uses the approach of using an extension method named StringConcatenate, as described in Refactoring Using an Extension Method.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Examples.LtxOpenXml;using System.Xml.Linq;using System.IO.Packaging; class Program{ public const string DocumentRelationshipType = ""; public const string StylesRelationshipType = ""; public const string WordProcessingMLNamespace = ""; static void Main(string[] args) { string filename = "OfficeXMLMarkupExplained_en.docx"; //string filename = "Test.docx"; // a good convention to use is to name the XNamespace // variable with the same name as the namespace prefix, // and to name XName variables with the local name of the element XNamespace w = WordProcessingMLNamespace; XName r = w + "r"; XName ins = w + "ins"; using (OpenXmlDocument doc = new OpenXmlDocument(filename)) { Relationship documentRelationship = ( from dr in doc.Relationships where dr.RelationshipType == DocumentRelationshipType select dr ).FirstOrDefault(); Relationship stylesRelationship = ( from sr in documentRelationship.Relationships where sr.RelationshipType == StylesRelationshipType select sr ).FirstOrDefault(); string defaultStyle = (string)( from style in stylesRelationship .XDocument.Root.Elements(w + "style") where (string)style.Attribute(w + "type") == "paragraph" && (string)style.Attribute(w + "default") == "1" select style ).First().Attribute(w + "styleId"); XDocument xDoc = documentRelationship.XDocument; // Find all paragraphs in the document. var paragraphs = from p in xDoc .Root .Element(w + "body") .Descendants(w + "p") let styleNode = p .Elements(w + "pPr") .Elements(w + "pStyle") .FirstOrDefault() select new {) }; Console.WriteLine("DefaultStyle: {0}", defaultStyle); foreach (var p in paragraphs) { Console.WriteLine("Style: {0} Text: >{1}<", p.StyleName.PadRight(16), p.Text); } } }} public static class LocalExtensions{ public static string StringConcatenate<T>(this IEnumerable<T> source, Func<T, string> func) { StringBuilder sb = new StringBuilder(); foreach (T item in source) sb.Append(func(item)); return sb.ToString(); }}
Don’t be discouraged if all of this code doesn’t make sense at first glance. It takes some study. However, this functional style of query construction is very powerful. Once you become familiar with this approach, you can write such code very easily. It tends to be shorter than the equivalent imperative code. In my experience, it works correctly more often, with less debugging. I personally believe that over the next few years, with the introduction of functional programming capabilities in both C# and VB, this style will become more and more familiar. It will eventually become absolutely essential for .NET developers to be familiar with this style of coding.
In the near future, I’m going to augment the above code, and create a new class, WordprocessingML, in the same namespace, which will derive from the OpenXmlDocument class. This class will contain functions and properties for some of the most common operations that you want to do on a WordprocessingML document. Following that, I’ll create a SpreadsheetML class that also derives from the OpenXmlDocument class.
These resource is for preparing the project ,supervised by MONO and GOOGLE SUMMER CODE 2008,Converting
Recently we spoke about converting XPS files and FixedDocuments to FlowDocuments . It works, but there | http://blogs.msdn.com/b/ericwhite/archive/2007/12/11/writing-linq-to-xml-queries-using-the-openxmldocument-class.aspx | CC-MAIN-2014-52 | refinedweb | 652 | 50.63 |
This article assumes the reader is generally familiar with the subject of container classes. Experience with some common container class libraries (such as STL and MFC) is desirable, though not mandatory.
To manipulate program data, you usually need an appropriate data structure. This can be an array, single/double direction linked list, tree, hash table, and etc. Depending on the requested functionality, we can choose one of those. I've been using STL for a long time. It supports linked lists (queue, list, stack), auto-growing arrays (vector), binary search tree (map), and a sophisticated linked list of arrays (dequeue). What it lacks is a map based on a hash table, but in most of the cases, binary trees can be used instead.
Once I had to write a device driver. And if you know, using libraries in drivers is a real pain in the neck. In kernel mode, you have a lot of limitations related to memory allocation, exception handling, paged code execution, and etc. Plus, some libraries need some global init/uninit, and they think they're clever enough to do it on-demand, whereas in some circumstances, drivers are not allowed to call some functions (related to IRQL). So, using STL (which is pretty bombastic) is kinda problematic there. Not to mention such a monster as MFC.
So, I decided to write my own container classes to manipulate my data structures. And, I wanted to achieve the following:
First, I took the code from STL and MFC container classes, and made some modifications to make it appropriable for my case. But then, at some point, I realized that those classes could be greatly improved. I'm not talking about the algorithm behind the binary tree or the linked list, but about the idea of how to design and use those classes. By using another design, I've improved the performance greatly, made the code smaller, and even more generic. And, I like my container classes so much that I don't use neither STL nor MFC containers in any of my applications since then.
Let's take a look at the list container class of STL. This is how it is declared:
template <
class Type,
class Allocator=allocator<type>
>
class list
{
// ...
};
In order to instantiate a linked list, you must specify the type you want to store in it, and optionally the allocation mechanism.
Now, how does this list actually store data? As we all know, in order to store a data element in a linked list, you have to construct another element, called Node. This node must contain the element we want to store, and pointers to prev/next nodes. So, the list in fact does not store elements you want to have in it, it instead stores elements of its own type, which in turn have elements of our type as members. If you look at the code of the STL list class, you'll find the following declaration:
Node
struct _Node {
_Nodeptr _Next, _Prev;
_Ty _Value;
};
// ...
_Nodeptr _Head;
size_type _Size;
Surprisingly, there's no _Tail member. That's because in this implementation, _Head is not really a pointer to the first inserted node. Instead, _Head is a pointer to a fictive node which is allocated at construction time. Its _Next and _Prev members are in fact the head and the tail of the linked list, and its _Value member is ignored.
_Tail
_Head
_Prev
_Value
Next, let's talk about iterators. It can be said that an iterator is an identifier of an element in the container class. (MFC container classes use a term POSITION). That is, when you insert an element to a list, you get in return its iterator. By using this iterator, you can get the value of the element you've inserted into the list. You can also erase this element from the list using its iterator. In our case, we can say the _NodePtr is an iterator. In other words, if you have _NodePtr, you can get the value of the element, and you can erase or reposition it in the list. In conclusion, we can say the following:
POSITION
_NodePtr
As we know, when you insert an element, the container allocates its own structure which contains the member of your type, and assigns this member the element you provide. That is, it does not store your element, instead it copies its value into another element.
Sometimes, you need to store simple types in the container, such as int. But usually, you have to store more complex elements. For example, you may want to store strings, or some objects that include strings, buffers, and pointers to other objects. In such a case, assignment is not a trivial operation. If your object contains strings, dynamic buffers, and etc., it can't be "just copied". You have to provide an assignment operator for such objects.
int
The meaning of assignment is to bring the object to the state which is identical by some definition to the state of another object. This usually means duplicating strings, buffers, and etc. Unfortunately, this approach is widely used. I've seen dozens of code like this:
struct UserInfo {
// ...
PCSTR m_szName;
// ...
// To make it container-compliant
UserInfo& operator = (const UserInfo& other)
{
free(m_szFirstName);
m_szFirstName = strdup(other.m_szFirstName);
}
};
In my opinion, this is ridiculous. Duplicate the object, including all its members (which may be complex objects in turn), just to insert it into the list!! It can be justified only if this is what you really need: preserve the state of your object in the linked list, and continue to modify your object. That is, what you need is really duplication of the object's state.
But sometimes, the situation is even more cruel. Suppose your object has a pointer/reference to another object. What should you do in the assignment then? Should you just assign the pointer, or duplicate the pointed object? And, if that object contains pointers to other objects too? Sometimes, the assignment is not only performance-killing, it's simply inappropriate. There's no logical context for the assignment.
A more correct way to handle complex objects is to make the container class contain pointers (or smart pointers) to objects instead of objects themselves. This way, you don't need to "invent" assignment for your objects. You can also insert the same object into different containers so that you can fetch it from one container and modify its members, then eventually take it from another container, and the changes are visible. Unfortunately, because this requires a bit more complex syntax to work with, many people neglect this rule.
Let's now look at the following example (taken from real life).
Suppose you have an object that exists (via pointers, not duplicated) in multiple containers. For example, you have a server. It contains a linked list of all clients connected to it. The list is sorted by the last activity time. (Clients that have sent something recently are at the head of the list.) To maintain the list in this order whenever we receive something from the client, we move it to the head of the list. Then, once in a while, we can walk through the list from tail to head and drop those clients that didn't send us anything for a long time, up until we encounter the first "valid" client.
Apart from this list, let's assume that every client has an ID, and we want a fast search by this ID. We need a sort of a map: either hash table or tree.
Suppose also that our server should immediately drop any client if it receives an I/O error for it. We have the following problematic scenarios:
How can these disadvantages be solved?
Answer: Add to your structure iterators that identify it in all containers it belongs to.
In our case, we have to add two members to our client structure: list iterator and map iterator. At construction time, we insert our structure to both containers, receive in return iterators, and store those iterators as members. Then, whenever we have a pointer to this structure, we can quickly perform any list/map operation on it.
This situation is a bit weird however: you have an object that has an iterator as a member. The iterator itself is a kind of a pointer to another structure that has the pointer to our object. So, we have a cross-linked data structure.
When we have two (or more) cross-linked structures, we can merge them into one struct, can't we? Suppose we have a client structure ClientInfo. Let's merge some members into it:
ClientInfo
struct ClientInfo {
// some common members.
// ...
// Activity linked list manipulation:
ClientInfo* m_pActivityNext;
ClientInfo* m_pActivityPrev;
// ID lookup manipulation, binary tree engine:
ULONG m_LookupID; // serves as key
ClientInfo* m_pLookupTop; // Tree parent
ClientInfo* m_pLookupLeft; // Tree left child
ClientInfo* m_pLookupRight; // Tree right child
int m_nLookupBalance; // Needed to auto-ballance the binary tree
// (AVL method).
};
struct ServerGlobalState {
// ...
// This is how our "containers" now look:
// Activity "list"
ClientInfo* m_pActivityFirst;
ClientInfo* m_pActivityLast;
// Lookup "tree"
ClientInfo* m_pLookupRoot;
};
We got rid of the list node and the tree structures. Instead, we've put their members into our struct. What exactly did we achieve by this? Actually, several things, but the most important point is that we don't need iterators any more. The object is an iterator to itself for all the data structures it belongs to. Once you've found an object in one data structure, you've found it in all the data structures. Let's compare this approach to the standard containers:
Pros:
Cons:
struct LinkList {
// node declaration
struct Node {
Node* m_pNext;
Node* m_pPrev;
};
// c'tor
LinkList()
:m_pHead(NULL)
,m_pTail(NULL)
{
}
// operations
void InsertHead(Node&);
void InsertTail(Node&);
void InsertAfter(Node& node, Node* pAfter);
// ... other variants of insertion
// ...
void Remove(Node&);
Node* GetHead() { return m_pHead; }
Node* GetTail() { return m_pHead; }
private:
Node* m_pHead;
Node* m_pTail;
};
template <class KEY, class ARG_KEY>
struct AvlTree {
// node declaration
struct Node {
KEY m_Key;
Node* m_pT;
Node* m_pL;
Node* m_pR;
int m_nBallance;
};
// c'tor
AvlTree ()
:m_pRoot(NULL)
{
}
// operations
void Insert(Node&);
void Remove(Node&);
Node* Find(ARG_KEY);
private:
Node* m_pRoot;
};
typedef AvlTree<ULONG,ULONG> AvlTreeULong;
struct ClientInfo
:public LinkList::Node
,public AvlTreeULong::Node
{
// some common members.
// ...
};
In this approach, we now have dedicated container classes. We've managed to move the container functionality out of our data structure. Instead, our data structure gets all the needed members by inheriting the appropriate container's Node. Our container classes manage some objects, without actually knowing what those objects are! That is, we can declare another structure that inherits LinkList::Node, and use exactly the same LinkList class to handle those objects too. Moreover, we can mix objects of different kinds into one linked list if we want.
LinkList::Node
LinkList
Note that STL and MFC container classes require you to provide the type you're going to store as a template argument. And, if you instantiate two linked lists of different data structures, you'll get (behind the scenes) two different container classes with different machine code. In our approach, however, we have a single machine code that works for all the types.
Our AvlTree class does have template arguments, but it's only related to the lookup key (obviously, for different key types, tree code should be different). But, for different data structures that use the same key type, we instantiate the same AvlTree class. In opposite, the MFC's hash table takes KEY, ARG_KEY, VALUE, and ARG_VALUE parameters, the STL map class takes Key and Type.
AvlTree
KEY
ARG_KEY
VALUE
ARG_VALUE
Key
Type
Another great advantage of our container classes, in my opinion, is that they don't allocate/free memory. No memory management at all! They don't create/destroy structures, they just manage their connections to each other.
Unfortunately, we have a little drawback. Our container classes manage objects that inherit their Node, without knowing what those objects are. As a result, when you call some function that is supposed to return you a contained object (such as a Tree's Find() function), you get in return a pointer to the Node, not to the actual object type. Then you should cast the returned pointer to the actual type. That is:
Find
AvlTreeULong map;
LinkList lst;
// ...
ClientInfo* pClient;
pClient = map.Find(117); // Error.
// Find() returns you a AvlTreeULong::Node*, not a ClientInfo*
pClient = (ClientInfo*) map.Find(117); // Correct
pClient = lst.GetHead(); // Error.
// lst.GetHead() returns you a LinkList::Node*, not a ClientInfo*
pClient = (ClientInfo*) lst.GetHead(); // Correct
ClientInfo* pActivityNext;
pActivityNext = pClient->m_pNext; // Error.
// m_pNext points of LinkList::Node, not to a ClientInfo
pActivityNext = (ClientInfo*) pClient->m_pNext; // Correct
Another relative disadvantage of our container classes is also related to the fact that they don't know what they actually manage. In STL and MFC container classes, we can leave some objects, and in the destructor, they are cleaned up. Our containers lack this functionality, because in order to destroy an object, we have to know what it is. We must clean our containers manually. Conclusion:
template <class CastNode>
struct LinkListEx
:public LinkList
{
// Insertion/Remove don't require extra casting.
// But retreive methods do.
CastNode* GetHead() { return (CastNode*) LinkList::GetHead(); }
CastNode* GetTail() { return (CastNode*) LinkList::GetTail(); }
static CastNode* GetNext(CastNode& node)
{ return (CastNode*) node.m_pNext; }
static CastNode* GetPrev(CastNode& node)
{ return (CastNode*) node.m_pPrev; }
};
template <class CastNode>
struct LinkListDyn
:public LinkListEx<CastNode>
{
// c'tor
~LinkListEx()
{
Clear(); // Auto-cleanup
}
// We can now add some functions that allocate new elements.
CastNode* CreateHead()
{
CastNode* pVal = new CastNode;
InsertHead(*pVal);
return pVal;
}
// ...
// Functions that destroy elemetns.
void Delete(CastNode* pNode)
{
ASSERT(pNode); // NULL is illegal for this function.
Remove(*pNode);
delete pNode;
}
void Clear()
{
for (CastNode* pNode; pNode = GetHead(); )
Delete(pNode);
}
};
We've described two extensions for our LinkList class. The first extension just provides a cast to the actual type. This allows to use the normal convenient syntax (without those infinite castings). Although this is a template class that may be instantiated for different data types, it does not produce extra code. It just automatically does what otherwise you'd have to do. The engine is still the LinkList class, which is single.
The second extension goes farther. It now handles objects creation/destruction. Hence, we can now have auto-cleanup, integrated CreateAndInsert and RemoveAndDelete functions, and etc.
CreateAndInsert
RemoveAnd
Worth to add that this extension is sometimes convenient and handy, but not always appropriate. For example, in our case, where ClientInfo belongs to both LinkList and AvlTreeULong, we can't just let our container classes automatically destroy our objects. First of all, the same object belongs to them both, and that means that only one of them should delete it. Also, in our case, when we delete an object, it must be removed from both containers. Hence, our destruction of objects is non-trivial. Let's rather clean them manually.
AvlTreeULong
Of course, similar extensions can be made for other container types too. Conclusion:
Let's list all our advantages once more:
In real life, there're always cons. Not always significant, but should be mentioned.
In our approach, we integrate the container Node's members into our structure. This means that, in fact, we have direct access to them. Hence, they can be corrupted by improper use. Well, this can be partially fixed. All you have to do is declare those members private in the container's Node, and optionally provide read-only public functions to them. But anyway, improper memory access can corrupt them. More likely than in the STL/MFC container.
private
More complex situations: suppose you've inserted an element to the LinkList. What if at some point you "forget" that this element is already in the list, and insert it again to the same list? Or delete it without removing it from the LinkList? The list will become corrupted most likely (skipped elements, closed circles, broken pointers).
Our approach puts more responsibility on the programmer. You have to know exactly where your objects belong to. By the way, the same applies to standard container classes too (and to programming in general, and not just here), you must know what you're doing. But if you mistakes, the consequences in our case may be more destructive.
Anyway, I personally prefer to use those container classes. I've been using them for a long time, and up until now no regrets.
Suppose you have a structure that you want to put in two containers. As we've seen with our server example, your structure should inherit both containers' nodes. But, what if you want to put it in two containers of the same type? For instance, our server could also maintain its client in one more linked list in which they're sorted by another criteria, say, by the last time the server sent something to them. So, once in a while, we can walk through this list (from tail to head) and send some keep-alive message to those clients. You can not write something like this:
// Error. You can't inherit the same class twice.
struct ClientInfo
:public LinkList::Node // sorted by client activity
,public LinkList::Node // sorted by server activity
{
};
I've found two ways to solve this situation:
struct ClientLstActivityClient
:public LinkList::Node {
};
struct ClientLstActivityServer
:public LinkList::Node {
};
struct ClientInfo
:ClientLstActivityClient
,ClientLstActivityServer
{
};
This way, we can convince the compiler to inherit the same struct twice. But now, you can't do this:
LinkListEx<ClientInfo> lstActivityClient;
// Error. Cast from LinkList::Node to ClientInfo is ambiguous.
ClientInfo* pVal = lstActivityClient.GetHead();
// Instead you'll have to write:
LinkListEx<ClientLstActivityClient> lstActivityClient;
ClientInfo* pVal = (ClientInfo*) lstActivityClient.GetHead(); // Correct
Again, you'll have to mess with castings. Fortunately, there's another method:
// This macro is handy when you have an object of some class
// as a member of another class. Knowing a pointer to the inner object
// and its offset within the outer one we can calculate the pointer to the outer.
#define GET_OUTER_OBJ(outer_class, this_var) \
outer_class& GetOuter() { return * (outer_class*) \
(((PBYTE) this) - (PBYTE) (&((outer_class*) NULL)->this_var)); } \
outer_class* GetOuterSafe() { return this ? &GetOuter() : NULL; }
struct ClientInfo
{
struct ActivityClient :public LinkList::Node {
GET_OUTER_OBJ(ClientInfo, m_ActClient)
} m_ActClient;
struct ActivityServer :public LinkList::Node {
GET_OUTER_OBJ(ClientInfo, m_ActServer)
} m_ActServer;
struct LookupID :public AvlTreeULong::Node {
GET_OUTER_OBJ(ClientInfo, m_LookupID)
} m_LookupID;
// more members
// ...
};
LinkListEx<ClientInfo::ActivityClient> lstActivityClient;
LinkListEx<ClientInfo::ActivityServer> lstActivityServer;
AvlTreeULong mapByID;
ClientInfo* pVal = lstActivityClient.GetHead()->GetOuterSafe(); // Correct
if (pVal)
{
ClientInfo* pNextByServerActivity =
lstActivityServer.GetNext(pVal->m_ActServer)->GetOuterSafe();
// ...
// At any time we see the client ID:
ULONG nClientID = pVal->m_LookupID.m_Key;
}
// ...
pVal = mapByID.Find(445)->GetOuterSafe();
if (pval)
{
// move it to the head in the client activity list
lstActivityClient.Remove(pval->m_ActClient);
lstActivityClient.InsertHead(pval->m_ActClient);
}
// ...
// Drop the client
mapByID.Remove(pVal->m_LookupID);
lstActivityClient.Remove(pVal->m_ActClient);
lstActivityServer.Remove(pVal->m_ActServer);
delete pVal;
// ...
// Create another client, insert it to all containers.
pVal = new ClientInfo;
lstActivityClient.InsertHead(pVal->m_ActClient);
lstActivityServer.InsertHead(pVal->m_ActServer);
pVal->m_LookpuID.m_Key = 535;
mapByID.Insert(pVal->m_LookupID);
Not so simple syntax. But our functionality is pretty sophisticated. I want to see you implement this with better syntax. After you get used to it, you just enjoy. Everything's transparent, you see exactly what you do.
If you are still reading this article, it means you've got interested about this approach, and maybe even thinking about using it. So, this section is for you.
I've implemented the following container classes:
Every container class can optionally be equipped with a counter, which always equals to the count of objects it contains.
In order to implement this without duplicating the container code for a minor thing (like the counter), we have to follow this pattern:
In order to use a linked list, you have to decide which variant of it you need. Once you've decided, you need to instantiate its engine. This is how it is declared:
template <bool Prev, bool Next, bool Head, bool Tail, class T_COUNT>
class ListEng;
Prev
Head
Tail
T_COUNT
size_t
void
Theoretically, we have 2^5 variants, which is 32. But not all of them are valid. For example, there's no use for a list with neither Prev nor Next. Same for neither Head nor Tail. Also, you can't have a forward-only list without the head pointer. So, generally speaking, we have the following variants:
* All sizes are given for 32bit architecture.
Example: Let's say we want a single-direction list with one end, something like a stack, without the counter. Then, let's instantiate it:
typedef ListEng<false, true, true, false, void> MyStack;
Now, declare the structure you want to be contained in such a stack:
struct MyObj :public NodeEx<MyStack, MyObj> {
// structure members.
};
This declaration is a bit different from what we saw earlier. Instead of inheriting MyStack::Node, we now inherit NodeEx<MyStack, MyObj>. Actually, it has the same effect, it just makes the usage a bit more convenient. It prevents direct access to the m_pNext/m_pPrev members. Instead, it gives you read/only GetNext()/GetPrev(). It also provides you with the cast.
MyStack::Node
NodeEx<MyStack, MyObj>
m_pNext
m_pPrev
GetNext
GetPrev
Now, let's instantiate the final container for our structure. Let's say we want manual create/destroy.
typedef ListEx<MyStack, MyObj> MyList;
Now, use it. Note that our list has limited functionality, because it is single-direction and has only one ending.
// ...
MyList lst;
MyObj* pObj = new MyObj;
lst.InsertTail(*pObj); // Error. We have no tail pointer.
lst.InsertHead(*pObj); // Correct
pObj = GetTail(); // Error. We have no tail pointer.
pObj = GetHead(); // Correct
pObj = pObj->_Next; // Correct
pObj = pObj->_Prev; // Error. We have no backward link.
size_t nCount = lst._Count; // Error. We have no counter.
bool bEmpty = lst._Empty; // Correct. Can be used even without counter.
lst.Remove(*pObj); // Error. This function requires bi-directional link.
lst.RemoveHead(); // Correct
lst.RemoveNext(*pObj); // Correct.
// Even though the list is single-directional - you can remove any
// element if you have its prev.
Hash table is a data structure that allows fast lookup using large memory. At construction time, you need to specify the count of hash table entries. The size of the container structure is the number of hash table entries multiplied by the size of a pointer (4 bytes for 32bit architecture). The average lookup time is proportional to N (number of elements so far) divided by the count of hash table entries. Hence, by using large memory, we can reduce the lookup time to any level.
The lookup key doesn't have to be of ordinal type. It can't be any type, you just need to specify an effective hash function for it and the comparison operator. Say, if your key is of type MyLookupType, and ARG_KEY is const MyLookupType&, you must provide the following function:
MyLookupType
const MyLookupType&
template <>
size_t MapInlHashKey(const MyLookupType& key);
In fact, hash functions on real-life input never produce equally-distributed values, usually there's some pattern. This, in turn, affects the effectiveness of the search. Because of this, it is good to pick the size of the hash table to be a prime number. It will diffuse the coverage of the hash table.
The size of the hash table node is 4 bytes plus the size of the lookup key.
Note: One major difference of this hash table compared to MFC's is that it permits duplicated keys. You can insert several elements with the same key. Find() will return you the first of them. If your intent is to avoid duplication, before every insert, you should attempt to find an element with the same key. If it already exists, either don't insert the new element, or drop the old, depending on the logic of your program.
Similarly to lists, you have to instantiate the hash table engine first.
template<class KEY, class ARG_KEY, class T_COUNT>
class HashEng;
Let's say our key is an int, and we want the counter. Then we have:
typedef HashEng<int, int size_t> MyHashEng;
Now, declare our data structure:
struct MyObj :public MyHashEng::Node {
// structure members.
};
Declare the final container: a hash table with 337 entries.
typedef HashEx<MyHashEng, 337, MyObj> MyHash;
Use it.
// ...
MyHash hash;
MyObj* pObj = new MyObj;
pObj->m_Key = 5499; // You must assign the key prior to insert.
hash.Inser(*pObj);
bool bEmpty = hash._Empty; // Error.
// This is not implemented for hash tables. Youse _Count instead.
size_t nCount = hash._Count; // Correct
pObj = hash.Find(5499);
hash.Remove(*pObj);
delete pObj;
If you want to iterate through all the elements, it is very ineffective for hash tables. The larger the size of the hash table, the more ineffective the walkthrough is. That is, you shoot your leg.
That's also the reason there's no variant of the hash table with auto-cleanup at destructor; for cleanup, you must find all your members.
If you need such a functionality, you better arrange your elements in a linked list as well.
AVL tree is an auto-balanced binary search tree. Similar to the hash table, it can be used for fast search by some key, but it works totally differently. There're many differences between their properties. Let's list the main differences:
So, trees have many advantages compared to hash tables. In most cases, it's better to use trees. Hash tables are only appropriate in the following scenarios:
Otherwise, it's better to use a tree.
One of the greatest advantages of trees is that you don't need to predict the count of elements for the tree, it'll always work in logarithmic time. Which is fast. For a thousand elements, you'll have to perform about 10 iterations, for million - 20, and for billion - 30.
One of the concerns about a hash table is that prediction of the elements count is very important. If you overestimate it, you'll grab bombastic memory without too much return. If you underestimate (by many times), the search may become very slow, much slower than what a tree offers.
It is possible to modify the hash table and make it adaptive. That is, whenever you detect that the size of the hash table is not adequate for the current elements count, silently rebuild it using another hash table size. This way, you'll get good overall performance without the need to predict the count of elements. The only drawback here is that upon silent rebuild, you'll get a performance spike.
Similar to hash tables, our trees permit duplicated keys (unlike STL trees). You can insert several elements with the same key. Find() will return you any of them.
First, you instantiate the tree engine, which is declared this way:
template <class KEY, class ARG_KEY, class T_COUNT>
class TreeEng;
Say, your key is an int (we'll discuss complex key types later), and you want the counter:
typedef TreeEng<int, int size_t> MyTreeEng;
Now, declare your structure:
struct MyObj :public MyTreeEng::Node {
// structure members.
};
The final container. Let's say we want the Create/Delete/Auto-Cleanup feature.
typedef TreeDyn<MyTreeEng, MyObj> MyTree;
Use it now.
// ...
MyTree tree;
MyObj* pObj = new MyObj;
pObj->m_Key = 5499; // Set the key prior to insert
tree.Insert(*pObj);
// Since our tree can create elements - we can also write the following:
pObj = tree.Create(5423);
bool bEmpty = tree._Empty;
size_t nCount = hash._Count;
pObj = tree.Find(5499);
hash.Delete(pObj); // equivalent to Remove-And-Destroy.
// Let's demonstrate the extra tree functionality that hash tables don't have:
pObj = tree.FindMin(); // Returns the pObj whose m_Key is minimal.
pObj = tree.FindMax(); // Returns the pObj whose m_Key is maximal.
pObj = tree.FindBigger(7634); // smallest, still bigger than 7634
pObj = tree.FindExactSmaller(12); // biggest, still not exceeding bigger 12
pObj = tree.FindNext(*pObj); // closest, greater or equal to your key.
Let's discuss complex keys.
For any two keys, the tree must know if they're equal, and if they not - which is greater. For ordinal types, such a comparison exists. For complex types, however, you must provide it. You can do it in several ways:
// Define comparison operators:
bool operator == (const MyKey& k1, const MyKey& k2);
bool operator < (const MyKey& k1, const MyKey& k2);
bool operator > (const MyKey& k1, const MyKey& k2);
This method however is ineffective: Sometimes the tree will ask if two keys are equal. If not, it will ask if the first is greater than the second. This way, it'll need to compare those keys twice. For trivial comparisons, there's no problem, but if the comparison is complex and time-consuming, there should be a better way. Eventually, I redesigned the tree to call the following function:
int Compare(const MyKey& k1, const MyKey& k2;
// Return 0 if they're equal, -1 if k1 < k2, 1 if k1 > k2. (Like strcmp).
This way, you need to call this function only once for two keys in order to decide what to do with them. But eventually, I realized there exists an even better way.
Imagine your key is a string. You have a lot of elements, and all the strings are very long. Suppose you're requested now to find an element. Then, you start from the root element, compare its key with the given one; depending on the comparison result, you move to either the left or right child, and so on.
The catch here is that as you approach your element, the keys you compare become more and more closer to your key. After a couple of iterations, the first letter of the keys we pass will stop changing and stay equal to your key's. Eventually, the second letter will, and so on. As you advance the search, you get some prefix that will remain equal to your key's prefix. And, this means that in order to compare two keys, you only need to compare their suffixes. Not the whole strings.
That's why I've redesigned the key comparison so that instead of comparing keys via a function, we'll declare the comparator object. This object will be instantiated each time we begin ordered keys comparison. And this object will be able to use the comparison history and optimize future comparisons.
For simple types, we don't use the history.
template <class ARG_KEY>
struct TreeInlComparator {
ARG_KEY m_Key;
TreeInlComparator(ARG_KEY key)
:m_Key(key)
{
}
int Compare(ARG_KEY key)
{
return (key < m_Key) ? (-1) : (key > m_Key) ? 1 : 0;
}
};
For strings, however, we make a more sophisticated comparator:
template <>
struct TreeInlComparator<const WString&> {
const WCHAR* m_szTxt;
size_t m_nLMatch;
size_t m_nRMatch;
TreeInlComparator_String(const WString& str)
:m_szTxt(str)
,m_nLMatch(0)
,m_nRMatch(0)
{
}
int Compare(const WString& str)
{
const WCHAR* szVal = str;
for (size_t nPos = min(m_nLMatch, m_nRMatch); ; nPos++)
{
T chThis = m_szTxt[nPos];
T chArg = szVal[nPos];
if (chArg < chThis)
{
m_nLMatch = nPos;
return -1;
}
if (chArg > chThis)
{
m_nRMatch = nPos;
return 1;
}
if (!chThis)
return 0;
}
}
};
Well, conclusion... I really like those container classes, I can hardly imagine programming with "standard" ones.
Some believe that the performance advantages are minor and can't be seen in real life. I deeply disagree with that. There is a huge difference between allocating one struct with all the needed members and allocating several small structs. For many applications, heap allocations in some critical code blocks are the performance bottleneck.
Consider even the example with our server: move the client in the activity list to the head. This is achieved by removing it from the list and re-inserting at the head. Our implementation does this without touching the heap at all. And, STL/MFC would delete their internal node at Remove, and allocate it at Insert.
Remove
Insert
I remember once I needed a map with some key, but without value. I mean, I needed only to know if that key existed, without storing any value for it. MFC can't offer you that. You just put some fictive type as VALUE and ARG_VALUE. STL does have such an option (set class), at the expense of the extra code generated.
set
And, our implementation easily handles this: you just override MyHashEng::Node, without adding any new members to it. You can even not override MyHashEng::Node at all, use it as your contained type.
MyHashEng::Node
What I like about linked lists is that they include only what you want them to have. Nothing unnecessary. For instance, inside the hash table implementations, I treat the hash table itself not as an array of pointers, but as an array of single-direction linked lists with one ending. It has the size of only 4 bytes, just like a regular pointer (because it just contains a single pointer).
One more advantage is that when you allocate a single data struct instead of several ones, it's easier to handle out-of-memory conditions. The structure is either allocated or not. And if it is, it can be inserted into all the containers, hence your data structures are always consistent. If you work with STL/MFC containers, it is possible that you allocate your structure, add it to one of the containers, but then eventually you'll get out-of-memory on an attempt to insert it into the second container. If you use a sort of a uniform error handling, you have a problem: at which stage did you get the error condition? Did you change your data structures? Are they consistent now? You have to invent some dirty method to know what you already did to your containers.
And, of course, we got rid of the iterators. No more iterators. The object is an iterator; once you have it, you can do whatever you want to it.
Syntax. Well, not quite simple, I admit. But do you think STL syntax is simpler? I doubt so. Our syntax becomes complicated when we do complicated things. For simple cases, and even not-so-simple ones, we have good syntax, not worse than what other containers have.
As I've already said, our containers put a bit more responsibility on us. You must know precisely what you're doing. Is this a disadvantage? Some believe so... Well, if you don't want the "responsibility", write programs in higher-level languages.
I'll appreciate comments. Both positive and negative. If you have some ideas to share, you're welcome.
Since this article was posted, I've updated the following:
TreeEng
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
pNext
zRotate
typedef list<int> LISTINT;
int main()
{
int rgTest1[] = {5,6,7};
int rgTest2[] = {10,11,12};
LISTINT listInt;
LISTINT listAnother;
LISTINT::iterator i;
// Insert one at a time
listInt.insert (listInt.begin(), 2);
listInt.insert (listInt.begin(), 1);
listInt.insert (listInt.end(), 3);
// 1 2 3
cout << "lintInt:";
for (i = listInt.begin(); i != listInt.end(); i++)
cout << " " << *i;
cout << endl;
// Insert 3 fours
listInt.insert (listInt.end(), 3, 4);
// 1 2 3 4 4 4
cout << "lintInt:";
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << " " << *i;
cout << endl;
// Insert an array in there
listInt.insert (listInt.end(), rgTest1, rgTest1 + 3);
// 1 2 3 4 4 4 5 6 7
cout << "lintInt:";
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << " " << *i;
cout << endl;
// Insert another LISTINT
listAnother.insert (listAnother.begin(), rgTest2, rgTest2+3);
listInt.insert (listInt.end(), listAnother.begin(), listAnother.end());
// 1 2 3 4 4 4 5 6 7 10 11 12
cout << "lintInt:";
for (i = listInt.begin(); i != listInt.end(); ++i)
cout << " " << *i;
cout << endl;
}
</int>
typedef list<int> LISTINT;
ListHTC
ListDyn
CreateXXXX
DeleteXXXX
InsertXXXX
RemoveXXXX
struct MyInt :public NodeEx<ListHTC, MyInt> {
int m_Int; // data member
};
typedef ListDyn<ListHTC> ListInt;
listInt.insert (listInt.begin(), 2);
listInt.insert (listInt.begin(), 1);
listInt.insert (listInt.end(), 3);
listInt.CreateHead()->m_Int = 2;
listInt.CreateHead()->m_Int = 1;
listInt.CreateTail()->m_Int = 3;
cout << "lintInt:";
for (i = listInt.begin(); i != listInt.end(); i++)
cout << " " << *i;
cout << endl;
cout << "lintInt:";
for (MyInt* pMyInt = listInt._Head; pMyInt; pMyInt = pMyInt->_Next)
cout << " " << pMyInt->m_Int;
cout << endl;
//pArray points to the current array and
//sizeArray contains the number of elements in the array.
SomeType* pNewArray = new SomeType[newSize];
memcpy(pNewArray, pArray, sizeArray);
delete []pArray;
pArray = pNewArray;
sizeArray = newSize;
pObj->_Prev
pObj->GetPrev()
Value
list
vector
enum
map
set<T>
map<string, int> myMap;
set<string> myMap;
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/20085/superior-container-classes-smaller-faster-flexible | CC-MAIN-2017-09 | refinedweb | 6,060 | 57.16 |
Swift Generic Protocols: What Are They Good For?
Swift Generic Protocols: What Are They Good For?
Generic protocols can’t be used they way we’re used to using them, that’s true. But they still serve a very important purpose in the swift world—defining type relationships.
Join the DZone community and get the full member experience.Join For Free
In the good old days, we had a pretty clear understanding of what we used protocols for, and we used them as interfaces. They were treated as first-order types that any conforming structure could hide behind. It was a pretty simple use case, and we were all accustomed to it. I mean really, just about every non-duck-typed programming language had this kind of construct. It didn’t matter if you called it a protocol, and interface, or a pure abstract class, we knew what these things were and how to use them.
Then Swift comes along and throws a wrench into everything with associated types.
For those of you who don’t know, an associated type as a type defined within a protocol with the typealias keyword. For example, in the
NiftyProtocol protocol, the
SomeType and
SomeOtherType types are declared as types, but are not defined within the protocol.
protocol NiftyProtocol { typealias SomeType typealias SomeOtherType func someFunc(info: SomeType) -> SomeOtherType }
These abstract types are called associated types in the Swift world. The thing is, you can’t do this with a protocol that contains associated types:
var niftyThing = NiftyProtocolImpl()
The compiler just won’t let you. Swift works really hard to make sure that all types and type relationships are clearly defined, and the
niftyThing object still has associated types hanging around, completely undefined. If the protocol didn’t have associated types, this would work just fine, but the protocol does, so it doesn’t.
So, if I can’t use these protocols for type abstraction, what are they good for? I mean, isn’t that why we have them in the first place?
What Generic Protocols Are Good For
Generic protocols can’t be used they way we’re used to using them, that’s true. But they still serve a very important purpose in the swift world—defining type relationships.
So Swift is designed to be strongly typed. It aggressively infers type information from other type definitions, and even requires developers to explicitly define nullable types (see optionals). The swift compiler is not about to let you be lazy with your typing after all the work it has to put in to try to ensure type correctness, believe me. So, what does this look like in practice?
Well, let’s start with some protocol definitions:
public protocol Automobile { typealias FuelType typealias ExhaustType func drive(fuel: FuelType) -> ExhaustType } public protocol Fuel { typealias ExhaustType func consume() -> ExhaustType } public protocol Exhaust { init() func emit() }
These are pretty simple but show some interesting type relationships. Here, the Automobile protocol is dependent on some
FuelType as well as some
ExhaustType. The
Fuel protocol is also dependent on some
ExhaustType, while the
Exhaust protocol is statically well defined.
Now, let’s look at some implementations:
public struct UnleadedGasoline<E: Exhaust>: Fuel { public func consume() -> E { print("...consuming unleaded gas...") return E() } } public struct CleanExhaust: Exhaust { public init() {} public func emit() { print("...this is some clean exhaust...") } } public class Car<F: Fuel,E: Exhaust where F.ExhaustType == E>: Automobile { public func drive(fuel: F) -> E { return fuel.consume() } }
We have the same type relationships in these implementations, but we need to declare relationships between types in order to appropriately constrain everything. The
CleanExhaust structure conforms to the
Exhaust protocol, which is already well defined. It can’t be generically defined as a result. At least, it can’t genericize any attributes associated with the
Exhaust protocol. The
UnleadedGasoline struct is a bit more flexible. Remember the
Fuel protocol has an associated type,
ExhaustType. This type doesn’t need to be explicitly defined within the
UnleadedGasoline structure, but if you don’t, you need to genericize the
UnleadedGasoline definition to that it can be associated with a concrete type when used. I’ve genericized the structure here, and specified that the E type must conform to the
Exhaust protocol.
Finally, take a look at the Car class - this is where the types are finally all related to one another. The
Automobile protocol defines the
FuelType and the
ExhaustType, and as the
Fuel protocol is also dependent on an
ExhaustType, we need to make sure that the
Fuel conforming object returns the same. Here, we do so by defining the
ExhaustType and ensuring that the
ExhaustType implemented by the submitted
Fuel conforming object is the same as that submitted via the class field in the class definition. We do this here via a where clause.
This where clause is vital in this design to tie together all the types into a cohesive dependency graph. We run the example like this:
var fusion = Car<UnleadedGasoline<CleanExhaust>, CleanExhaust>() fusion .drive(UnleadedGasoline<CleanExhaust>()) .emit()
And the output should be:
...consuming unleaded gas...
...this is some clean exhaust...
Now, there’s another way to do this as well, that’s arguably better and still ties the types together:
public class Car<F: Fuel>: Automobile { public func drive(fuel: F) -> F.ExhaustType { return fuel.consume() } } var fusion = Car<UnleadedGasoline<CleanExhaust>>()
Here, we tie the types together via the use of the
F.ExhaustType associated type defined over the
Fuel protocol. The output from the example’s the same in this case, even with the slightly more terse type definitions.
So, what’re generic protocols good for in Swift? They allow you to define type relationships and defer concrete definitions of those type relationships. This leads to stronger typing, more robust design capabilities, and the possibility for more robust software when implemented correctly. The downside is more potential complexity and difficulty in understanding type relationships, though I’ve found that I’m thinking more and more easily in these terms as I work more in Swift. I doubted the effectiveness of associated types initially, but now that I understand them, I find myself using them more and more every day. I hope you do too.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/swift-generic-protocols-what-are-they-good-for | CC-MAIN-2019-04 | refinedweb | 1,056 | 55.44 |
Convert PNG to JPG in Python
Get FREE domain for 1st year and build your brand new site
We can easily convert PNG images to JPG images in Python using the library "Python Image Library (PIL)" (also known as pillow).
There are 4 steps to the process:
- Install PIL library
pip install pillow --user
- Import the PIL library
from PIL import Image
- Open the file that needs to be converted
im = Image.open("file.png")
- Save the file in JPG format
im.save("file.jpg", "JPEG")
In short, this can be achieved as follows:
from PIL import Image im = Image.open("file.png") im.save("file.jpg", "JPEG")
Script to convert all JPG images to PNG
Quick Python script to convert all files in current directory to "png" images:
from PIL import Image from os import listdir from os.path import splitext target_directory = '.' target = '.jpg' for file in listdir(target_directory): filename, extension = splitext(file) try: if extension not in ['.py', target]: im = Image.open(filename + extension) im.save(filename + target, "JPEG") (JPG in our case)
target_directory = '.' target = '.jpg'
- Get the list of files in the current directory
listdir(target_directory)
- Traverse through all files
for file in listdir(target_directory)
- Get the filename and extension of the current file
filename, extension = splitext(file)
- Open image and convert to JPG file
im = Image.open(filename + extension) im.save(filename + target, "JPEG")
- Error handling in the process of saving PNG image
try: if extension not in ['.py', target]: im = Image.open(filename + extension) im.save(filename + target, "JPEG") except OSError: print('Cannot convert %s' % file)
Conclusion
JPG and PNG are two different image formats (differing in how images are represented internally) and often, conversion between the two formats are needed. In this article, we demonstrated how easy it is to convert PNG images to JPG images in Python. Enjoy. | https://iq.opengenus.org/convert-png-to-jpg-in-python/ | CC-MAIN-2021-21 | refinedweb | 305 | 55.13 |
Can someone explain this syntax (in REPL)?
include("Filename.jl") using .Filename
I can sort of understand the first, but what is the . in front of Filename mean?
Can someone explain this syntax (in REPL)?
include("Filename.jl") using .Filename
I can sort of understand the first, but what is the . in front of Filename mean?
I’ve not used that format before, but a quick read of the module documentation indicates that you can access module hierarchy’s using the “.” notation. LOL, I didn’t even know you could have submodules !
Actually the filename has nothing to do with
using .Filename.
Filename is expected to be a module defined in the file.
You can see the effect of
using .ModuleName without needing to worry about
include at all. Here’s a simple example:
julia> module MyModule export foo foo() = println("hello world") end Main.MyModule
Here I’ve defined a module which exports one function (
foo). But I’ve only defined that module, I haven’t
using-ed it, so I don’t yet have access to that exported function:
julia> foo ERROR: UndefVarError: foo not defined
To get
foo into my current namespace, I need
using. But if I just do
using MyModule, it doesn’t work:
julia> using MyModule ERROR: ArgumentError: Package MyModule not found in current path:
That’s because
using MyModule tells Julia to look for some module with that name in a file in the
LOAD_PATH or in the current package environment. That’s not what we want–we already defined that module.
Instead, we can do
using .MyModule which says "find a module named
MyModule which is already defined in the current namespace (in this case, in
Main), and activate it:
julia> using .MyModule julia> foo() hello world
You can add additional dots to activate modules in a parent module:
julia> module A export bar bar() = println("bar") module B using ..A function f() println("Calling `bar` which was defined in the parent module `A`:") bar() end end end Main.A julia> A.B.f() Calling `bar` which was defined in the parent module `A`: bar | https://discourse.julialang.org/t/what-does-this-syntax-using-filename-mean/59420 | CC-MAIN-2022-21 | refinedweb | 353 | 65.42 |
Introduction :
In this post, I will show you how to check if a character is white-space or not using isspace function. A white-space character can be a space(’ ’), horizontal tab(‘\t’), newline(‘\n’), vertical tab(‘\v’), feed(‘\f’) or carriage return(‘\r’). We will use isspace() function to check that. This function is defined is ctype header file.
Syntax of isspace :
The syntax of isspace is as below :
int isspace(int char)
It takes one integer value and returns one integer based on the provided value is white-space or not. If we pass one character, it is converted to an integer. If the return value is zero, it is false i.e. it is not a white-space. If the return value is not zero, it is a white-space.
Example program :
Let me show you one example of how it works :
#include <stdio.h> #include <ctype.h> int main() { char inputChar[] = {' ', '\t', '\n', '\v', '\f', '\r', 'c'}; for (int i = 0; i < sizeof(inputChar); i++) { printf("%d\n", isspace(inputChar[i])); } }
Here, we have one array of characters inputChar with different types of characters including white-space characters. It will print the below output :
1 1 1 1 1 1 0
As you can see, it returns 0 only for the character ‘c’. For other characters, it returns 1 i.e. these are white-space characters.
Similar tutorials :
- C program to print the ASCII value of a character
- C program to print pyramid using star or any other character
- C program to print a diamond pattern using star or any character
- C program to remove all characters from a string keeping all numbers
- C program to sort characters in a string as per their ASCII values
- C program to find the first and the last position of a character in a string | https://www.codevscolor.com/c-check-character-white-space | CC-MAIN-2020-40 | refinedweb | 306 | 61.87 |
import "github.com/spf13/hugo/helpers"
Package helpers implements general utility functions that work with and on content. The helper functions defined here lay down the foundation of how Hugo works with files and filepaths, and perform string operations on content.
baseURL.go content.go content_renderer.go emoji.go general.go hugo.go language.go path.go pathspec.go pygments.go url.go
FilePathSeparator as defined by os.Separator.
var ( // DistinctErrorLog can be used to avoid spamming the logs with errors. DistinctErrorLog = NewDistinctErrorLogger() // DistinctWarnLog can be used to avoid spamming the logs with warnings. DistinctWarnLog = NewDistinctWarnLogger() // DistinctFeedbackLog can be used to avoid spamming the logs with info messages. DistinctFeedbackLog = NewDistinctFeedbackLogger() )
var ( // ErrThemeUndefined is returned when a theme has not be defined by the user. ErrThemeUndefined = errors.New("no theme set") ErrWalkRootTooShort = errors.New("Path too short. Stop walking.") )
var CurrentHugoVersion = HugoVersion{ Number: 0.22, PatchLevel: 0, Suffix: "-DEV", }
CurrentHugoVersion represents the current build version. This should be the only one.
SummaryDivider denotes where content summarization should end. The default is "<!--more-->".
SummaryLength is the length of the summary that Hugo extracts from a content.
AddContextRoot adds the context root to an URL if it's not already set. For relative URL entries on sites with a base url with a context root set (i.e.), relative URLs must not include the context root if canonifyURLs is enabled. But if it's disabled, it must be set.
BytesToHTML converts bytes to type template.HTML.
CompareVersion compares the given version string or number against the running Hugo version. It returns -1 if the given version is less than, 0 if equal and 1 if greater than the running version.
Deprecated informs about a deprecation, but only once for a given set of arguments' values. If the err flag is enabled, it logs as an ERROR (will exit with -1) and the text will point at the next Hugo release. The idea is two remove an item in two Hugo releases to give users and theme authors plenty of time to fix their templates.
DiffStringSlices returns the difference between two string slices. Useful in tests. See:
DirExists checks if a path exists and is a directory.
Emojify "emojifies" the input source. Note that the input byte slice will be modified if needed. See
Exists checks if a file or directory exists.
ExtractRootPaths extracts the root paths from the supplied list of paths. The resulting root path will not contain any file separators, but there may be duplicates. So "/content/section/" becomes "content"
ExtractTOC extracts Table of Contents from content.
FileContains checks if a file contains a specified string.
FileContainsAny checks if a file contains any of the specified strings.
Filename takes a path, strips out the extension, and returns the name of the file.
FindAvailablePort returns an available and valid TCP port.
FindCWD returns the current working directory from where the Hugo executable is run.
FirstUpper returns a string with the first character as upper case.
GetDottedRelativePath expects a relative path starting after the content directory. It returns a relative path with dots ("..") navigating up the path structure.
GetRealPath returns the real file path for the given path, whether it is a symlink or not.
GetRelativePath returns the relative path of a given path.
GetTempDir returns a temporary directory with the given sub path.
GuessSection returns the section given a source path. A section is the part between the root slash and the second slash or before the first slash.
GuessType attempts to guess the type of file from a given string.
HasAsciidoc returns whether Asciidoctor or Asciidoc is installed on this computer.
HasPygments checks to see if Pygments is installed and available on the system.
HasRst returns whether rst2html is installed on this computer.
Highlight takes some code and returns highlighted code.
InStringArray checks if a string is an element of a slice of strings and returns a boolean value.
InitLoggers sets up the global distinct loggers.
IsAbsURL determines whether the given path points to an absolute URL.
IsDir checks if a given path is a directory.
IsEmpty checks if a given path is empty.
IsWhitespace determines if the given rune is whitespace.
MakePermalink combines base URL with content path to create full URL paths. Example
base: path: post/how-i-blog result:
MakeTitle converts the path given to a suitable title, trimming whitespace and replacing hyphens with whitespace.
Md5String takes a string and returns its MD5 hash.
NormalizeHugoFlags facilitates transitions of Hugo command-line flags, e.g. --baseUrl to --baseURL, --uglyUrls to --uglyURLs
PathPrep prepares the path using the uglify setting to create paths on either the form /section/name/index.html or /section/name.html.
PrettifyPath is the same as PrettifyURLPath but for file paths.
/section/name.html becomes /section/name/index.html /section/name/ becomes /section/name/index.html /section/name/index.html becomes /section/name/index.html
PrettifyURL takes a URL string and returns a semantic, clean URL.
PrettifyURLPath takes a URL path to a content and converts it to enable pretty URLs.
/section/name.html becomes /section/name/index.html /section/name/ becomes /section/name/index.html /section/name/index.html becomes /section/name/index.html
ReaderContains reports whether subslice is within r.
ReaderToBytes takes an io.Reader argument, reads from it and returns bytes.
ReaderToString is the same as ReaderToBytes, but returns a string.
ReplaceExtension takes a path and an extension, strips the old extension and returns the path with the new extension.
SafeWriteToDisk is the same as WriteToDisk but it also checks to see if file/directory already exists.
SanitizeURL sanitizes the input URL string.
SanitizeURLKeepTrailingSlash is the same as SanitizeURL, but will keep any trailing slash.
SliceToLower goes through the source slice and lowers all values.
StripHTML accepts a string, strips out all HTML tags and returns it.
SymbolicWalk is like filepath.Walk, but it supports the root being a symbolic link. It will still not follow symbolic links deeper down in the file structure
ToLowerMap makes all the keys in the given map lower cased and will do so recursively. Notes: * This will modify the map given. * Any nested map[interface{}]interface{} will be converted to map[string]interface{}.
TotalWords counts instance of one or more consecutive white space characters, as defined by unicode.IsSpace, in s. This is a cheaper way of word counting than the obvious len(strings.Fields(s)).
TruncateWordsByRune truncates words by runes.
TruncateWordsToWholeSentence takes content and truncates to whole sentence limited by max number of words. It also returns whether it is truncated.
Uglify does the opposite of PrettifyURLPath().
/section/name/index.html becomes /section/name.html /section/name/ becomes /section/name.html /section/name.html becomes /section/name.html
UniqueStrings returns a new slice with any duplicates removed.
WriteToDisk writes content to disk.
A BaseURL in Hugo is normally on the form scheme://path, but the form scheme: is also valid (mailto:hugo@rules.com).
Protocol is normally on the form "scheme://", i.e. "webcal://".
type Blackfriday struct { Smartypants bool AngledQuotes bool Fractions bool HrefTargetBlank bool SmartDashes bool LatexDashes bool TaskLists bool PlainIDAnchors bool SourceRelativeLinksEval bool SourceRelativeLinksProjectFolder string Extensions []string ExtensionsMask []string }
Blackfriday holds configuration values for Blackfriday rendering.
func NewContentSpec(cfg config.Provider) *ContentSpec
func (c ContentSpec) NewBlackfriday() *Blackfriday
NewBlackfriday creates a new Blackfriday filled with site config or some sane defaults.
func (c ContentSpec) RenderBytes(ctx *RenderingContext) []byte
RenderBytes renders a []byte.
DistinctLogger ignores duplicate log statements.
func NewDistinctErrorLogger() *DistinctLogger
NewDistinctErrorLogger creates a new DistinctLogger that logs ERRORs
func NewDistinctFeedbackLogger() *DistinctLogger
NewDistinctFeedbackLogger creates a new DistinctLogger that can be used to give feedback to the user while not spamming with duplicates.
func NewDistinctWarnLogger() *DistinctLogger
NewDistinctWarnLogger creates a new DistinctLogger that logs WARNs
func (l *DistinctLogger) Printf(format string, v ...interface{})
Printf will log the string returned from fmt.Sprintf given the arguments, but not if it has been logged before. Note: A newline is appended.
func (l *DistinctLogger) Println(v ...interface{})
Println will log the string returned from fmt.Sprintln given the arguments, but not if it has been logged before.
type HugoHTMLRenderer struct { *RenderingContext blackfriday.Renderer }
HugoHTMLRenderer wraps a blackfriday.Renderer, typically a blackfriday.Html Enabling Hugo to customise the rendering experience
List adds task list support to the Blackfriday renderer.
ListItem adds task list support to the Blackfriday renderer.
HugoMmarkHTMLRenderer wraps a mmark.Renderer, typically a mmark.html Enabling Hugo to customise the rendering experience
func (r *HugoMmarkHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string, caption []byte, subfigure bool, callouts bool)
type HugoVersion struct { // Major and minor version. Number float32 // Increment this for bug releases PatchLevel int // HugoVersionSuffix is the suffix used in the Hugo version string. // It will be blank for release versions. Suffix string }
HugoVersion represents the Hugo build version.
func (v HugoVersion) Next() HugoVersion
Next returns the next Hugo release version.
func (v HugoVersion) NextPatchLevel(level int) HugoVersion
NextPatchLevel returns the next patch/bugfix Hugo version. This will be a patch increment on the previous Hugo version.
func (v HugoVersion) Prev() HugoVersion
Pre returns the previous Hugo release version.
func (v HugoVersion) ReleaseVersion() HugoVersion
ReleaseVersion represents the release version.
func (v HugoVersion) String() string
type Language struct { Lang string LanguageName string Title string Weight int Cfg config.Provider // contains filtered or unexported fields }
Get returns a value associated with the key relying on specified language. Get is case-insensitive for a key.
Get returns an interface. For a specific value use one of the Get____ methods.
GetBool returns the value associated with the key as a boolean.
GetInt returns the value associated with the key as an int.
GetString returns the value associated with the key as a string.
GetStringMap returns the value associated with the key as a map of interfaces.
GetStringMapString returns the value associated with the key as a map of strings.
IsSet checks whether the key is set in the language or the related config store.
Set sets the value for the key in the language's params.
SetParam sets param with the given key and value. SetParam is case-insensitive.
PathSpec holds methods that decides how paths in URLs and files in Hugo should look like.
NewPathSpec creats a new PathSpec from the given filesystems and Language.
AbsPathify creates an absolute path if given a relative path. If already absolute, the path is just cleaned.
AbsURL creates an absolute URL from the relative path given and the BaseURL set in config.
GetLayoutDirPath returns the absolute path to the layout file dir for the current Hugo project.
GetRelativeThemeDir gets the relative root directory of the current theme, if there is one. If there is no theme, returns the empty string.
GetStaticDirPath returns the absolute path to the static file dir for the current Hugo project.
GetThemeDataDirPath returns the theme's data dir path if theme is set. If theme is set and the data dir doesn't exist, an error is returned.
GetThemeDir gets the root directory of the current theme, if there is one. If there is no theme, returns the empty string.
GetThemeI18nDirPath returns the theme's i18n dir path if theme is set. If theme is set and the i18n dir doesn't exist, an error is returned.
GetThemeStaticDirPath returns the theme's static dir path if theme is set. If theme is set and the static dir doesn't exist, an error is returned.
GetThemesDirPath gets the static files directory of the current theme, if there is one. Ignores underlying errors. TODO(bep) Candidate for deprecation?
LayoutDir returns the relative layout dir in the currenct Hugo project.
MakePath takes a string with any characters and replace it so the string could be used in a path. It does so by creating a Unicode-sanitized string, with the spaces replaced, whilst preserving the original casing of the string. E.g. Social Media -> Social-Media
MakePathSanitized creates a Unicode-sanitized string, with the spaces replaced
MakeStaticPathRelative makes a relative path to the static files directory. It does so by taking either the project's static path or the theme's static path into consideration.
PaginatePath returns the configured root path used for paginator pages.
PrependBasePath prepends any baseURL sub-folder to the given resource if canonifyURLs is disabled. If canonifyURLs is set, we will globally prepend the absURL with any sub-folder, so avoid doing anything here to avoid getting double paths.
RelURL creates a URL relative to the BaseURL root. Note: The result URL will not include the context root if canonifyURLs is enabled.
Theme returns the theme name if set.
ThemeSet checks whether a theme is in use or not.
URLEscape escapes unicode letters.
URLPrep applies misc sanitation to the given URL.
URLize is similar to MakePath, but with Unicode handling Example:
uri: Vim (text editor) urlize: vim-text-editor
URLizeAndPrep applies misc sanitation to the given URL to get it in line with the Hugo standard.
URLizeFilename creates an URL from a filename by esacaping unicode letters and turn any filepath separator into forward slashes.
UnicodeSanitize sanitizes string to be used in Hugo URL's, allowing only a predefined set of special Unicode characters. If RemovePathAccents configuration flag is enabled, Uniccode accents are also removed.
WorkingDir returns the configured workingDir.
type RenderingContext struct { Content []byte PageFmt string DocumentID string DocumentName string Config *Blackfriday RenderTOC bool FileResolver FileResolverFunc LinkResolver LinkResolverFunc Cfg config.Provider }
RenderingContext holds contextual information, like content and configuration, for a given content rendering. By creating you must set the Config, otherwise it will panic.
Package helpers imports 37 packages (graph) and is imported by 493 packages. Updated 2017-05-22. Refresh now. Tools for package owners. | https://godoc.org/github.com/spf13/hugo/helpers | CC-MAIN-2017-22 | refinedweb | 2,258 | 51.75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.